@hostclubeos/miraos 0.0.8-beta → 0.0.9-beta

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 (238) hide show
  1. package/chunks/{MaxSizedBox-YR2SA5XW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-VEXSGLU4.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
  3. package/chunks/{acp-subagent-executor-ATOLWCVC.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
  4. package/chunks/{acpAgent-DN46FTZ2.js → acpAgent-PCXQRPNU.js} +3 -3
  5. package/chunks/{advisor-6MI5JQGC.js → advisor-WDZ5N5ZP.js} +1 -1
  6. package/chunks/{agent-6HPQ4XCT.js → agent-I7Q3IPSS.js} +1 -1
  7. package/chunks/{agent-headless-KXAJBOPG.js → agent-headless-6LOYWI5T.js} +1 -1
  8. package/chunks/{agent-host-client-NOZRE2ZR.js → agent-host-client-PZZKCNQF.js} +1 -1
  9. package/chunks/{agent-host-connections-6FOSHEWD.js → agent-host-connections-TWWSRTKJ.js} +1 -1
  10. package/chunks/{autofix-pr-IMJA2KZF.js → autofix-pr-RQPGPQ4D.js} +1 -1
  11. package/chunks/{batch-L5VJ4XGP.js → batch-UJD5TSBN.js} +1 -1
  12. package/chunks/{bridge-CCRTJSIM.js → bridge-4TYLRPXZ.js} +1 -1
  13. package/chunks/{channel-settings-store-SB7BP6XT.js → channel-settings-store-RENJMOQ5.js} +1 -1
  14. package/chunks/{chunk-UC455ZS7.js → chunk-24PHAWM3.js} +1 -1
  15. package/chunks/{chunk-CNGBG3X5.js → chunk-26JPBN6V.js} +1 -1
  16. package/chunks/{chunk-W4M6JXZB.js → chunk-2MQH3J4U.js} +1 -1
  17. package/chunks/{chunk-GS4FZF6I.js → chunk-2RXOWQSQ.js} +1 -1
  18. package/chunks/{chunk-LRXYXGMT.js → chunk-323HUW2T.js} +1 -1
  19. package/chunks/{chunk-7DJYSBNJ.js → chunk-3BHXE7CB.js} +1 -1
  20. package/chunks/{chunk-7Q6RNE77.js → chunk-3GYAEXAA.js} +1 -1
  21. package/chunks/{chunk-VOIC5ZW2.js → chunk-3YBZW4HP.js} +1 -1
  22. package/chunks/{chunk-JRIVHFCG.js → chunk-4RJ2RRGZ.js} +1 -1
  23. package/chunks/{chunk-3NA5O4QO.js → chunk-5DIW4X4P.js} +1 -1
  24. package/chunks/{chunk-YELFN6AG.js → chunk-5GB6JNJX.js} +1 -1
  25. package/chunks/{chunk-6TNX3S5H.js → chunk-5HSNCG73.js} +2 -2
  26. package/chunks/{chunk-FC5IAX56.js → chunk-6HDMM7TJ.js} +1 -1
  27. package/chunks/{chunk-CJLKKIUW.js → chunk-6STNGEYC.js} +1 -1
  28. package/chunks/{chunk-ZJOVJLIH.js → chunk-7EFWNFJJ.js} +1 -1
  29. package/chunks/{chunk-SMO4PEHK.js → chunk-7EWIKIJI.js} +1 -1
  30. package/chunks/{chunk-S5NTCBEI.js → chunk-7TB6VG72.js} +1 -1
  31. package/chunks/{chunk-6AAVML2M.js → chunk-7TLL4JLR.js} +1 -1
  32. package/chunks/{chunk-IWIGJDPL.js → chunk-AOMXZNMX.js} +1 -1
  33. package/chunks/{chunk-5YULNQF3.js → chunk-AUM57JI2.js} +1 -1
  34. package/chunks/{chunk-ZQZK267X.js → chunk-AW5UCOZO.js} +1 -1
  35. package/chunks/{chunk-D4WMUCSK.js → chunk-C6HVNDQT.js} +2 -2
  36. package/chunks/{chunk-2DPE27WB.js → chunk-CC6E5CQV.js} +1 -1
  37. package/chunks/{chunk-SK5C26Y6.js → chunk-CLKUQP27.js} +1 -1
  38. package/chunks/{chunk-ARILWFTZ.js → chunk-DFMQQM4M.js} +1 -1
  39. package/chunks/{chunk-IJIQDCNJ.js → chunk-DP7LJTG2.js} +5 -5
  40. package/chunks/{chunk-7EEWU6XO.js → chunk-DQT5VL7G.js} +1 -1
  41. package/chunks/{chunk-AHV4IMUX.js → chunk-E4QOAV5O.js} +1 -1
  42. package/chunks/{chunk-G3COGFSZ.js → chunk-E4REGDEZ.js} +1 -1
  43. package/chunks/{chunk-MOXZO5PM.js → chunk-EAG7VZJJ.js} +1 -1
  44. package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
  45. package/chunks/{chunk-IJH5HZTB.js → chunk-EMR4QK2F.js} +1 -1
  46. package/chunks/{chunk-YFXKRGHT.js → chunk-EYECE2PH.js} +1 -1
  47. package/chunks/{chunk-7HO5DQ6V.js → chunk-EZDXHUHB.js} +1 -1
  48. package/chunks/{chunk-66N3SLXJ.js → chunk-FJFTKA4H.js} +1 -1
  49. package/chunks/{chunk-DNCXESHL.js → chunk-FSLDNLNU.js} +1 -1
  50. package/chunks/{chunk-K3RWL2YH.js → chunk-FSRXTX3N.js} +1 -1
  51. package/chunks/{chunk-4RRQ7CPF.js → chunk-FWSXFRIQ.js} +1 -1
  52. package/chunks/{chunk-M3IQE5G4.js → chunk-G4ATLMDH.js} +1 -1
  53. package/chunks/{chunk-WUZ53TKN.js → chunk-GAS3HKRX.js} +1 -1
  54. package/chunks/{chunk-LTXZHHNK.js → chunk-GFFL2LR2.js} +1 -1
  55. package/chunks/{chunk-IK5TB2CB.js → chunk-GYFIY7TD.js} +1 -1
  56. package/chunks/{chunk-XJKDC7OE.js → chunk-GYXRI4P5.js} +1 -1
  57. package/chunks/{chunk-4C5BOFDC.js → chunk-H3U7DXIU.js} +1 -1
  58. package/chunks/{chunk-5AJKMBPM.js → chunk-HEDVPRMD.js} +1 -1
  59. package/chunks/{chunk-32DLSPV5.js → chunk-HI3644FQ.js} +1 -1
  60. package/chunks/{chunk-CLLQQMTU.js → chunk-HTHYLMBO.js} +1 -1
  61. package/chunks/{chunk-VAFRD2H4.js → chunk-IW7RPDV2.js} +1 -1
  62. package/chunks/{chunk-5BWVS5D3.js → chunk-IXQI4K6O.js} +1 -1
  63. package/chunks/{chunk-BWLMXGA2.js → chunk-IYH3IZL4.js} +1 -1
  64. package/chunks/{chunk-XGPGIMZK.js → chunk-J52J35K4.js} +1 -1
  65. package/chunks/{chunk-BWFZEDYG.js → chunk-J7L5IHLG.js} +1 -1
  66. package/chunks/{chunk-6STDVRH5.js → chunk-JHS5B4N7.js} +2 -2
  67. package/chunks/{chunk-EHM4KL2U.js → chunk-JRSO5ZGU.js} +1 -1
  68. package/chunks/{chunk-NYGJ53Y7.js → chunk-JS6VAGRQ.js} +1 -1
  69. package/chunks/{chunk-QCSGHQ2P.js → chunk-KAFPULGU.js} +1 -1
  70. package/chunks/{chunk-CNZS2RPX.js → chunk-LDP47G5M.js} +1 -1
  71. package/chunks/{chunk-GM6YF6IS.js → chunk-LMZZWPKA.js} +1 -1
  72. package/chunks/{chunk-5SX4UPMN.js → chunk-LNCELICB.js} +1 -1
  73. package/chunks/{chunk-K2PGOAJP.js → chunk-LY2DRNTZ.js} +1 -1
  74. package/chunks/{chunk-KZZ5ZQHX.js → chunk-MMGGGYSJ.js} +1 -1
  75. package/chunks/{chunk-SVNSF5ZH.js → chunk-MTBU2ZIM.js} +1 -1
  76. package/chunks/{chunk-MV7LX23I.js → chunk-N27KICJQ.js} +1 -1
  77. package/chunks/{chunk-OPFBBIAQ.js → chunk-NHYFTK4O.js} +1 -1
  78. package/chunks/{chunk-NUDHRTIM.js → chunk-NRDHXSEE.js} +1 -1
  79. package/chunks/{chunk-QZNCYZ7H.js → chunk-NV5VVTYQ.js} +1 -1
  80. package/chunks/{chunk-7GU7HKIT.js → chunk-OEDMFKZL.js} +1 -1
  81. package/chunks/{chunk-V3ASW57P.js → chunk-OQAVMR6K.js} +1 -1
  82. package/chunks/{chunk-GBEQD55S.js → chunk-OY3Y6EMV.js} +1 -1
  83. package/chunks/{chunk-G7D42XGP.js → chunk-OZL4ZMGQ.js} +2 -2
  84. package/chunks/{chunk-PGKVSOWW.js → chunk-PKSPKVFH.js} +1 -1
  85. package/chunks/{chunk-OXG4BLFF.js → chunk-PNFKCYZT.js} +1 -1
  86. package/chunks/{chunk-JT5EN5MI.js → chunk-PTWHFVGG.js} +2 -2
  87. package/chunks/{chunk-3VKLOQ2P.js → chunk-QJ6ZTZFC.js} +1 -1
  88. package/chunks/{chunk-WZAUO3LV.js → chunk-QRGWB7IX.js} +1 -1
  89. package/chunks/{chunk-JCWNB45W.js → chunk-QRP2GXQD.js} +1 -1
  90. package/chunks/{chunk-CEVKKM22.js → chunk-RES5ET63.js} +1 -1
  91. package/chunks/{chunk-HCKF74X7.js → chunk-ROSJCTWB.js} +1 -1
  92. package/chunks/{chunk-WJXADORN.js → chunk-RR3NFNWL.js} +1 -1
  93. package/chunks/{chunk-HCCONFJY.js → chunk-RYQDRFLW.js} +1 -1
  94. package/chunks/{chunk-WSXRO2YB.js → chunk-S7CWSAUQ.js} +1 -1
  95. package/chunks/{chunk-MXFS555I.js → chunk-SAJKF4WS.js} +1 -1
  96. package/chunks/chunk-SINRWOVD.js +36 -0
  97. package/chunks/{chunk-DNXQKR5E.js → chunk-SJNQ6I23.js} +1 -1
  98. package/chunks/{chunk-DTRSC73M.js → chunk-T2GM4S4G.js} +3 -3
  99. package/chunks/{chunk-C3ZJUOTJ.js → chunk-TCQJO42E.js} +1 -1
  100. package/chunks/{chunk-G4OSEVOV.js → chunk-TIIDF23U.js} +2 -2
  101. package/chunks/{chunk-NNYAXFFN.js → chunk-TKH5R7RZ.js} +1 -1
  102. package/chunks/{chunk-JHGMLUAL.js → chunk-TSRTZD3X.js} +1 -1
  103. package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
  104. package/chunks/{chunk-MCY3IS2E.js → chunk-UYI5AMPI.js} +1 -1
  105. package/chunks/{chunk-7L4MR4QM.js → chunk-VO6SPDH4.js} +1 -1
  106. package/chunks/{chunk-SPCIIUIG.js → chunk-VRIHYTDI.js} +1 -1
  107. package/chunks/{chunk-Q4NEZZ6L.js → chunk-VT47A26Q.js} +1 -1
  108. package/chunks/{chunk-E743PFSX.js → chunk-VZOZUCZX.js} +1 -1
  109. package/chunks/{chunk-WW43VZ6O.js → chunk-WLEGTKGA.js} +1 -1
  110. package/chunks/{chunk-77GGGTWS.js → chunk-XHCJN4A2.js} +1 -1
  111. package/chunks/{chunk-UZAFPEVN.js → chunk-XTRZ5PHG.js} +1 -1
  112. package/chunks/{chunk-DTNW2CM3.js → chunk-Y4GZOZWD.js} +1 -1
  113. package/chunks/{chunk-YOBM4ZFW.js → chunk-YUCAGV52.js} +2 -2
  114. package/chunks/{chunk-WOMJLK3E.js → chunk-YWQM4TSO.js} +1 -1
  115. package/chunks/{chunk-WN6Z3J27.js → chunk-YYTOHY4V.js} +1 -1
  116. package/chunks/{chunk-VOCM2M4K.js → chunk-Z25W2S5N.js} +1 -1
  117. package/chunks/{chunk-QWNTORRT.js → chunk-Z6GECBAJ.js} +1 -1
  118. package/chunks/{chunk-XNP5JXCS.js → chunk-ZJU4B4WX.js} +1 -1
  119. package/chunks/{chunk-MCHMWRNO.js → chunk-ZSHDQPAO.js} +1 -1
  120. package/chunks/{chunk-POMEWCFJ.js → chunk-ZUWLTGSR.js} +6 -6
  121. package/chunks/{codex-subagent-executor-TPO62HU5.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
  122. package/chunks/{config-utils-6GWIYBUK.js → config-utils-5B2LYCON.js} +1 -1
  123. package/chunks/{contextCommand-WWVGDTOL.js → contextCommand-UPQGRXWK.js} +1 -1
  124. package/chunks/{core-runtime-ASQR33TV.js → core-runtime-DPMH2BXK.js} +1 -1
  125. package/chunks/{create-sub-session-XY2FXSPE.js → create-sub-session-EJVB3FE5.js} +1 -1
  126. package/chunks/{cron-create-HY3TLNV2.js → cron-create-V2A7PMQC.js} +1 -1
  127. package/chunks/{daemon-git-worktree-guard-ILW3NJJC.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
  128. package/chunks/{daemon-status-provider-JVOGEKWY.js → daemon-status-provider-6BRB5TG3.js} +1 -1
  129. package/chunks/{daemon-trust-policy-XXRBG4JE.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
  130. package/chunks/{daemon-trust-policy-monitor-UL73ADOZ.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
  131. package/chunks/{deferred-core-runtime-PT747R7S.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
  132. package/chunks/{edit-4PJ3NPFA.js → edit-LRG3TMHP.js} +1 -1
  133. package/chunks/{enterPlanMode-KQ62QN7S.js → enterPlanMode-KOUSHJHR.js} +1 -1
  134. package/chunks/{environment-H4HADXGA.js → environment-54CM3OXE.js} +1 -1
  135. package/chunks/{errors-OSD4ZZGR.js → errors-D6XR3NH4.js} +1 -1
  136. package/chunks/{execution-tool-PHHGLKWC.js → execution-tool-7RZ2JLEK.js} +1 -1
  137. package/chunks/{execution-worker-MH3CV66T.js → execution-worker-LXQ7WAFG.js} +1 -1
  138. package/chunks/{exitPlanMode-OU5YP4XN.js → exitPlanMode-4FGFA2QC.js} +1 -1
  139. package/chunks/{fast-path-WKOMHBWN.js → fast-path-4B7OKPYK.js} +1 -1
  140. package/chunks/{glob-FYCOEQPM.js → glob-N2D7SY23.js} +1 -1
  141. package/chunks/{goal-tools-T27GSDNM.js → goal-tools-7RNSDRFO.js} +1 -1
  142. package/chunks/{handleAutoUpdate-XXCPJLKO.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
  143. package/chunks/{i18n-3B2PRJM2.js → i18n-F3OAHCLJ.js} +1 -1
  144. package/chunks/{initializer-HSFVDRTR.js → initializer-OL3DDWR7.js} +1 -1
  145. package/chunks/{installationInfo-SJJ2DYZ6.js → installationInfo-D2L743RV.js} +1 -1
  146. package/chunks/{interactive-mod-session-BWY2JRSQ.js → interactive-mod-session-2GXRCQKR.js} +1 -1
  147. package/chunks/{list-TGCI3MBM.js → list-PU7ZXBY5.js} +1 -1
  148. package/chunks/{llm-FYR73GKD.js → llm-V42HGUVH.js} +4 -4
  149. package/chunks/{loadedSettingsAdapter-DUDCINQL.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
  150. package/chunks/{local-7PEOBJKE.js → local-KM5F5RAB.js} +1 -1
  151. package/chunks/{local-execution-environment-Q4OOA7BL.js → local-execution-environment-OEO2KW3M.js} +1 -1
  152. package/chunks/{loggingContentGenerator-VVESQOIQ.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
  153. package/chunks/{loop-wakeup-M2XLAAKZ.js → loop-wakeup-CJICM24Y.js} +1 -1
  154. package/chunks/{manage-memory-FRVWHM2C.js → manage-memory-7CV6LF4C.js} +1 -1
  155. package/chunks/{managed-execution-engine-AVIM6AQU.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
  156. package/chunks/{managed-local-serve-GIXHGFIU.js → managed-local-serve-KA37YWRW.js} +1 -1
  157. package/chunks/{managed-npm-update-3QSXGSHW.js → managed-npm-update-TSUUH3NN.js} +1 -1
  158. package/chunks/{managed-runtime-attestation-worker-ML4TCRAW.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
  159. package/chunks/{managed-runtime-bootstrap-JWJFGLBM.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
  160. package/chunks/{managed-runtime-session-worker-4ISKROGZ.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
  161. package/chunks/{managed-runtime-ssh-worker-C44V2CPM.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
  162. package/chunks/{managed-session-authority-UJ3FSKMD.js → managed-session-authority-5FYS3G3M.js} +1 -1
  163. package/chunks/{mcp-BWCLHHZ6.js → mcp-TRPV3K74.js} +1 -1
  164. package/chunks/{memory-5XQ2JVNS.js → memory-5CMNRPM2.js} +1 -1
  165. package/chunks/{model-call-collection-DXK2SIDR.js → model-call-collection-S4JKVFUO.js} +1 -1
  166. package/chunks/{model-configuration-6OLZS4C3.js → model-configuration-NEIDLKWQ.js} +1 -1
  167. package/chunks/{modelConfigUtils-5S5PC2RR.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
  168. package/chunks/{monitor-6GKCWWUI.js → monitor-5MNKK5AO.js} +1 -1
  169. package/chunks/{nonInteractiveCli-ROHAB2H7.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
  170. package/chunks/{nonInteractiveToolExecutor-OWCCSC5Y.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
  171. package/chunks/{notebook-edit-WNRQ3QJZ.js → notebook-edit-7HIBTFFW.js} +1 -1
  172. package/chunks/{omni-DJ5RGNKA.js → omni-MX7BMOL5.js} +1 -1
  173. package/chunks/{openaiContentGenerator-237NVB63.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
  174. package/chunks/{openaiResponsesContentGenerator-J33TCZKQ.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
  175. package/chunks/{pidfile-F7IYTFLX.js → pidfile-OHAGZOTV.js} +1 -1
  176. package/chunks/{processUtils-C6CSXITS.js → processUtils-TCDNCYVB.js} +1 -1
  177. package/chunks/{prompt-terminal-ledger-ZGYWPFJF.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
  178. package/chunks/{reactive-degrade-QKXPZQ3W.js → reactive-degrade-C7CGUJNP.js} +1 -1
  179. package/chunks/{read-file-GSNUMHRE.js → read-file-L4ZF6VDG.js} +1 -1
  180. package/chunks/{resumeHistoryUtils-4GUCHQGU.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
  181. package/chunks/{review-M2QGZFIO.js → review-F6JGI2LP.js} +1 -1
  182. package/chunks/{ripGrep-X4JTJZC6.js → ripGrep-L6M2GPCM.js} +1 -1
  183. package/chunks/{run-qwen-serve-4WW37RL2.js → run-qwen-serve-D5HB55SC.js} +1 -1
  184. package/chunks/{runtime-EFHJ6REE.js → runtime-CH3RAOQL.js} +1 -1
  185. package/chunks/{sandboxConfig-5XMIRDS4.js → sandboxConfig-EADWCO37.js} +1 -1
  186. package/chunks/{scheduled-tasks-ZCYM5YQJ.js → scheduled-tasks-PBKD4BHY.js} +1 -1
  187. package/chunks/{scheduler-5UAKCD5Z.js → scheduler-U5K3523K.js} +1 -1
  188. package/chunks/{search-memory-KKPYK33Q.js → search-memory-Y2IPKBDP.js} +1 -1
  189. package/chunks/{send-message-KOZRSWXO.js → send-message-JJQG2S6D.js} +1 -1
  190. package/chunks/{serve-5HSHEBMT.js → serve-2ZYS47MO.js} +1 -1
  191. package/chunks/{server-MC6KHP3G.js → server-5GMO4IHU.js} +3 -3
  192. package/chunks/{session-Z5HFG4IQ.js → session-LLOOVSHK.js} +1 -1
  193. package/chunks/{session-attachments-root-K2E5ETD4.js → session-attachments-root-XCLXH2XO.js} +1 -1
  194. package/chunks/{session-execution-engine-selector-NZA6CAJB.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
  195. package/chunks/{session-pr-refresh-OYJ56U3L.js → session-pr-refresh-MDBOAN3R.js} +1 -1
  196. package/chunks/{sessionService-BC56MX3G.js → sessionService-VKAHCTCC.js} +1 -1
  197. package/chunks/{settings-OHB77GXH.js → settings-ULEB2IYZ.js} +1 -1
  198. package/chunks/{shell-VKSH7JVL.js → shell-RBEKIYKU.js} +1 -1
  199. package/chunks/{skill-HQ4C2C3X.js → skill-GEVOEFMZ.js} +1 -1
  200. package/chunks/{skill-settings-6WPQFE3V.js → skill-settings-4IMGLYJW.js} +1 -1
  201. package/chunks/{spawnChannel-MXKVLS24.js → spawnChannel-B7L5PWQ6.js} +1 -1
  202. package/chunks/{standalone-update-NZP3OAZZ.js → standalone-update-SYQM6NOC.js} +1 -1
  203. package/chunks/{start-opentui-ui-25YQQD3O.js → start-opentui-ui-N427PLF4.js} +2 -2
  204. package/chunks/{startInteractiveUI-DWQJNIIV.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
  205. package/chunks/{team-create-RSD7IADX.js → team-create-MN6FHUHU.js} +1 -1
  206. package/chunks/{team-plan-approval-XAOKZ6BR.js → team-plan-approval-OUYBIT7H.js} +1 -1
  207. package/chunks/{terminal-image-renderer-P5AGEOYS.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
  208. package/chunks/{theme-manager-YBKJYPVQ.js → theme-manager-QOYSKWFK.js} +1 -1
  209. package/chunks/{tool-call-HJCSPR6N.js → tool-call-Q5NLEQFD.js} +1 -1
  210. package/chunks/{tool-result-media-SPWVV3OS.js → tool-result-media-NZJZTOBQ.js} +1 -1
  211. package/chunks/{tool-search-YWCOODLL.js → tool-search-D6Y45RNQ.js} +1 -1
  212. package/chunks/{total-session-admission-HKACVEI2.js → total-session-admission-36W7MDHP.js} +1 -1
  213. package/chunks/{trustedFolders-BXLZULWO.js → trustedFolders-XW5VH6HK.js} +1 -1
  214. package/chunks/{update-relaunch-CBJVLG6S.js → update-relaunch-KQPR2HAP.js} +1 -1
  215. package/chunks/{updateCheck-2J6RY3L3.js → updateCheck-SRW67WAX.js} +1 -1
  216. package/chunks/{upload-config-EN5XYA3V.js → upload-config-BTJNYMRX.js} +1 -1
  217. package/chunks/{useAutoAcceptIndicator-LF7VIUER.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
  218. package/chunks/{validateNonInterActiveAuth-63TR5JOG.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
  219. package/chunks/{version-F22SKNME.js → version-6R6LSGXO.js} +1 -1
  220. package/chunks/{web-fetch-ULH7TOLR.js → web-fetch-Y7LBAU3R.js} +1 -1
  221. package/chunks/{web-search-C3ORWAWR.js → web-search-IB4NYYUH.js} +1 -1
  222. package/chunks/{workflow-4ATPGZ5N.js → workflow-TR4YIPJO.js} +1 -1
  223. package/chunks/{workflow-ancestor-trust-AJ27EBZD.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
  224. package/chunks/{workspace-agents-VLAJGYJF.js → workspace-agents-MY2NFL6A.js} +1 -1
  225. package/chunks/{workspace-providers-status-TFAXNJ6L.js → workspace-providers-status-DNCCKFVE.js} +1 -1
  226. package/chunks/{workspace-recovery-worker-GKYYJPXV.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
  227. package/chunks/{workspace-registration-store-ANR3STGQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
  228. package/chunks/{workspace-registry-OVHNLVBM.js → workspace-registry-E6LFL5GL.js} +1 -1
  229. package/chunks/{workspace-runtime-coordinator-IEN2G7JP.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
  230. package/chunks/{workspace-service-NISFZTBE.js → workspace-service-OVEYIQOC.js} +1 -1
  231. package/chunks/{workspace-skills-status-QRF5ZXMT.js → workspace-skills-status-3NKXA5SK.js} +1 -1
  232. package/chunks/{workspace-trust-reconciler-X3XMX2GJ.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
  233. package/chunks/{write-file-SF42KZAH.js → write-file-FSTHYKKZ.js} +1 -1
  234. package/chunks/{zoom-image-4UMB6G3P.js → zoom-image-JP3EUDXE.js} +1 -1
  235. package/cli.js +2 -2
  236. package/execution-worker.js +1 -1
  237. package/package.json +2 -2
  238. package/chunks/chunk-OHOG4HSN.js +0 -31
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-ZLUQTFP3.js";import{historyPath,parseHostedFileHistoryState,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryState}from"./chunk-66N3SLXJ.js";import{MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST,MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{computeManagedContextDigest,isCanonicalDecimalText}from"./chunk-YJ6APXNB.js";import{resolveManagedRuntimeBrokerBaseUrl}from"./chunk-6S5XOXJ2.js";import{authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore}from"./chunk-H5A2YPMV.js";import{DAEMON_ACP_NDJSON_LIMITS,hasBoundedJsonStructure}from"./chunk-3Y4UVTLL.js";import{MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,Qn,cloneFromGit,convertClaudeToQwenConfig,convertGeminiToQwenConfig,createCronGateRunner,downloadFromArchiveUrl,downloadFromGitHubRelease,downloadFromNpmRegistry,extractArchiveFile,gateCommandError,managedToolDigest,parseManagedToolCallIdentity,parseManagedToolConfirmationPayload,parseManagedToolContentModification,parseManagedToolInvocationReference,parseManagedToolMediaContext,require_toml}from"./chunk-POMEWCFJ.js";import{MANAGED_SESSION_LIMITS,MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,assertManagedSessionDurableRef,assertManagedSessionStableId,impliedStatus,parseManagedSessionRecordJson,parseToolResultManifest,parseToolResultPage}from"./chunk-HMCTSPVJ.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import{parseSkillContent}from"./chunk-DNYXZVBT.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{BaseDeclarativeTool,BaseToolInvocation,ToolConfirmationOutcome}from"./chunk-D6CEQ2GY.js";import{resolveBuiltinToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var WORKSPACE_EXECUTION_PROFILE="managed-workspace-execution/1";var WORKSPACE_CONTEXT_CONFIG_REF="sha256:5fa15183dcfe582ce54c28bf25aff62801d19038a9ec649e9bfc67b06f2a389f";var WORKSPACE_CAPABILITY_DIGEST="sha256:7df3981fa14b397fe09f6ba84ed0c096c71902394da667bf47f3b315866e7f91";var MEASURED_WORKSPACE_CAPABILITY_DIGEST="sha256:b2ab403f278282eb8f2ca06c926be96bd3d85877714f64dc926eab535f544580";var MEASURED_WORKSPACE_EXECUTION_PROFILE="managed-workspace-execution/2";function isWorkspaceToolCapability(digest2){return digest2===WORKSPACE_CAPABILITY_DIGEST||digest2===MEASURED_WORKSPACE_CAPABILITY_DIGEST}__name(isWorkspaceToolCapability,"isWorkspaceToolCapability");var RESIDENT_WORKSPACE_PROFILE="resident-workspace-files/1";var RESIDENT_WORKSPACE_CAPABILITY_DIGEST="sha256:2cbf6f3825230848a65a546ec70714fbb2a53d1862a6caba73ae4cebf307b4ad";function resolveManagedShellPublisherMode(input){const resident=input.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST;const requiresActivation=isWorkspaceToolCapability(input.capabilityDigest)||resident||input.managedExtensions;const remotePublisher=!input.capturePublisher&&requiresActivation&&!resident;return{resident,requiresActivation,remotePublisher,publisher:input.capturePublisher||input.remotePublishers||remotePublisher,installRoute:remotePublisher}}__name(resolveManagedShellPublisherMode,"resolveManagedShellPublisherMode");var WORKSPACE_ACTIVATION_ROUTE=Object.freeze({key:"activation",method:"POST",path:"/internal/managed-runtime/v3/activation",protocolVersion:1,requestBodyLimitBytes:16*1024,responseBodyLimitBytes:16*1024,cacheControl:"no-store"});var KEYS=["contextConfigRef","contextDigest","operation","profile","protocolVersion","sessionId"].join(",");var WorkspaceActivations=class{static{__name(this,"WorkspaceActivations")}sessions=new Map;isActive(sessionId){return this.sessions.get(sessionId)===true}register(app,boot,installations,executor){app.post(WORKSPACE_ACTIVATION_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(WORKSPACE_ACTIVATION_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body=req.body;if(body===null||typeof body!=="object"||Array.isArray(body)||Object.keys(body).sort().join(",")!==KEYS){res.status(400).json({code:"managed_activation_invalid"});return}const request=body;const binding=typeof request["sessionId"]==="string"?installations.installed(request["sessionId"]):void 0;if(request["protocolVersion"]!==1||request["operation"]!=="activate"&&request["operation"]!=="release"||(boot.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST?boot.isolationClass!=="workspace"||request["profile"]!==RESIDENT_WORKSPACE_PROFILE:![WORKSPACE_CAPABILITY_DIGEST,MEASURED_WORKSPACE_CAPABILITY_DIGEST,...boot.managedExtensions?[MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST]:[]].includes(boot.capabilityDigest)||request["profile"]!==(boot.capabilityDigest===MEASURED_WORKSPACE_CAPABILITY_DIGEST?MEASURED_WORKSPACE_EXECUTION_PROFILE:WORKSPACE_EXECUTION_PROFILE))||binding===void 0||binding.contextConfigRef!==WORKSPACE_CONTEXT_CONFIG_REF||request["contextConfigRef"]!==binding.contextConfigRef||request["contextDigest"]!==computeManagedContextDigest(binding)){res.status(409).json({code:"managed_activation_conflict"});return}const sessionId=request["sessionId"];const active=request["operation"]==="activate";if(active&&(!executor.isAdmissionOpen||this.sessions.get(sessionId)===false||boot.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST&&[...this.sessions].some(([id3,admitted])=>id3!==sessionId&&admitted))){res.status(409).json({code:"managed_activation_conflict"});return}if(!active&&executor.hasActiveSession(sessionId)){await executor.stopBackgroundSession(sessionId);if(executor.hasActiveSession(sessionId)){res.status(409).json({code:"managed_activation_conflict"});return}}this.sessions.set(sessionId,active);res.json({...request,runtimeInstanceId:boot.runtimeInstanceId,runtimeIncarnation:boot.runtimeIncarnation,epoch:boot.epoch,active})},handleManagedRuntimeJsonError)}};init_esbuild_shims();var CSI_FILES_RETIREMENT_CAPABILITY_DIGEST="sha256:116dcd2afce7292bdf0bf4c76010964f7a7148ad512b2939e48e3d55ea91118d";var CSI_FILES_DIAGNOSTICS_CAPABILITY_DIGEST="sha256:e973d9401c00a917e8b3de2d8fd63a0d1b09e3c4407aecf64826cdfff6c1c321";var CSI_FILES_ACTIVITY_CAPABILITY_DIGEST="sha256:5462b4edf53081cbb4aabebdcb23801b30f355f7b365c467f6a851f2fefabbf0";function isCsiFilesCapability(digest2){return digest2===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||digest2===CSI_FILES_DIAGNOSTICS_CAPABILITY_DIGEST||digest2===CSI_FILES_ACTIVITY_CAPABILITY_DIGEST}__name(isCsiFilesCapability,"isCsiFilesCapability");var sessionProfiles=new WeakMap;async function readHostedCsiFileProfile(session){const saved=sessionProfiles.get(session.authority);if(saved)return saved;const definition=JSON.parse((await session.resources.read(session.authority.sessionHeader.definitionRef)).toString("utf8"));const profile=definition.toolProfile;if(profile!=="csi-files-retirement/1"&&profile!=="csi-files-retirement/2"&&profile!=="csi-files-retirement/3")throw new Error("Invalid CSI Session profile.");sessionProfiles.set(session.authority,profile);return profile}__name(readHostedCsiFileProfile,"readHostedCsiFileProfile");function matchesCsiFilesProfile(profile,capabilityDigest){return profile==="csi-files-retirement/1"&&capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||profile==="csi-files-retirement/2"&&capabilityDigest===CSI_FILES_DIAGNOSTICS_CAPABILITY_DIGEST||profile==="csi-files-retirement/3"&&capabilityDigest===CSI_FILES_ACTIVITY_CAPABILITY_DIGEST}__name(matchesCsiFilesProfile,"matchesCsiFilesProfile");init_esbuild_shims();import{createHash}from"node:crypto";var MANAGED_CSI_PROTOCOL="managed-csi/1";var MANAGED_CSI_ATTEST_PATH="/internal/managed-runtime/csi/v1/attest";var MANAGED_CSI_DRAIN_PATH="/internal/managed-runtime/csi/v1/drain";var MANAGED_CSI_ACK_PATH="/internal/managed-runtime/csi/v1/acknowledge";var MANAGED_CSI_WORKER_ACK_PROTOCOL="managed-csi-original-worker-ack/1";var MANAGED_CSI_ACK_LIMIT_BYTES=16*1024;var ManagedCsiAckRequestError=class extends Error{constructor(status){super("Managed CSI acknowledgement conflicts.");this.status=status}static{__name(this,"ManagedCsiAckRequestError")}};function parseManagedCsiAckJson(bytes){const text3=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text3,MANAGED_CSI_ACK_LIMIT_BYTES);return JSON.parse(text3,(_key,value,context)=>{if(typeof value==="number"&&(context?.source===void 0||!/^[1-9][0-9]*$/.test(context.source)))throw new Error("Managed CSI acknowledgement JSON is invalid.");return value})}__name(parseManagedCsiAckJson,"parseManagedCsiAckJson");function parseManagedCsiAcknowledgement(value){const ack=closed(value,["deliveryStatus","executionCallId","historyRevision","manifest"]);const manifest=assertManagedSessionDurableRef(ack["manifest"],"manifest");if(ack["deliveryStatus"]!=="committed"||!Number.isSafeInteger(ack["historyRevision"])||ack["historyRevision"]<1||manifest.kind!=="managed-tool-result-manifest"||manifest.schemaVersion!==1||manifest.byteLength<1||manifest.byteLength>65536)throw new Error;return{executionCallId:stableId(ack["executionCallId"]),manifest,deliveryStatus:"committed",historyRevision:ack["historyRevision"]}}__name(parseManagedCsiAcknowledgement,"parseManagedCsiAcknowledgement");function parseManagedCsiCaptureIdentity(value){const identity=closed(value,["bindingGeneration","callId","captureId","executionCallId","invocationDigest","revision","sessionId","tenantId","turnId"]);if(!isCanonicalDecimalText(identity["bindingGeneration"])||identity["revision"]!==1||typeof identity["captureId"]!=="string"||!/^[a-z0-9_-]{1,128}$/.test(identity["captureId"])||!invocationDigest(identity["invocationDigest"]))throw new Error;return{tenantId:stableId(identity["tenantId"]),sessionId:stableId(identity["sessionId"]),turnId:stableId(identity["turnId"]),executionCallId:stableId(identity["executionCallId"]),callId:stableId(identity["callId"]),invocationDigest:identity["invocationDigest"],bindingGeneration:identity["bindingGeneration"],captureId:identity["captureId"],revision:1}}__name(parseManagedCsiCaptureIdentity,"parseManagedCsiCaptureIdentity");function parseManagedCsiAckRequest(value,boot,pod){let request;let reference;let acknowledgement;const context=createManagedContextAttestationResponse(boot.context);try{request=closed(value,ACK_REQUEST_KEYS);if(typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error;const ref2=closed(request["reference"],["argsDigest","callId","promptId","sessionId"]);if(!invocationDigest(ref2["argsDigest"]))throw new Error;reference={sessionId:stableId(ref2["sessionId"]),promptId:stableId(ref2["promptId"]),callId:stableId(ref2["callId"]),argsDigest:ref2["argsDigest"]};acknowledgement=parseManagedCsiAcknowledgement(request["acknowledgement"]);closed(request["context"],Object.keys(context).sort());closed(request["storage"],STORAGE_KEYS);closed(request["pod"],["namespace","nodeName","uid"])}catch{throw new ManagedCsiAckRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL||request["workerAck"]!==MANAGED_CSI_WORKER_ACK_PROTOCOL||boot.context.isolationClass!=="workspace")throw new Error;for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",pod]]){const fields2=request[key];if(!Object.entries(expected).every(([name,field])=>fields2[name]===field))throw new Error}}catch{throw new ManagedCsiAckRequestError(409)}return{protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,workerAck:MANAGED_CSI_WORKER_ACK_PROTOCOL,retirementId:request["retirementId"],context,storage:{...boot.storage},pod:{...pod},reference,acknowledgement}}__name(parseManagedCsiAckRequest,"parseManagedCsiAckRequest");function parseManagedCsiAckResponse(value,boot,pod){try{const response=closed(value,[...ACK_REQUEST_KEYS,"captureIdentity","state"].sort());if(response["state"]!=="ACKNOWLEDGED")throw new Error;const request=parseManagedCsiAckRequest(Object.fromEntries(ACK_REQUEST_KEYS.map(key=>[key,response[key]])),boot,pod);const identity=parseManagedCsiCaptureIdentity(response["captureIdentity"]);if(identity.tenantId!==boot.context.tenantId||identity.executionCallId!==request.acknowledgement.executionCallId||identity.callId!==request.reference.callId||identity.invocationDigest!==request.reference.argsDigest)throw new Error;return{...request,state:"ACKNOWLEDGED",captureIdentity:identity}}catch{throw new ManagedCsiAckRequestError(409)}}__name(parseManagedCsiAckResponse,"parseManagedCsiAckResponse");var ACK_REQUEST_KEYS=["acknowledgement","context","managedCsi","pod","protocolVersion","reference","retirementId","storage","workerAck"];function stableId(value){return assertManagedSessionStableId(value,"id")}__name(stableId,"stableId");function invocationDigest(value){return typeof value==="string"&&/^(?:sha256:)?[0-9a-f]{64}$/.test(value)}__name(invocationDigest,"invocationDigest");function createManagedCsiAttestationRequest(boot){return Object.freeze({protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,provisionRequestId:boot.context.provisionRequestId,physicalKey:boot.storage.physicalKey,registrationRevision:boot.storage.registrationRevision,reservationId:boot.storage.reservationId,reservationRevision:boot.storage.reservationRevision})}__name(createManagedCsiAttestationRequest,"createManagedCsiAttestationRequest");var ManagedCsiDrainRequestError=class extends Error{constructor(status){super("Managed CSI drain request is invalid.");this.status=status}static{__name(this,"ManagedCsiDrainRequestError")}};function parseManagedCsiDrainRequest(value,boot,pod){let request;try{request=closed(value,["context","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);if(request["operation"]!=="seal"&&request["operation"]!=="status"||typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error}catch{throw new ManagedCsiDrainRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL)throw new Error;for(const[key,expected]of[["context",createManagedContextAttestationResponse(boot.context)],["storage",boot.storage],["pod",pod]]){const actual=closed(request[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>actual[name]===field))throw new Error}}catch{throw new ManagedCsiDrainRequestError(409)}return{operation:request["operation"],retirementId:request["retirementId"]}}__name(parseManagedCsiDrainRequest,"parseManagedCsiDrainRequest");function validateManagedCsiAttestationRequest(value,boot){const expected=createManagedCsiAttestationRequest(boot);try{const actual=closed(value,Object.keys(expected).sort());if(!Object.entries(expected).every(([key,field])=>actual[key]===field))throw new Error}catch{throw new Error("Managed CSI attestation request is invalid.")}}__name(validateManagedCsiAttestationRequest,"validateManagedCsiAttestationRequest");function validateManagedCsiPodIdentity(value,namespace){const pod=closed(value,["namespace","nodeName","uid"]);if(typeof pod["uid"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(pod["uid"])||pod["namespace"]!==namespace||typeof pod["nodeName"]!=="string"||pod["nodeName"].length>253||!pod["nodeName"].split(".").every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)))throw new Error("Managed CSI Pod identity is unavailable.")}__name(validateManagedCsiPodIdentity,"validateManagedCsiPodIdentity");function validateManagedCsiAttestationResponse(value,boot,expectedPod){try{validateManagedCsiPodIdentity(expectedPod,boot.storage.namespace);const response=closed(value,["context","managedCsi","mount","pod","protocolVersion","storage"]);const context=createManagedContextAttestationResponse(boot.context);for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",expectedPod]]){const fields2=closed(response[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>fields2[name]===field))throw new Error}const mount=closed(response["mount"],["device","diskSerial","mountId","rootDevice","rootInode","source"]);if(response["protocolVersion"]!==1||response["managedCsi"]!==MANAGED_CSI_PROTOCOL||!unsignedDecimal(mount["mountId"],0xffffffffn,true)||typeof mount["source"]!=="string"||mount["source"].length>128||!/^\/dev\/nvme(?:0|[1-9][0-9]*)n[1-9][0-9]*$/.test(mount["source"])||mount["diskSerial"]!==boot.storage.diskSerial||!unsignedDecimal(mount["rootDevice"],0xffffffffffffffffn,false)||!unsignedDecimal(mount["rootInode"],0xffffffffffffffffn,true)||linuxDeviceNumber(mount["device"])!==mount["rootDevice"])throw new Error}catch{throw new Error("Managed CSI attestation response is invalid.")}}__name(validateManagedCsiAttestationResponse,"validateManagedCsiAttestationResponse");function linuxDeviceNumber(value){if(typeof value!=="string")throw new Error;const parts=value.split(":");if(parts.length!==2||!parts.every(part=>unsignedDecimal(part,0xffffffffn,false)))throw new Error;const major=BigInt(parts[0]);const minor=BigInt(parts[1]);return((major&0xfffn)<<8n|(major&0xfffff000n)<<32n|minor&0xffn|(minor&0xffffff00n)<<12n).toString()}__name(linuxDeviceNumber,"linuxDeviceNumber");function unsignedDecimal(value,maximum,positive){return typeof value==="string"&&/^(?:0|[1-9][0-9]{0,19})$/.test(value)&&(!positive||value!=="0")&&BigInt(value)<=maximum}__name(unsignedDecimal,"unsignedDecimal");var BOOT_KEYS=["context","managedCsi","storage","type","version"];var STORAGE_KEYS=["backendDomain","clusterDomain","diskSerial","driver","namespace","physicalKey","pvUid","pvcUid","registrationRevision","reservationId","reservationRevision","volumeHandle"];var INVALID="Managed CSI boot document is invalid.";function parseManagedCsiBoot(value){try{const boot=closed(value,BOOT_KEYS);const storage=closed(boot["storage"],STORAGE_KEYS);const context=parseManagedContextBoot(boot["context"]);if(boot["type"]!=="boot"||boot["version"]!==3||boot["managedCsi"]!==MANAGED_CSI_PROTOCOL){throw new Error(INVALID)}for(const[key,maximum]of[["clusterDomain",256],["backendDomain",256],["volumeHandle",512],["pvcUid",128],["pvUid",128]]){const text3=storage[key];if(typeof text3!=="string"||text3===""||/^[ \u1680\u2000-\u2006\u2008-\u200a\u2028\u2029\u205f\u3000]+$/u.test(text3)||text3.length>maximum||Array.from(text3).some(char=>char.charCodeAt(0)<=31||char.charCodeAt(0)>=127&&char.charCodeAt(0)<=159)||/[\ud800-\udfff]/u.test(text3))throw new Error(INVALID)}if(typeof storage["namespace"]!=="string"||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(storage["namespace"])||storage["driver"]!=="diskplugin.csi.alibabacloud.com"||typeof storage["diskSerial"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(storage["diskSerial"])||!isCanonicalDecimalText(storage["registrationRevision"])||!isCanonicalDecimalText(storage["reservationRevision"])||typeof storage["reservationId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(storage["reservationId"])||typeof storage["physicalKey"]!=="string"||!/^[0-9a-f]{64}$/.test(storage["physicalKey"])||!context.mountRoot.startsWith("/")||context.mountRoot.length>2048||context.mountRoot.includes("\\")||!context.mountRoot.slice(1).split("/").every(part=>part!==""&&part!=="."&&part!=="..")||physicalKey(storage["backendDomain"],storage["driver"],storage["volumeHandle"])!==storage["physicalKey"])throw new Error(INVALID);return Object.freeze({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context,storage:Object.freeze({...storage})})}catch{throw new Error(INVALID)}}__name(parseManagedCsiBoot,"parseManagedCsiBoot");function physicalKey(backend,driver,handle){const hash=createHash("sha256");for(const field of["qwen-csi-physical/1",backend,driver,handle]){const bytes=Buffer.from(field,"utf8");const size=Buffer.alloc(4);size.writeUInt32BE(bytes.byteLength);hash.update(size).update(bytes)}return hash.digest("hex")}__name(physicalKey,"physicalKey");function closed(value,keys2){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(INVALID);const fields2=Object.keys(value).sort();if(fields2.length!==keys2.length||!fields2.every((field,index)=>field===keys2[index]))throw new Error(INVALID);return value}__name(closed,"closed");init_esbuild_shims();import{isDeepStrictEqual}from"node:util";var MANAGED_CSI_FILE_PROTOCOL="managed-csi/2";var MANAGED_CSI_FILE_PREFIX="/internal/managed-runtime/csi/v2";var CSI_FILE_FINALIZATION_FORMAT="qwen-csi-file-finalize/1";var MANAGED_CSI_FILE_ROUTES=Object.freeze(["context-attest","context","attest","drain"].map(name=>Object.freeze({method:"POST",path:`${MANAGED_CSI_FILE_PREFIX}/${name}`})));function parseManagedCsiFileJson(bytes,limit){if(bytes.byteLength>limit)throw new Error("Invalid CSI file JSON.");const text3=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text3,limit);return JSON.parse(text3,(_key,value,context)=>{if(typeof value==="number"&&(!Number.isSafeInteger(value)||context?.source===void 0||!/^(?:0|[1-9][0-9]*)$/.test(context.source)))throw new Error("Invalid CSI file JSON.");return value})}__name(parseManagedCsiFileJson,"parseManagedCsiFileJson");function parseManagedCsiFileBoot(value){try{const authorityBoot=value!==null&&typeof value==="object"&&"version"in value&&(value.version===5||value.version===6);const finalizationBoot=authorityBoot&&value.version===6;const boot=closed2(value,[...authorityBoot?["authority"]:[],"context",...finalizationBoot?["finalization"]:[],"identity","managedCsi","storage","type","version"]);const identity=closed2(boot["identity"],["capabilityDigest","profile","sessionId"]);const data=parseManagedCsiBoot({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot["context"],storage:boot["storage"]});if(boot["type"]!=="boot"||boot["version"]!==4&&!authorityBoot||finalizationBoot&&boot["finalization"]!==CSI_FILE_FINALIZATION_FORMAT||boot["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||!matchesCsiFilesProfile(identity["profile"],identity["capabilityDigest"])||typeof identity["sessionId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(identity["sessionId"])||data.context.isolationClass!=="session"||data.context.capabilityDigest!==identity["capabilityDigest"])throw new Error;const fields2={type:"boot",managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:Object.freeze(identity),context:data.context,storage:data.storage};return finalizationBoot?Object.freeze({...fields2,version:6,authority:readManagedCsiNativeAuthority(boot["authority"]),finalization:CSI_FILE_FINALIZATION_FORMAT}):authorityBoot?Object.freeze({...fields2,version:5,authority:readManagedCsiNativeAuthority(boot["authority"])}):Object.freeze({...fields2,version:4})}catch{throw new Error("Managed CSI file boot document is invalid.")}}__name(parseManagedCsiFileBoot,"parseManagedCsiFileBoot");function readManagedCsiNativeAuthority(value){const authority=closed2(value,["origin","protocolVersion"]);const origin=authority["origin"];if(authority["protocolVersion"]!==1||typeof origin!=="string"||origin.length>2048)throw new Error("Managed CSI authority origin is invalid.");const url=resolveManagedRuntimeBrokerBaseUrl(origin);const hostname=url.hostname;if(url.origin!==origin||/(^|\.)xn--/.test(hostname)||!hostname.startsWith("[")&&!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/.test(hostname)||!hostname.startsWith("[")&&hostname.includes(".")&&!/^\d+\.\d+\.\d+\.\d+$/.test(hostname)&&!/^[a-z]/.test(hostname.split(".").at(-1)??"")||url.port!==""&&Number(url.port)===0)throw new Error("Managed CSI authority origin is not canonical.");return Object.freeze({protocolVersion:1,origin})}__name(readManagedCsiNativeAuthority,"readManagedCsiNativeAuthority");function dataBoot(boot){return{type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot.context,storage:boot.storage}}__name(dataBoot,"dataBoot");function createManagedCsiFileReady(boot,port){return Object.freeze({type:"ready",version:boot.version,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context:createManagedContextReady(boot.context,port)})}__name(createManagedCsiFileReady,"createManagedCsiFileReady");function wrapManagedCsiFileContext(boot,context){return Object.freeze({protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context})}__name(wrapManagedCsiFileContext,"wrapManagedCsiFileContext");function readManagedCsiFileContext(value,boot){const body=closed2(value,["context","identity","managedCsi","protocolVersion"]);checkIdentity(body,boot);return body["context"]}__name(readManagedCsiFileContext,"readManagedCsiFileContext");function createManagedCsiFileAttestationRequest(boot){return{...createManagedCsiAttestationRequest(dataBoot(boot)),protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity}}__name(createManagedCsiFileAttestationRequest,"createManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationRequest(value,boot){if(!isDeepStrictEqual(value,createManagedCsiFileAttestationRequest(boot)))throw new Error("CSI file identity conflicts.")}__name(validateManagedCsiFileAttestationRequest,"validateManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationResponse(value,boot,pod){const body=closed2(value,["context","identity","managedCsi","mount","pod","protocolVersion","storage"]);checkIdentity(body,boot);const{identity:_identity,...data}=body;validateManagedCsiAttestationResponse({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(validateManagedCsiFileAttestationResponse,"validateManagedCsiFileAttestationResponse");function readManagedCsiFileDrain(value,boot,pod){const body=closed2(value,["context","identity","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);checkIdentity(body,boot);const{identity:_identity,...data}=body;return parseManagedCsiDrainRequest({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(readManagedCsiFileDrain,"readManagedCsiFileDrain");function checkIdentity(body,boot){if(body["protocolVersion"]!==2||body["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||!isDeepStrictEqual(body["identity"],boot.identity))throw new Error("CSI file identity conflicts.")}__name(checkIdentity,"checkIdentity");function closed2(value,keys2){if(!value||typeof value!=="object"||Array.isArray(value)||!isDeepStrictEqual(Object.keys(value).sort(),keys2))throw new Error;return{...value}}__name(closed2,"closed");init_esbuild_shims();var ManagedMcpRecipeError=class extends Error{static{__name(this,"ManagedMcpRecipeError")}constructor(){super("Invalid Managed MCP recipe.");this.name="ManagedMcpRecipeError"}};var fields=new Set(["command","args","env","timeout","url","httpUrl","headers","type"]);function text(value){return typeof value==="string"&&!value.includes("\0")}__name(text,"text");function strings(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&Object.entries(value).every(([key,item])=>text(key)&&key.length>0&&text(item))}__name(strings,"strings");function parseManagedMcpRecipe(value,options={}){const invalid2=__name(()=>{throw new ManagedMcpRecipeError},"invalid");if(!value||typeof value!=="object"||Array.isArray(value))invalid2();const recipe=value;if(Object.keys(recipe).some(key=>!fields.has(key))||recipe["timeout"]!==void 0&&(!Number.isSafeInteger(recipe["timeout"])||Number(recipe["timeout"])<1||Number(recipe["timeout"])>6e5)||recipe["type"]!==void 0&&(typeof recipe["type"]!=="string"||!["stdio","sse","http"].includes(recipe["type"])))invalid2();if(recipe["command"]!==void 0){if(!text(recipe["command"])||!recipe["command"].trim()||recipe["url"]!==void 0||recipe["httpUrl"]!==void 0||recipe["headers"]!==void 0||recipe["type"]!==void 0&&recipe["type"]!=="stdio"||recipe["args"]!==void 0&&(!Array.isArray(recipe["args"])||!recipe["args"].every(text))||recipe["env"]!==void 0&&!strings(recipe["env"]))invalid2()}else{const url=recipe["httpUrl"]??recipe["url"];if(!text(url)||!url.trim()||recipe["url"]!==void 0&&recipe["httpUrl"]!==void 0||recipe["args"]!==void 0||recipe["env"]!==void 0||recipe["type"]==="stdio"||recipe["headers"]!==void 0&&!strings(recipe["headers"]))invalid2();if(!(options.allowPlaceholders&&/\$\{[^}]+\}/u.test(url))){try{const parsed=new URL(url);if(!["http:","https:"].includes(parsed.protocol)||parsed.username||parsed.password||parsed.hash)invalid2()}catch{invalid2()}}if(recipe["headers"]!==void 0&&Object.entries(recipe["headers"]).some(([key,item])=>!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(key)||/[\r\n]/u.test(item)))invalid2()}return structuredClone(recipe)}__name(parseManagedMcpRecipe,"parseManagedMcpRecipe");init_esbuild_shims();var import_toml=__toESM(require_toml(),1);import{createHash as createHash2}from"node:crypto";import*as fs from"node:fs/promises";import{createReadStream}from"node:fs";import*as path from"node:path";import*as os from"node:os";init_esbuild_shims();var ManagedSkillCompatibilityError=class extends Error{static{__name(this,"ManagedSkillCompatibilityError")}};function parseManagedSkillContent(content,file){const metadata=parseMarkdownCommand(content).frontmatter??{};for(const key of["allowedTools","allowed-tools","hooks","paths","arguments","args-file"]){if(metadata[key]!==void 0)throw new ManagedSkillCompatibilityError(`Managed Skill field ${key} is unsupported.`)}if(metadata["model"]!==void 0&&metadata["model"]!=="inherit")throw new ManagedSkillCompatibilityError("Managed Skill model override is unsupported.");return parseSkillContent(content,file)}__name(parseManagedSkillContent,"parseManagedSkillContent");var MANAGED_PACKAGE_COMPILER_VERSION=1;var MANAGED_PACKAGE_MAX_ARCHIVE_BYTES=100*1024*1024;var ManagedPackageCompatibilityError=class extends Error{constructor(reasons){super(`Managed extension package is incompatible: ${reasons.join(", ")}`);this.reasons=reasons;this.name="ManagedPackageCompatibilityError"}static{__name(this,"ManagedPackageCompatibilityError")}};function object(value,field){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedPackageCompatibilityError([`${field}: invalid object`]);return value}__name(object,"object");function text2(value,field,maxBytes=512*1024){if(typeof value!=="string"||!value.trim()||Buffer.byteLength(value)>maxBytes)throw new ManagedPackageCompatibilityError([`${field}: invalid text`]);return value}__name(text2,"text");function managedPackageRelativePath(value){const normalized=value.replace(/^\.\//,"");if(!normalized||normalized.includes("\\")||normalized.includes(":")||normalized.includes("\0")||normalized.startsWith("/")||normalized.split("/").some(part=>!part||part==="."||part===".."))throw new ManagedPackageCompatibilityError(["package resource path escapes its root"]);return normalized}__name(managedPackageRelativePath,"managedPackageRelativePath");function frontmatter(content){const parsed=parseMarkdownCommand(content);return{metadata:parsed.frontmatter??{},body:parsed.prompt}}__name(frontmatter,"frontmatter");function hasValue(value){return value!==void 0&&value!==null&&value!==false&&value!==""&&(!Array.isArray(value)||value.length>0)&&(typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>0)}__name(hasValue,"hasValue");function rejectFields(value,fields2,source){const reasons=fields2.filter(key=>hasValue(value[key])).map(key=>`${source}.${key}: unsupported`);if(reasons.length)throw new ManagedPackageCompatibilityError(reasons)}__name(rejectFields,"rejectFields");var PRIVATE_FILES=new Set([".git",".env",".qwen-extension-settings.json",".qwen-extension-git-credentials.json",".qwen-extension-install.json"]);async function listManagedPackageFiles(root,excludePrivate=false){const files=[];let total=0;const visit=__name(async relative=>{const entries=await fs.readdir(path.join(root,relative),{withFileTypes:true});for(const entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(excludePrivate&&(PRIVATE_FILES.has(entry.name)||entry.name.startsWith(".env.")))continue;const name=relative?`${relative}/${entry.name}`:entry.name;managedPackageRelativePath(name);if(entry.isSymbolicLink()||!entry.isDirectory()&&!entry.isFile())throw new ManagedPackageCompatibilityError([`${name}: unsupported resource type`]);if(entry.isDirectory())await visit(name);else{total+=(await fs.lstat(path.join(root,name))).size;files.push(name);if(files.length>MAX_ARCHIVE_ENTRIES||total>MAX_ARCHIVE_EXPANDED_BYTES)throw new ManagedPackageCompatibilityError(["package resource limit exceeded"])}}},"visit");await visit("");return files}__name(listManagedPackageFiles,"listManagedPackageFiles");async function readText(root,relative){const file=managedPackageRelativePath(relative);const info=await fs.lstat(path.join(root,file));if(!info.isFile()||info.isSymbolicLink()||info.size>1024*1024)throw new ManagedPackageCompatibilityError([`${file}: invalid text resource`]);return new TextDecoder("utf-8",{fatal:true}).decode(await fs.readFile(path.join(root,file)))}__name(readText,"readText");async function readObject(root,relative){return object(JSON.parse(await readText(root,relative)),relative)}__name(readObject,"readObject");async function rawConfig(root,files){if(files.includes("qwen-extension.json"))return readObject(root,"qwen-extension.json");if(files.includes("gemini-extension.json")){const raw=await readObject(root,"gemini-extension.json");rejectFields(raw,["lspServers","channels","workflows","executor","outputStyles"],"gemini-extension.json");return{...raw,...convertGeminiToQwenConfig(root)}}const pluginFile=files.includes(".claude-plugin/plugin.json")?".claude-plugin/plugin.json":files.includes(".qoder-plugin/plugin.json")?".qoder-plugin/plugin.json":void 0;if(pluginFile){const raw=await readObject(root,pluginFile);rejectFields(raw,["lspServers","channels","workflows","outputStyles","executor"],pluginFile);const config={...convertClaudeToQwenConfig(raw),name:raw["name"],version:raw["version"]??"1.0.0"};for(const key of["commands","skills","agents","contextFileName","settings","mcpServers","hooks"])if(raw[key]!==void 0)config[key]=raw[key];return config}if(files.includes("plugin.json")){const raw=await readObject(root,"plugin.json");if(raw["$schema"]!=="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json")throw new ManagedPackageCompatibilityError(["plugin.json: unsupported schema"]);rejectFields(raw,["lspServers","channels","workflows","executor","outputStyles"],"plugin.json");return{...raw,name:raw["name"],version:raw["version"]??"1.0.0"}}throw new ManagedPackageCompatibilityError(["extension manifest missing"])}__name(rawConfig,"rawConfig");function resourceRoots(config,key,fallback){const value=config[key]??fallback;const roots=typeof value==="string"?[value]:value;if(!Array.isArray(roots)||roots.some(item=>typeof item!=="string"))throw new ManagedPackageCompatibilityError([`${key}: invalid resource roots`]);return roots.map(managedPackageRelativePath)}__name(resourceRoots,"resourceRoots");function selectedFiles(files,roots){return files.filter(file=>roots.some(root=>file===root||file.startsWith(`${root}/`)))}__name(selectedFiles,"selectedFiles");function strings2(value,field){if(value===void 0)return void 0;const entries=typeof value==="string"?value.split(",").map(item=>item.trim()).filter(Boolean):value;if(!Array.isArray(entries)||entries.some(entry=>typeof entry!=="string"||!entry))throw new ManagedPackageCompatibilityError([`${field}: invalid list`]);return entries.map(entry=>resolveBuiltinToolName(entry)??entry)}__name(strings2,"strings");async function compileManagedExtensionPackage(root,options){const files=await listManagedPackageFiles(root);if(files.some(file=>file.split("/").some(part=>PRIVATE_FILES.has(part)||part.startsWith(".env."))))throw new ManagedPackageCompatibilityError(["package contains private settings or credentials"]);const config=await rawConfig(root,files);let packageTarget=options.target;if(config["managedTarget"]!==void 0){const target=object(config["managedTarget"],"managedTarget");if(target["platform"]!==options.target.platform||target["arch"]!=="any"&&target["arch"]!==options.target.arch){throw new ManagedPackageCompatibilityError(["package target does not match this Runtime"])}packageTarget={platform:options.target.platform,arch:target["arch"]}}rejectFields(config,["lspServers","channels","workflows","executor","outputStyles"],"manifest");if(files.some(file=>/^(?:workflows|channels|lsp)\//.test(file)))throw new ManagedPackageCompatibilityError(["package contains unsupported executable components"]);const name=text2(config["name"],"name",128);if(!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name))throw new ManagedPackageCompatibilityError(["name: invalid identity"]);const contributions={skills:[],commands:[],agents:[],context:[],mcpServers:{},hooks:{},settings:[]};for(const file of selectedFiles(files,resourceRoots(config,"skills","skills")).filter(file2=>file2.endsWith("/SKILL.md"))){const content=await readText(root,file);let skill;try{skill=parseManagedSkillContent(content,file)}catch(error){if(error instanceof ManagedSkillCompatibilityError)throw new ManagedPackageCompatibilityError([`${file}: ${error.message}`]);throw error}contributions.skills.push({name:qualifySkillName(name,skill.name),description:skill.description,body:skill.body,assetDirectory:path.posix.dirname(file),model_invocable:skill.disableModelInvocation!==true,user_invocable:skill.userInvocable!==false})}const commandRoots=resourceRoots(config,"commands","commands");for(const file of selectedFiles(files,commandRoots).filter(file2=>/\.(?:md|toml)$/.test(file2))){const content=await readText(root,file);const parsed=file.endsWith(".toml")?{metadata:{},body:"",definition:object((0,import_toml.parse)(content),file)}:{...frontmatter(content),definition:void 0};if(!parsed.definition)MarkdownCommandDefSchema.parse({frontmatter:parsed.metadata,prompt:parsed.body});const metadata=parsed.definition??parsed.metadata;rejectFields(metadata,["allowed-tools","allowedTools","hooks","model","context","agent"],file);const relative=commandRoots.find(entry=>file.startsWith(`${entry}/`));const authored=(relative?file.slice(relative.length+1):path.posix.basename(file)).replace(/\.(?:md|toml)$/,"").split("/").map(part=>part.replaceAll(":","_")).join(":");contributions.commands.push({name:`${name}:${authored}`,description:typeof metadata["description"]==="string"?metadata["description"]:authored,prompt:text2(parsed.definition?.["prompt"]??parsed.body,file),...typeof metadata["argument-hint"]==="string"?{argumentHint:metadata["argument-hint"]}:{},modelInvocable:metadata["disable-model-invocation"]!==true&&metadata["disable-model-invocation"]!=="true"})}for(const file of selectedFiles(files,resourceRoots(config,"agents","agents")).filter(file2=>file2.endsWith(".md"))){const{metadata,body}=frontmatter(await readText(root,file));rejectFields(metadata,["mcpServers","mcp_servers","hooks","executor","container","isolation","skills","permissionMode","approvalMode","background","memory"],file);const agent={name:`${name}:${text2(metadata["name"]??path.posix.basename(file,".md"),file,128)}`,description:text2(metadata["description"],`${file}.description`,4096),systemPrompt:text2(body,file),...metadata["tools"]!==void 0?{tools:strings2(metadata["tools"],file)}:{},...metadata["disallowedTools"]!==void 0?{disallowedTools:strings2(metadata["disallowedTools"],file)}:{},...metadata["model"]!==void 0?{model:text2(metadata["model"],`${file}.model`,512)}:{}};contributions.agents.push(agent)}const contextRoots=config["contextFileName"]===void 0?files.includes("QWEN.md")?["QWEN.md"]:files.includes("system-prompt.md")?["system-prompt.md"]:[]:resourceRoots(config,"contextFileName","QWEN.md");for(const file of contextRoots)contributions.context.push({path:file,body:await readText(root,file)});let mcp=config["mcpServers"];if(typeof mcp==="string")mcp=await readObject(root,managedPackageRelativePath(mcp));if(mcp===void 0&&files.includes(".mcp.json")){const loaded=await readObject(root,".mcp.json");mcp=loaded["mcpServers"]??loaded}if(mcp===void 0&&files.includes("mcp.json")){const loaded=await readObject(root,"mcp.json");mcp=loaded["mcpServers"]??loaded["servers"]??loaded}if(mcp!==void 0)contributions.mcpServers=Object.fromEntries(Object.entries(object(mcp,"mcpServers")).map(([name2,recipe])=>[name2,parseManagedMcpRecipe(recipe,{allowPlaceholders:true})]));let hooks=config["hooks"];if(typeof hooks==="string")hooks=await readObject(root,managedPackageRelativePath(hooks));if(hooks===void 0&&files.includes("hooks/hooks.json"))hooks=await readObject(root,"hooks/hooks.json");if(hooks!==void 0){const loaded=object(hooks,"hooks");contributions.hooks=object(loaded["hooks"]??loaded,"hooks")}if(config["settings"]!==void 0){if(!Array.isArray(config["settings"]))throw new ManagedPackageCompatibilityError(["settings: invalid list"]);contributions.settings=config["settings"].map(entry=>{const setting=object(entry,"setting");const envVar=text2(setting["envVar"],"setting.envVar",128);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(envVar)||envVar.startsWith("QWEN_MANAGED_")||["QWEN_EXTENSION_ROOT","CLAUDE_PLUGIN_ROOT","extensionPath","workspacePath"].includes(envVar))throw new ManagedPackageCompatibilityError(["setting.envVar: reserved or invalid"]);return{name:text2(setting["name"],"setting.name",512),envVar,sensitive:setting["sensitive"]===true}})}if(options.resolveRecipes!==false){const environment={...options.environment,extensionPath:root,CLAUDE_PLUGIN_ROOT:root,QWEN_EXTENSION_ROOT:root,workspacePath:options.workspaceDirectory??"",workspaceFolder:options.workspaceDirectory??"",pathSeparator:"/","/":"/"};const hydrate=__name(value=>{if(typeof value==="string")return value.replace(/\$\{([^}]+)\}/g,(_,variable)=>{if(!Object.hasOwn(environment,variable))throw new ManagedPackageCompatibilityError([`setting ${variable}: required`]);return environment[variable]});if(Array.isArray(value))return value.map(hydrate);if(value&&typeof value==="object")return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,hydrate(item)]));return value},"hydrate");contributions.mcpServers=Object.fromEntries(Object.entries(hydrate(contributions.mcpServers)).map(([name2,recipe])=>[name2,parseManagedMcpRecipe(recipe)]));contributions.hooks=hydrate(contributions.hooks)}for(const entries of[contributions.skills,contributions.commands,contributions.agents]){if(new Set(entries.map(entry=>entry.name)).size!==entries.length)throw new ManagedPackageCompatibilityError(["duplicate component identity"])}if(contributions.skills.length>256||Object.keys(contributions.mcpServers).length>16||contributions.settings.length>128)throw new ManagedPackageCompatibilityError(["component catalog limit exceeded"]);const components=[];if(contributions.skills.length)components.push("skills");if(contributions.commands.length)components.push("commands");if(contributions.agents.length)components.push("agents");if(contributions.context.length)components.push("context");if(Object.keys(contributions.mcpServers).length)components.push("mcp");if(Object.keys(contributions.hooks).length)components.push("hooks");if(contributions.settings.length)components.push("settings");return{manifest:{schemaVersion:1,compilerVersion:MANAGED_PACKAGE_COMPILER_VERSION,name,version:text2(config["version"]??"1.0.0","version",128),target:packageTarget,components,...config["managedSource"]?{sourceType:text2(object(config["managedSource"],"managedSource")["type"],"sourceType",64),sourceRevision:text2(object(config["managedSource"],"managedSource")["revision"],"sourceRevision",256)}:{}},contributions}}__name(compileManagedExtensionPackage,"compileManagedExtensionPackage");async function prepareManagedExtensionPackage(source,options){if(["local","link","snapshot"].includes(source.type)){const isDirectory=(await fs.stat(source.source)).isDirectory();const installed=isDirectory&&await fs.lstat(path.join(source.source,".qwen-extension-install.json")).catch(error=>{if(error.code!=="ENOENT")throw error;return void 0});if(installed)throw new ManagedPackageCompatibilityError(["installed package requires its original source"])}const temporary=await fs.mkdtemp(path.join(os.tmpdir(),"qwen-managed-package-"));const root=path.join(temporary,"package");await fs.mkdir(root);let sourceRevision=source.ref??"";try{if(source.type==="git")sourceRevision=await cloneFromGit(source,root,options.signal);else if(source.type==="npm"){const result=await downloadFromNpmRegistry({...source},root,options.signal,{enforceResourceLimits:true});sourceRevision=result.version}else if(source.type==="github-release"){const result=await downloadFromGitHubRelease(source,root,options.signal,options.target,{enforceResourceLimits:true});sourceRevision=result.tagName}else if(source.type==="archive-url")await downloadFromArchiveUrl(source,root,options.signal,{enforceResourceLimits:true});else if(/\.(?:zip|tar\.gz)$/i.test(source.source))await extractArchiveFile(source.source,root,options.signal,{enforceResourceLimits:true});else{const files2=await listManagedPackageFiles(source.source,true);for(const file of files2){const destination=path.join(root,file);await fs.mkdir(path.dirname(destination),{recursive:true});await fs.copyFile(path.join(source.source,file),destination)}}options.signal?.throwIfAborted();const scrub=__name(async directory=>{for(const entry of await fs.readdir(directory,{withFileTypes:true})){const file=path.join(directory,entry.name);if(PRIVATE_FILES.has(entry.name)||entry.name.startsWith(".env.")){await fs.rm(file,{recursive:true,force:true})}else if(entry.isDirectory())await scrub(file)}},"scrub");await scrub(root);let files=await listManagedPackageFiles(root);const config=await rawConfig(root,files);config["managedTarget"]=options.target;config["managedSource"]={type:source.type==="local"?/\.(?:zip|tar\.gz)$/i.test(source.source)?"archive":"directory":source.type,revision:sourceRevision||text2(config["version"]??"snapshot","version",128)};await fs.writeFile(path.join(root,"qwen-extension.json"),JSON.stringify(config));files=await listManagedPackageFiles(root);const compiled=await compileManagedExtensionPackage(root,{target:options.target,resolveRecipes:false});await fs.mkdir(options.destination,{recursive:true});const archivePath=path.join(options.destination,"package.tar.gz");for(const file of files){const absolute=path.join(root,file);const mode=(await fs.stat(absolute)).mode;await fs.chmod(absolute,mode&73?493:420)}await Qn({cwd:root,file:archivePath,gzip:true,portable:true,noMtime:true},files.sort());if((await fs.stat(archivePath)).size>MANAGED_PACKAGE_MAX_ARCHIVE_BYTES)throw new ManagedPackageCompatibilityError(["compressed package limit exceeded"]);const hash=createHash2("sha256");for await(const chunk of createReadStream(archivePath))hash.update(chunk);const packageDigest=hash.digest("hex");return{archivePath,packageDigest,manifest:compiled.manifest,sourceRevision:sourceRevision||packageDigest}}finally{await fs.rm(temporary,{recursive:true,force:true})}}__name(prepareManagedExtensionPackage,"prepareManagedExtensionPackage");init_esbuild_shims();init_esbuild_shims();var MAX_MANAGED_MEDIA_RESPONSE_BYTES=DAEMON_ACP_NDJSON_LIMITS.maxFrameBytes-64*1024;function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)?value:void 0}__name(record,"record");function isBase64(data){if(data.length%4!==0)return false;const padding=data.endsWith("==")?2:data.endsWith("=")?1:0;const body=data.slice(0,data.length-padding);if(/[^A-Za-z0-9+/]/.test(body))return false;if(padding===0)return true;const last="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(body.at(-1));return padding===2?(last&15)===0:(last&3)===0}__name(isBase64,"isBase64");function managedToolResponseMediaBytes(result,operation){const json=JSON.stringify(result);if(json===void 0||Buffer.byteLength(json)>MAX_MANAGED_MEDIA_RESPONSE_BYTES){throw new Error("Managed Runtime media response exceeded its size limit.")}const wire=JSON.parse(json);if(!hasBoundedJsonStructure({jsonrpc:"2.0",id:"0",result:wire})){throw new Error("Managed Runtime media response exceeded ACP structure limits.")}const status=record(wire);if(operation!=="execute"&&status?.["state"]!=="settled")return 0;const execution2=operation==="execute"?status:record(status?.["result"]);if(!["not_started","success","error","cancelled"].includes(String(execution2?.["executionStatus"])))return 0;const content=record(execution2?.["result"])?.["llmContent"];const parts=Array.isArray(content)?content:[content];let mediaBytes=0;for(const part of parts){const object5=record(part);if(!object5||!Object.hasOwn(object5,"inlineData"))continue;const inline=record(object5["inlineData"]);if(!inline||typeof inline["data"]!=="string"||typeof inline["mimeType"]!=="string"||!/^(?:(?:image|audio|video)\/[a-z0-9.+-]+|application\/pdf)$/i.test(inline["mimeType"])||!isBase64(inline["data"])){throw new Error("Managed Runtime returned invalid inline media.")}mediaBytes+=inline["data"].length}return mediaBytes}__name(managedToolResponseMediaBytes,"managedToolResponseMediaBytes");var MANAGED_RUNTIME_PROVIDER_PROTOCOL="managed-runtime-provider/1";var MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES=768*1024;var MAX_PROVIDER_MEDIA_RESULT_BYTES=896*1024;var MANAGED_RUNTIME_PROVIDER_ROUTE=Object.freeze({key:"provider-control",method:"POST",path:"/internal/managed-runtime/provider/v1/control",protocolVersion:1,requestBodyLimitBytes:8*1024*1024,responseBodyLimitBytes:8*1024*1024,cacheControl:"no-store"});var MANAGED_WORKSPACE_CONTEXT_FILES=["QWEN.md","AGENTS.md"];var MANAGED_WORKSPACE_CONTEXT_FILE_CHARS=64*1024;var ManagedRuntimeProviderProtocolError=class extends Error{constructor(message="Managed Runtime provider request is invalid.",status=400,code="managed_runtime_provider_invalid"){super(message);this.status=status;this.code=code;this.name="ManagedRuntimeProviderProtocolError"}static{__name(this,"ManagedRuntimeProviderProtocolError")}};function object2(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedRuntimeProviderProtocolError;return value}__name(object2,"object");function keys(value,required,optional=[]){if(required.some(key=>!Object.hasOwn(value,key))||Object.keys(value).some(key=>!required.includes(key)&&!optional.includes(key)))throw new ManagedRuntimeProviderProtocolError}__name(keys,"keys");function id(value){if(typeof value!=="string"||!value.length||value.length>512||value.includes("\0"))throw new ManagedRuntimeProviderProtocolError;return value}__name(id,"id");var SESSION_ID=/^[A-Za-z0-9._-]{1,512}$/;function envelopeSessionId(value){if(typeof value!=="string"||!SESSION_ID.test(value)||value==="."||value.includes(".."))throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity must be 1-512 ASCII letters, digits, '.', '_' or '-', without '..'.")}__name(envelopeSessionId,"envelopeSessionId");function sequence(value){if(!Number.isSafeInteger(value)||Number(value)<0)throw new ManagedRuntimeProviderProtocolError}__name(sequence,"sequence");function oneOf(value,values){return typeof value==="string"&&values.includes(value)}__name(oneOf,"oneOf");function checkSession(identity,session){if(identity.sessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity conflicts.",409,"managed_runtime_identity_conflict")}__name(checkSession,"checkSession");function managedRuntimeProviderLimit(kind){return["bind-history","checkpoint","history"].includes(kind)?8*1024*1024:1024*1024}__name(managedRuntimeProviderLimit,"managedRuntimeProviderLimit");function parseManagedRuntimeProviderOperation(value,session,boundedByCaller=false){const op=object2(value);const kind=id(op["kind"]);if(!boundedByCaller)managedToolDigest(value,managedRuntimeProviderLimit(kind));switch(kind){case"raw-file-history":{const action=op["action"];if(action==="bind"){keys(op,["kind","action","state"]);if(op["state"]!==null)parseHostedFileHistoryState(op["state"],session.harnessSessionId)}else if(action==="prepare"){keys(op,["kind","action","promptId","paths"]);parseManagedToolFileHistoryPromptId(op["promptId"]);if(!Array.isArray(op["paths"])||!op["paths"].length)throw new ManagedRuntimeProviderProtocolError;op["paths"].forEach(historyPath)}else if(action==="rewind"){keys(op,["kind","action","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"])}else if(action==="snapshot")keys(op,["kind","action"]);else throw new ManagedRuntimeProviderProtocolError;break}case"acquire":case"release":case"manifest":case"history":case"workspace-context":keys(op,["kind"]);break;case"begin-turn":case"prepare":{keys(op,kind==="prepare"?["kind","identity","toolName","input"]:["kind","identity"],kind==="prepare"?["modification","mediaContext"]:[]);checkSession(parseManagedToolCallIdentity(op["identity"]),session);if(kind==="prepare"){id(op["toolName"]);object2(op["input"]);if("modification"in op)checkSession(parseManagedToolContentModification(op["modification"]).source,session);if("mediaContext"in op)parseManagedToolMediaContext(op["mediaContext"])}break}case"confirmation":case"confirm":case"preflight":case"execute":case"status":case"cancel":keys(op,kind==="confirm"?["kind","reference","outcome"]:["kind","reference"],kind==="confirm"?["payload","phase"]:kind==="status"?["afterSequence"]:[]);checkSession(parseManagedToolInvocationReference(op["reference"]),session);if(kind==="confirm"){if(!Object.values(ToolConfirmationOutcome).includes(op["outcome"])||op["outcome"]==="restore_previous")throw new ManagedRuntimeProviderProtocolError;if("payload"in op)parseManagedToolConfirmationPayload(op["payload"]);if("phase"in op&&!oneOf(op["phase"],["permission","preflight"]))throw new ManagedRuntimeProviderProtocolError}if("afterSequence"in op)sequence(op["afterSequence"]);break;case"bind-history":{keys(op,["kind","binding"]);const binding=parseManagedToolFileHistoryBinding(op["binding"]);if(binding.ownerSessionId!==session.harnessSessionId||binding.ownerRuntimeSessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime file history owner conflicts.",409,"managed_runtime_identity_conflict");break}case"checkpoint":keys(op,["kind","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"]);break;default:throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider operation is unsupported.",501,"managed_runtime_provider_unsupported")}return structuredClone(value)}__name(parseManagedRuntimeProviderOperation,"parseManagedRuntimeProviderOperation");function parseManagedRuntimeProviderRequest(value){const request=object2(value);keys(request,["protocolVersion","providerProtocol","session","operation"]);if(request["protocolVersion"]!==1||request["providerProtocol"]!==MANAGED_RUNTIME_PROVIDER_PROTOCOL)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider protocol is incompatible.",409,"managed_runtime_provider_incompatible");const session=object2(request["session"]);keys(session,["harnessSessionId","runtimeSessionId","turnKind"]);envelopeSessionId(session["harnessSessionId"]);envelopeSessionId(session["runtimeSessionId"]);if(!oneOf(session["turnKind"],["bootstrap","continuation"]))throw new ManagedRuntimeProviderProtocolError;const parsedSession=session;const parsed={protocolVersion:1,providerProtocol:MANAGED_RUNTIME_PROVIDER_PROTOCOL,session:structuredClone(parsedSession),operation:parseManagedRuntimeProviderOperation(request["operation"],parsedSession,true)};managedToolDigest(value,managedRuntimeProviderLimit(parsed.operation.kind));return parsed}__name(parseManagedRuntimeProviderRequest,"parseManagedRuntimeProviderRequest");function parseManagedRuntimeProviderResult(operation,value,session){managedToolDigest(value,managedRuntimeProviderLimit(operation.kind));if(operation.kind==="begin-turn"||operation.kind==="confirm"){if(value!==null)throw new ManagedRuntimeProviderProtocolError;return null}if(operation.kind==="acquire"||operation.kind==="release"){if(value!==true)throw new ManagedRuntimeProviderProtocolError;return true}const result=object2(value);switch(operation.kind){case"raw-file-history":{if(operation.action!=="rewind")return parseHostedFileHistoryState(value,session.harnessSessionId);keys(result,["state","filesChanged","filesFailed","conflict"]);const state=parseHostedFileHistoryState(result["state"],session.harnessSessionId);if(!Array.isArray(result["filesChanged"])||!Array.isArray(result["filesFailed"])||typeof result["conflict"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;result["filesChanged"].forEach(historyPath);result["filesFailed"].forEach(historyPath);if(new Set(result["filesChanged"]).size!==result["filesChanged"].length||result["filesChanged"].some(file=>!Object.hasOwn(state.files,file))||!state.snapshots.some(snapshot=>snapshot.promptId===operation.promptId)||result["conflict"]&&result["filesChanged"].length!==0)throw new ManagedRuntimeProviderProtocolError("Invalid Hosted file history rewind outcome.");break}case"workspace-context":{keys(result,["files"]);if(!Array.isArray(result["files"]))throw new ManagedRuntimeProviderProtocolError;let next=0;for(const entry of result["files"]){const file=object2(entry);keys(file,["name","text"]);const index=MANAGED_WORKSPACE_CONTEXT_FILES.indexOf(file["name"]);if(index<next||typeof file["text"]!=="string"||file["text"].length>MANAGED_WORKSPACE_CONTEXT_FILE_CHARS)throw new ManagedRuntimeProviderProtocolError("Invalid Workspace context result.");next=index+1}return result["files"]}case"bind-history":case"checkpoint":case"history":{const state=parseManagedToolFileHistoryState(value);if(state.ownerSessionId!==session.harnessSessionId)throw new ManagedRuntimeProviderProtocolError("Managed file history owner changed.");return state}case"manifest":keys(result,["tools","capabilityDigest","policyRevision"]);id(result["policyRevision"]);if(!Array.isArray(result["tools"])||managedToolDigest(result["tools"],1024*1024)!==result["capabilityDigest"])throw new ManagedRuntimeProviderProtocolError("Managed tool manifest digest changed.");for(const tool of result["tools"]){const descriptor=object2(tool);id(descriptor["name"]);object2(descriptor["schema"])}break;case"prepare":{const reference=Object.fromEntries(["sessionId","promptId","callId","capabilityDigest","policyRevision","invocationId","argsDigest"].map(key=>[key,result[key]]));checkSession(parseManagedToolInvocationReference(reference),session);for(const[key,expected]of Object.entries(operation.identity))if(result[key]!==expected)throw new ManagedRuntimeProviderProtocolError;object2(result["params"]);if(managedToolDigest(result["params"])!==result["argsDigest"]||typeof result["description"]!=="string"||!Array.isArray(result["locations"])||!oneOf(result["defaultPermission"],["allow","ask","deny","default"])||typeof result["requiresUserInteraction"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;id(result["toolUseId"]);break}case"confirmation":{if(!oneOf(result["type"],["edit","exec","mcp","info"])||typeof result["title"]!=="string")throw new ManagedRuntimeProviderProtocolError;const required={edit:["fileName","filePath","fileDiff","newContent"],exec:["command","rootCommand"],mcp:["serverName","toolName","toolDisplayName"],info:["prompt"]}[result["type"]];if(required.some(key=>typeof result[key]!=="string")||result["type"]==="edit"&&result["originalContent"]!==null&&typeof result["originalContent"]!=="string")throw new ManagedRuntimeProviderProtocolError;break}case"preflight":if(typeof result["shouldProceed"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;break;case"execute":if(!oneOf(result["executionStatus"],["not_started","success","error","cancelled"]))throw new ManagedRuntimeProviderProtocolError;if(result["executionStatus"]==="success")object2(result["result"]);break;case"status":case"cancel":if(result["state"]==="unknown"){keys(result,["state"]);break}if(!oneOf(result["state"],["prepared","executing","cancel_requested","settled"])||typeof result["cancelRequested"]!=="boolean"||typeof result["progressGap"]!=="boolean"||!Array.isArray(result["progress"]))throw new ManagedRuntimeProviderProtocolError;sequence(result["lastSeq"]);sequence(result["firstAvailableSeq"]);if(result["state"]==="settled")parseManagedRuntimeProviderResult({kind:"execute",reference:operation.reference},result["result"],session);else if("result"in result)throw new ManagedRuntimeProviderProtocolError;break;default:throw new ManagedRuntimeProviderProtocolError}return structuredClone(value)}__name(parseManagedRuntimeProviderResult,"parseManagedRuntimeProviderResult");function providerFitNotice(omitted,budgetBytes){return`
3
+ import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-ZLUQTFP3.js";import{historyPath,parseHostedFileHistoryState,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryState}from"./chunk-FJFTKA4H.js";import{MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST,MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,createManagedContextAttestationResponse,createManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{computeManagedContextDigest,isCanonicalDecimalText}from"./chunk-YJ6APXNB.js";import{resolveManagedRuntimeBrokerBaseUrl}from"./chunk-6S5XOXJ2.js";import{authorizeManagedRuntime,handleManagedRuntimeJsonError,managedRuntimeJsonBody,managedRuntimeNoStore}from"./chunk-H5A2YPMV.js";import{DAEMON_ACP_NDJSON_LIMITS,hasBoundedJsonStructure}from"./chunk-3Y4UVTLL.js";import{MAX_ARCHIVE_ENTRIES,MAX_ARCHIVE_EXPANDED_BYTES,Qn,cloneFromGit,convertClaudeToQwenConfig,convertGeminiToQwenConfig,createCronGateRunner,downloadFromArchiveUrl,downloadFromGitHubRelease,downloadFromNpmRegistry,extractArchiveFile,gateCommandError,managedToolDigest,parseManagedToolCallIdentity,parseManagedToolConfirmationPayload,parseManagedToolContentModification,parseManagedToolInvocationReference,parseManagedToolMediaContext,require_toml}from"./chunk-ZUWLTGSR.js";import{MANAGED_SESSION_LIMITS,MANAGED_TOOL_RESULT_KINDS,MANAGED_TOOL_RESULT_LIMITS,MANAGED_TOOL_RESULT_PROTOCOL,assertManagedSessionDurableRef,assertManagedSessionStableId,impliedStatus,parseManagedSessionRecordJson,parseToolResultManifest,parseToolResultPage}from"./chunk-HMCTSPVJ.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import{parseSkillContent}from"./chunk-DNYXZVBT.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{BaseDeclarativeTool,BaseToolInvocation,ToolConfirmationOutcome}from"./chunk-D6CEQ2GY.js";import{resolveBuiltinToolName}from"./chunk-SBZFGYYS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var WORKSPACE_EXECUTION_PROFILE="managed-workspace-execution/1";var WORKSPACE_CONTEXT_CONFIG_REF="sha256:5fa15183dcfe582ce54c28bf25aff62801d19038a9ec649e9bfc67b06f2a389f";var WORKSPACE_CAPABILITY_DIGEST="sha256:7df3981fa14b397fe09f6ba84ed0c096c71902394da667bf47f3b315866e7f91";var MEASURED_WORKSPACE_CAPABILITY_DIGEST="sha256:b2ab403f278282eb8f2ca06c926be96bd3d85877714f64dc926eab535f544580";var MEASURED_WORKSPACE_EXECUTION_PROFILE="managed-workspace-execution/2";function isWorkspaceToolCapability(digest2){return digest2===WORKSPACE_CAPABILITY_DIGEST||digest2===MEASURED_WORKSPACE_CAPABILITY_DIGEST}__name(isWorkspaceToolCapability,"isWorkspaceToolCapability");var RESIDENT_WORKSPACE_PROFILE="resident-workspace-files/1";var RESIDENT_WORKSPACE_CAPABILITY_DIGEST="sha256:2cbf6f3825230848a65a546ec70714fbb2a53d1862a6caba73ae4cebf307b4ad";function resolveManagedShellPublisherMode(input){const resident=input.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST;const requiresActivation=isWorkspaceToolCapability(input.capabilityDigest)||resident||input.managedExtensions;const remotePublisher=!input.capturePublisher&&requiresActivation&&!resident;return{resident,requiresActivation,remotePublisher,publisher:input.capturePublisher||input.remotePublishers||remotePublisher,installRoute:remotePublisher}}__name(resolveManagedShellPublisherMode,"resolveManagedShellPublisherMode");var WORKSPACE_ACTIVATION_ROUTE=Object.freeze({key:"activation",method:"POST",path:"/internal/managed-runtime/v3/activation",protocolVersion:1,requestBodyLimitBytes:16*1024,responseBodyLimitBytes:16*1024,cacheControl:"no-store"});var KEYS=["contextConfigRef","contextDigest","operation","profile","protocolVersion","sessionId"].join(",");var WorkspaceActivations=class{static{__name(this,"WorkspaceActivations")}sessions=new Map;isActive(sessionId){return this.sessions.get(sessionId)===true}register(app,boot,installations,executor){app.post(WORKSPACE_ACTIVATION_ROUTE.path,managedRuntimeNoStore,authorizeManagedRuntime(boot),managedRuntimeJsonBody(WORKSPACE_ACTIVATION_ROUTE.requestBodyLimitBytes),async(req,res)=>{const body=req.body;if(body===null||typeof body!=="object"||Array.isArray(body)||Object.keys(body).sort().join(",")!==KEYS){res.status(400).json({code:"managed_activation_invalid"});return}const request=body;const binding=typeof request["sessionId"]==="string"?installations.installed(request["sessionId"]):void 0;if(request["protocolVersion"]!==1||request["operation"]!=="activate"&&request["operation"]!=="release"||(boot.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST?boot.isolationClass!=="workspace"||request["profile"]!==RESIDENT_WORKSPACE_PROFILE:![WORKSPACE_CAPABILITY_DIGEST,MEASURED_WORKSPACE_CAPABILITY_DIGEST,...boot.managedExtensions?[MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST]:[]].includes(boot.capabilityDigest)||request["profile"]!==(boot.capabilityDigest===MEASURED_WORKSPACE_CAPABILITY_DIGEST?MEASURED_WORKSPACE_EXECUTION_PROFILE:WORKSPACE_EXECUTION_PROFILE))||binding===void 0||binding.contextConfigRef!==WORKSPACE_CONTEXT_CONFIG_REF||request["contextConfigRef"]!==binding.contextConfigRef||request["contextDigest"]!==computeManagedContextDigest(binding)){res.status(409).json({code:"managed_activation_conflict"});return}const sessionId=request["sessionId"];const active=request["operation"]==="activate";if(active&&(!executor.isAdmissionOpen||this.sessions.get(sessionId)===false||boot.capabilityDigest===RESIDENT_WORKSPACE_CAPABILITY_DIGEST&&[...this.sessions].some(([id3,admitted])=>id3!==sessionId&&admitted))){res.status(409).json({code:"managed_activation_conflict"});return}if(!active&&executor.hasActiveSession(sessionId)){await executor.stopBackgroundSession(sessionId);if(executor.hasActiveSession(sessionId)){res.status(409).json({code:"managed_activation_conflict"});return}}this.sessions.set(sessionId,active);res.json({...request,runtimeInstanceId:boot.runtimeInstanceId,runtimeIncarnation:boot.runtimeIncarnation,epoch:boot.epoch,active})},handleManagedRuntimeJsonError)}};init_esbuild_shims();var CSI_FILES_RETIREMENT_CAPABILITY_DIGEST="sha256:116dcd2afce7292bdf0bf4c76010964f7a7148ad512b2939e48e3d55ea91118d";var CSI_FILES_DIAGNOSTICS_CAPABILITY_DIGEST="sha256:e973d9401c00a917e8b3de2d8fd63a0d1b09e3c4407aecf64826cdfff6c1c321";var CSI_FILES_ACTIVITY_CAPABILITY_DIGEST="sha256:5462b4edf53081cbb4aabebdcb23801b30f355f7b365c467f6a851f2fefabbf0";function isCsiFilesCapability(digest2){return digest2===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||digest2===CSI_FILES_DIAGNOSTICS_CAPABILITY_DIGEST||digest2===CSI_FILES_ACTIVITY_CAPABILITY_DIGEST}__name(isCsiFilesCapability,"isCsiFilesCapability");var sessionProfiles=new WeakMap;async function readHostedCsiFileProfile(session){const saved=sessionProfiles.get(session.authority);if(saved)return saved;const definition=JSON.parse((await session.resources.read(session.authority.sessionHeader.definitionRef)).toString("utf8"));const profile=definition.toolProfile;if(profile!=="csi-files-retirement/1"&&profile!=="csi-files-retirement/2"&&profile!=="csi-files-retirement/3")throw new Error("Invalid CSI Session profile.");sessionProfiles.set(session.authority,profile);return profile}__name(readHostedCsiFileProfile,"readHostedCsiFileProfile");function matchesCsiFilesProfile(profile,capabilityDigest){return profile==="csi-files-retirement/1"&&capabilityDigest===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||profile==="csi-files-retirement/2"&&capabilityDigest===CSI_FILES_DIAGNOSTICS_CAPABILITY_DIGEST||profile==="csi-files-retirement/3"&&capabilityDigest===CSI_FILES_ACTIVITY_CAPABILITY_DIGEST}__name(matchesCsiFilesProfile,"matchesCsiFilesProfile");init_esbuild_shims();import{createHash}from"node:crypto";var MANAGED_CSI_PROTOCOL="managed-csi/1";var MANAGED_CSI_ATTEST_PATH="/internal/managed-runtime/csi/v1/attest";var MANAGED_CSI_DRAIN_PATH="/internal/managed-runtime/csi/v1/drain";var MANAGED_CSI_ACK_PATH="/internal/managed-runtime/csi/v1/acknowledge";var MANAGED_CSI_WORKER_ACK_PROTOCOL="managed-csi-original-worker-ack/1";var MANAGED_CSI_ACK_LIMIT_BYTES=16*1024;var ManagedCsiAckRequestError=class extends Error{constructor(status){super("Managed CSI acknowledgement conflicts.");this.status=status}static{__name(this,"ManagedCsiAckRequestError")}};function parseManagedCsiAckJson(bytes){const text3=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text3,MANAGED_CSI_ACK_LIMIT_BYTES);return JSON.parse(text3,(_key,value,context)=>{if(typeof value==="number"&&(context?.source===void 0||!/^[1-9][0-9]*$/.test(context.source)))throw new Error("Managed CSI acknowledgement JSON is invalid.");return value})}__name(parseManagedCsiAckJson,"parseManagedCsiAckJson");function parseManagedCsiAcknowledgement(value){const ack=closed(value,["deliveryStatus","executionCallId","historyRevision","manifest"]);const manifest=assertManagedSessionDurableRef(ack["manifest"],"manifest");if(ack["deliveryStatus"]!=="committed"||!Number.isSafeInteger(ack["historyRevision"])||ack["historyRevision"]<1||manifest.kind!=="managed-tool-result-manifest"||manifest.schemaVersion!==1||manifest.byteLength<1||manifest.byteLength>65536)throw new Error;return{executionCallId:stableId(ack["executionCallId"]),manifest,deliveryStatus:"committed",historyRevision:ack["historyRevision"]}}__name(parseManagedCsiAcknowledgement,"parseManagedCsiAcknowledgement");function parseManagedCsiCaptureIdentity(value){const identity=closed(value,["bindingGeneration","callId","captureId","executionCallId","invocationDigest","revision","sessionId","tenantId","turnId"]);if(!isCanonicalDecimalText(identity["bindingGeneration"])||identity["revision"]!==1||typeof identity["captureId"]!=="string"||!/^[a-z0-9_-]{1,128}$/.test(identity["captureId"])||!invocationDigest(identity["invocationDigest"]))throw new Error;return{tenantId:stableId(identity["tenantId"]),sessionId:stableId(identity["sessionId"]),turnId:stableId(identity["turnId"]),executionCallId:stableId(identity["executionCallId"]),callId:stableId(identity["callId"]),invocationDigest:identity["invocationDigest"],bindingGeneration:identity["bindingGeneration"],captureId:identity["captureId"],revision:1}}__name(parseManagedCsiCaptureIdentity,"parseManagedCsiCaptureIdentity");function parseManagedCsiAckRequest(value,boot,pod){let request;let reference;let acknowledgement;const context=createManagedContextAttestationResponse(boot.context);try{request=closed(value,ACK_REQUEST_KEYS);if(typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error;const ref2=closed(request["reference"],["argsDigest","callId","promptId","sessionId"]);if(!invocationDigest(ref2["argsDigest"]))throw new Error;reference={sessionId:stableId(ref2["sessionId"]),promptId:stableId(ref2["promptId"]),callId:stableId(ref2["callId"]),argsDigest:ref2["argsDigest"]};acknowledgement=parseManagedCsiAcknowledgement(request["acknowledgement"]);closed(request["context"],Object.keys(context).sort());closed(request["storage"],STORAGE_KEYS);closed(request["pod"],["namespace","nodeName","uid"])}catch{throw new ManagedCsiAckRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL||request["workerAck"]!==MANAGED_CSI_WORKER_ACK_PROTOCOL||boot.context.isolationClass!=="workspace")throw new Error;for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",pod]]){const fields2=request[key];if(!Object.entries(expected).every(([name,field])=>fields2[name]===field))throw new Error}}catch{throw new ManagedCsiAckRequestError(409)}return{protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,workerAck:MANAGED_CSI_WORKER_ACK_PROTOCOL,retirementId:request["retirementId"],context,storage:{...boot.storage},pod:{...pod},reference,acknowledgement}}__name(parseManagedCsiAckRequest,"parseManagedCsiAckRequest");function parseManagedCsiAckResponse(value,boot,pod){try{const response=closed(value,[...ACK_REQUEST_KEYS,"captureIdentity","state"].sort());if(response["state"]!=="ACKNOWLEDGED")throw new Error;const request=parseManagedCsiAckRequest(Object.fromEntries(ACK_REQUEST_KEYS.map(key=>[key,response[key]])),boot,pod);const identity=parseManagedCsiCaptureIdentity(response["captureIdentity"]);if(identity.tenantId!==boot.context.tenantId||identity.executionCallId!==request.acknowledgement.executionCallId||identity.callId!==request.reference.callId||identity.invocationDigest!==request.reference.argsDigest)throw new Error;return{...request,state:"ACKNOWLEDGED",captureIdentity:identity}}catch{throw new ManagedCsiAckRequestError(409)}}__name(parseManagedCsiAckResponse,"parseManagedCsiAckResponse");var ACK_REQUEST_KEYS=["acknowledgement","context","managedCsi","pod","protocolVersion","reference","retirementId","storage","workerAck"];function stableId(value){return assertManagedSessionStableId(value,"id")}__name(stableId,"stableId");function invocationDigest(value){return typeof value==="string"&&/^(?:sha256:)?[0-9a-f]{64}$/.test(value)}__name(invocationDigest,"invocationDigest");function createManagedCsiAttestationRequest(boot){return Object.freeze({protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL,provisionRequestId:boot.context.provisionRequestId,physicalKey:boot.storage.physicalKey,registrationRevision:boot.storage.registrationRevision,reservationId:boot.storage.reservationId,reservationRevision:boot.storage.reservationRevision})}__name(createManagedCsiAttestationRequest,"createManagedCsiAttestationRequest");var ManagedCsiDrainRequestError=class extends Error{constructor(status){super("Managed CSI drain request is invalid.");this.status=status}static{__name(this,"ManagedCsiDrainRequestError")}};function parseManagedCsiDrainRequest(value,boot,pod){let request;try{request=closed(value,["context","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);if(request["operation"]!=="seal"&&request["operation"]!=="status"||typeof request["retirementId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(request["retirementId"]))throw new Error}catch{throw new ManagedCsiDrainRequestError(400)}try{validateManagedCsiPodIdentity(pod,boot.storage.namespace);if(request["protocolVersion"]!==1||request["managedCsi"]!==MANAGED_CSI_PROTOCOL)throw new Error;for(const[key,expected]of[["context",createManagedContextAttestationResponse(boot.context)],["storage",boot.storage],["pod",pod]]){const actual=closed(request[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>actual[name]===field))throw new Error}}catch{throw new ManagedCsiDrainRequestError(409)}return{operation:request["operation"],retirementId:request["retirementId"]}}__name(parseManagedCsiDrainRequest,"parseManagedCsiDrainRequest");function validateManagedCsiAttestationRequest(value,boot){const expected=createManagedCsiAttestationRequest(boot);try{const actual=closed(value,Object.keys(expected).sort());if(!Object.entries(expected).every(([key,field])=>actual[key]===field))throw new Error}catch{throw new Error("Managed CSI attestation request is invalid.")}}__name(validateManagedCsiAttestationRequest,"validateManagedCsiAttestationRequest");function validateManagedCsiPodIdentity(value,namespace){const pod=closed(value,["namespace","nodeName","uid"]);if(typeof pod["uid"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(pod["uid"])||pod["namespace"]!==namespace||typeof pod["nodeName"]!=="string"||pod["nodeName"].length>253||!pod["nodeName"].split(".").every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)))throw new Error("Managed CSI Pod identity is unavailable.")}__name(validateManagedCsiPodIdentity,"validateManagedCsiPodIdentity");function validateManagedCsiAttestationResponse(value,boot,expectedPod){try{validateManagedCsiPodIdentity(expectedPod,boot.storage.namespace);const response=closed(value,["context","managedCsi","mount","pod","protocolVersion","storage"]);const context=createManagedContextAttestationResponse(boot.context);for(const[key,expected]of[["context",context],["storage",boot.storage],["pod",expectedPod]]){const fields2=closed(response[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>fields2[name]===field))throw new Error}const mount=closed(response["mount"],["device","diskSerial","mountId","rootDevice","rootInode","source"]);if(response["protocolVersion"]!==1||response["managedCsi"]!==MANAGED_CSI_PROTOCOL||!unsignedDecimal(mount["mountId"],0xffffffffn,true)||typeof mount["source"]!=="string"||mount["source"].length>128||!/^\/dev\/nvme(?:0|[1-9][0-9]*)n[1-9][0-9]*$/.test(mount["source"])||mount["diskSerial"]!==boot.storage.diskSerial||!unsignedDecimal(mount["rootDevice"],0xffffffffffffffffn,false)||!unsignedDecimal(mount["rootInode"],0xffffffffffffffffn,true)||linuxDeviceNumber(mount["device"])!==mount["rootDevice"])throw new Error}catch{throw new Error("Managed CSI attestation response is invalid.")}}__name(validateManagedCsiAttestationResponse,"validateManagedCsiAttestationResponse");function linuxDeviceNumber(value){if(typeof value!=="string")throw new Error;const parts=value.split(":");if(parts.length!==2||!parts.every(part=>unsignedDecimal(part,0xffffffffn,false)))throw new Error;const major=BigInt(parts[0]);const minor=BigInt(parts[1]);return((major&0xfffn)<<8n|(major&0xfffff000n)<<32n|minor&0xffn|(minor&0xffffff00n)<<12n).toString()}__name(linuxDeviceNumber,"linuxDeviceNumber");function unsignedDecimal(value,maximum,positive){return typeof value==="string"&&/^(?:0|[1-9][0-9]{0,19})$/.test(value)&&(!positive||value!=="0")&&BigInt(value)<=maximum}__name(unsignedDecimal,"unsignedDecimal");var BOOT_KEYS=["context","managedCsi","storage","type","version"];var STORAGE_KEYS=["backendDomain","clusterDomain","diskSerial","driver","namespace","physicalKey","pvUid","pvcUid","registrationRevision","reservationId","reservationRevision","volumeHandle"];var INVALID="Managed CSI boot document is invalid.";function parseManagedCsiBoot(value){try{const boot=closed(value,BOOT_KEYS);const storage=closed(boot["storage"],STORAGE_KEYS);const context=parseManagedContextBoot(boot["context"]);if(boot["type"]!=="boot"||boot["version"]!==3||boot["managedCsi"]!==MANAGED_CSI_PROTOCOL){throw new Error(INVALID)}for(const[key,maximum]of[["clusterDomain",256],["backendDomain",256],["volumeHandle",512],["pvcUid",128],["pvUid",128]]){const text3=storage[key];if(typeof text3!=="string"||text3===""||/^[ \u1680\u2000-\u2006\u2008-\u200a\u2028\u2029\u205f\u3000]+$/u.test(text3)||text3.length>maximum||Array.from(text3).some(char=>char.charCodeAt(0)<=31||char.charCodeAt(0)>=127&&char.charCodeAt(0)<=159)||/[\ud800-\udfff]/u.test(text3))throw new Error(INVALID)}if(typeof storage["namespace"]!=="string"||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(storage["namespace"])||storage["driver"]!=="diskplugin.csi.alibabacloud.com"||typeof storage["diskSerial"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(storage["diskSerial"])||!isCanonicalDecimalText(storage["registrationRevision"])||!isCanonicalDecimalText(storage["reservationRevision"])||typeof storage["reservationId"]!=="string"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(storage["reservationId"])||typeof storage["physicalKey"]!=="string"||!/^[0-9a-f]{64}$/.test(storage["physicalKey"])||!context.mountRoot.startsWith("/")||context.mountRoot.length>2048||context.mountRoot.includes("\\")||!context.mountRoot.slice(1).split("/").every(part=>part!==""&&part!=="."&&part!=="..")||physicalKey(storage["backendDomain"],storage["driver"],storage["volumeHandle"])!==storage["physicalKey"])throw new Error(INVALID);return Object.freeze({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context,storage:Object.freeze({...storage})})}catch{throw new Error(INVALID)}}__name(parseManagedCsiBoot,"parseManagedCsiBoot");function physicalKey(backend,driver,handle){const hash=createHash("sha256");for(const field of["qwen-csi-physical/1",backend,driver,handle]){const bytes=Buffer.from(field,"utf8");const size=Buffer.alloc(4);size.writeUInt32BE(bytes.byteLength);hash.update(size).update(bytes)}return hash.digest("hex")}__name(physicalKey,"physicalKey");function closed(value,keys2){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(INVALID);const fields2=Object.keys(value).sort();if(fields2.length!==keys2.length||!fields2.every((field,index)=>field===keys2[index]))throw new Error(INVALID);return value}__name(closed,"closed");init_esbuild_shims();import{isDeepStrictEqual}from"node:util";var MANAGED_CSI_FILE_PROTOCOL="managed-csi/2";var MANAGED_CSI_FILE_PREFIX="/internal/managed-runtime/csi/v2";var CSI_FILE_FINALIZATION_FORMAT="qwen-csi-file-finalize/1";var MANAGED_CSI_FILE_ROUTES=Object.freeze(["context-attest","context","attest","drain"].map(name=>Object.freeze({method:"POST",path:`${MANAGED_CSI_FILE_PREFIX}/${name}`})));function parseManagedCsiFileJson(bytes,limit){if(bytes.byteLength>limit)throw new Error("Invalid CSI file JSON.");const text3=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text3,limit);return JSON.parse(text3,(_key,value,context)=>{if(typeof value==="number"&&(!Number.isSafeInteger(value)||context?.source===void 0||!/^(?:0|[1-9][0-9]*)$/.test(context.source)))throw new Error("Invalid CSI file JSON.");return value})}__name(parseManagedCsiFileJson,"parseManagedCsiFileJson");function parseManagedCsiFileBoot(value){try{const authorityBoot=value!==null&&typeof value==="object"&&"version"in value&&(value.version===5||value.version===6);const finalizationBoot=authorityBoot&&value.version===6;const boot=closed2(value,[...authorityBoot?["authority"]:[],"context",...finalizationBoot?["finalization"]:[],"identity","managedCsi","storage","type","version"]);const identity=closed2(boot["identity"],["capabilityDigest","profile","sessionId"]);const data=parseManagedCsiBoot({type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot["context"],storage:boot["storage"]});if(boot["type"]!=="boot"||boot["version"]!==4&&!authorityBoot||finalizationBoot&&boot["finalization"]!==CSI_FILE_FINALIZATION_FORMAT||boot["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||!matchesCsiFilesProfile(identity["profile"],identity["capabilityDigest"])||typeof identity["sessionId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(identity["sessionId"])||data.context.isolationClass!=="session"||data.context.capabilityDigest!==identity["capabilityDigest"])throw new Error;const fields2={type:"boot",managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:Object.freeze(identity),context:data.context,storage:data.storage};return finalizationBoot?Object.freeze({...fields2,version:6,authority:readManagedCsiNativeAuthority(boot["authority"]),finalization:CSI_FILE_FINALIZATION_FORMAT}):authorityBoot?Object.freeze({...fields2,version:5,authority:readManagedCsiNativeAuthority(boot["authority"])}):Object.freeze({...fields2,version:4})}catch{throw new Error("Managed CSI file boot document is invalid.")}}__name(parseManagedCsiFileBoot,"parseManagedCsiFileBoot");function readManagedCsiNativeAuthority(value){const authority=closed2(value,["origin","protocolVersion"]);const origin=authority["origin"];if(authority["protocolVersion"]!==1||typeof origin!=="string"||origin.length>2048)throw new Error("Managed CSI authority origin is invalid.");const url=resolveManagedRuntimeBrokerBaseUrl(origin);const hostname=url.hostname;if(url.origin!==origin||/(^|\.)xn--/.test(hostname)||!hostname.startsWith("[")&&!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/.test(hostname)||!hostname.startsWith("[")&&hostname.includes(".")&&!/^\d+\.\d+\.\d+\.\d+$/.test(hostname)&&!/^[a-z]/.test(hostname.split(".").at(-1)??"")||url.port!==""&&Number(url.port)===0)throw new Error("Managed CSI authority origin is not canonical.");return Object.freeze({protocolVersion:1,origin})}__name(readManagedCsiNativeAuthority,"readManagedCsiNativeAuthority");function dataBoot(boot){return{type:"boot",version:3,managedCsi:MANAGED_CSI_PROTOCOL,context:boot.context,storage:boot.storage}}__name(dataBoot,"dataBoot");function createManagedCsiFileReady(boot,port){return Object.freeze({type:"ready",version:boot.version,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context:createManagedContextReady(boot.context,port)})}__name(createManagedCsiFileReady,"createManagedCsiFileReady");function wrapManagedCsiFileContext(boot,context){return Object.freeze({protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity,context})}__name(wrapManagedCsiFileContext,"wrapManagedCsiFileContext");function readManagedCsiFileContext(value,boot){const body=closed2(value,["context","identity","managedCsi","protocolVersion"]);checkIdentity(body,boot);return body["context"]}__name(readManagedCsiFileContext,"readManagedCsiFileContext");function createManagedCsiFileAttestationRequest(boot){return{...createManagedCsiAttestationRequest(dataBoot(boot)),protocolVersion:2,managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:boot.identity}}__name(createManagedCsiFileAttestationRequest,"createManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationRequest(value,boot){if(!isDeepStrictEqual(value,createManagedCsiFileAttestationRequest(boot)))throw new Error("CSI file identity conflicts.")}__name(validateManagedCsiFileAttestationRequest,"validateManagedCsiFileAttestationRequest");function validateManagedCsiFileAttestationResponse(value,boot,pod){const body=closed2(value,["context","identity","managedCsi","mount","pod","protocolVersion","storage"]);checkIdentity(body,boot);const{identity:_identity,...data}=body;validateManagedCsiAttestationResponse({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(validateManagedCsiFileAttestationResponse,"validateManagedCsiFileAttestationResponse");function readManagedCsiFileDrain(value,boot,pod){const body=closed2(value,["context","identity","managedCsi","operation","pod","protocolVersion","retirementId","storage"]);checkIdentity(body,boot);const{identity:_identity,...data}=body;return parseManagedCsiDrainRequest({...data,protocolVersion:1,managedCsi:MANAGED_CSI_PROTOCOL},dataBoot(boot),pod)}__name(readManagedCsiFileDrain,"readManagedCsiFileDrain");function checkIdentity(body,boot){if(body["protocolVersion"]!==2||body["managedCsi"]!==MANAGED_CSI_FILE_PROTOCOL||!isDeepStrictEqual(body["identity"],boot.identity))throw new Error("CSI file identity conflicts.")}__name(checkIdentity,"checkIdentity");function closed2(value,keys2){if(!value||typeof value!=="object"||Array.isArray(value)||!isDeepStrictEqual(Object.keys(value).sort(),keys2))throw new Error;return{...value}}__name(closed2,"closed");init_esbuild_shims();var ManagedMcpRecipeError=class extends Error{static{__name(this,"ManagedMcpRecipeError")}constructor(){super("Invalid Managed MCP recipe.");this.name="ManagedMcpRecipeError"}};var fields=new Set(["command","args","env","timeout","url","httpUrl","headers","type"]);function text(value){return typeof value==="string"&&!value.includes("\0")}__name(text,"text");function strings(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&Object.entries(value).every(([key,item])=>text(key)&&key.length>0&&text(item))}__name(strings,"strings");function parseManagedMcpRecipe(value,options={}){const invalid2=__name(()=>{throw new ManagedMcpRecipeError},"invalid");if(!value||typeof value!=="object"||Array.isArray(value))invalid2();const recipe=value;if(Object.keys(recipe).some(key=>!fields.has(key))||recipe["timeout"]!==void 0&&(!Number.isSafeInteger(recipe["timeout"])||Number(recipe["timeout"])<1||Number(recipe["timeout"])>6e5)||recipe["type"]!==void 0&&(typeof recipe["type"]!=="string"||!["stdio","sse","http"].includes(recipe["type"])))invalid2();if(recipe["command"]!==void 0){if(!text(recipe["command"])||!recipe["command"].trim()||recipe["url"]!==void 0||recipe["httpUrl"]!==void 0||recipe["headers"]!==void 0||recipe["type"]!==void 0&&recipe["type"]!=="stdio"||recipe["args"]!==void 0&&(!Array.isArray(recipe["args"])||!recipe["args"].every(text))||recipe["env"]!==void 0&&!strings(recipe["env"]))invalid2()}else{const url=recipe["httpUrl"]??recipe["url"];if(!text(url)||!url.trim()||recipe["url"]!==void 0&&recipe["httpUrl"]!==void 0||recipe["args"]!==void 0||recipe["env"]!==void 0||recipe["type"]==="stdio"||recipe["headers"]!==void 0&&!strings(recipe["headers"]))invalid2();if(!(options.allowPlaceholders&&/\$\{[^}]+\}/u.test(url))){try{const parsed=new URL(url);if(!["http:","https:"].includes(parsed.protocol)||parsed.username||parsed.password||parsed.hash)invalid2()}catch{invalid2()}}if(recipe["headers"]!==void 0&&Object.entries(recipe["headers"]).some(([key,item])=>!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(key)||/[\r\n]/u.test(item)))invalid2()}return structuredClone(recipe)}__name(parseManagedMcpRecipe,"parseManagedMcpRecipe");init_esbuild_shims();var import_toml=__toESM(require_toml(),1);import{createHash as createHash2}from"node:crypto";import*as fs from"node:fs/promises";import{createReadStream}from"node:fs";import*as path from"node:path";import*as os from"node:os";init_esbuild_shims();var ManagedSkillCompatibilityError=class extends Error{static{__name(this,"ManagedSkillCompatibilityError")}};function parseManagedSkillContent(content,file){const metadata=parseMarkdownCommand(content).frontmatter??{};for(const key of["allowedTools","allowed-tools","hooks","paths","arguments","args-file"]){if(metadata[key]!==void 0)throw new ManagedSkillCompatibilityError(`Managed Skill field ${key} is unsupported.`)}if(metadata["model"]!==void 0&&metadata["model"]!=="inherit")throw new ManagedSkillCompatibilityError("Managed Skill model override is unsupported.");return parseSkillContent(content,file)}__name(parseManagedSkillContent,"parseManagedSkillContent");var MANAGED_PACKAGE_COMPILER_VERSION=1;var MANAGED_PACKAGE_MAX_ARCHIVE_BYTES=100*1024*1024;var ManagedPackageCompatibilityError=class extends Error{constructor(reasons){super(`Managed extension package is incompatible: ${reasons.join(", ")}`);this.reasons=reasons;this.name="ManagedPackageCompatibilityError"}static{__name(this,"ManagedPackageCompatibilityError")}};function object(value,field){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedPackageCompatibilityError([`${field}: invalid object`]);return value}__name(object,"object");function text2(value,field,maxBytes=512*1024){if(typeof value!=="string"||!value.trim()||Buffer.byteLength(value)>maxBytes)throw new ManagedPackageCompatibilityError([`${field}: invalid text`]);return value}__name(text2,"text");function managedPackageRelativePath(value){const normalized=value.replace(/^\.\//,"");if(!normalized||normalized.includes("\\")||normalized.includes(":")||normalized.includes("\0")||normalized.startsWith("/")||normalized.split("/").some(part=>!part||part==="."||part===".."))throw new ManagedPackageCompatibilityError(["package resource path escapes its root"]);return normalized}__name(managedPackageRelativePath,"managedPackageRelativePath");function frontmatter(content){const parsed=parseMarkdownCommand(content);return{metadata:parsed.frontmatter??{},body:parsed.prompt}}__name(frontmatter,"frontmatter");function hasValue(value){return value!==void 0&&value!==null&&value!==false&&value!==""&&(!Array.isArray(value)||value.length>0)&&(typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>0)}__name(hasValue,"hasValue");function rejectFields(value,fields2,source){const reasons=fields2.filter(key=>hasValue(value[key])).map(key=>`${source}.${key}: unsupported`);if(reasons.length)throw new ManagedPackageCompatibilityError(reasons)}__name(rejectFields,"rejectFields");var PRIVATE_FILES=new Set([".git",".env",".qwen-extension-settings.json",".qwen-extension-git-credentials.json",".qwen-extension-install.json"]);async function listManagedPackageFiles(root,excludePrivate=false){const files=[];let total=0;const visit=__name(async relative=>{const entries=await fs.readdir(path.join(root,relative),{withFileTypes:true});for(const entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(excludePrivate&&(PRIVATE_FILES.has(entry.name)||entry.name.startsWith(".env.")))continue;const name=relative?`${relative}/${entry.name}`:entry.name;managedPackageRelativePath(name);if(entry.isSymbolicLink()||!entry.isDirectory()&&!entry.isFile())throw new ManagedPackageCompatibilityError([`${name}: unsupported resource type`]);if(entry.isDirectory())await visit(name);else{total+=(await fs.lstat(path.join(root,name))).size;files.push(name);if(files.length>MAX_ARCHIVE_ENTRIES||total>MAX_ARCHIVE_EXPANDED_BYTES)throw new ManagedPackageCompatibilityError(["package resource limit exceeded"])}}},"visit");await visit("");return files}__name(listManagedPackageFiles,"listManagedPackageFiles");async function readText(root,relative){const file=managedPackageRelativePath(relative);const info=await fs.lstat(path.join(root,file));if(!info.isFile()||info.isSymbolicLink()||info.size>1024*1024)throw new ManagedPackageCompatibilityError([`${file}: invalid text resource`]);return new TextDecoder("utf-8",{fatal:true}).decode(await fs.readFile(path.join(root,file)))}__name(readText,"readText");async function readObject(root,relative){return object(JSON.parse(await readText(root,relative)),relative)}__name(readObject,"readObject");async function rawConfig(root,files){if(files.includes("qwen-extension.json"))return readObject(root,"qwen-extension.json");if(files.includes("gemini-extension.json")){const raw=await readObject(root,"gemini-extension.json");rejectFields(raw,["lspServers","channels","workflows","executor","outputStyles"],"gemini-extension.json");return{...raw,...convertGeminiToQwenConfig(root)}}const pluginFile=files.includes(".claude-plugin/plugin.json")?".claude-plugin/plugin.json":files.includes(".qoder-plugin/plugin.json")?".qoder-plugin/plugin.json":void 0;if(pluginFile){const raw=await readObject(root,pluginFile);rejectFields(raw,["lspServers","channels","workflows","outputStyles","executor"],pluginFile);const config={...convertClaudeToQwenConfig(raw),name:raw["name"],version:raw["version"]??"1.0.0"};for(const key of["commands","skills","agents","contextFileName","settings","mcpServers","hooks"])if(raw[key]!==void 0)config[key]=raw[key];return config}if(files.includes("plugin.json")){const raw=await readObject(root,"plugin.json");if(raw["$schema"]!=="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json")throw new ManagedPackageCompatibilityError(["plugin.json: unsupported schema"]);rejectFields(raw,["lspServers","channels","workflows","executor","outputStyles"],"plugin.json");return{...raw,name:raw["name"],version:raw["version"]??"1.0.0"}}throw new ManagedPackageCompatibilityError(["extension manifest missing"])}__name(rawConfig,"rawConfig");function resourceRoots(config,key,fallback){const value=config[key]??fallback;const roots=typeof value==="string"?[value]:value;if(!Array.isArray(roots)||roots.some(item=>typeof item!=="string"))throw new ManagedPackageCompatibilityError([`${key}: invalid resource roots`]);return roots.map(managedPackageRelativePath)}__name(resourceRoots,"resourceRoots");function selectedFiles(files,roots){return files.filter(file=>roots.some(root=>file===root||file.startsWith(`${root}/`)))}__name(selectedFiles,"selectedFiles");function strings2(value,field){if(value===void 0)return void 0;const entries=typeof value==="string"?value.split(",").map(item=>item.trim()).filter(Boolean):value;if(!Array.isArray(entries)||entries.some(entry=>typeof entry!=="string"||!entry))throw new ManagedPackageCompatibilityError([`${field}: invalid list`]);return entries.map(entry=>resolveBuiltinToolName(entry)??entry)}__name(strings2,"strings");async function compileManagedExtensionPackage(root,options){const files=await listManagedPackageFiles(root);if(files.some(file=>file.split("/").some(part=>PRIVATE_FILES.has(part)||part.startsWith(".env."))))throw new ManagedPackageCompatibilityError(["package contains private settings or credentials"]);const config=await rawConfig(root,files);let packageTarget=options.target;if(config["managedTarget"]!==void 0){const target=object(config["managedTarget"],"managedTarget");if(target["platform"]!==options.target.platform||target["arch"]!=="any"&&target["arch"]!==options.target.arch){throw new ManagedPackageCompatibilityError(["package target does not match this Runtime"])}packageTarget={platform:options.target.platform,arch:target["arch"]}}rejectFields(config,["lspServers","channels","workflows","executor","outputStyles"],"manifest");if(files.some(file=>/^(?:workflows|channels|lsp)\//.test(file)))throw new ManagedPackageCompatibilityError(["package contains unsupported executable components"]);const name=text2(config["name"],"name",128);if(!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name))throw new ManagedPackageCompatibilityError(["name: invalid identity"]);const contributions={skills:[],commands:[],agents:[],context:[],mcpServers:{},hooks:{},settings:[]};for(const file of selectedFiles(files,resourceRoots(config,"skills","skills")).filter(file2=>file2.endsWith("/SKILL.md"))){const content=await readText(root,file);let skill;try{skill=parseManagedSkillContent(content,file)}catch(error){if(error instanceof ManagedSkillCompatibilityError)throw new ManagedPackageCompatibilityError([`${file}: ${error.message}`]);throw error}contributions.skills.push({name:qualifySkillName(name,skill.name),description:skill.description,body:skill.body,assetDirectory:path.posix.dirname(file),model_invocable:skill.disableModelInvocation!==true,user_invocable:skill.userInvocable!==false})}const commandRoots=resourceRoots(config,"commands","commands");for(const file of selectedFiles(files,commandRoots).filter(file2=>/\.(?:md|toml)$/.test(file2))){const content=await readText(root,file);const parsed=file.endsWith(".toml")?{metadata:{},body:"",definition:object((0,import_toml.parse)(content),file)}:{...frontmatter(content),definition:void 0};if(!parsed.definition)MarkdownCommandDefSchema.parse({frontmatter:parsed.metadata,prompt:parsed.body});const metadata=parsed.definition??parsed.metadata;rejectFields(metadata,["allowed-tools","allowedTools","hooks","model","context","agent"],file);const relative=commandRoots.find(entry=>file.startsWith(`${entry}/`));const authored=(relative?file.slice(relative.length+1):path.posix.basename(file)).replace(/\.(?:md|toml)$/,"").split("/").map(part=>part.replaceAll(":","_")).join(":");contributions.commands.push({name:`${name}:${authored}`,description:typeof metadata["description"]==="string"?metadata["description"]:authored,prompt:text2(parsed.definition?.["prompt"]??parsed.body,file),...typeof metadata["argument-hint"]==="string"?{argumentHint:metadata["argument-hint"]}:{},modelInvocable:metadata["disable-model-invocation"]!==true&&metadata["disable-model-invocation"]!=="true"})}for(const file of selectedFiles(files,resourceRoots(config,"agents","agents")).filter(file2=>file2.endsWith(".md"))){const{metadata,body}=frontmatter(await readText(root,file));rejectFields(metadata,["mcpServers","mcp_servers","hooks","executor","container","isolation","skills","permissionMode","approvalMode","background","memory"],file);const agent={name:`${name}:${text2(metadata["name"]??path.posix.basename(file,".md"),file,128)}`,description:text2(metadata["description"],`${file}.description`,4096),systemPrompt:text2(body,file),...metadata["tools"]!==void 0?{tools:strings2(metadata["tools"],file)}:{},...metadata["disallowedTools"]!==void 0?{disallowedTools:strings2(metadata["disallowedTools"],file)}:{},...metadata["model"]!==void 0?{model:text2(metadata["model"],`${file}.model`,512)}:{}};contributions.agents.push(agent)}const contextRoots=config["contextFileName"]===void 0?files.includes("QWEN.md")?["QWEN.md"]:files.includes("system-prompt.md")?["system-prompt.md"]:[]:resourceRoots(config,"contextFileName","QWEN.md");for(const file of contextRoots)contributions.context.push({path:file,body:await readText(root,file)});let mcp=config["mcpServers"];if(typeof mcp==="string")mcp=await readObject(root,managedPackageRelativePath(mcp));if(mcp===void 0&&files.includes(".mcp.json")){const loaded=await readObject(root,".mcp.json");mcp=loaded["mcpServers"]??loaded}if(mcp===void 0&&files.includes("mcp.json")){const loaded=await readObject(root,"mcp.json");mcp=loaded["mcpServers"]??loaded["servers"]??loaded}if(mcp!==void 0)contributions.mcpServers=Object.fromEntries(Object.entries(object(mcp,"mcpServers")).map(([name2,recipe])=>[name2,parseManagedMcpRecipe(recipe,{allowPlaceholders:true})]));let hooks=config["hooks"];if(typeof hooks==="string")hooks=await readObject(root,managedPackageRelativePath(hooks));if(hooks===void 0&&files.includes("hooks/hooks.json"))hooks=await readObject(root,"hooks/hooks.json");if(hooks!==void 0){const loaded=object(hooks,"hooks");contributions.hooks=object(loaded["hooks"]??loaded,"hooks")}if(config["settings"]!==void 0){if(!Array.isArray(config["settings"]))throw new ManagedPackageCompatibilityError(["settings: invalid list"]);contributions.settings=config["settings"].map(entry=>{const setting=object(entry,"setting");const envVar=text2(setting["envVar"],"setting.envVar",128);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(envVar)||envVar.startsWith("QWEN_MANAGED_")||["QWEN_EXTENSION_ROOT","CLAUDE_PLUGIN_ROOT","extensionPath","workspacePath"].includes(envVar))throw new ManagedPackageCompatibilityError(["setting.envVar: reserved or invalid"]);return{name:text2(setting["name"],"setting.name",512),envVar,sensitive:setting["sensitive"]===true}})}if(options.resolveRecipes!==false){const environment={...options.environment,extensionPath:root,CLAUDE_PLUGIN_ROOT:root,QWEN_EXTENSION_ROOT:root,workspacePath:options.workspaceDirectory??"",workspaceFolder:options.workspaceDirectory??"",pathSeparator:"/","/":"/"};const hydrate=__name(value=>{if(typeof value==="string")return value.replace(/\$\{([^}]+)\}/g,(_,variable)=>{if(!Object.hasOwn(environment,variable))throw new ManagedPackageCompatibilityError([`setting ${variable}: required`]);return environment[variable]});if(Array.isArray(value))return value.map(hydrate);if(value&&typeof value==="object")return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,hydrate(item)]));return value},"hydrate");contributions.mcpServers=Object.fromEntries(Object.entries(hydrate(contributions.mcpServers)).map(([name2,recipe])=>[name2,parseManagedMcpRecipe(recipe)]));contributions.hooks=hydrate(contributions.hooks)}for(const entries of[contributions.skills,contributions.commands,contributions.agents]){if(new Set(entries.map(entry=>entry.name)).size!==entries.length)throw new ManagedPackageCompatibilityError(["duplicate component identity"])}if(contributions.skills.length>256||Object.keys(contributions.mcpServers).length>16||contributions.settings.length>128)throw new ManagedPackageCompatibilityError(["component catalog limit exceeded"]);const components=[];if(contributions.skills.length)components.push("skills");if(contributions.commands.length)components.push("commands");if(contributions.agents.length)components.push("agents");if(contributions.context.length)components.push("context");if(Object.keys(contributions.mcpServers).length)components.push("mcp");if(Object.keys(contributions.hooks).length)components.push("hooks");if(contributions.settings.length)components.push("settings");return{manifest:{schemaVersion:1,compilerVersion:MANAGED_PACKAGE_COMPILER_VERSION,name,version:text2(config["version"]??"1.0.0","version",128),target:packageTarget,components,...config["managedSource"]?{sourceType:text2(object(config["managedSource"],"managedSource")["type"],"sourceType",64),sourceRevision:text2(object(config["managedSource"],"managedSource")["revision"],"sourceRevision",256)}:{}},contributions}}__name(compileManagedExtensionPackage,"compileManagedExtensionPackage");async function prepareManagedExtensionPackage(source,options){if(["local","link","snapshot"].includes(source.type)){const isDirectory=(await fs.stat(source.source)).isDirectory();const installed=isDirectory&&await fs.lstat(path.join(source.source,".qwen-extension-install.json")).catch(error=>{if(error.code!=="ENOENT")throw error;return void 0});if(installed)throw new ManagedPackageCompatibilityError(["installed package requires its original source"])}const temporary=await fs.mkdtemp(path.join(os.tmpdir(),"qwen-managed-package-"));const root=path.join(temporary,"package");await fs.mkdir(root);let sourceRevision=source.ref??"";try{if(source.type==="git")sourceRevision=await cloneFromGit(source,root,options.signal);else if(source.type==="npm"){const result=await downloadFromNpmRegistry({...source},root,options.signal,{enforceResourceLimits:true});sourceRevision=result.version}else if(source.type==="github-release"){const result=await downloadFromGitHubRelease(source,root,options.signal,options.target,{enforceResourceLimits:true});sourceRevision=result.tagName}else if(source.type==="archive-url")await downloadFromArchiveUrl(source,root,options.signal,{enforceResourceLimits:true});else if(/\.(?:zip|tar\.gz)$/i.test(source.source))await extractArchiveFile(source.source,root,options.signal,{enforceResourceLimits:true});else{const files2=await listManagedPackageFiles(source.source,true);for(const file of files2){const destination=path.join(root,file);await fs.mkdir(path.dirname(destination),{recursive:true});await fs.copyFile(path.join(source.source,file),destination)}}options.signal?.throwIfAborted();const scrub=__name(async directory=>{for(const entry of await fs.readdir(directory,{withFileTypes:true})){const file=path.join(directory,entry.name);if(PRIVATE_FILES.has(entry.name)||entry.name.startsWith(".env.")){await fs.rm(file,{recursive:true,force:true})}else if(entry.isDirectory())await scrub(file)}},"scrub");await scrub(root);let files=await listManagedPackageFiles(root);const config=await rawConfig(root,files);config["managedTarget"]=options.target;config["managedSource"]={type:source.type==="local"?/\.(?:zip|tar\.gz)$/i.test(source.source)?"archive":"directory":source.type,revision:sourceRevision||text2(config["version"]??"snapshot","version",128)};await fs.writeFile(path.join(root,"qwen-extension.json"),JSON.stringify(config));files=await listManagedPackageFiles(root);const compiled=await compileManagedExtensionPackage(root,{target:options.target,resolveRecipes:false});await fs.mkdir(options.destination,{recursive:true});const archivePath=path.join(options.destination,"package.tar.gz");for(const file of files){const absolute=path.join(root,file);const mode=(await fs.stat(absolute)).mode;await fs.chmod(absolute,mode&73?493:420)}await Qn({cwd:root,file:archivePath,gzip:true,portable:true,noMtime:true},files.sort());if((await fs.stat(archivePath)).size>MANAGED_PACKAGE_MAX_ARCHIVE_BYTES)throw new ManagedPackageCompatibilityError(["compressed package limit exceeded"]);const hash=createHash2("sha256");for await(const chunk of createReadStream(archivePath))hash.update(chunk);const packageDigest=hash.digest("hex");return{archivePath,packageDigest,manifest:compiled.manifest,sourceRevision:sourceRevision||packageDigest}}finally{await fs.rm(temporary,{recursive:true,force:true})}}__name(prepareManagedExtensionPackage,"prepareManagedExtensionPackage");init_esbuild_shims();init_esbuild_shims();var MAX_MANAGED_MEDIA_RESPONSE_BYTES=DAEMON_ACP_NDJSON_LIMITS.maxFrameBytes-64*1024;function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)?value:void 0}__name(record,"record");function isBase64(data){if(data.length%4!==0)return false;const padding=data.endsWith("==")?2:data.endsWith("=")?1:0;const body=data.slice(0,data.length-padding);if(/[^A-Za-z0-9+/]/.test(body))return false;if(padding===0)return true;const last="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(body.at(-1));return padding===2?(last&15)===0:(last&3)===0}__name(isBase64,"isBase64");function managedToolResponseMediaBytes(result,operation){const json=JSON.stringify(result);if(json===void 0||Buffer.byteLength(json)>MAX_MANAGED_MEDIA_RESPONSE_BYTES){throw new Error("Managed Runtime media response exceeded its size limit.")}const wire=JSON.parse(json);if(!hasBoundedJsonStructure({jsonrpc:"2.0",id:"0",result:wire})){throw new Error("Managed Runtime media response exceeded ACP structure limits.")}const status=record(wire);if(operation!=="execute"&&status?.["state"]!=="settled")return 0;const execution2=operation==="execute"?status:record(status?.["result"]);if(!["not_started","success","error","cancelled"].includes(String(execution2?.["executionStatus"])))return 0;const content=record(execution2?.["result"])?.["llmContent"];const parts=Array.isArray(content)?content:[content];let mediaBytes=0;for(const part of parts){const object5=record(part);if(!object5||!Object.hasOwn(object5,"inlineData"))continue;const inline=record(object5["inlineData"]);if(!inline||typeof inline["data"]!=="string"||typeof inline["mimeType"]!=="string"||!/^(?:(?:image|audio|video)\/[a-z0-9.+-]+|application\/pdf)$/i.test(inline["mimeType"])||!isBase64(inline["data"])){throw new Error("Managed Runtime returned invalid inline media.")}mediaBytes+=inline["data"].length}return mediaBytes}__name(managedToolResponseMediaBytes,"managedToolResponseMediaBytes");var MANAGED_RUNTIME_PROVIDER_PROTOCOL="managed-runtime-provider/1";var MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES=768*1024;var MAX_PROVIDER_MEDIA_RESULT_BYTES=896*1024;var MANAGED_RUNTIME_PROVIDER_ROUTE=Object.freeze({key:"provider-control",method:"POST",path:"/internal/managed-runtime/provider/v1/control",protocolVersion:1,requestBodyLimitBytes:8*1024*1024,responseBodyLimitBytes:8*1024*1024,cacheControl:"no-store"});var MANAGED_WORKSPACE_CONTEXT_FILES=["QWEN.md","AGENTS.md"];var MANAGED_WORKSPACE_CONTEXT_FILE_CHARS=64*1024;var ManagedRuntimeProviderProtocolError=class extends Error{constructor(message="Managed Runtime provider request is invalid.",status=400,code="managed_runtime_provider_invalid"){super(message);this.status=status;this.code=code;this.name="ManagedRuntimeProviderProtocolError"}static{__name(this,"ManagedRuntimeProviderProtocolError")}};function object2(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedRuntimeProviderProtocolError;return value}__name(object2,"object");function keys(value,required,optional=[]){if(required.some(key=>!Object.hasOwn(value,key))||Object.keys(value).some(key=>!required.includes(key)&&!optional.includes(key)))throw new ManagedRuntimeProviderProtocolError}__name(keys,"keys");function id(value){if(typeof value!=="string"||!value.length||value.length>512||value.includes("\0"))throw new ManagedRuntimeProviderProtocolError;return value}__name(id,"id");var SESSION_ID=/^[A-Za-z0-9._-]{1,512}$/;function envelopeSessionId(value){if(typeof value!=="string"||!SESSION_ID.test(value)||value==="."||value.includes(".."))throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity must be 1-512 ASCII letters, digits, '.', '_' or '-', without '..'.")}__name(envelopeSessionId,"envelopeSessionId");function sequence(value){if(!Number.isSafeInteger(value)||Number(value)<0)throw new ManagedRuntimeProviderProtocolError}__name(sequence,"sequence");function oneOf(value,values){return typeof value==="string"&&values.includes(value)}__name(oneOf,"oneOf");function checkSession(identity,session){if(identity.sessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider Session identity conflicts.",409,"managed_runtime_identity_conflict")}__name(checkSession,"checkSession");function managedRuntimeProviderLimit(kind){return["bind-history","checkpoint","history"].includes(kind)?8*1024*1024:1024*1024}__name(managedRuntimeProviderLimit,"managedRuntimeProviderLimit");function parseManagedRuntimeProviderOperation(value,session,boundedByCaller=false){const op=object2(value);const kind=id(op["kind"]);if(!boundedByCaller)managedToolDigest(value,managedRuntimeProviderLimit(kind));switch(kind){case"raw-file-history":{const action=op["action"];if(action==="bind"){keys(op,["kind","action","state"]);if(op["state"]!==null)parseHostedFileHistoryState(op["state"],session.harnessSessionId)}else if(action==="prepare"){keys(op,["kind","action","promptId","paths"]);parseManagedToolFileHistoryPromptId(op["promptId"]);if(!Array.isArray(op["paths"])||!op["paths"].length)throw new ManagedRuntimeProviderProtocolError;op["paths"].forEach(historyPath)}else if(action==="rewind"){keys(op,["kind","action","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"])}else if(action==="snapshot")keys(op,["kind","action"]);else throw new ManagedRuntimeProviderProtocolError;break}case"acquire":case"release":case"manifest":case"history":case"workspace-context":keys(op,["kind"]);break;case"begin-turn":case"prepare":{keys(op,kind==="prepare"?["kind","identity","toolName","input"]:["kind","identity"],kind==="prepare"?["modification","mediaContext"]:[]);checkSession(parseManagedToolCallIdentity(op["identity"]),session);if(kind==="prepare"){id(op["toolName"]);object2(op["input"]);if("modification"in op)checkSession(parseManagedToolContentModification(op["modification"]).source,session);if("mediaContext"in op)parseManagedToolMediaContext(op["mediaContext"])}break}case"confirmation":case"confirm":case"preflight":case"execute":case"status":case"cancel":keys(op,kind==="confirm"?["kind","reference","outcome"]:["kind","reference"],kind==="confirm"?["payload","phase"]:kind==="status"?["afterSequence"]:[]);checkSession(parseManagedToolInvocationReference(op["reference"]),session);if(kind==="confirm"){if(!Object.values(ToolConfirmationOutcome).includes(op["outcome"])||op["outcome"]==="restore_previous")throw new ManagedRuntimeProviderProtocolError;if("payload"in op)parseManagedToolConfirmationPayload(op["payload"]);if("phase"in op&&!oneOf(op["phase"],["permission","preflight"]))throw new ManagedRuntimeProviderProtocolError}if("afterSequence"in op)sequence(op["afterSequence"]);break;case"bind-history":{keys(op,["kind","binding"]);const binding=parseManagedToolFileHistoryBinding(op["binding"]);if(binding.ownerSessionId!==session.harnessSessionId||binding.ownerRuntimeSessionId!==session.runtimeSessionId)throw new ManagedRuntimeProviderProtocolError("Managed Runtime file history owner conflicts.",409,"managed_runtime_identity_conflict");break}case"checkpoint":keys(op,["kind","promptId"]);parseManagedToolFileHistoryPromptId(op["promptId"]);break;default:throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider operation is unsupported.",501,"managed_runtime_provider_unsupported")}return structuredClone(value)}__name(parseManagedRuntimeProviderOperation,"parseManagedRuntimeProviderOperation");function parseManagedRuntimeProviderRequest(value){const request=object2(value);keys(request,["protocolVersion","providerProtocol","session","operation"]);if(request["protocolVersion"]!==1||request["providerProtocol"]!==MANAGED_RUNTIME_PROVIDER_PROTOCOL)throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider protocol is incompatible.",409,"managed_runtime_provider_incompatible");const session=object2(request["session"]);keys(session,["harnessSessionId","runtimeSessionId","turnKind"]);envelopeSessionId(session["harnessSessionId"]);envelopeSessionId(session["runtimeSessionId"]);if(!oneOf(session["turnKind"],["bootstrap","continuation"]))throw new ManagedRuntimeProviderProtocolError;const parsedSession=session;const parsed={protocolVersion:1,providerProtocol:MANAGED_RUNTIME_PROVIDER_PROTOCOL,session:structuredClone(parsedSession),operation:parseManagedRuntimeProviderOperation(request["operation"],parsedSession,true)};managedToolDigest(value,managedRuntimeProviderLimit(parsed.operation.kind));return parsed}__name(parseManagedRuntimeProviderRequest,"parseManagedRuntimeProviderRequest");function parseManagedRuntimeProviderResult(operation,value,session){managedToolDigest(value,managedRuntimeProviderLimit(operation.kind));if(operation.kind==="begin-turn"||operation.kind==="confirm"){if(value!==null)throw new ManagedRuntimeProviderProtocolError;return null}if(operation.kind==="acquire"||operation.kind==="release"){if(value!==true)throw new ManagedRuntimeProviderProtocolError;return true}const result=object2(value);switch(operation.kind){case"raw-file-history":{if(operation.action!=="rewind")return parseHostedFileHistoryState(value,session.harnessSessionId);keys(result,["state","filesChanged","filesFailed","conflict"]);const state=parseHostedFileHistoryState(result["state"],session.harnessSessionId);if(!Array.isArray(result["filesChanged"])||!Array.isArray(result["filesFailed"])||typeof result["conflict"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;result["filesChanged"].forEach(historyPath);result["filesFailed"].forEach(historyPath);if(new Set(result["filesChanged"]).size!==result["filesChanged"].length||result["filesChanged"].some(file=>!Object.hasOwn(state.files,file))||!state.snapshots.some(snapshot=>snapshot.promptId===operation.promptId)||result["conflict"]&&result["filesChanged"].length!==0)throw new ManagedRuntimeProviderProtocolError("Invalid Hosted file history rewind outcome.");break}case"workspace-context":{keys(result,["files"]);if(!Array.isArray(result["files"]))throw new ManagedRuntimeProviderProtocolError;let next=0;for(const entry of result["files"]){const file=object2(entry);keys(file,["name","text"]);const index=MANAGED_WORKSPACE_CONTEXT_FILES.indexOf(file["name"]);if(index<next||typeof file["text"]!=="string"||file["text"].length>MANAGED_WORKSPACE_CONTEXT_FILE_CHARS)throw new ManagedRuntimeProviderProtocolError("Invalid Workspace context result.");next=index+1}return result["files"]}case"bind-history":case"checkpoint":case"history":{const state=parseManagedToolFileHistoryState(value);if(state.ownerSessionId!==session.harnessSessionId)throw new ManagedRuntimeProviderProtocolError("Managed file history owner changed.");return state}case"manifest":keys(result,["tools","capabilityDigest","policyRevision"]);id(result["policyRevision"]);if(!Array.isArray(result["tools"])||managedToolDigest(result["tools"],1024*1024)!==result["capabilityDigest"])throw new ManagedRuntimeProviderProtocolError("Managed tool manifest digest changed.");for(const tool of result["tools"]){const descriptor=object2(tool);id(descriptor["name"]);object2(descriptor["schema"])}break;case"prepare":{const reference=Object.fromEntries(["sessionId","promptId","callId","capabilityDigest","policyRevision","invocationId","argsDigest"].map(key=>[key,result[key]]));checkSession(parseManagedToolInvocationReference(reference),session);for(const[key,expected]of Object.entries(operation.identity))if(result[key]!==expected)throw new ManagedRuntimeProviderProtocolError;object2(result["params"]);if(managedToolDigest(result["params"])!==result["argsDigest"]||typeof result["description"]!=="string"||!Array.isArray(result["locations"])||!oneOf(result["defaultPermission"],["allow","ask","deny","default"])||typeof result["requiresUserInteraction"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;id(result["toolUseId"]);break}case"confirmation":{if(!oneOf(result["type"],["edit","exec","mcp","info"])||typeof result["title"]!=="string")throw new ManagedRuntimeProviderProtocolError;const required={edit:["fileName","filePath","fileDiff","newContent"],exec:["command","rootCommand"],mcp:["serverName","toolName","toolDisplayName"],info:["prompt"]}[result["type"]];if(required.some(key=>typeof result[key]!=="string")||result["type"]==="edit"&&result["originalContent"]!==null&&typeof result["originalContent"]!=="string")throw new ManagedRuntimeProviderProtocolError;break}case"preflight":if(typeof result["shouldProceed"]!=="boolean")throw new ManagedRuntimeProviderProtocolError;break;case"execute":if(!oneOf(result["executionStatus"],["not_started","success","error","cancelled"]))throw new ManagedRuntimeProviderProtocolError;if(result["executionStatus"]==="success")object2(result["result"]);break;case"status":case"cancel":if(result["state"]==="unknown"){keys(result,["state"]);break}if(!oneOf(result["state"],["prepared","executing","cancel_requested","settled"])||typeof result["cancelRequested"]!=="boolean"||typeof result["progressGap"]!=="boolean"||!Array.isArray(result["progress"]))throw new ManagedRuntimeProviderProtocolError;sequence(result["lastSeq"]);sequence(result["firstAvailableSeq"]);if(result["state"]==="settled")parseManagedRuntimeProviderResult({kind:"execute",reference:operation.reference},result["result"],session);else if("result"in result)throw new ManagedRuntimeProviderProtocolError;break;default:throw new ManagedRuntimeProviderProtocolError}return structuredClone(value)}__name(parseManagedRuntimeProviderResult,"parseManagedRuntimeProviderResult");function providerFitNotice(omitted,budgetBytes){return`
4
4
  [Managed Runtime provider omitted ${omitted} characters here to fit the ${budgetBytes}-byte wire limit.]
5
5
  `}__name(providerFitNotice,"providerFitNotice");var PROVIDER_RESULT_STUB="[Managed Runtime provider omitted this tool result to fit the wire limit.]";function providerFitSlots(target){const slots=[];const collect=__name((owner,key,mark)=>{if(typeof owner[key]!=="string")return;slots.push({get:__name(()=>owner[key],"get"),set:__name(next=>{owner[key]=next;mark?.()},"set")})},"collect");const result=target["result"];if(result&&typeof result==="object"&&!Array.isArray(result)){const toolResult=result;const llmContent=toolResult["llmContent"];if(typeof llmContent==="string")collect(toolResult,"llmContent");else if(Array.isArray(llmContent)){for(const part of llmContent)if(part&&typeof part==="object"&&!Array.isArray(part))collect(part,"text")}const display=toolResult["returnDisplay"];if(typeof display==="string")collect(toolResult,"returnDisplay");else if(isShellResultDisplay(display)){const mark=__name(()=>{display.truncated=true},"mark");const record2=display;collect(record2,"output",mark);collect(record2,"text",mark);collect(record2,"error",mark);display.notices.forEach((_,index)=>slots.push({get:__name(()=>display.notices[index],"get"),set:__name(next=>{display.notices[index]=next;mark()},"set")}))}}const error=target["error"];if(error&&typeof error==="object"&&!Array.isArray(error))collect(error,"message");return slots}__name(providerFitSlots,"providerFitSlots");function jsonCodePointBytes(codePoint){if(codePoint===34||codePoint===92)return 2;if(codePoint<32)return[8,9,10,12,13].includes(codePoint)?2:6;if(codePoint<128)return 1;if(codePoint<2048)return 2;if(codePoint>=55296&&codePoint<=57343)return 6;return codePoint<65536?3:4}__name(jsonCodePointBytes,"jsonCodePointBytes");function jsonTextBytes(text3){return Buffer.byteLength(JSON.stringify(text3),"utf8")-2}__name(jsonTextBytes,"jsonTextBytes");function cutProviderFitSlot(slot,targetBytes,budgetBytes){const text3=slot.get();const size=jsonTextBytes(text3);if(size<=targetBytes)return;const keep=Math.max(0,targetBytes-jsonTextBytes(providerFitNotice(text3.length,budgetBytes)));let head=0;let headBytes=0;while(head<text3.length){const codePoint=text3.codePointAt(head);const cost=jsonCodePointBytes(codePoint);if(headBytes+cost>Math.ceil(keep/2))break;headBytes+=cost;head+=codePoint>65535?2:1}let tail=text3.length;let tailBytes=0;while(tail>head){let start=tail-1;const unit=text3.charCodeAt(start);if(unit>=56320&&unit<=57343&&start>head){const previous=text3.charCodeAt(start-1);if(previous>=55296&&previous<=56319)start--}const cost=jsonCodePointBytes(text3.codePointAt(start));if(headBytes+tailBytes+cost>keep)break;tailBytes+=cost;tail=start}let omitted=0;for(const _ of text3.slice(head,tail))omitted++;const next=text3.slice(0,head)+providerFitNotice(omitted,budgetBytes)+text3.slice(tail);if(omitted>0&&jsonTextBytes(next)<size)slot.set(next)}__name(cutProviderFitSlot,"cutProviderFitSlot");function providerFitShed(slots,level){return slots.reduce((shed,{bytes,floor})=>shed+Math.max(0,bytes-Math.max(level,floor)),0)}__name(providerFitShed,"providerFitShed");function providerFitLevel(slots,excess){let low=0;let high=slots.reduce((largest,{bytes})=>Math.max(largest,bytes),0);while(low<high){const middle=Math.ceil((low+high)/2);if(providerFitShed(slots,middle)>=excess)low=middle;else high=middle-1}return low}__name(providerFitLevel,"providerFitLevel");function fitManagedRuntimeProviderResult(operation,value,budgetBytes){if(operation.kind!=="execute"&&operation.kind!=="status"&&operation.kind!=="cancel")return value;if(!value||typeof value!=="object"||Array.isArray(value))return value;const root=value;const fits=__name(()=>Buffer.byteLength(JSON.stringify(root),"utf8")<=budgetBytes,"fits");const status=operation.kind==="execute"?void 0:root;const execution2=operation.kind==="execute"?root:status?.["result"];const toolResult=execution2?.["result"];const content=toolResult&&typeof toolResult==="object"&&!Array.isArray(toolResult)?toolResult["llmContent"]:void 0;const mediaResult=(Array.isArray(content)?content:[content]).some(part=>part!==null&&typeof part==="object"&&!Array.isArray(part)&&Object.hasOwn(part,"inlineData"));if(mediaResult){let mediaBytes;try{mediaBytes=managedToolResponseMediaBytes({executionStatus:execution2?.["executionStatus"],result:toolResult},"execute")}catch{throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider returned invalid inline media.")}if(mediaBytes>MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES||Buffer.byteLength(JSON.stringify(toolResult),"utf8")>MAX_PROVIDER_MEDIA_RESULT_BYTES){throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider media result exceeds its admitted budget.")}}if(fits())return value;const progress=status?.["progress"];if(status!==void 0&&Array.isArray(progress)&&progress.length>0){const lastSeq=typeof status["lastSeq"]==="number"?status["lastSeq"]:0;const sizes=progress.map(event=>Buffer.byteLength(JSON.stringify(event),"utf8")+1);let bytes=Buffer.byteLength(JSON.stringify(root),"utf8");let evict=0;while(evict<progress.length&&bytes>budgetBytes)bytes-=sizes[evict++];let retained=progress.slice(evict);while(true){status["progress"]=retained;const first=retained[0];status["firstAvailableSeq"]=first&&typeof first==="object"&&typeof first["seq"]==="number"?first["seq"]:lastSeq+1;status["progressGap"]=true;if(retained.length===0||Buffer.byteLength(JSON.stringify(root),"utf8")<=budgetBytes)break;retained=retained.slice(1)}}if(mediaResult&&execution2){if(!fits()){const hook=execution2["postHook"];if(hook&&typeof hook==="object"&&!Array.isArray(hook)&&typeof hook["shouldStop"]==="boolean"){const fields2=hook;const reason=fields2["stopReason"];const hookError=fields2["hookError"];execution2["postHook"]={shouldStop:fields2["shouldStop"],...typeof reason==="string"?{stopReason:reason}:{},...typeof hookError==="string"?{hookError}:{}}}else{delete execution2["postHook"]}delete execution2["failureHook"];const retained=execution2["postHook"];if(retained){const diagnostics=["stopReason","hookError"].filter(field=>typeof retained[field]==="string").sort((a,b)=>Buffer.byteLength(retained[b],"utf8")-Buffer.byteLength(retained[a],"utf8"));for(const field of diagnostics){if(fits())break;retained[field]=`Runtime Hook ${field} omitted to fit the media response.`}}}if(!fits())throw new ManagedRuntimeProviderProtocolError("Managed Runtime provider media observation exceeds its wire budget.");return value}if(execution2&&!fits()){const measure=__name(()=>providerFitSlots(execution2).map(slot=>({slot,bytes:jsonTextBytes(slot.get()),floor:jsonTextBytes(providerFitNotice(slot.get().length,budgetBytes))})),"measure");let slots=measure();const overflows=__name(()=>Buffer.byteLength(JSON.stringify(root),"utf8")-providerFitShed(slots,0)>budgetBytes,"overflows");const result=execution2["result"];const toolResult2=result&&typeof result==="object"&&!Array.isArray(result)?result:void 0;const display=toolResult2?.["returnDisplay"];if(toolResult2&&display!==void 0&&typeof display!=="string"&&overflows()){toolResult2["returnDisplay"]=PROVIDER_RESULT_STUB;slots=measure()}if(toolResult2&&toolResult2["artifacts"]!==void 0&&overflows())delete toolResult2["artifacts"];if(overflows()){delete execution2["postHook"];delete execution2["failureHook"]}if(!fits()){const level=providerFitLevel(slots,Buffer.byteLength(JSON.stringify(root),"utf8")-budgetBytes);for(const{slot,bytes}of slots)if(bytes>level)cutProviderFitSlot(slot,level,budgetBytes)}}if(!fits()&&execution2){const result=execution2["result"];if(result&&typeof result==="object"&&!Array.isArray(result))result["llmContent"]=PROVIDER_RESULT_STUB}return value}__name(fitManagedRuntimeProviderResult,"fitManagedRuntimeProviderResult");init_esbuild_shims();import path3 from"node:path";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();var range=__name((a,b,str)=>{let begs,beg,left,right=void 0,result;let ai=str.indexOf(a);let bi=str.indexOf(b,ai+1);let i=ai;if(ai>=0&&bi>0){if(a===b){return[ai,bi]}begs=[];left=str.length;while(i>=0&&!result){if(i===ai){begs.push(i);ai=str.indexOf(a,i+1)}else if(begs.length===1){const r=begs.pop();if(r!==void 0)result=[r,bi]}else{beg=begs.pop();if(beg!==void 0&&beg<left){left=beg;right=bi}bi=str.indexOf(b,i+1)}i=ai<bi&&ai>=0?ai:bi}if(begs.length&&right!==void 0){result=[left,right]}}return result},"range");var escSlash="\0SLASH"+Math.random().toFixed(16)+"\0";var escOpen="\0OPEN"+Math.random().toFixed(16)+"\0";var escClose="\0CLOSE"+Math.random().toFixed(16)+"\0";var escComma="\0COMMA"+Math.random().toFixed(16)+"\0";var escPeriod="\0PERIOD"+Math.random().toFixed(16)+"\0";var escSlashPattern=new RegExp(escSlash,"g");var escOpenPattern=new RegExp(escOpen,"g");var escClosePattern=new RegExp(escClose,"g");var escCommaPattern=new RegExp(escComma,"g");var escPeriodPattern=new RegExp(escPeriod,"g");var slashPattern=/\\\\/g;var openPattern=/\\{/g;var closePattern=/\\}/g;var commaPattern=/\\,/g;var periodPattern=/\\\./g;var EXPANSION_MAX=1e5;var EXPANSION_MAX_LENGTH=4e6;var EXPANSION_MAX_DEPTH=1e3;var EXPANSION_MAX_REWRITES=1e3;var EXPANSION_MAX_STEPS=2e7;var CALL_STEPS=16;function numeric(str){return!isNaN(str)?parseInt(str,10):str.charCodeAt(0)}__name(numeric,"numeric");function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}__name(escapeBraces,"escapeBraces");function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}__name(unescapeBraces,"unescapeBraces");function pushAll(target,items){for(let i=0;i<items.length;i++){target.push(items[i])}}__name(pushAll,"pushAll");function balancedWithBudget(str,masked,budget){if(budget.remaining<0){return void 0}const r=range("{","}",masked);const unmatched=r!==void 0&&masked.indexOf("{")<r[0];budget.remaining-=r&&!unmatched?r[1]+1:str.length;if(!r||budget.remaining<0){return void 0}return{end:r[1],pre:str.slice(0,r[0]),body:str.slice(r[0]+1,r[1]),post:str.slice(r[1]+1),unmatched}}__name(balancedWithBudget,"balancedWithBudget");function maskUnmatchedOpens(masked,budget){budget.remaining-=masked.length;const open=[];for(let i=0;i<masked.length;i++){const c=masked.charCodeAt(i);if(c===123){open.push(i)}else if(c===125&&open.length){open.pop()}}let out="";let last=0;for(let i=0;i<open.length;i++){const at=open[i];out+=masked.slice(last,at)+"\0";last=at+1}return out+masked.slice(last)}__name(maskUnmatchedOpens,"maskUnmatchedOpens");function commaSetFollows(str,budget){budget.remaining-=str.length;if(budget.remaining<0){return false}let close=false;for(let i=str.length-1;i>=0;i--){const c=str.charCodeAt(i);if(c===125){close=true}else if(c===10||c===13||c===8232||c===8233){close=false}else if(c===44&&close&&str.charCodeAt(i+1)!==44){return true}}return false}__name(commaSetFollows,"commaSetFollows");function parseCommaParts(str,budget){const parts=[];let carry="";for(;;){const m=balancedWithBudget(str,str,budget);if(budget.remaining<0){return void 0}if(!m){const tail=str.split(",");tail[0]=carry+tail[0];pushAll(parts,tail);return parts}const{pre,body,post}=m;const p=pre.split(",");p[0]=carry+p[0];p[p.length-1]+="{"+body+"}";if(!post.length){pushAll(parts,p);return parts}carry=p.pop();pushAll(parts,p);str=post}}__name(parseCommaParts,"parseCommaParts");function bound(value,fallback){return value===void 0||isNaN(value)?fallback:value}__name(bound,"bound");function expand(str,options={}){if(!str){return[]}const max=bound(options.max,EXPANSION_MAX);const maxLength=bound(options.maxLength,EXPANSION_MAX_LENGTH);const maxDepth=bound(options.maxDepth,EXPANSION_MAX_DEPTH);const maxRewrites=bound(options.maxRewrites,EXPANSION_MAX_REWRITES);const maxSteps=bound(options.maxSteps,EXPANSION_MAX_STEPS);if(str.slice(0,2)==="{}"){str="\\{\\}"+str.slice(2)}return expand_(escapeBraces(str),max,maxLength,maxDepth,0,maxRewrites,{remaining:maxSteps},true).map(unescapeBraces)}__name(expand,"expand");function embrace(str){return"{"+str+"}"}__name(embrace,"embrace");function isPadded(el){return/^-?0\d/.test(el)}__name(isPadded,"isPadded");function lte(i,y){return i<=y}__name(lte,"lte");function gte(i,y){return i>=y}__name(gte,"gte");function combine(acc,pre,values,max,maxLength,dropEmpties,budget){const out=[];let length=0;let nonEmpty;outer:for(let a=0;a<acc.length;a++){const prefix2=acc[a]+pre;let vs=values;if(dropEmpties&&!prefix2){if(!nonEmpty)nonEmpty=values.filter(v=>v);vs=nonEmpty}for(let v=0;v<vs.length;v++){if(out.length>=max)break outer;const expansion=prefix2+vs[v];if(length+expansion.length>maxLength)break outer;out.push(expansion);length+=expansion.length}}budget.remaining-=out.length;return out}__name(combine,"combine");function expandSequence(body,isAlphaSequence,max,maxLength,budget){const n=body.split(/\.\./);const N=[];if(n[0]===void 0||n[1]===void 0){return N}const x=numeric(n[0]);const y=numeric(n[1]);const width=Math.max(n[0].length,n[1].length);let incr=n.length===3&&n[2]!==void 0?Math.max(Math.abs(numeric(n[2])),1):1;let test=lte;const reverse=y<x;if(reverse){incr*=-1;test=gte}const pad=n.some(isPadded);const cost=pad?width:1;let length=0;for(let i=x;test(i,y)&&N.length<max;i+=incr){budget.remaining-=cost;if(budget.remaining<0){return void 0}let c;if(isAlphaSequence){c=String.fromCharCode(i);if(c==="\\"){c=""}}else{c=String(i);if(pad){const need=width-c.length;if(need>0){const z=new Array(need+1).join("0");if(i<0){c="-"+z+c.slice(1)}else{c=z+c}}}}if(length+c.length>maxLength)break;N.push(c);length+=c.length}return N}__name(expandSequence,"expandSequence");function expand_(str,max,maxLength,maxDepth,depth,maxRewrites,budget,isTop){budget.remaining-=CALL_STEPS;if(depth>maxDepth){return[str]}let acc=[""];let rewrites=0;let dropEmpties=false;let firstGroup=true;let masked=str;for(;;){const m=balancedWithBudget(str,masked,budget);if(!m){return combine(acc,str,[""],max,maxLength,dropEmpties,budget)}if(m.unmatched){masked=maskUnmatchedOpens(masked,budget)}const pre=m.pre;const literal2=__name(()=>combine(acc,pre+"{"+m.body+"}"+m.post,[""],max,maxLength,dropEmpties,budget),"literal");if(/\$$/.test(pre)){acc=combine(acc,pre+"{"+m.body+"}",[""],max,maxLength,dropEmpties&&!m.post.length,budget);firstGroup=false;if(!m.post.length)break;str=m.post;masked=masked.slice(m.end+1);continue}const isNumericSequence=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);const isAlphaSequence=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);const isSequence=isNumericSequence||isAlphaSequence;const isOptions=m.body.indexOf(",")>=0;if(!isSequence&&!isOptions){if(rewrites<maxRewrites&&commaSetFollows(m.post,budget)){rewrites++;str=m.pre+"{"+m.body+escClose+m.post;masked=masked.slice(0,m.end)+escClose+masked.slice(m.end+1);isTop=true;continue}return literal2()}if(firstGroup){dropEmpties=isTop&&!isSequence;firstGroup=false}let values;if(isSequence){values=expandSequence(m.body,isAlphaSequence,max,maxLength,budget);if(!values){return literal2()}}else{let n=parseCommaParts(m.body,budget);if(!n){return literal2()}if(n.length===1&&n[0]!==void 0){n=expand_(n[0],max,maxLength,maxDepth,depth+1,maxRewrites,budget,false).map(embrace);if(budget.remaining<0){return literal2()}if(n.length===1){const next2=combine(acc,pre+n[0],[""],max,maxLength,dropEmpties&&!m.post.length,budget);if(budget.remaining<0){return literal2()}acc=next2;if(!m.post.length)break;str=m.post;masked=masked.slice(m.end+1);continue}}let dropsEmpties=dropEmpties&&!m.post.length&&!pre;for(let d=0;dropsEmpties&&d<acc.length;d++){if(acc[d]){dropsEmpties=false}}values=[];let valuesLength=0;outer:for(let j=0;j<n.length;j++){const expanded=expand_(n[j],max,maxLength,maxDepth,depth+1,maxRewrites,budget,false);if(budget.remaining<0){return literal2()}for(let k=0;k<expanded.length;k++){const v=expanded[k];if(dropsEmpties&&!v)continue;if(values.length>=max||valuesLength+v.length>maxLength){break outer}values.push(v);valuesLength+=v.length}}}const next=combine(acc,pre,values,max,maxLength,dropEmpties&&!m.post.length,budget);if(budget.remaining<0){return literal2()}acc=next;if(!m.post.length)break;str=m.post;masked=masked.slice(m.end+1)}return acc}__name(expand_,"expand_");init_esbuild_shims();init_esbuild_shims();var digit=__name((a,b)=>a===b?{t:"lit",ch:String(a)}:{t:"class",re:new RegExp(`^[${a}-${b}]$`)},"digit");var prefix=__name((d,alts)=>alts.map(s=>[digit(d,d),...s]),"prefix");var fixed=__name((a,b)=>{if(!a)return[[]];let lo=+a[0];let hi=+b[0];const ra=a.slice(1);const rb=b.slice(1);if(lo===hi)return prefix(lo,fixed(ra,rb));const zeros="0".repeat(ra.length);const nines="9".repeat(ra.length);const out=[];if(ra!==zeros)out.push(...prefix(lo++,fixed(ra,nines)));const last=rb===nines?[]:prefix(hi--,fixed(zeros,rb));if(lo<=hi){out.push([digit(lo,hi),...Array.from(ra,()=>digit(0,9))])}out.push(...last);return out},"fixed");var nonneg=__name((a,b,width)=>{if(width){return fixed(String(a).padStart(width,"0"),String(b).padStart(width,"0"))}const out=[];for(let len=String(a).length;len<=String(b).length;len++){const lo=Math.max(a,len===1?0:10**(len-1));const hi=Math.min(b,10**len-1);out.push(...fixed(String(lo),String(hi)))}return out},"nonneg");var numericRange=__name((loStr,hiStr)=>{let lo=Number(loStr);let hi=Number(hiStr);if(!Number.isSafeInteger(lo)||!Number.isSafeInteger(hi))return;if(lo>hi)[lo,hi]=[hi,lo];const padded=/^-?0\d/.test(loStr)||/^-?0\d/.test(hiStr);const width=padded?Math.max(loStr.length,hiStr.length):0;const out=[];if(lo<0){const neg=nonneg(Math.max(-hi,1),-lo,width&&width-1);out.push(...neg.map(s=>[{t:"lit",ch:"-"},...s]))}if(hi>=0)out.push(...nonneg(Math.max(lo,0),hi,width));return out},"numericRange");init_esbuild_shims();var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",true],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]};var braceEscape=__name(s=>s.replace(/[[\]\\-]/g,"\\$&"),"braceEscape");var noMatch=/$./;var parseClass=__name((glob,position,nocase=false,form)=>{const norm=__name(c=>{const n=form?c.normalize(form):c;return[...n].length===1?n:c},"norm");const pos=position;if(glob.charAt(pos)!=="["){throw new Error("not in a brace expression")}const ranges=[];const negs=[];let i=pos+1;let sawStart=false;let escaping=false;let negate=false;let endPos=pos;let rangeStart="";WHILE:while(i<glob.length){const c=String.fromCodePoint(glob.codePointAt(i));if((c==="!"||c==="^")&&i===pos+1){negate=true;i++;continue}if(c==="]"&&sawStart&&!escaping){endPos=i+1;break}sawStart=true;if(c==="\\"){if(!escaping){escaping=true;i++;continue}}if(c==="["&&!escaping){for(const[cls,[unip,neg]]of Object.entries(posixClasses)){if(glob.startsWith(cls,i)){if(rangeStart){return[noMatch,glob.length-pos]}i+=cls.length;if(neg)negs.push(unip);else ranges.push(unip);continue WHILE}}}escaping=false;const n=norm(c);if(rangeStart){if(n.codePointAt(0)>rangeStart.codePointAt(0)){ranges.push(braceEscape(rangeStart)+"-"+braceEscape(n))}else if(n===rangeStart){ranges.push(braceEscape(n))}rangeStart="";i+=c.length;continue}if(glob.startsWith("-]",i+c.length)){ranges.push(braceEscape(n+"-"));i+=c.length+1;continue}if(glob.startsWith("-",i+c.length)){rangeStart=n;i+=c.length+1;continue}ranges.push(braceEscape(n));i+=c.length}if(endPos<i){return[noMatch,0]}if(!ranges.length&&!negs.length){return[noMatch,glob.length-pos]}const sranges="["+(negate?"^":"")+ranges.join("")+"]";const snegs="["+(negate?"":"^")+negs.join("")+"]";const comb="^"+(ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs);return[new RegExp(comb,nocase?"iu":"u"),endPos-pos]},"parseClass");var MATCH={t:"match",id:0};var extTypes="!?+*@";var lit=__name(ch=>({t:"lit",ch}),"lit");var reEscape=__name(s=>s.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),"reEscape");var newFoldRe=__name(s=>new RegExp(`^${reEscape(s)}$`,"iu"),"newFoldRe");var foldCache=new Map;var foldRe=__name(ch=>{let re=foldCache.get(ch);if(!re){re=newFoldRe(ch);if(foldCache.size>=1e3)foldCache.clear();foldCache.set(ch,re)}return re},"foldRe");var litMatch=__name((l,c)=>{if(c===l.ch)return true;if(!l.re)return false;const code=c.charCodeAt(0);if(code>=128)return l.re.test(c);const ascii=l.ascii??=new Uint8Array(128);ascii[code]||=l.re.test(c)?1:2;return ascii[code]===1},"litMatch");var tokenize=__name((p,nocase,noext,form,mark)=>{const toks=[];for(let i=0;i<p.length;){const c=String.fromCodePoint(p.codePointAt(i));if(mark){const m=c==="\\"&&p.startsWith(mark,i+1)?1:0;if(m||c===mark){const start=i+m+mark.length;const end=p.indexOf(mark,start);const r=/^(-?\d+)\.\.(-?\d+)$/.exec(p.slice(start,end));const alts=end!==-1&&r&&numericRange(r[1],r[2]);if(alts){toks.push({t:"ext",type:"@",alts});i=end+mark.length;continue}}}if(c==="\\"){const e=p.codePointAt(i+1);const ch=e===void 0?c:String.fromCodePoint(e);toks.push(lit(ch));i+=1+ch.length;continue}if(c==="["){const[re,consumed]=parseClass(p,i,nocase,form);if(consumed){toks.push({t:"class",re});i+=consumed;continue}}if(!noext&&extTypes.includes(c)&&p[i+1]==="("){toks.push({t:"open",type:c});i+=2;continue}toks.push(!noext&&c==="|"?{t:"bar"}:!noext&&c===")"?{t:"close"}:c==="*"?{t:"star"}:c==="?"?{t:"any"}:lit(c));i+=c.length}return toks},"tokenize");var pair=__name(toks=>{const pairs=new Map;const stack=[];toks.forEach((tok,i)=>{if(tok.t==="open")stack.push(i);else if(tok.t==="close"&&stack.length)pairs.set(stack.pop(),i)});return pairs},"pair");var build=__name((toks,pairs,start,end,top)=>{let seq=[];const alts=[seq];for(let i=start;i<end;i++){const tok=toks[i];const close=pairs.get(i);if(tok.t==="open"&&close!==void 0){const sub=build(toks,pairs,i+1,close,false);seq.push({t:"ext",type:tok.type,alts:sub});i=close}else if(tok.t==="bar"&&!top){alts.push(seq=[])}else if(tok.t==="open"){seq.push(lit(tok.type),lit("("))}else if(tok.t==="bar"){seq.push(lit("|"))}else if(tok.t==="close"){seq.push(lit(")"))}else{seq.push(tok)}}return alts},"build");var normalize=__name((items,form)=>{const out=[];let run="";const flush=__name(()=>{for(const ch of run.normalize(form))out.push(lit(ch));run=""},"flush");for(const it of items){if(it.t==="lit"){run+=it.ch;continue}flush();out.push(it.t==="ext"?{...it,alts:it.alts.map(a=>normalize(a,form))}:it)}flush();return out},"normalize");var compile=__name((items,nocase)=>{let id3=1;const split=__name(out=>({t:"split",id:id3++,out}),"split");const seq=__name((items2,next)=>items2.reduceRight((next2,it)=>item(it,next2),next),"seq");const item=__name((it,next)=>{switch(it.t){case"lit":const re=nocase?foldRe(it.ch):void 0;return{t:"lit",id:id3++,ch:it.ch,re,next};case"any":case"star":return{t:it.t,id:id3++,next};case"class":return{t:"class",id:id3++,re:it.re,next}}const alts=__name(next2=>it.alts.map(a=>seq(a,next2)),"alts");switch(it.type){case"@":return split(alts(next));case"?":return split([next,...alts(next)]);case"!":return{t:"neg",id:id3++,sub:split(alts(MATCH)),next}}const after=split([]);const entry=split(alts(after));after.out.push(next,entry);return it.type==="*"?after:entry},"item");const start=seq(items,MATCH);return[start,id3]},"compile");var show=__name(start=>{const lines=[];const seen=new Set;const ref2=__name(n=>n.t==="match"?"match":String(n.id),"ref");const walk=__name((n,indent)=>{if(n.t==="match"||seen.has(n))return;seen.add(n);const line=__name(desc=>lines.push(`${indent}${n.id}: ${desc}`),"line");switch(n.t){case"split":line(`split -> ${n.out.map(ref2).join(", ")}`);for(const o of n.out)walk(o,indent);return;case"neg":line(`!(${ref2(n.sub)}) -> ${ref2(n.next)}`);walk(n.sub,indent+" ");return walk(n.next,indent);case"lit":line(`${JSON.stringify(n.ch)} -> ${ref2(n.next)}`);break;case"class":line(`${n.re} -> ${ref2(n.next)}`);break;default:line(`${n.t==="any"?"?":"*"} -> ${ref2(n.next)}`)}walk(n.next,indent)},"walk");walk(start,"");return[`start -> ${ref2(start)}`,...lines].join("\n")},"show");var State=class{static{__name(this,"State")}gen;threads=[];match=false;runs=[];ids=[];constructor(gen){this.gen=gen}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}};var sameState=__name((a,b)=>{if(a.ids.length!==b.ids.length)return false;if(a.runs.length!==b.runs.length)return false;if(a.ids.some((id3,i)=>id3!==b.ids[i]))return false;return a.runs.every(r=>b.runs.some(o=>o.neg===r.neg&&sameState(o.state,r.state)))},"sameState");var marks=__name(size=>({has:new Float64Array(size),seen:new Float64Array(size),gen:0}),"marks");var Sim=class{static{__name(this,"Sim")}dots;dotStart;#marks;constructor(dots,dotStart,marks2){this.dots=dots;this.dotStart=dotStart;this.#marks=marks2}state(){return new State(++this.#marks.gen)}done(state){state.ids=state.threads.map(n=>n.id).sort((a,b)=>a-b);if(state.match)state.ids.unshift(MATCH.id);return state}#visit(state,node){const{seen}=this.#marks;if(seen[node.id]===state.gen)return false;seen[node.id]=state.gen;return true}#addThread(state,node){const{has}=this.#marks;if(has[node.id]===state.gen)return false;has[node.id]=state.gen;state.threads.push(node);return true}restricted(i,top){return top&&(this.dots||this.dotStart&&i===0)}add(state,node,i,top){switch(node.t){case"split":if(!this.#visit(state,node))return;for(const o of node.out)this.add(state,o,i,top);return;case"neg":if(!this.#visit(state,node))return;const sub=this.state();this.add(sub,node.sub,i,false);this.done(sub);return this.addRun(state,{t:"run",neg:node,state:sub},i,top);case"star":if(this.restricted(i,top))return;if(this.#addThread(state,node))this.add(state,node.next,i,top);return;case"match":state.match=true;return;default:this.#addThread(state,node)}}addRun(state,run,i,top){for(const r of state.runs){if(r.neg===run.neg&&sameState(r.state,run.state))return}state.runs.push(run);if(!run.state.match){this.add(state,run.neg.next,i,top)}}step(state,c,i,top){const next=this.state();for(const th of state.threads){switch(th.t){case"lit":if(litMatch(th,c)){this.add(next,th.next,i+1,top)}break;case"any":if(!this.restricted(i,top))this.add(next,th.next,i+1,top);break;case"class":if(!this.restricted(i,top)&&th.re.test(c)){this.add(next,th.next,i+1,top)}break;case"star":if(!this.restricted(i,top))this.add(next,th,i+1,top)}}if(!this.restricted(i,top)){for(const run of state.runs){if(run.state.dead){this.addRun(next,run,i+1,top);continue}const sub=this.step(run.state,c,i,false);this.addRun(next,{t:"run",neg:run.neg,state:sub},i+1,top)}}return this.done(next)}};var stateKey=__name(state=>{const ids=state.ids.join();if(!state.runs.length)return ids;const runs=state.runs.map(r=>`${r.neg.id}(${stateKey(r.state)})`);return`${ids}|${runs.sort().join("|")}`},"stateKey");var DFA_BUDGET=1<<18;var Dfa=class{static{__name(this,"Dfa")}#start;#states=new Map;#size=0;#plain;#dotStart;#sim;#dotSim;constructor(start,marks2){this.#start=start;this.#sim=new Sim(false,false,marks2);this.#dotSim=new Sim(false,true,marks2)}#make(state){return{state,match:state.match,dead:state.dead,next:new Map}}#intern(state){const key=stateKey(state);const found=this.#states.get(key);if(found)return found;if(this.#size>DFA_BUDGET)this.#clear();const d=this.#make(state);this.#states.set(key,d);this.#size+=key.length+1;return d}#clear(){this.#states.clear();this.#size=0;this.#plain=void 0;this.#dotStart=void 0}start(dotStart){if(dotStart){if(this.#dotStart)return this.#dotStart;const state2=this.#dotSim.state();this.#dotSim.add(state2,this.#start,0,true);return this.#dotStart=this.#make(this.#dotSim.done(state2))}if(this.#plain)return this.#plain;const state=this.#sim.state();this.#sim.add(state,this.#start,0,true);return this.#plain=this.#intern(this.#sim.done(state))}next(d,c){const code=c.charCodeAt(0);const found=code<128?void 0:d.next.get(c);if(found)return found;const n=d===this.#dotStart?this.#intern(this.#dotSim.step(d.state,c,0,true)):this.#intern(this.#sim.step(d.state,c,1,true));if(code<128){if(!d.ascii){d.ascii=new Array(128);this.#size+=128}d.ascii[code]=n}else{d.next.set(c,n)}this.#size++;return n}};var linear=__name(start=>{const nodes=[];for(let n=start;n.t!=="match";n=n.next){if(n.t==="split"||n.t==="neg")return void 0;nodes.push(n)}return nodes},"linear");var testLinear=__name((nodes,chars,start,end)=>{let ni=0;let ci=start;let starNi=-1;let starCi=0;while(ci<end){const n=nodes[ni];if(n?.t==="star"){starNi=ni++;starCi=ci;continue}const c=chars[ci];if(n&&(n.t==="any"||n.t==="lit"&&litMatch(n,c)||n.t==="class"&&n.re.test(c))){ni++;ci++;continue}if(starNi===-1)return false;ni=starNi+1;ci=++starCi}while(nodes[ni]?.t==="star")ni++;return ni===nodes.length},"testLinear");var lengths=__name(items=>{let min=0;let max=0;for(const it of items){const[lo,hi]=itemLengths(it);min+=lo;max+=hi}return[min,max]},"lengths");var itemLengths=__name(it=>{if(it.t==="star")return[0,Infinity];if(it.t!=="ext")return[1,1];if(it.type==="!")return[0,Infinity];const alts=it.alts.map(lengths);const min=Math.min(...alts.map(a=>a[0]));const max=Math.max(...alts.map(a=>a[1]));const loop=max===0?0:Infinity;return it.type==="@"?[min,max]:it.type==="?"?[0,max]:it.type==="*"?[0,loop]:[min,loop]},"itemLengths");var hasAffix=__name((lits,chars,start)=>{for(let j=0;j<lits.length;j++){if(!litMatch(lits[j],chars[start+j]))return false}return true},"hasAffix");var slashOrSurrogate=/[/\ud800-\udfff]/;var surrogate=/[\ud800-\udfff]/;var codePoints=__name(s=>surrogate.test(s)?[...s]:s,"codePoints");var noSlash=__name(s=>{if(s.includes("/")){throw new Error("can only match a single path portion, got: "+s)}},"noSlash");var Matcher=class{static{__name(this,"Matcher")}pattern;options;#start;#size;#marks;#dotsSim;#literal;#literalFold=false;#literalRe;#linear;#wild=false;#min=0;#max=Infinity;#prefix=[];#suffix=[];#prefixStr;#suffixStr;#affix=false;#dfa;#form;constructor(pattern,options={}){if(pattern.includes("/")){throw new Error("can only match a single path portion, got pattern: "+pattern)}this.pattern=pattern;this.options=options;const{nocase=false,noext=false,normalize:n}=options;this.#form=n===true?"NFC":n||void 0;const literal2=/^[?*+@]\(\)$/.test(pattern);const toks=tokenize(pattern,nocase,noext||literal2,this.#form,options.rangeMark);let[items]=build(toks,pair(toks),0,toks.length,true);if(this.#form)items=normalize(items,this.#form);const[start,size]=compile(items,nocase);this.#start=start;this.#size=size;if(items.every(it=>it.t==="lit")){this.#literal=items.map(it=>it.ch).join("");this.#literalFold=nocase}else{const lit2=__name(it=>it.t!=="lit"?void 0:nocase?{ch:it.ch,re:foldRe(it.ch)}:{ch:it.ch},"lit");for(const it of items){const l=lit2(it);if(!l)break;this.#prefix.push(l)}for(let j=items.length-1;j>=0;j--){const l=lit2(items[j]);if(!l)break;this.#suffix.unshift(l)}this.#affix=!!(this.#prefix.length||this.#suffix.length);if(!nocase){this.#prefixStr=this.#prefix.map(l=>l.ch).join("");this.#suffixStr=this.#suffix.map(l=>l.ch).join("")}this.#linear=linear(this.#start)?.slice(this.#prefix.length,-this.#suffix.length||void 0);this.#wild=!!this.#linear?.every(n2=>n2.t==="star"||n2.t==="any");const[min,max]=lengths(items);this.#min=min;this.#max=max}}test(s){if(this.#form){noSlash(s);return this.#test(s.normalize(this.#form))}if(slashOrSurrogate.test(s)){noSlash(s);return this.#test(s,[...s])}return this.#test(s,s)}testUnchecked(s){return this.#test(this.#form?s.normalize(this.#form):s)}#test(s,chars){if(this.#literal!==void 0){return this.#literalFold?(this.#literalRe??=newFoldRe(this.#literal)).test(s):s===this.#literal}const min=this.#min;const max=this.#max;if(chars===void 0){const most=s.length;const least=most+1>>1;if(most<min||least>max)return false;if(least<min||most>max)chars=codePoints(s)}if(chars!==void 0&&(chars.length<min||chars.length>max)){return false}const prefix2=this.#prefix.length;if(this.#affix){if(this.#prefixStr!==void 0&&this.#suffixStr!==void 0){if(!s.startsWith(this.#prefixStr)||!s.endsWith(this.#suffixStr)){return false}}else{chars??=codePoints(s);const end=chars.length-this.#suffix.length;if(!hasAffix(this.#prefix,chars,0)||!hasAffix(this.#suffix,chars,end)){return false}}}const dotStart=!this.options.dot&&s.startsWith(".");if(this.#linear){if(s==="."||s==="..")return false;if(dotStart&&!prefix2)return false;if(this.#wild)return true;chars??=codePoints(s);const end=chars.length-this.#suffix.length;return testLinear(this.#linear,chars,prefix2,end)}chars??=codePoints(s);if(s==="."||s===".."){this.#marks??=marks(this.#size);const sim=this.#dotsSim??=new Sim(true,false,this.#marks);const start=sim.state();sim.add(start,this.#start,0,true);let state=sim.done(start);for(let i=0;i<chars.length;i++){state=sim.step(state,chars[i],i,true)}return state.match}this.#marks??=marks(this.#size);const dfa=this.#dfa??=new Dfa(this.#start,this.#marks);let d=dfa.start(dotStart);const str=chars===s;for(let i=0;i<chars.length;i++){if(d.dead)return false;const code=str?s.charCodeAt(i):chars[i].charCodeAt(0);d=d.ascii?.[code]??dfa.next(d,chars[i])}return d.match}toString(){return show(this.#start)}};init_esbuild_shims();var MAX_PATTERN_LENGTH=1024*64;var assertValidPattern=__name(pattern=>{if(typeof pattern!=="string"){throw new TypeError("invalid pattern")}if(pattern.length>MAX_PATTERN_LENGTH){throw new TypeError("pattern is too long")}},"assertValidPattern");init_esbuild_shims();var escape=__name((s,{windowsPathsNoEscape=false,magicalBraces=false}={})=>{const e=magicalBraces?windowsPathsNoEscape?s.replace(/[?*()[\]{}]/g,"[$&]"):s.replace(/[?*()[\]\\{}]/g,"\\$&"):windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");const c=e.charAt(0);if(c==="#"){return(windowsPathsNoEscape?"[#]":"\\#")+e.slice(1)}if(c==="!"){return(windowsPathsNoEscape?"@(!)":"\\!")+e.slice(1)}return e},"escape");init_esbuild_shims();var unescape=__name((s,{windowsPathsNoEscape=false,magicalBraces=true}={})=>{if(windowsPathsNoEscape&&s.startsWith("@(!)")){return"!"+unescape(s.slice(4),{windowsPathsNoEscape,magicalBraces})}if(magicalBraces){return windowsPathsNoEscape?s.replace(/\[([^/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1")}return windowsPathsNoEscape?s.replace(/\[([^/\\{}])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1")},"unescape");var DEFAULT_BRACE_EXPAND_MAX=1e5;var DEFAULT_GLOB_STAR_RECURSION_MAX=200;var AWE_KEY="allowWindowsEscape";var minimatch=__name((p,pattern,options)=>{assertValidPattern(pattern);if(!options?.nocomment&&pattern.charAt(0)==="#"){return false}return cachedMinimatch(pattern,options).match(p)},"minimatch");var cache=new Map;var oldCache=new Map;var cacheSize=0;var cacheTotalWeight=0;var cacheMax=256;var cacheMaxWeight=1<<15;var cacheMaxEntryWeight=1<<12;var cacheWeight=__name(mm=>{let w=mm.pattern.length;for(const s of mm.globSet){w+=s.length+1;if(w>cacheMaxEntryWeight)break}return w},"cacheWeight");var tri=__name(v=>v===void 0?0:v?2:1,"tri");var booleanWeights=new Map(Object.keys({nobrace:0,nocomment:0,nonegate:0,noglobstar:0,noext:0,nonull:0,partial:0,dot:0,nocase:0,nocaseMagicOnly:0,magicalBraces:0,matchBase:0,flipNegate:0,preserveMultipleSlashes:0,windowsNoMagicRoot:0}).map((k,i)=>[k,24*3**i]));var optionsKey=__name(o=>{let n=0;let wpe=false;for(const k in o){const v=o[k];switch(k){case"windowsPathsNoEscape":if(v)wpe=true;break;case AWE_KEY:if(v===false)wpe=true;break;case"platform":{const p=v||defaultPlatform;if(p===defaultPlatform)break;if(p==="darwin")n+=3;else if(p==="win32")n+=6;else if(p==="linux")n+=9;else return JSON.stringify(o);break}case"optimizationLevel":if(v===void 0)break;n+=v>=2?1:v>=1?0:2;break;case"braceExpandMax":if(v!==void 0&&v!==DEFAULT_BRACE_EXPAND_MAX){return JSON.stringify(o)}break;case"maxGlobstarRecursion":if(v!==void 0&&v!==DEFAULT_GLOB_STAR_RECURSION_MAX){return JSON.stringify(o)}break;case"normalize":if(v!==void 0)return JSON.stringify(o);break;default:n+=(booleanWeights.get(k)??0)*tri(v)}}return wpe?n+12:n},"optionsKey");var copyOptions=__name(o=>{const copy={};for(const k in o)copy[k]=o[k];return copy},"copyOptions");var cachedMinimatch=__name((pattern,options)=>{const key=options?optionsKey(options):0;let mm=cache.get(key)?.get(pattern);if(mm)return mm;mm=oldCache.get(key)?.get(pattern)??new Minimatch(pattern,copyOptions(options));const weight=cacheWeight(mm);if(weight>cacheMaxEntryWeight)return mm;if(cacheSize>=cacheMax||cacheTotalWeight+weight>cacheMaxWeight){oldCache=cache;cache=new Map;cacheSize=0;cacheTotalWeight=0}let byPattern=cache.get(key);if(!byPattern)cache.set(key,byPattern=new Map);byPattern.set(pattern,mm);cacheSize++;cacheTotalWeight+=weight;return mm},"cachedMinimatch");var defaultPlatform=typeof process==="object"&&process?process.env?.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";var path2={win32:{sep:"\\"},posix:{sep:"/"}};var sep=defaultPlatform==="win32"?path2.win32.sep:path2.posix.sep;minimatch.sep=sep;var GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;var filter=__name((pattern,options)=>{let mm;return p=>(mm??=cachedMinimatch(pattern,options)).match(p)},"filter");minimatch.filter=filter;var ext=__name((a,b={})=>Object.assign({},a,b),"ext");var defaults=__name(def=>{if(!def||typeof def!=="object"||!Object.keys(def).length){return minimatch}const orig=minimatch;const m=__name((p,pattern,options={})=>orig(p,pattern,ext(def,options)),"m");return Object.assign(m,{Minimatch:class Minimatch extends orig.Minimatch{static{__name(this,"Minimatch")}constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},unescape:__name((s,options={})=>orig.unescape(s,ext(def,options)),"unescape"),escape:__name((s,options={})=>orig.escape(s,ext(def,options)),"escape"),filter:__name((pattern,options={})=>orig.filter(pattern,ext(def,options)),"filter"),defaults:__name(options=>orig.defaults(ext(def,options)),"defaults"),braceExpand:__name((pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),"braceExpand"),match:__name((list2,pattern,options={})=>orig.match(list2,pattern,ext(def,options)),"match"),sep:orig.sep,GLOBSTAR})},"defaults");minimatch.defaults=defaults;var braceExpand=__name((pattern,options={})=>{assertValidPattern(pattern);if(options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)){return[pattern]}let p=pattern.replace(/\\\\/g,"\\\\\\\\");if(options.windowsPathsNoEscape||options[AWE_KEY]===false){p=p.replace(/\[([{}])\]/g,"[\\$1]")}return expand(p,{max:options.braceExpandMax})},"braceExpand");minimatch.braceExpand=braceExpand;var RANGE_MIN=100;var rangeRe=/(?<![\\$])\{(-?\d+)\.\.(-?\d+)\}/g;var match=__name((list2,pattern,options={})=>{const mm=new Minimatch(pattern,options);list2=list2.filter(f=>mm.match(f));if(mm.options.nonull&&!list2.length){list2.push(pattern)}return list2},"match");minimatch.match=match;var globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;var classEnd=__name((pattern,start)=>{let i=start+1;if(pattern.charAt(i)==="!"||pattern.charAt(i)==="^")i++;let sawStart=false;for(;i<pattern.length;i++){const c=pattern.charAt(i);if(c==="]"&&sawStart)return i;sawStart=true;if(c==="\\")i++}return-1},"classEnd");var literal=__name((pattern,noext)=>{if(!noext&&(pattern==="+()"||pattern==="@()"))return pattern;let lit2="";for(let i=0;i<pattern.length;i++){const c=pattern.charAt(i);if(c==="\\"){lit2+=pattern.charAt(++i)||c}else if(c==="*"||c==="?"){return void 0}else if(c==="["){const close=classEnd(pattern,i);if(close===-1){lit2+=c;continue}let body=pattern.slice(i+1,close);if(body.startsWith("\\"))body=body.slice(1);if([...body].length!==1||"!^".includes(pattern.charAt(i+1))){return void 0}lit2+=body;i=close}else if(!noext&&"+@!".includes(c)&&pattern.charAt(i+1)==="("&&pattern.includes(")",i+2)){return void 0}else{lit2+=c}}return lit2},"literal");var MAX_EXTGLOBS=256;var extglobCount=__name(pattern=>{let n=0;for(let i=0;i<pattern.length-1;i++){const c=pattern.charAt(i);if(c==="\\"){i++}else if("+@!?*".includes(c)&&pattern.charAt(i+1)==="("){n++;i++}}return n},"extglobCount");var assertValidExtglobs=__name(pattern=>{if(extglobCount(pattern)>MAX_EXTGLOBS){throw new TypeError("pattern has too many extglobs")}},"assertValidExtglobs");var extSafe=__name(pattern=>{if(/^[?*+@]\(\)$/.test(pattern)||pattern.includes("[:"))return false;let depth=0;for(let i=0;i<pattern.length;i++){const c=pattern.charAt(i);if(c==="\\"){if(++i===pattern.length)return false}else if(c==="["){const close=classEnd(pattern,i);if(close!==-1)i=close}else if("+@!?*".includes(c)&&pattern.charAt(i+1)==="("){depth++;i++}else if(c===")"){if(!depth--)return false}else if(c==="|"&&!depth){return false}}return!depth},"extSafe");var lastSplit;var lastChecked;var portionMatch=__name((p,f)=>typeof p==="string"?f===p:f!==""&&p.testUnchecked(f),"portionMatch");var endIndex=__name((p,last,lastStart,prev,prevStart)=>portionMatch(p,last)?lastStart:prev!==void 0&&portionMatch(p,prev)?prevStart:-1,"endIndex");var isDots=__name(p=>p==="."||p==="..","isDots");var isDrive=__name(p=>typeof p==="string"&&/^[a-z]:$/i.test(p),"isDrive");var isLongUNC=__name(p=>typeof p==="string"&&/^unc$/i.test(p),"isLongUNC");var uncHost=__name(p=>{if(p[0]!==""||p[1]!=="")return-1;const h=p[2]!=="?"?2:isLongUNC(p[3])?4:-1;const host=p[h];const share=p[h+1];return h!==-1&&host!==void 0&&host!==""&&host!==GLOBSTAR&&share!==void 0&&share!==""&&share!==GLOBSTAR?h:-1},"uncHost");var walkable=__name((p,dot)=>!isDots(p)&&(dot||!p.startsWith(".")),"walkable");var dotPortion=__name((f,start,end,dot,sep2)=>{for(let k=start;k<end;){if(f.charCodeAt(k)===46){if(!dot)return true;const n=f.charCodeAt(k+1)===46?k+2:k+1;if(n>=end||isSep(f.charCodeAt(n),sep2))return true}const s=nextSep(f,k,sep2);if(s===-1)return false;k=s+1;while(k<end&&isSep(f.charCodeAt(k),sep2))k++}return false},"dotPortion");var isSep=__name((c,sep2)=>sep2==="/"?c===47:sep2==="\\"?c===92:c===47||c===92,"isSep");var nextSep=__name((f,from,sep2)=>{if(sep2!=="both")return f.indexOf(sep2,from);const s=f.indexOf("/",from);const b=f.indexOf("\\",from);return s===-1?b:b===-1?s:Math.min(s,b)},"nextSep");var lastSep=__name((f,from,sep2)=>sep2!=="both"?f.lastIndexOf(sep2,from):Math.max(f.lastIndexOf("/",from),f.lastIndexOf("\\",from)),"lastSep");var PENDING={};var Minimatch=class{static{__name(this,"Minimatch")}options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;#endCheck;#literalCheck;#level2;#form;#literals=[];#shapes=[];#endRows=[];#matchers=new Map;#pending=false;#rangeMark;#globstarParts=new WeakMap;constructor(pattern,options={}){assertValidPattern(pattern);options=options||{};this.options=options;this.maxGlobstarRecursion=options.maxGlobstarRecursion??DEFAULT_GLOB_STAR_RECURSION_MAX;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows=this.platform==="win32";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options[AWE_KEY]===false;if(this.windowsPathsNoEscape){this.pattern=this.pattern.replace(/\\/g,"/")}this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.negate=false;this.nonegate=!!options.nonegate;this.comment=false;this.empty=false;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=options.windowsNoMagicRoot!==void 0?options.windowsNoMagicRoot:!!(this.isWindows&&this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.#endCheck=!this.preserveMultipleSlashes;this.#level2=(options.optimizationLevel??1)>=2;const n=options.normalize;this.#form=n===true?"NFC":n||void 0;this.make();const drives=this.set.map(row=>this.#rootIndex(row));this.#endRows=this.set.map((row,r)=>this.#endCheck&&row.length-1>drives[r]);this.#literals=this.set.map((row,r)=>{const end=this.#endRows[r]?row.length-1:row.length;const lits=row.slice(drives[r]+1,end).filter(p=>typeof p==="string"&&!!p);return[...new Set(lits)]});this.#literalCheck=this.#literals.some(l=>l.length);this.#shapes=this.set.map((row,r)=>{const[p0,p1,p2]=row;if(this.#endRows[r]&&row.length===2){if(p0===GLOBSTAR&&p1!==GLOBSTAR)return"tail"}if(this.#endRows[r]&&options.matchBase&&row.length===1&&p0!==GLOBSTAR&&p0!==""){return"base"}if(!this.#endCheck||drives[r]!==-1)return void 0;if(row.length===3&&p0===GLOBSTAR&&p2===GLOBSTAR&&p1!==GLOBSTAR&&p1!==""&&this.maxGlobstarRecursion>0){return"mid"}if(row.length===2&&p1===GLOBSTAR&&p0!==GLOBSTAR&&p0!==""){return"head"}return void 0})}#norm(p){return this.#form?p.normalize(this.#form):p}#rootIndex(row){if(!this.isWindows)return-1;if(isDrive(row[0]))return 0;const uncDrive=row[0]===""&&row[1]===""&&row[2]==="?"&&isDrive(row[3]);if(uncDrive)return 3;const h=uncHost(row);return h===-1?-1:h+1}hasMagic(){if(this.options.magicalBraces&&this.set.length>1){return true}for(const pattern of this.set){for(const part of pattern){if(typeof part!=="string")return true}}return false}make(){const pattern=this.pattern;const options=this.options;if(!options.nocomment&&pattern.charAt(0)==="#"){this.comment=true;return}if(!pattern){this.empty=true;return}this.parseNegate();this.globSet=[...new Set(this.#expandBraces())];const rawGlobParts=this.globSet.map(s=>this.#slashSplit(s));this.globParts=this.preprocess(rawGlobParts);this.#pending=true;let set=this.globParts.map((s,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const n=s[2]==="?"&&isLongUNC(s[3])?6:4;const isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&s.slice(3,n).every(p=>!globMagic.test(p));const isDrive2=/^[a-z]:/i.test(s[0]);if(isUNC){return[...s.slice(0,n).map(p=>this.#norm(p)),...s.slice(n).map(ss=>this.parse(ss))]}else if(isDrive2){return[this.#norm(s[0]),...s.slice(1).map(ss=>this.parse(ss))]}}return s.map(ss=>this.parse(ss))});this.set=set.filter(s=>s.indexOf(false)===-1);if(this.isWindows){for(let i=0;i<this.set.length;i++){const p=this.set[i];if(p[0]===""&&p[1]===""&&this.globParts[i][2]==="?"&&(isDrive(p[3])||isLongUNC(this.globParts[i][3]))){if(isLongUNC(this.globParts[i][3]))p[3]="UNC";p[2]="?"}}}if(!options.noext)this.mergeRows();this.#pending=false;this.set.forEach((row,i)=>{for(let k=0;k<row.length;k++){if(row[k]===PENDING){row[k]=this.parse(this.globParts[i][k])}}})}mergeRows(){let merged=true;while(merged){merged=false;if(this.set.length<2)return;let keys2=this.#mergeKeys();const len=Math.max(0,...this.set.map(r=>r.length));for(let k=0;k<len;k++){const groups=new Map;const R=this.set.length+1;this.set.forEach((row,i)=>{if(!(row[k]instanceof Matcher||row[k]===PENDING)||!extSafe(this.globParts[i][k])){return}const{pre,suf}=keys2[i];const key=pre[k]*R+suf[k+1];const g=groups.get(key);if(g)g.push(i);else groups.set(key,[i])});const drop=new Set;for(const g of groups.values()){if(g.length<2)continue;const[first,...rest]=g;const alts=g.map(i=>this.globParts[i][k]);const glob=`@(${alts.join("|")})`;if(extglobCount(glob)>MAX_EXTGLOBS)continue;this.globParts[first][k]=glob;this.set[first][k]=this.parse(glob);for(const i of rest)drop.add(i)}if(drop.size){merged=true;this.set=this.set.filter((_,i)=>!drop.has(i));this.globParts=this.globParts.filter((_,i)=>!drop.has(i));if(this.set.length<2)return;keys2=this.#mergeKeys()}}}}#mergeKeys(){const partIds=new Map;const ids=this.globParts.map(parts=>parts.map(s=>{let id3=partIds.get(s);if(id3===void 0)partIds.set(s,id3=partIds.size);return id3}));const P=partIds.size;const len=Math.max(0,...ids.map(r=>r.length));const keys2=ids.map(r=>({pre:[0],suf:new Array(r.length+1).fill(0)}));for(let k=0;k<len;k++){const m=new Map;ids.forEach((r,i)=>{if(k>=r.length)return;const{pre}=keys2[i];const key=pre[k]*P+r[k];let id3=m.get(key);if(id3===void 0)m.set(key,id3=m.size+1);pre.push(id3)})}for(let k=len-1;k>=0;k--){const m=new Map;ids.forEach((r,i)=>{if(k>=r.length)return;const{suf}=keys2[i];const key=suf[k+1]*P+r[k];let id3=m.get(key);if(id3===void 0)m.set(key,id3=m.size+1);suf[k]=id3})}return keys2}preprocess(globParts){if(this.options.noglobstar){for(const partset of globParts){for(let j=0;j<partset.length;j++){if(partset[j]==="**"){partset[j]="*"}}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else if(optimizationLevel>=1){globParts=this.levelOneOptimize(globParts)}else{globParts=this.adjascentGlobstarOptimize(globParts)}return globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs=-1;while(-1!==(gs=parts.indexOf("**",gs+1))){let i=gs;while(parts[i+1]==="**"){i++}if(i!==gs){parts.splice(gs,i-gs)}}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>{const root=this.#rootIndex(parts)+1;parts=parts.reduce((set,part)=>{const prev=set[set.length-1];if(part==="**"&&prev==="**"){return set}if(part===".."){if(set.length>root&&prev&&prev!==".."&&prev!=="."&&prev!=="**"){set.pop();return set}}set.push(part);return set},[]);return parts.length===0?[""]:parts})}#canMatch(f){const sep2=!this.isWindows||!f.includes("\\")?"/":f.includes("/")?"both":"\\";let ends=this.#endCheck?0:-1;let last="";let lastStart=0;let prev;let prevStart=0;const dot=!!this.options.dot;ROWS:for(let r=0;r<this.set.length;r++){const row=this.set[r];const p=row[row.length-1];let end=ends!==-1&&this.#endRows[r]&&p!==GLOBSTAR;if(end&&ends===0){const i=lastSep(f,f.length,sep2);lastStart=i+1;last=f.slice(lastStart);if(last===""&&i>=0){let j=i;while(j>0&&isSep(f.charCodeAt(j-1),sep2))j--;prevStart=j===0?0:lastSep(f,j-1,sep2)+1;prev=f.slice(prevStart,j)}const resolves=this.#level2&&(isDots(last)||last===""&&prev!==void 0&&isDots(prev));ends=resolves?-1:1;end=!resolves}let tailStart=-1;if(end&&typeof p==="string"){tailStart=endIndex(p,last,lastStart,prev,prevStart);if(tailStart===-1)continue}if(this.#literalCheck){for(const l of this.#literals[r]){if(!f.includes(l))continue ROWS}}if(end&&typeof p==="object"){tailStart=endIndex(p,last,lastStart,prev,prevStart);if(tailStart===-1)continue}const shape=this.#shapes[r];if(shape==="base"&&end)return"yes";if(shape==="tail"&&end){if(this.#level2&&dotPortion(f,0,tailStart,true,sep2)){return"maybe"}if(!dotPortion(f,0,tailStart,dot,sep2))return"yes";continue}if(shape==="mid"||shape==="head"){const m=this.#walk(f,row,shape==="head",dot,sep2);if(m!=="no")return m;continue}return"maybe"}return"no"}#matchShape(file,row,shape){const dot=!!this.options.dot;const n=file.length;if(shape==="head"){if(n<2||!portionMatch(row[0],file[0])){return false}for(let i=1;i<n;i++)if(!walkable(file[i],dot))return false;return true}const x=row[1];if(shape==="tail"){let t=n-1;if(!portionMatch(x,file[t])){if(file[t]!==""||n===1||!portionMatch(x,file[--t])){return false}}for(let i=0;i<t;i++)if(!walkable(file[i],dot))return false;return true}for(let k=0;k<n;k++){if(portionMatch(x,file[k])&&k+1<n){let i=k+1;while(i<n&&walkable(file[i],dot))i++;if(i===n)return true}if(!walkable(file[k],dot))return false}return false}#walk(f,row,head,dot,sep2){if(this.#level2&&dotPortion(f,0,f.length,true,sep2))return"maybe";const x=row[head?0:1];let s=0;for(let e=nextSep(f,s,sep2);e!==-1;e=nextSep(f,s,sep2)){let next=e+1;while(next<f.length&&isSep(f.charCodeAt(next),sep2))next++;const hit=typeof x==="string"?e-s===x.length&&f.startsWith(x,s):e>s&&x.testUnchecked(f.slice(s,e));if(hit&&!dotPortion(f,next,f.length,dot,sep2))return"yes";if(head||dotPortion(f,s,next,dot,sep2))return"no";s=next}return"no"}#cachedSplit(f){const last=lastSplit;return last?.f===f&&last.isWindows===this.isWindows&&last.preserveMultipleSlashes===this.preserveMultipleSlashes&&last.normalize===this.#form?last:void 0}#split(f){const{isWindows,preserveMultipleSlashes}=this;let parts=this.#slashSplit(isWindows?f.split("\\").join("/"):f);const normalize2=this.#form;if(normalize2)parts=parts.map(p=>p.normalize(normalize2));lastSplit={f,isWindows,preserveMultipleSlashes,normalize:normalize2,parts};return lastSplit}#levelTwoFileOptimize(file){const parts=[...file];let didSomething=false;do{didSomething=false;if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){const p=parts[i];if(i===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i,1);i--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}const root=this.#rootIndex(parts)+1;let dd=root;while(-1!==(dd=parts.indexOf("..",dd+1))){const p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;parts.splice(dd-1,2);dd=Math.max(dd-2,root)}}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){const{braceExpandMax=DEFAULT_BRACE_EXPAND_MAX}=this.options;let splitCells=0;const maxSplitCells=1e6;let didSomething=false;do{didSomething=false;for(let parts of globParts){let gs=-1;while(-1!==(gs=parts.indexOf("**",gs+1))){let gss=gs;while(parts[gss+1]==="**"){gss++}if(gss>gs){parts.splice(gs+1,gss-gs)}let next=parts[gs+1];const p=parts[gs+2];const p2=parts[gs+3];if(next!=="..")continue;if(!p||p==="."||p===".."||!p2||p2==="."||p2===".."){continue}const addedCells=parts.length-1;if(globParts.length>=braceExpandMax||splitCells+addedCells>maxSplitCells){throw new RangeError(`optimizationLevel 2: too many patterns from '**/..'`)}didSomething=true;parts.splice(gs,1);const other=parts.slice(0);other[gs]="**";splitCells+=addedCells;globParts.push(other);gs--}if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){const p=parts[i];if(i===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i,1);i--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}const root=this.#rootIndex(parts)+1;let dd=root;while(-1!==(dd=parts.indexOf("..",dd+1))){const p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;const needDot=dd===1&&parts[dd+1]==="**";const splin=needDot?["."]:[];parts.splice(dd-1,2,...splin);if(parts.length===0)parts.push("");dd=Math.max(dd-2,root)}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){const keys2=new Set;const rows=globParts.filter(parts=>{const key=parts.join("/");if(keys2.has(key))return false;keys2.add(key);return true});const stars=new Map;for(const parts of rows){const s=[];for(let i=0;i<parts.length;i++){if(parts[i]==="*")s.push(i)}if(s.length)stars.set(s.join(","),s)}if(!stars.size||rows.length*stars.size>1e5)return rows;const{dot}=this.options;return rows.filter(parts=>{for(const s of stars.values()){if(s[s.length-1]>=parts.length)continue;const c=[...parts];let ok=true;let changed=false;for(const i of s){const p=parts[i];if(p==="*")continue;if(!p||p==="**"||!dot&&p.startsWith(".")){ok=false;break}c[i]="*";changed=true}if(ok&&changed&&keys2.has(c.join("/")))return false}return true})}parseNegate(){if(this.nonegate)return;const pattern=this.pattern;let negate=false;let negateOffset=0;for(let i=0;i<pattern.length&&pattern.charAt(i)==="!";i++){negate=!negate;negateOffset++}if(negateOffset)this.pattern=pattern.slice(negateOffset);this.negate=negate}#matchRow(file,resolved,pattern,partial){let fileStartIndex=0;let patternStartIndex=0;const fh=this.isWindows?uncHost(resolved):-1;const ph=fh===-1?-1:uncHost(pattern);if(ph!==-1){const host=pattern[ph];const share=pattern[ph+1];if(typeof host!=="string"||typeof share!=="string"){fileStartIndex=fh;patternStartIndex=ph}else if(resolved[fh].toLowerCase()===host.toLowerCase()&&resolved[fh+1].toLowerCase()===share.toLowerCase()){fileStartIndex=fh+2;patternStartIndex=ph+2}}else if(this.isWindows){const fileDrive=typeof file[0]==="string"&&/^[a-z]:$/i.test(file[0]);const fileUNC=!fileDrive&&file[0]===""&&file[1]===""&&file[2]==="?"&&/^[a-z]:$/i.test(file[3]);const patternDrive=typeof pattern[0]==="string"&&/^[a-z]:$/i.test(pattern[0]);const patternUNC=!patternDrive&&pattern[0]===""&&pattern[1]===""&&pattern[2]==="?"&&typeof pattern[3]==="string"&&/^[a-z]:$/i.test(pattern[3]);const fdi=fileUNC?3:fileDrive?0:void 0;const pdi=patternUNC?3:patternDrive?0:void 0;if(typeof fdi==="number"&&typeof pdi==="number"){const[fd,pd]=[file[fdi],pattern[pdi]];if(fd.toLowerCase()===pd.toLowerCase()){patternStartIndex=pdi+1;fileStartIndex=fdi+1}}}file=resolved;if(pattern.includes(GLOBSTAR)){return this.#matchGlobstar(file,pattern,partial,fileStartIndex,patternStartIndex)}return this.#matchOne(file,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file,pattern,partial,fileIndex,patternIndex){const{head,body,tail,segments}=this.#getGlobstarParts(pattern,partial,patternIndex);if(head.length){const headEnd=fileIndex+head.length;if(!this.#matchOne(file,head,partial,fileIndex,0,headEnd)){return false}fileIndex+=head.length;patternIndex+=head.length}let fileTailMatch=0;if(tail.length){if(tail.length+fileIndex>file.length)return false;let tailStart=file.length-tail.length;if(this.#matchOne(file,tail,partial,tailStart,0)){fileTailMatch=tail.length}else{if(file[file.length-1]!==""||fileIndex+tail.length===file.length){return false}tailStart--;if(!this.#matchOne(file,tail,partial,tailStart,0)){return false}fileTailMatch=tail.length+1}}if(!body.length){let sawSome=!!fileTailMatch;for(let i=fileIndex;i<file.length-fileTailMatch;i++){const f=String(file[i]);sawSome=true;if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}}return partial||sawSome}return!!this.#matchGlobStarBodySections(file,segments,file.length-fileTailMatch,fileIndex,0,partial,0,!!fileTailMatch,new Set)}#getGlobstarParts(pattern,partial,patternIndex){let byStart=this.#globstarParts.get(pattern);if(!byStart){byStart=[];this.#globstarParts.set(pattern,byStart)}const key=patternIndex*2+(partial?1:0);const found=byStart[key];if(found)return found;const firstgs=pattern.indexOf(GLOBSTAR,patternIndex);const lastgs=pattern.lastIndexOf(GLOBSTAR);const head=pattern.slice(patternIndex,firstgs);const body=pattern.slice(firstgs+1,partial?void 0:lastgs);const tail=partial?[]:pattern.slice(lastgs+1);const segments=[[[],0]];let current=segments[0];let nonGsParts=0;const nonGsPartsSums=[0];for(const b of body){if(b===GLOBSTAR){nonGsPartsSums.push(nonGsParts);current=[[],0];segments.push(current)}else{current[0].push(b);nonGsParts++}}segments.forEach((b,i)=>{b[1]=nonGsParts-nonGsPartsSums[i]});const parts={head,body,tail,segments};byStart[key]=parts;return parts}#matchGlobStarBodySections(file,bodySegments,fileLength,fileIndex,bodyIndex,partial,globStarDepth,sawTail,tried){const bs=bodySegments[bodyIndex];if(!bs){if(partial){return fileIndex>=fileLength||fileIndex===fileLength-1&&file[fileIndex]===""}for(let i=fileIndex;i<fileLength;i++){sawTail=true;const f=file[i];if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}}return sawTail}const[body,need]=bs;const after=partial?fileLength:fileLength-need;while(fileIndex<=after){const key=bodyIndex*(file.length+1)+fileIndex;if(tried.has(key))return false;tried.add(key);const m=this.#matchOne(file,body,partial,fileIndex,0,fileIndex+body.length);if(m&&globStarDepth<this.maxGlobstarRecursion){const sub=this.#matchGlobStarBodySections(file,bodySegments,fileLength,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail,tried);if(sub!==false){return sub}}if(fileIndex===after)break;const f=file[fileIndex];if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}fileIndex++}return partial||null}#matchOne(file,pattern,partial,fileIndex,patternIndex,fileEnd=file.length){let fi;let pi;let pl;let fl;for(fi=fileIndex,pi=patternIndex,fl=Math.min(fileEnd,file.length),pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){let p=pattern[pi];let f=file[fi];if(p===false||p===GLOBSTAR){return false}if(!portionMatch(p,f))return false}if(fi===fl&&pi===pl){return true}else if(fi===fl){return partial}else if(pi===pl){return fi===fl-1&&file[fi]===""}else{throw new Error("wtf?")}}braceExpand(){return braceExpand(this.pattern,this.options)}#expandBraces(){const{pattern}=this;if(this.options.nobrace)return this.braceExpand();let code=57344;while(pattern.includes(String.fromCharCode(code))){if(++code>63743)return this.braceExpand()}const mark=String.fromCharCode(code);let found=false;const marked=pattern.replace(rangeRe,(m,lo,hi)=>{const a=Number(lo);const b=Number(hi);if(!Number.isSafeInteger(a)||!Number.isSafeInteger(b)||Math.abs(a-b)+1<RANGE_MIN){return m}found=true;return`${mark}${lo}..${hi}${mark}`});if(!found)return this.braceExpand();const set=braceExpand(marked,this.options);for(const p of set){for(const portion of p.split("/")){const c=portion.indexOf("[");if(c!==-1&&c<portion.lastIndexOf(mark)){return this.braceExpand()}}}this.#rangeMark=mark;return set}parse(pattern){assertValidPattern(pattern);const options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";const{nocase,nocaseMagicOnly,noext=false,dot,normalize:normalize2}=options;const rangeMark=this.#rangeMark;const lit2=rangeMark&&pattern.includes(rangeMark)?void 0:literal(pattern,noext);if(lit2!==void 0&&!(nocase&&!nocaseMagicOnly&&pattern.toUpperCase()!==pattern.toLowerCase())){return this.#norm(lit2)}if(this.#pending)return PENDING;let m=this.#matchers.get(pattern);if(!m){if(!noext)assertValidExtglobs(pattern);m=new Matcher(pattern,{nocase,noext,dot,normalize:normalize2,...rangeMark&&{rangeMark}});this.#matchers.set(pattern,m)}return m}#slashSplit(p){if(this.preserveMultipleSlashes){return p.split("/")}else if(this.isWindows&&/^\/\/[^/]+/.test(p)){return["",...p.split(/\/+/)]}else{return p.split(/\/+/)}}match(f,partial=this.partial){if(this.comment){return false}if(this.empty){return f===""}if(f==="/"&&partial){return true}const options=this.options;let split=this.#cachedSplit(f);if(!split){if(!partial&&!this.#form&&(this.#endCheck||this.#literalCheck)&&lastChecked!==f){lastChecked=f;const can=this.#canMatch(f);if(can==="no")return options.flipNegate?false:this.negate;if(can==="yes")return options.flipNegate?true:!this.negate}split=this.#split(f)}const ff=split.parts;const resolved=this.#level2?split.resolved??=this.#levelTwoFileOptimize(ff):ff;const set=this.set;let filename=ff[ff.length-1];if(!filename){for(let i=ff.length-2;!filename&&i>=0;i--){filename=ff[i]}}for(let r=0;r<set.length;r++){const pattern=set[r];const shape=partial?void 0:this.#shapes[r];const hit=shape==="base"?portionMatch(pattern[0],filename):shape?this.#matchShape(resolved,pattern,shape):options.matchBase&&pattern.length===1?this.#matchRow([filename],[filename],pattern,partial):this.#matchRow(ff,resolved,pattern,partial);if(hit){if(options.flipNegate){return true}return!this.negate}}if(options.flipNegate){return false}return this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;var HOSTED_GLOB_PATTERN_MAX_LENGTH=1024;var HOSTED_GLOB_MAX_ALTERNATIVES=64;var MAX_BRACE_DEPTH=8;var SEQUENCE=/^(?:(-?\d+)\.\.(-?\d+)|([a-zA-Z])\.\.([a-zA-Z]))(?:\.\.(-?\d+))?$/;var HOSTED_GLOB_TOO_COMPLEX=`Hosted glob patterns are limited to ${HOSTED_GLOB_PATTERN_MAX_LENGTH} characters, balanced braces and ${HOSTED_GLOB_MAX_ALTERNATIVES} brace alternatives. Split the search into simpler patterns and retry.`;function checkHostedGlobPattern(pattern){if(pattern.length>HOSTED_GLOB_PATTERN_MAX_LENGTH||alternativesBound(pattern)>HOSTED_GLOB_MAX_ALTERNATIVES)return"too-complex";return braceExpand(pattern).some(alternative=>{const shape=unescape(alternative);return path3.isAbsolute(shape)||shape.split(/[\\/]/).includes("..")})?"escapes":"ok"}__name(checkHostedGlobPattern,"checkHostedGlobPattern");function alternativesBound(text3){let index=0;const limit=HOSTED_GLOB_MAX_ALTERNATIVES+1;const sequence2=__name(depth=>{let product=1;while(index<text3.length){const char=text3[index];if(char==="\\"){index+=2}else if(char==="{"){if(depth>=MAX_BRACE_DEPTH)return Infinity;index++;product=Math.min(product*group(depth+1),limit)}else if((char===","||char==="}")&&depth>0){return product}else if(char==="}"){return Infinity}else{index++}}return depth>0?Infinity:product},"sequence");const group=__name(depth=>{const start=index;const items=[sequence2(depth)];while(text3[index]===","){index++;items.push(sequence2(depth))}if(text3[index]!=="}")return Infinity;const body=text3.slice(start,index);index++;if(items.length>1)return Math.min(items.reduce((sum,item)=>sum+item,0),limit);if(items[0]>1||body.includes("{"))return Infinity;const range2=SEQUENCE.exec(body);if(!range2)return 1;if([range2[1],range2[2],range2[5]].some(value=>value!==void 0&&!Number.isSafeInteger(Number(value))))return Infinity;const step=Math.max(Math.abs(Number(range2[5]??1)),1);const span=range2[1]!==void 0?Math.abs(Number(range2[2])-Number(range2[1])):Math.abs(range2[4].charCodeAt(0)-range2[3].charCodeAt(0));if(!Number.isSafeInteger(span))return Infinity;return Math.min(Math.floor(span/step)+1,limit)},"group");return sequence2(0)}__name(alternativesBound,"alternativesBound");init_esbuild_shims();import{createHash as createHash3}from"node:crypto";import{constants}from"node:os";var SEGMENT_BYTES=1024*1024;var SEGMENTS_PER_PAGE=512;function stream(id3){return{id:id3,buffer:Buffer.allocUnsafe(SEGMENT_BYTES),hash:createHash3("sha256"),pages:[],pendingSegments:[],used:0,byteLength:0,ordinal:0,pageOffset:0,pageOrdinal:0,observed:0,ended:false,sealed:false,queue:Promise.resolve()}}__name(stream,"stream");function signalName(value){if(value===null)return null;return Object.entries(constants.signals).find(([name,number])=>name.startsWith("SIG")&&number===value)?.[0]??null}__name(signalName,"signalName");var LocalShellResultCapture=class{constructor(store,resources2,identity,assertWritable=async()=>{}){this.store=store;this.resources=resources2;this.identity=identity;this.assertWritable=assertWritable;if(identity.revision!==1){throw new Error("Foreground Shell capture requires revision 1.")}}static{__name(this,"LocalShellResultCapture")}streams={stdout:stream("stdout"),stderr:stream("stderr")};started=false;processResult=null;failed=false;failureReason=null;finalEnvelope=null;setStarted(_pid){this.started=true}setProcessResult(result){this.processResult=result}setStopRequested(){}failCapture(){this.fail(new Error("Capture transport failed."))}write(id3,chunk){const state=this.streams[id3];state.observed+=chunk.byteLength;return state.queue=state.queue.then(()=>this.append(state,chunk))}async append(state,chunk){if(this.failed||state.ended)return;try{for(let offset=0;offset<chunk.byteLength;){const length=Math.min(SEGMENT_BYTES-state.used,chunk.byteLength-offset);chunk.copy(state.buffer,state.used,offset,offset+length);state.used+=length;offset+=length;if(state.used===SEGMENT_BYTES)await this.publishSegment(state)}}catch(cause){this.fail(cause)}}finish(id3,complete){const state=this.streams[id3];return state.queue=state.queue.then(()=>this.end(state,complete))}async end(state,complete){const id3=state.id;if(state.ended)return;state.ended=true;try{if(!this.failed&&state.used>0)await this.publishSegment(state);if(!this.failed&&complete){const sealed=await this.store.seal({captureId:this.identity.captureId,streamId:id3,segmentCount:state.ordinal,byteLength:state.byteLength,digest:state.hash.copy().digest("hex")});if(sealed.status!=="ok")throw new Error(sealed.code);state.sealed=true}}catch(cause){this.fail(cause)}finally{state.buffer=Buffer.alloc(0);state.used=0}}fail(cause){this.failed=true;this.failureReason=cause instanceof Error&&cause.message==="size_limit"?"size_limit":cause instanceof Error&&cause.message==="quota_exhausted"?"quota_exhausted":"storage_failed"}async publishSegment(state){await this.assertWritable();if(state.ordinal>MANAGED_TOOL_RESULT_LIMITS.maxOrdinal){throw new Error("size_limit")}const bytes=state.buffer.subarray(0,state.used);const published=await this.store.publish({captureId:this.identity.captureId,streamId:state.id,ordinal:state.ordinal,bytes});if(published.status!=="ok")throw new Error(published.code);state.hash.update(bytes);state.byteLength+=bytes.byteLength;state.pendingSegments.push({byteLength:published.result.byteLength,digest:published.result.digest});state.ordinal++;state.used=0;if(state.pendingSegments.length===SEGMENTS_PER_PAGE){await this.publishPage(state)}}async publishPage(state){if(state.pendingSegments.length===0)return;await this.assertWritable();if(state.pages.length>=MANAGED_TOOL_RESULT_LIMITS.maxPagesPerStream){this.failureReason="size_limit";throw new Error("size_limit")}const page=parseToolResultPage({toolResult:MANAGED_TOOL_RESULT_PROTOCOL,type:"page",captureId:this.identity.captureId,streamId:state.id,firstOrdinal:state.pageOrdinal,offset:state.pageOffset,segments:state.pendingSegments});const bytes=Buffer.from(JSON.stringify(page));if(bytes.byteLength>MANAGED_TOOL_RESULT_LIMITS.maxPageBytes){this.failureReason="size_limit";throw new Error("size_limit")}const ref2=await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.page,bytes);const byteLength=state.pendingSegments.reduce((length,segment)=>length+segment.byteLength,0);state.pages.push({ref:ref2,segmentCount:state.pendingSegments.length,byteLength});state.pageOffset+=byteLength;state.pageOrdinal+=state.pendingSegments.length;state.pendingSegments.length=0}async finalize(executionStatus,responseParts,error){if(this.finalEnvelope)return this.finalEnvelope;if(!this.started){this.finalEnvelope={executionStatus:"not_started",responseParts,...error?{error}:{},capture:null};return this.finalEnvelope}if(!this.processResult){throw new Error("Started Shell has no physical outcome.")}if(executionStatus==="not_started"){throw new Error("Started Shell cannot have a not_started result.")}let pagesAvailable=!this.failed;if(pagesAvailable){for(const state of Object.values(this.streams)){try{await this.publishPage(state)}catch(cause){this.fail(cause);pagesAvailable=false;break}}}const contents=pagesAvailable?Object.values(this.streams).map(state=>({streamId:state.id,role:state.id,mimeType:"application/octet-stream",state:state.sealed?"sealed":"incomplete",byteLength:state.byteLength,digest:state.hash.copy().digest("hex"),missingRanges:state.sealed?[]:[{start:state.byteLength,end:null}],body:{pages:state.pages}})):[];const implied=impliedStatus(contents);const captureStatus=implied==="pending"?"partial":implied;const captureReason=captureStatus==="complete"?null:this.failureReason??"producer_lost";let manifestRef=null;try{const manifest=parseToolResultManifest({toolResult:MANAGED_TOOL_RESULT_PROTOCOL,type:"manifest",...this.identity,executionStatus,exitCode:this.processResult.exitCode,signal:signalName(this.processResult.signal),captureScope:"process_pipes",capturePolicy:"complete_required",captureStatus,captureReason,upstreamTruncated:false,contents});const bytes=Buffer.from(JSON.stringify(manifest));if(bytes.byteLength>MANAGED_TOOL_RESULT_LIMITS.maxManifestBytes){throw new Error("size_limit")}await this.assertWritable();manifestRef=await this.resources.publish(MANAGED_TOOL_RESULT_KINDS.manifest,bytes)}catch(cause){this.fail(cause)}const status=manifestRef?captureStatus:"unavailable";this.finalEnvelope={executionStatus,responseParts,...error?{error}:{},capture:{captureStatus:status,captureReason:manifestRef?captureReason:this.failureReason??"storage_failed",manifest:manifestRef,previewTruncated:this.streams.stdout.observed+this.streams.stderr.observed>Math.min(this.processResult.rawOutput.byteLength,3e4),deliveryStatus:"pending"}};return this.finalEnvelope}};init_esbuild_shims();var MANAGED_MCP_TOOL="managed_mcp_call";var MANAGED_MCP_ROUTE="/internal/managed-runtime/v3/mcp";var MANAGED_MCP_MAX_CONNECTIONS=16;init_esbuild_shims();var MANAGED_AUTOMATION_GATE_TOOL="managed_automation_gate";var MANAGED_AUTOMATION_GATE_TIMEOUT_MS=2e4;var ManagedAutomationGateInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"ManagedAutomationGateInvocation")}getDescription(){return`Automation gate: ${this.params.gate}`}async execute(signal,_updateOutput,_shellExecutionConfig,onProcessGroup){const run=createCronGateRunner(this.config,{timeoutMs:MANAGED_AUTOMATION_GATE_TIMEOUT_MS,...onProcessGroup?{onProcessGroup}:{}});const result=await run(this.params.gate,{signal,approvedInProcess:true});return{llmContent:JSON.stringify(result),returnDisplay:`Automation gate ${result.kind}`}}};var ManagedAutomationGateTool=class _ManagedAutomationGateTool extends BaseDeclarativeTool{constructor(config){super(_ManagedAutomationGateTool.Name,"Automation gate","Runs a managed automation definition gate command outside the model. Internal to the Runtime worker.","execute",{type:"object",properties:{gate:{type:"string",description:"The gate command to run in the Session directory."}},required:["gate"]});this.config=config}static{__name(this,"ManagedAutomationGateTool")}static Name=MANAGED_AUTOMATION_GATE_TOOL;validateToolParamValues(params){const error=gateCommandError(params.gate);return error===null?null:`gate ${error}`}createInvocation(params){return new ManagedAutomationGateInvocation(this.config,params)}};function parseManagedAutomationGateResult(responseParts){const first=responseParts[0];const text3=first&&typeof first==="object"&&"text"in first?first.text:void 0;if(typeof text3!=="string")return null;let parsed;try{parsed=JSON.parse(text3)}catch{return null}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)){return null}const result=parsed;const durationMs=typeof result["durationMs"]==="number"&&Number.isFinite(result["durationMs"])?Math.max(0,Math.round(result["durationMs"])):void 0;switch(result["kind"]){case"quiet":return durationMs!==void 0?{kind:"quiet",durationMs}:null;case"output":return typeof result["stdout"]==="string"&&typeof result["truncated"]==="boolean"&&durationMs!==void 0?{kind:"output",stdout:result["stdout"],truncated:result["truncated"],durationMs}:null;case"failed":return typeof result["detail"]==="string"&&typeof result["stderr"]==="string"&&durationMs!==void 0?{kind:"failed",detail:result["detail"],stderr:result["stderr"],durationMs}:null;case"blocked":return typeof result["reason"]==="string"?{kind:"blocked",reason:result["reason"],...typeof result["rule"]==="string"?{rule:result["rule"]}:{}}:null;default:return null}}__name(parseManagedAutomationGateResult,"parseManagedAutomationGateResult");init_esbuild_shims();import{createHash as createHash4,randomUUID}from"node:crypto";import{isDeepStrictEqual as isDeepStrictEqual2}from"node:util";var CSI_NATIVE_READBACK_PATH="/internal/runtime-broker/csi/v1/native:read";var CSI_NATIVE_REQUEST_LIMIT=16*1024;var CSI_NATIVE_RESPONSE_LIMIT=8*1024*1024;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var CONFIG=`sha256:${createHash4("sha256").update("csi-files-retirement-tools/1\0csi-files-retirement-policy/1").digest("hex")}`;var COMMON=["protocolVersion","requestId","action","identity","context","installedContext"];function readCsiNativeRequest(value){const body=closed3(value,[...COMMON,"subject"]);common(body);switch(body["action"]){case"bind":ensure(body["subject"]===null);break;case"prepare":ref(body["subject"],"managed-file_history");break;case"execute":id2(body["subject"]);break;default:throw invalid()}ensure(Buffer.byteLength(JSON.stringify(body))<=CSI_NATIVE_REQUEST_LIMIT);return structuredClone(body)}__name(readCsiNativeRequest,"readCsiNativeRequest");function readCsiNativeResponse(value,request){readCsiNativeRequest(request);const body=closed3(value,[...COMMON,"head","evidence"]);common(body);for(const field of COMMON)ensure(isDeepStrictEqual2(body[field],request[field]));const head=closed3(body["head"],["revision","sequence","digest"]);ensure(counter(head["revision"])>0&&counter(head["sequence"])>0);digest(head["digest"]);const owner=object3(body["identity"])["sessionId"];const evidence=object3(body["evidence"]);switch(body["action"]){case"bind":closed3(evidence,["kind"]);ensure(evidence["kind"]==="ready");break;case"prepare":{closed3(evidence,["kind","intentRef","resources","members"]);ensure(evidence["kind"]==="intent"&&isDeepStrictEqual2(evidence["intentRef"],request.subject));const required=new Map;add(required,ref(evidence["intentRef"],"managed-file_history"));const members=list(evidence["members"]);ensure(members.length>0&&members.length<=4096);let previous=-1;let prompt;let batch;const calls=new Set;const functions=new Set;for(const candidate of members){const member=execution(candidate,owner);const ordinal=counter(member["ordinal"]);ensure(ordinal>previous&&!calls.has(member["callId"])&&!functions.has(member["functionCallId"]));ensure(prompt===void 0||prompt===member["promptId"]&&batch===member["batchId"]);prompt=member["promptId"];batch=member["batchId"];previous=ordinal;calls.add(member["callId"]);functions.add(member["functionCallId"]);add(required,ref(member["inputRef"],"managed-tool-input"));add(required,ref(member["toolDefinitionRef"],"managed-tool-definition"))}resources(evidence["resources"],required);break}case"execute":{closed3(evidence,["kind","executionReference","preparedRef","authorizationRevision","authorizationSequence","grant","resources"]);ensure(evidence["kind"]==="authorization");const reference=execution(evidence["executionReference"],owner);const required=new Map;const inputRef=ref(reference["inputRef"],"managed-tool-input");add(required,inputRef);add(required,ref(reference["toolDefinitionRef"],"managed-tool-definition"));const prepared=evidence["preparedRef"];if(prepared!==null)add(required,ref(prepared,"managed-file_history"));const grant=readCsiNativeGrant(evidence["grant"]);ensure(grant["executionCallId"]===request.subject&&isDeepStrictEqual2(grant["executionReference"],reference)&&isDeepStrictEqual2(grant["preparedRef"],prepared));for(const field of["authorizationRevision","authorizationSequence"]){const count=counter(evidence[field]);ensure(count===grant[field]&&count<=counter(head[field==="authorizationRevision"?"revision":"sequence"]))}for(const field of["identity","context","installedContext"])ensure(isDeepStrictEqual2(grant[field],body[field]));const bytes=resources(evidence["resources"],required);const input=closed3(parseManagedCsiFileJson(bytes.get(inputRef.resourceId),64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure(input["harnessSessionId"]===owner&&input["runtimeSessionId"]===owner&&typeof input["payloadJson"]==="string");ensure(`sha256:${createHash4("sha256").update(input["payloadJson"]).digest("hex")}`===reference["argsDigest"]);const payload=closed3(parseManagedSessionRecordJson(input["payloadJson"],64*1024),["toolName","input"]);if(prepared===null)ensure(payload["toolName"]==="read_file");break}default:throw invalid()}ensure(Buffer.byteLength(JSON.stringify(body))<=CSI_NATIVE_RESPONSE_LIMIT);return structuredClone(body)}__name(readCsiNativeResponse,"readCsiNativeResponse");function readCsiNativeGrant(value){const grant=closed3(value,["protocolVersion","runtimeBindingId","bindingGeneration","authorizedBindingVersion","executionCallId","dispatchGeneration","authorizationRevision","authorizationSequence","executionReference","intent","checkpointRef","preparedRef","identity","context","installedContext"]);ensure(grant["protocolVersion"]===1);commonContext(grant);id2(grant["runtimeBindingId"]);id2(grant["executionCallId"]);execution(grant["executionReference"],object3(grant["identity"])["sessionId"]);for(const field of["bindingGeneration","authorizedBindingVersion","dispatchGeneration"])ensure(isCanonicalDecimalText(grant[field]));for(const field of["authorizationRevision","authorizationSequence"])ensure(counter(grant[field])>0);const intent=closed3(grant["intent"],["revision","sequence"]);ensure(counter(intent["revision"])>0&&counter(intent["sequence"])>0&&counter(intent["revision"])<counter(grant["authorizationRevision"])&&counter(intent["sequence"])<counter(grant["authorizationSequence"]));ref(grant["checkpointRef"],"managed-checkpoint");if(grant["preparedRef"]!==null)ref(grant["preparedRef"],"managed-file_history");return grant}__name(readCsiNativeGrant,"readCsiNativeGrant");function common(value){ensure(value["protocolVersion"]===1);uuid(value["requestId"]);commonContext(value)}__name(common,"common");function commonContext(value){const identity=closed3(value["identity"],["profile","sessionId","capabilityDigest"]);ensure(matchesCsiFilesProfile(identity["profile"],identity["capabilityDigest"]));uuid(identity["sessionId"]);const context=closed3(value["context"],["protocolVersion","managedContext","runtimeInstanceId","runtimeIncarnation","leaseId","epoch","provisionRequestId","tenantId","workspaceId","workspaceGeneration","storageId","mountRoot","capabilityDigest","isolationClass"]);ensure(context["protocolVersion"]===3&&context["isolationClass"]==="session"&&context["capabilityDigest"]===identity["capabilityDigest"]);const{protocolVersion:_version,...fields2}=context;parseManagedContextBoot({...fields2,type:"boot",version:2,token:"validation-token"});const installed=closed3(value["installedContext"],["protocolVersion","managedContext","operationId","sessionId","contextDigest","binding"]);ensure(installed["protocolVersion"]===3&&installed["managedContext"]==="managed-context/1"&&installed["sessionId"]===identity["sessionId"]);const owner=identity["sessionId"];const hash=createHash4("md5").update(owner).digest();hash[6]=hash[6]&15|48;hash[8]=hash[8]&63|128;const hex=hash.toString("hex");ensure(installed["operationId"]===`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`);const binding=closed3(installed["binding"],["tenantId","workspaceId","workspaceGeneration","storageId","cwdRelative","contextConfigRef","contextRevision"]);for(const field of["tenantId","workspaceId","workspaceGeneration","storageId"])ensure(binding[field]===context[field]);ensure(binding["cwdRelative"]==="."&&binding["contextRevision"]==="1"&&binding["contextConfigRef"]===CONFIG);ensure(computeManagedContextDigest(binding)===installed["contextDigest"])}__name(commonContext,"commonContext");function execution(value,owner){const result=closed3(value,["sessionId","promptId","callId","argsDigest","batchId","functionCallId","partIndex","ordinal","inputRef","toolDefinitionRef","dispatchMode"]);ensure(result["sessionId"]===owner&&result["dispatchMode"]==="deferred");for(const field of["promptId","callId","batchId"])uuid(result[field]);id2(result["functionCallId"]);digest(result["argsDigest"],true);counter(result["partIndex"]);counter(result["ordinal"]);ensure(ref(result["inputRef"],"managed-tool-input").resourceId!==ref(result["toolDefinitionRef"],"managed-tool-definition").resourceId);return result}__name(execution,"execution");function resources(value,required){const result=new Map;for(const candidate of list(value)){const entry=closed3(candidate,["reference","bytesBase64"]);const reference=object3(entry["reference"]);const resourceId=id2(reference["resourceId"]);ensure(required.has(resourceId)&&isDeepStrictEqual2(required.get(resourceId),reference));ensure(typeof entry["bytesBase64"]==="string");const encoded=entry["bytesBase64"];const bytes=Buffer.from(encoded,"base64");ensure(bytes.toString("base64")===encoded&&bytes.length<=64*1024&&bytes.length===reference["byteLength"]&&createHash4("sha256").update(bytes).digest("hex")===reference["digest"]&&!result.has(resourceId));result.set(resourceId,bytes)}ensure(result.size===required.size);return result}__name(resources,"resources");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"CSI native resource");ensure(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:64*1024));return result}__name(ref,"ref");function add(required,reference){const previous=required.get(reference.resourceId);ensure(previous===void 0||isDeepStrictEqual2(previous,reference));required.set(reference.resourceId,reference)}__name(add,"add");function counter(value){ensure(Number.isSafeInteger(value)&&value>=0);return value}__name(counter,"counter");function id2(value){return assertManagedSessionStableId(value,"CSI native identity")}__name(id2,"id");function digest(value,prefix2=false){ensure(typeof value==="string"&&(prefix2?/^sha256:[0-9a-f]{64}$/:/^[0-9a-f]{64}$/).test(value))}__name(digest,"digest");function uuid(value){ensure(typeof value==="string"&&UUID.test(value))}__name(uuid,"uuid");function list(value){ensure(Array.isArray(value));return value}__name(list,"list");function object3(value){ensure(value!==null&&typeof value==="object"&&!Array.isArray(value));return value}__name(object3,"object");function closed3(value,keys2){const result=object3(value);ensure(isDeepStrictEqual2(Object.keys(result).sort(),[...keys2].sort()));return result}__name(closed3,"closed");function ensure(condition){if(!condition)throw invalid()}__name(ensure,"ensure");function invalid(){return new Error("Invalid private CSI native readback.")}__name(invalid,"invalid");async function readCurrentCsiNative(boot,installedContext,action,subject){if(boot.version!==5&&boot.version!==6)throw invalid();const request=readCsiNativeRequest({protocolVersion:1,requestId:randomUUID(),action,identity:boot.identity,context:createManagedContextAttestationResponse(boot.context),installedContext,subject});const response=await fetch(`${boot.authority.origin}${CSI_NATIVE_READBACK_PATH}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{authorization:`Bearer ${boot.context.token}`,"content-type":"application/json","cache-control":"no-store"},body:JSON.stringify(request)});ensure(response.status===200&&response.headers.get("content-encoding")===null&&response.headers.get("cache-control")==="no-store"&&response.headers.get("content-type")?.split(";")[0].trim()==="application/json");const reader=response.body?.getReader();if(!reader)throw invalid();const chunks=[];let length=0;try{while(true){const next=await reader.read();if(next.done)break;length+=next.value.length;ensure(length<=CSI_NATIVE_RESPONSE_LIMIT);chunks.push(next.value)}}finally{await reader.cancel();reader.releaseLock()}return readCsiNativeResponse(parseManagedCsiFileJson(Buffer.concat(chunks),CSI_NATIVE_RESPONSE_LIMIT),request)}__name(readCurrentCsiNative,"readCurrentCsiNative");init_esbuild_shims();import{isDeepStrictEqual as isDeepStrictEqual3}from"node:util";import{createHash as createHash5}from"node:crypto";var CSI_FILE_HISTORY_PATH="/internal/managed-runtime/csi/v2/file-history";function readCsiPreparationEvidence(response){ensure2(response.action==="prepare");const owner=response.identity["sessionId"];ensure2(typeof owner==="string");const evidence=response.evidence;ensure2(evidence["kind"]==="intent"&&Array.isArray(evidence["resources"])&&Array.isArray(evidence["members"]));const resources2=new Map;for(const candidate of evidence["resources"]){const item=object4(candidate);const ref2=object4(item["reference"]);ensure2(typeof ref2["resourceId"]==="string"&&typeof item["bytesBase64"]==="string");resources2.set(ref2["resourceId"],Buffer.from(item["bytesBase64"],"base64"))}const originalRef=object4(evidence["intentRef"]);ensure2(typeof originalRef["resourceId"]==="string");const bytes=resources2.get(originalRef["resourceId"]);ensure2(bytes!==void 0);const body=closed4(parseManagedCsiFileJson(bytes,64*1024),["operationId","revision","previousRecordRef","schemaVersion","profile","runtimeSessionId","state","backupDirectory","retainedBackups","preparation","record"]);ensure2(body["schemaVersion"]===2&&body["profile"]===response.identity["profile"]&&body["runtimeSessionId"]===owner);const preparation=closed4(body["preparation"],["stage","turnId","promptId","batchId","invocations","paths"]);ensure2(preparation["stage"]==="intent"&&preparation["turnId"]===preparation["promptId"]&&Array.isArray(preparation["invocations"])&&Array.isArray(preparation["paths"])&&preparation["invocations"].length===evidence["members"].length);const paths=new Set;for(const[index,candidate]of preparation["invocations"].entries()){const invocation=closed4(candidate,["executionCallId","callId","functionCallId","toolName","partIndex","ordinal","requestDigest","inputRef","toolDefinitionRef"]);ensure2(typeof invocation["executionCallId"]==="string"&&invocation["executionCallId"].length>0);const member=object4(evidence["members"][index]);ensure2(isDeepStrictEqual3(member,{sessionId:owner,promptId:preparation["promptId"],batchId:preparation["batchId"],callId:invocation["callId"],functionCallId:invocation["functionCallId"],partIndex:invocation["partIndex"],ordinal:invocation["ordinal"],argsDigest:invocation["requestDigest"],inputRef:invocation["inputRef"],toolDefinitionRef:invocation["toolDefinitionRef"],dispatchMode:"deferred"}));const inputRef=object4(invocation["inputRef"]);ensure2(typeof inputRef["resourceId"]==="string");const inputBytes=resources2.get(inputRef["resourceId"]);ensure2(inputBytes!==void 0);const wrapper=closed4(parseManagedCsiFileJson(inputBytes,64*1024),["harnessSessionId","runtimeSessionId","payloadJson"]);ensure2(wrapper["harnessSessionId"]===owner&&wrapper["runtimeSessionId"]===owner&&typeof wrapper["payloadJson"]==="string");ensure2(`sha256:${createHash5("sha256").update(wrapper["payloadJson"]).digest("hex")}`===invocation["requestDigest"]);const payload=closed4(parseManagedSessionRecordJson(wrapper["payloadJson"],64*1024),["toolName","input"]);ensure2(payload["toolName"]===invocation["toolName"]&&["read_file","write_file","edit"].includes(String(invocation["toolName"])));const file=historyPath(object4(payload["input"])["file_path"]);if(invocation["toolName"]!=="read_file")paths.add(file)}ensure2(paths.size>0&&isDeepStrictEqual3([...paths].sort(),preparation["paths"]));return{preparation:structuredClone(preparation),observation:readCsiFileHistoryObservation({state:body["state"],backupDirectory:body["backupDirectory"],retainedBackups:body["retainedBackups"]},owner)}}__name(readCsiPreparationEvidence,"readCsiPreparationEvidence");function readCsiFileHistoryOperation(value){const operation=object4(value);closed4(operation,["kind","version","action",...operation["action"]==="prepare"?["preparationRef"]:[]]);ensure2(operation["kind"]==="csi-file-history"&&operation["version"]===1);ensure2(["bind","snapshot","prepare"].includes(String(operation["action"])));if(operation["action"]==="prepare"){const reference=assertManagedSessionDurableRef(operation["preparationRef"],"CSI preparation");ensure2(reference.kind==="managed-file_history"&&reference.schemaVersion===1&&reference.byteLength>0&&reference.byteLength<=64*1024)}return structuredClone(operation)}__name(readCsiFileHistoryOperation,"readCsiFileHistoryOperation");function readCsiFileHistoryEnvelope(value,boot,installedContext){const body=closed4(value,["protocolVersion","managedCsi","identity","context","installedContext","operation"]);ensure2((boot.version===5||boot.version===6)&&body["protocolVersion"]===2&&body["managedCsi"]===MANAGED_CSI_FILE_PROTOCOL);ensure2(isDeepStrictEqual3(body["identity"],boot.identity)&&isDeepStrictEqual3(body["context"],createManagedContextAttestationResponse(boot.context))&&isDeepStrictEqual3(body["installedContext"],installedContext));readCsiNativeRequest({protocolVersion:1,requestId:"00000000-0000-4000-8000-000000000000",action:"bind",identity:boot.identity,context:body["context"],installedContext,subject:null});return readCsiFileHistoryOperation(body["operation"])}__name(readCsiFileHistoryEnvelope,"readCsiFileHistoryEnvelope");function readCsiFileHistoryObservation(value,owner){const body=closed4(value,["state","backupDirectory","retainedBackups"]);const state=parseHostedFileHistoryState(body["state"],owner);const directory=closed4(body["backupDirectory"],["volumeDevice","volumeInode","directoryDevice","directoryInode"]);for(const value2 of Object.values(directory))decimal(value2);ensure2(directory["volumeDevice"]===directory["directoryDevice"]);ensure2(Array.isArray(body["retainedBackups"]));const pins=new Map;let previous="";for(const candidate of body["retainedBackups"]){const pin=closed4(candidate,["name","device","inode","byteLength","digest","mode"]);const name=pin["name"];ensure2(typeof name==="string"&&name.length>0&&name.length<=256&&name!=="."&&name!==".."&&!/[/\\]/.test(name)&&[...name].every(char=>char.charCodeAt(0)>31&&char.charCodeAt(0)!==127)&&name>previous);decimal(pin["device"]);decimal(pin["inode"]);ensure2(pin["device"]===directory["volumeDevice"]);ensure2(Number.isSafeInteger(pin["byteLength"])&&pin["byteLength"]>=0&&pin["byteLength"]<Number.MAX_SAFE_INTEGER);ensure2(Number.isSafeInteger(pin["mode"])&&pin["mode"]>=0&&pin["mode"]<=4095);ensure2(typeof pin["digest"]==="string"&&/^[0-9a-f]{64}$/.test(pin["digest"]));pins.set(name,structuredClone(pin));previous=name}const names=new Set;for(const snapshot of state.snapshots){ensure2(snapshot.promptId.normalize("NFC")===snapshot.promptId&&Buffer.byteLength(snapshot.promptId)<=512&&[...snapshot.promptId].every(char=>char.charCodeAt(0)>31&&(char.charCodeAt(0)<127||char.charCodeAt(0)>159)));for(const backup of Object.values(snapshot.trackedFileBackups)){ensure2(backup.failed!==true&&backup.version<Number.MAX_SAFE_INTEGER);if(backup.backupFileName!==null){ensure2(pins.has(backup.backupFileName));names.add(backup.backupFileName)}}}ensure2(names.size===pins.size);return{state,backupDirectory:structuredClone(directory),retainedBackups:[...pins.values()]}}__name(readCsiFileHistoryObservation,"readCsiFileHistoryObservation");function decimal(value){ensure2(typeof value==="string"&&/^(?:0|[1-9][0-9]*)$/.test(value)&&value.length<=20&&BigInt(value)<=18446744073709551615n)}__name(decimal,"decimal");function object4(value){ensure2(value!==null&&typeof value==="object"&&!Array.isArray(value));return value}__name(object4,"object");function closed4(value,keys2){const body=object4(value);ensure2(isDeepStrictEqual3(Object.keys(body).sort(),[...keys2].sort()));return body}__name(closed4,"closed");function ensure2(condition){if(!condition)throw new Error("Invalid private CSI file history.")}__name(ensure2,"ensure");function csiHistoryContentDigest(content){const canonical=__name(value=>{if(Array.isArray(value))return`[${value.map(canonical).join(",")}]`;if(value!==null&&typeof value==="object")return`{${Object.keys(value).sort().map(key=>`${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;const result=JSON.stringify(value);ensure2(result!==void 0);return result},"canonical");const semantic={...content};delete semantic["record"];return createHash5("sha256").update(canonical(semantic)).digest("hex")}__name(csiHistoryContentDigest,"csiHistoryContentDigest");init_esbuild_shims();var MANAGED_HOOK_ROUTE="/internal/managed-runtime/v3/hooks";var MANAGED_HOOK_MAX_RUNNING=16;var MANAGED_HOOK_MAX_REQUEST_BYTES=8*1024*1024;export{parseManagedSkillContent,ManagedMcpRecipeError,parseManagedMcpRecipe,MANAGED_PACKAGE_COMPILER_VERSION,MANAGED_PACKAGE_MAX_ARCHIVE_BYTES,ManagedPackageCompatibilityError,listManagedPackageFiles,compileManagedExtensionPackage,prepareManagedExtensionPackage,MANAGED_HOOK_ROUTE,MANAGED_HOOK_MAX_RUNNING,MANAGED_HOOK_MAX_REQUEST_BYTES,MAX_PROVIDER_INLINE_MEDIA_BASE64_BYTES,MAX_PROVIDER_MEDIA_RESULT_BYTES,MANAGED_RUNTIME_PROVIDER_ROUTE,MANAGED_WORKSPACE_CONTEXT_FILES,MANAGED_WORKSPACE_CONTEXT_FILE_CHARS,ManagedRuntimeProviderProtocolError,managedRuntimeProviderLimit,parseManagedRuntimeProviderRequest,parseManagedRuntimeProviderResult,fitManagedRuntimeProviderResult,WORKSPACE_CONTEXT_CONFIG_REF,WORKSPACE_CAPABILITY_DIGEST,MEASURED_WORKSPACE_CAPABILITY_DIGEST,isWorkspaceToolCapability,RESIDENT_WORKSPACE_CAPABILITY_DIGEST,resolveManagedShellPublisherMode,WORKSPACE_ACTIVATION_ROUTE,WorkspaceActivations,minimatch,HOSTED_GLOB_TOO_COMPLEX,checkHostedGlobPattern,LocalShellResultCapture,MANAGED_MCP_TOOL,MANAGED_MCP_ROUTE,MANAGED_MCP_MAX_CONNECTIONS,MANAGED_AUTOMATION_GATE_TOOL,MANAGED_AUTOMATION_GATE_TIMEOUT_MS,ManagedAutomationGateTool,parseManagedAutomationGateResult,CSI_FILES_RETIREMENT_CAPABILITY_DIGEST,CSI_FILES_DIAGNOSTICS_CAPABILITY_DIGEST,CSI_FILES_ACTIVITY_CAPABILITY_DIGEST,isCsiFilesCapability,readHostedCsiFileProfile,matchesCsiFilesProfile,MANAGED_CSI_PROTOCOL,MANAGED_CSI_ATTEST_PATH,MANAGED_CSI_DRAIN_PATH,MANAGED_CSI_ACK_PATH,MANAGED_CSI_ACK_LIMIT_BYTES,ManagedCsiAckRequestError,parseManagedCsiAckJson,parseManagedCsiAcknowledgement,parseManagedCsiCaptureIdentity,parseManagedCsiAckRequest,parseManagedCsiAckResponse,ManagedCsiDrainRequestError,parseManagedCsiDrainRequest,validateManagedCsiAttestationRequest,validateManagedCsiPodIdentity,validateManagedCsiAttestationResponse,linuxDeviceNumber,parseManagedCsiBoot,MANAGED_CSI_FILE_PROTOCOL,MANAGED_CSI_FILE_PREFIX,CSI_FILE_FINALIZATION_FORMAT,MANAGED_CSI_FILE_ROUTES,parseManagedCsiFileJson,parseManagedCsiFileBoot,createManagedCsiFileReady,wrapManagedCsiFileContext,readManagedCsiFileContext,validateManagedCsiFileAttestationRequest,validateManagedCsiFileAttestationResponse,readManagedCsiFileDrain,CSI_NATIVE_RESPONSE_LIMIT,readCsiNativeRequest,readCsiNativeGrant,readCurrentCsiNative,CSI_FILE_HISTORY_PATH,readCsiPreparationEvidence,readCsiFileHistoryEnvelope,readCsiFileHistoryObservation,csiHistoryContentDigest};
6
6
  /**