@qwen-code/qwen-code 0.26.2-preview.0 → 0.26.2-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/chunks/{MaxSizedBox-K6YUM3DX.js → MaxSizedBox-EGHZ2BPF.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-75IC33SN.js → StandaloneSessionPicker-UVCW6YW3.js} +1 -1
  3. package/chunks/{acp-subagent-executor-3NHBJRPL.js → acp-subagent-executor-AQ7AWSD4.js} +1 -1
  4. package/chunks/{acpAgent-JT6KQPTH.js → acpAgent-IV7JAGD7.js} +3 -3
  5. package/chunks/{advisor-TI2UVEZK.js → advisor-UZ4TF65D.js} +1 -1
  6. package/chunks/{agent-SWIZZZMY.js → agent-CNLVAWDD.js} +1 -1
  7. package/chunks/{agent-headless-USWEJ4GW.js → agent-headless-ZJUJLUJS.js} +1 -1
  8. package/chunks/{agent-host-client-ZFIMQX33.js → agent-host-client-SN5V2KBH.js} +1 -1
  9. package/chunks/{agent-host-connections-LOFD7O7Q.js → agent-host-connections-VKMAJIIU.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-HMLEI4FI.js → anthropicContentGenerator-QTJVPAMI.js} +1 -1
  11. package/chunks/{autofix-pr-NKR2VSLB.js → autofix-pr-U7GNSH27.js} +1 -1
  12. package/chunks/{batch-JQZ3TOHA.js → batch-MBEWETXN.js} +1 -1
  13. package/chunks/{bridge-EIWWT4P6.js → bridge-TEJLNYV3.js} +1 -1
  14. package/chunks/{channel-settings-store-FLRLUA67.js → channel-settings-store-QNCKWWBL.js} +1 -1
  15. package/chunks/{chunk-244YTFYD.js → chunk-23KDY7UW.js} +1 -1
  16. package/chunks/{chunk-7TDMQJTD.js → chunk-2DWWSMTV.js} +1 -1
  17. package/chunks/{chunk-UU2LTNSF.js → chunk-3IZMVLVZ.js} +1 -1
  18. package/chunks/{chunk-B6T4ESBM.js → chunk-3JI7IKJL.js} +1 -1
  19. package/chunks/{chunk-Y5TT2G3N.js → chunk-427MARCP.js} +1 -1
  20. package/chunks/{chunk-KX7JS2P7.js → chunk-4NNNGSQY.js} +3 -3
  21. package/chunks/{chunk-6TQS2WQO.js → chunk-4RM7KY3Z.js} +2 -2
  22. package/chunks/{chunk-YL3N2UGG.js → chunk-5X7S4AE6.js} +5 -5
  23. package/chunks/{chunk-K2HAY5PY.js → chunk-5XAECBED.js} +1 -1
  24. package/chunks/{chunk-VCHFBETO.js → chunk-66KKSLUO.js} +1 -1
  25. package/chunks/{chunk-BSJR2KEF.js → chunk-6CIIDUZW.js} +1 -1
  26. package/chunks/{chunk-22CLK7PK.js → chunk-7EBRMQYW.js} +1 -1
  27. package/chunks/{chunk-J4TFGZ4A.js → chunk-7FSC2NKA.js} +1 -1
  28. package/chunks/{chunk-6JFC5M6B.js → chunk-A5TAAMML.js} +1 -1
  29. package/chunks/{chunk-DHHACQVN.js → chunk-AOYSX44A.js} +1 -1
  30. package/chunks/{chunk-VFVZ2DY7.js → chunk-AZCMQ3DD.js} +2 -2
  31. package/chunks/{chunk-BQJXWIMR.js → chunk-B6F7CVBP.js} +1 -1
  32. package/chunks/{chunk-OVPEAKOQ.js → chunk-BDQOLT37.js} +1 -1
  33. package/chunks/{chunk-5SYUBQNO.js → chunk-BIWEUAKG.js} +1 -1
  34. package/chunks/{chunk-BZM66PQO.js → chunk-BJ5R7LOM.js} +1 -1
  35. package/chunks/{chunk-4R2OHBH3.js → chunk-BKUFRNME.js} +1 -1
  36. package/chunks/{chunk-NIYWNFVF.js → chunk-BNZSPX2I.js} +1 -1
  37. package/chunks/{chunk-FJV2ECNY.js → chunk-D2URRVOK.js} +1 -1
  38. package/chunks/{chunk-GT6CHVAI.js → chunk-DANP7CMW.js} +1 -1
  39. package/chunks/{chunk-FHFLD4DR.js → chunk-DBHLRZGI.js} +1 -1
  40. package/chunks/{chunk-Y2UXZJLM.js → chunk-DL7TKH2E.js} +2 -2
  41. package/chunks/{chunk-MCQE2U7N.js → chunk-DOWKH5OZ.js} +6 -6
  42. package/chunks/{chunk-UHRLBY3C.js → chunk-DPHQJPCU.js} +1 -1
  43. package/chunks/{chunk-PV2VT25U.js → chunk-DPNGBOI7.js} +1 -1
  44. package/chunks/{chunk-NCDNF7UJ.js → chunk-DXRXF4QD.js} +1 -1
  45. package/chunks/{chunk-OCVRMNEQ.js → chunk-DZ3GV34J.js} +1 -1
  46. package/chunks/{chunk-3QIAXWWW.js → chunk-EU2MKUK4.js} +1 -1
  47. package/chunks/{chunk-KMAVI6FB.js → chunk-EVBUXPGM.js} +1 -1
  48. package/chunks/{chunk-BVSTV4JM.js → chunk-F3ZRU2SA.js} +1 -1
  49. package/chunks/{chunk-TBZY477Y.js → chunk-FCZYH27X.js} +1 -1
  50. package/chunks/{chunk-JCOK67LT.js → chunk-FNDMWG43.js} +1 -1
  51. package/chunks/{chunk-5SF32OGU.js → chunk-GDXLJJSW.js} +1 -1
  52. package/chunks/{chunk-SO6FCPRI.js → chunk-GZYIXB7Y.js} +1 -1
  53. package/chunks/{chunk-WZPTWC7X.js → chunk-HHNAH4IH.js} +1 -1
  54. package/chunks/{chunk-7KCAOXNL.js → chunk-HOKROBQZ.js} +1 -1
  55. package/chunks/{chunk-34ZBUQJV.js → chunk-IGPAATQW.js} +1 -1
  56. package/chunks/{chunk-2ZTRKK2O.js → chunk-INFBJDWM.js} +1 -1
  57. package/chunks/{chunk-IEJ2CGRN.js → chunk-J3R7ZNSA.js} +1 -1
  58. package/chunks/{chunk-KT5MPRYB.js → chunk-JCRS367I.js} +1 -1
  59. package/chunks/{chunk-7JWJTRP6.js → chunk-JFVXZFMV.js} +1 -1
  60. package/chunks/{chunk-47LP4MBD.js → chunk-JKMGS2VD.js} +1 -1
  61. package/chunks/{chunk-WRJ3PMDZ.js → chunk-JUQ7T2MV.js} +1 -1
  62. package/chunks/{chunk-NZX3UWNF.js → chunk-KQ4TDFNE.js} +1 -1
  63. package/chunks/{chunk-X7D4VKMX.js → chunk-L6BKKN42.js} +1 -1
  64. package/chunks/{chunk-YG5HVFMY.js → chunk-L7Y6MOHS.js} +1 -1
  65. package/chunks/{chunk-UFTIUKD4.js → chunk-LGYXZJI3.js} +1 -1
  66. package/chunks/{chunk-JQGGILML.js → chunk-LPOEVTKD.js} +1 -1
  67. package/chunks/{chunk-5KI55A6S.js → chunk-LRXS7ZI2.js} +1 -1
  68. package/chunks/{chunk-CKVHEYXW.js → chunk-LYYVSCNL.js} +1 -1
  69. package/chunks/{chunk-LIIMQ4DI.js → chunk-LZNBHBAJ.js} +6 -6
  70. package/chunks/{chunk-H4GDEXMF.js → chunk-M3C6RDGC.js} +1 -1
  71. package/chunks/{chunk-KKKUB3RQ.js → chunk-MNVMHVQJ.js} +1 -1
  72. package/chunks/{chunk-2B3W7IQY.js → chunk-MVGQFFIK.js} +1 -1
  73. package/chunks/{chunk-Q35A2RGO.js → chunk-NC7BCZPQ.js} +1 -1
  74. package/chunks/{chunk-2ZOTG3NW.js → chunk-NE627MUW.js} +1 -1
  75. package/chunks/{chunk-W4P2EN3V.js → chunk-NZNRCPGE.js} +1 -1
  76. package/chunks/{chunk-YPDQJQ3S.js → chunk-P3M4WWRA.js} +1 -1
  77. package/chunks/{chunk-DVB36ASH.js → chunk-P534ONQN.js} +1 -1
  78. package/chunks/{chunk-EL5J4ESB.js → chunk-QF44NNSC.js} +1 -1
  79. package/chunks/{chunk-IQPJOBPI.js → chunk-QHGCDHNW.js} +1 -1
  80. package/chunks/{chunk-EVZC4KEQ.js → chunk-QWJX7NIP.js} +1 -1
  81. package/chunks/{chunk-J2TJL2F4.js → chunk-S53G54DW.js} +2 -2
  82. package/chunks/{chunk-3A6LFJJV.js → chunk-SMNFL3AD.js} +1 -1
  83. package/chunks/{chunk-WDO3K3P2.js → chunk-TOBNWST4.js} +1 -1
  84. package/chunks/{chunk-AVGJ4HE3.js → chunk-TQSBUHAM.js} +1 -1
  85. package/chunks/{chunk-ABUS7DNN.js → chunk-TW5QEP2J.js} +1 -1
  86. package/chunks/{chunk-WYM4Z4D5.js → chunk-UEB2F43V.js} +1 -1
  87. package/chunks/{chunk-FUUPMVD2.js → chunk-UPPE4I6H.js} +1 -1
  88. package/chunks/{chunk-UHBJVFZA.js → chunk-US42COBM.js} +1 -1
  89. package/chunks/{chunk-RMQNBSMK.js → chunk-UUY6XSQI.js} +1 -1
  90. package/chunks/{chunk-UVQUQNCA.js → chunk-UZI3IA27.js} +1 -1
  91. package/chunks/{chunk-SXJ2E33J.js → chunk-V6VMUJ47.js} +1 -1
  92. package/chunks/{chunk-5UFCNJGN.js → chunk-VG2ZINTO.js} +1 -1
  93. package/chunks/{chunk-JPPPJ2GN.js → chunk-VJI6MHWX.js} +1 -1
  94. package/chunks/{chunk-AUI7WVSU.js → chunk-VOBNHBCJ.js} +1 -1
  95. package/chunks/{chunk-3BNJDZHU.js → chunk-VUEZWMI4.js} +1 -1
  96. package/chunks/{chunk-LMNKCL55.js → chunk-W7ZX6WB3.js} +2 -2
  97. package/chunks/{chunk-HVS6V2UZ.js → chunk-WA2LKUVP.js} +1 -1
  98. package/chunks/{chunk-7APLU2XE.js → chunk-WFFCJ5PF.js} +1 -1
  99. package/chunks/{chunk-3TD4WAG5.js → chunk-WQY5GE65.js} +1 -1
  100. package/chunks/{chunk-3YWRMF6C.js → chunk-WSESLSKK.js} +1 -1
  101. package/chunks/{chunk-NILCQMZ7.js → chunk-XFJV5NYT.js} +1 -1
  102. package/chunks/{chunk-LGBGUITT.js → chunk-XIYLRIW4.js} +1 -1
  103. package/chunks/{chunk-KS74L67R.js → chunk-XQ2NYKJH.js} +1 -1
  104. package/chunks/{chunk-JB2NOB6W.js → chunk-Y3VRWG52.js} +1 -1
  105. package/chunks/{chunk-GVZ6D2NL.js → chunk-YBISME5B.js} +1 -1
  106. package/chunks/{chunk-2C2253QI.js → chunk-YJNWPSB3.js} +1 -1
  107. package/chunks/{chunk-O2T3GQ6F.js → chunk-YWVV5STA.js} +1 -1
  108. package/chunks/{chunk-MAQZSOHI.js → chunk-ZH4J3FL6.js} +1 -1
  109. package/chunks/{chunk-THNEKTPK.js → chunk-ZSKCF6DI.js} +1 -1
  110. package/chunks/{chunk-Z7BAHKO5.js → chunk-ZW6456SD.js} +1 -1
  111. package/chunks/{chunk-DMSZ2TB3.js → chunk-ZWM3LLT7.js} +1 -1
  112. package/chunks/{codex-subagent-executor-DQ5LQQWO.js → codex-subagent-executor-DWWT7246.js} +1 -1
  113. package/chunks/{config-utils-CY6HLKZ5.js → config-utils-NGZB522W.js} +1 -1
  114. package/chunks/{contextCommand-SGBWI7O6.js → contextCommand-7QCW2YNX.js} +1 -1
  115. package/chunks/{core-runtime-4DP27LCC.js → core-runtime-PSVNDJPD.js} +1 -1
  116. package/chunks/{create-sub-session-ECPDZMBX.js → create-sub-session-JTSEMEJE.js} +1 -1
  117. package/chunks/{cron-create-OO4OG3EI.js → cron-create-VGIDTUMX.js} +1 -1
  118. package/chunks/{daemon-git-worktree-guard-OYDNHT7P.js → daemon-git-worktree-guard-IQRGS7IH.js} +1 -1
  119. package/chunks/{daemon-status-provider-JGDLXPC6.js → daemon-status-provider-R4MYCYPG.js} +1 -1
  120. package/chunks/{daemon-trust-policy-5HRARS54.js → daemon-trust-policy-VAUKFZ2N.js} +1 -1
  121. package/chunks/{daemon-trust-policy-monitor-RM7FVIIC.js → daemon-trust-policy-monitor-E5HIO6RP.js} +1 -1
  122. package/chunks/{deferred-core-runtime-3CXBZIOG.js → deferred-core-runtime-FLOFQJPU.js} +1 -1
  123. package/chunks/{edit-DJPESAAY.js → edit-OOVQUGKV.js} +1 -1
  124. package/chunks/{enterPlanMode-IHBLRIF3.js → enterPlanMode-AUWVTQLT.js} +1 -1
  125. package/chunks/{environment-JN5SD347.js → environment-RM5OXYP4.js} +1 -1
  126. package/chunks/{errors-NUJCME3Y.js → errors-CLDJGHVD.js} +1 -1
  127. package/chunks/{execution-tool-I3SWG6I3.js → execution-tool-JFBVOKPW.js} +1 -1
  128. package/chunks/{execution-worker-62UZMAMJ.js → execution-worker-MNJZD72W.js} +1 -1
  129. package/chunks/{exitPlanMode-JIC4V3FE.js → exitPlanMode-PC6XG4TW.js} +1 -1
  130. package/chunks/{fast-path-NIOIL5YI.js → fast-path-V4DN3CRZ.js} +1 -1
  131. package/chunks/{glob-EQ4QNAHF.js → glob-DTZROBDS.js} +1 -1
  132. package/chunks/{goal-tools-DYTTSBQG.js → goal-tools-FUVGTY33.js} +1 -1
  133. package/chunks/{handleAutoUpdate-44BTG5L5.js → handleAutoUpdate-U4LVTHGU.js} +1 -1
  134. package/chunks/{i18n-FTHZAHCT.js → i18n-XOKNDFYP.js} +1 -1
  135. package/chunks/{initializer-MSGKXC75.js → initializer-XBR5J4CY.js} +1 -1
  136. package/chunks/{installationInfo-4XJMJJYU.js → installationInfo-4AOEOUI6.js} +1 -1
  137. package/chunks/{interactive-mod-session-DFLRYO2Q.js → interactive-mod-session-YGZK2JK2.js} +1 -1
  138. package/chunks/{list-ODZ7Z6VI.js → list-TCGKVPH4.js} +1 -1
  139. package/chunks/{llm-O64DHKP7.js → llm-SKFTN5UN.js} +4 -4
  140. package/chunks/{llm-content-generator-SK24I6QS.js → llm-content-generator-GWHXT3WS.js} +1 -1
  141. package/chunks/{loadedSettingsAdapter-6PEBUZT5.js → loadedSettingsAdapter-ZALZGZE7.js} +1 -1
  142. package/chunks/{local-ED3UEKWP.js → local-RWTWYS5Z.js} +1 -1
  143. package/chunks/{local-execution-environment-PUKES5LO.js → local-execution-environment-R6JWLD65.js} +1 -1
  144. package/chunks/{loggingContentGenerator-UHOJVSRR.js → loggingContentGenerator-UJV6QFOY.js} +1 -1
  145. package/chunks/{loop-wakeup-NSJQETPZ.js → loop-wakeup-BU2RRYHA.js} +1 -1
  146. package/chunks/{manage-memory-5RRB6FLH.js → manage-memory-XI57JN4T.js} +1 -1
  147. package/chunks/{managed-execution-engine-MZAP7SK6.js → managed-execution-engine-BA5PABMP.js} +1 -1
  148. package/chunks/{managed-local-serve-XMES3HXL.js → managed-local-serve-MFKN22K6.js} +1 -1
  149. package/chunks/{managed-npm-update-R5KGY7G2.js → managed-npm-update-ZGN43NUA.js} +1 -1
  150. package/chunks/{managed-runtime-attestation-worker-O2KNHHV6.js → managed-runtime-attestation-worker-YN2VBGYN.js} +1 -1
  151. package/chunks/{managed-runtime-bootstrap-HOTLM6DE.js → managed-runtime-bootstrap-SGQVMUJE.js} +1 -1
  152. package/chunks/{managed-runtime-session-worker-QZX44ZTD.js → managed-runtime-session-worker-4UMF3VBY.js} +1 -1
  153. package/chunks/{managed-runtime-ssh-worker-U425WQ65.js → managed-runtime-ssh-worker-7XA6KRBN.js} +1 -1
  154. package/chunks/{managed-session-authority-THHDHCBP.js → managed-session-authority-IJGYAOEL.js} +1 -1
  155. package/chunks/{mcp-AR7EK4WY.js → mcp-V3L7B5YK.js} +1 -1
  156. package/chunks/{memory-C2TSF6BK.js → memory-3T6FPNAK.js} +1 -1
  157. package/chunks/{model-call-collection-25WR55OH.js → model-call-collection-WTTITWWM.js} +1 -1
  158. package/chunks/{model-configuration-KC7DQGKV.js → model-configuration-T6SSGI4J.js} +1 -1
  159. package/chunks/{modelConfigUtils-QEHMVLSQ.js → modelConfigUtils-TQA25QJC.js} +1 -1
  160. package/chunks/{monitor-PDQUZD23.js → monitor-5ZAOJSEE.js} +1 -1
  161. package/chunks/{nonInteractiveCli-WY2YFONU.js → nonInteractiveCli-YFINLVA7.js} +1 -1
  162. package/chunks/{nonInteractiveToolExecutor-7RJZYPHJ.js → nonInteractiveToolExecutor-DE3WACL5.js} +1 -1
  163. package/chunks/{notebook-edit-P4ITXF5H.js → notebook-edit-UK6HBRO3.js} +1 -1
  164. package/chunks/{omni-AYUPB2QM.js → omni-65LF5QK4.js} +1 -1
  165. package/chunks/{openaiContentGenerator-V5IK4ITO.js → openaiContentGenerator-HX7NCSV5.js} +1 -1
  166. package/chunks/{openaiResponsesContentGenerator-DYDH6KWT.js → openaiResponsesContentGenerator-CFA6U6Y5.js} +1 -1
  167. package/chunks/{pidfile-INPBL2DK.js → pidfile-ZVKJUNTZ.js} +1 -1
  168. package/chunks/{processUtils-J4UDEDS4.js → processUtils-VS6CJT7E.js} +1 -1
  169. package/chunks/{prompt-terminal-ledger-QLOQWHYE.js → prompt-terminal-ledger-UF5RDB57.js} +1 -1
  170. package/chunks/{qwenContentGenerator-RU43XKKB.js → qwenContentGenerator-GM3ZSI7E.js} +1 -1
  171. package/chunks/{reactive-degrade-2Q3Z3KAR.js → reactive-degrade-TSAQWZ5F.js} +1 -1
  172. package/chunks/{read-file-472BQ25I.js → read-file-J267NT45.js} +1 -1
  173. package/chunks/{resumeHistoryUtils-7SUFKZDC.js → resumeHistoryUtils-IM46VFDV.js} +1 -1
  174. package/chunks/{review-WX52IWJR.js → review-4B64XTCL.js} +1 -1
  175. package/chunks/{ripGrep-4GPGLKAM.js → ripGrep-YLOSXO7P.js} +1 -1
  176. package/chunks/{run-qwen-serve-MXK4RBKL.js → run-qwen-serve-SAHEC44O.js} +1 -1
  177. package/chunks/{runtime-WHU3AGFT.js → runtime-SJDZHV6J.js} +1 -1
  178. package/chunks/{sandboxConfig-7DBXEQJH.js → sandboxConfig-47EXXMUA.js} +1 -1
  179. package/chunks/{scheduled-tasks-O5RV6G6U.js → scheduled-tasks-E6RCTUUS.js} +1 -1
  180. package/chunks/{scheduler-HLMS5LR5.js → scheduler-SE3IWIWA.js} +1 -1
  181. package/chunks/{search-memory-PYND7ZX3.js → search-memory-2W7VJC4Q.js} +1 -1
  182. package/chunks/{send-message-TMLYTQOI.js → send-message-63YGQP6G.js} +1 -1
  183. package/chunks/{serve-EBNBRAME.js → serve-F4ML2WNL.js} +1 -1
  184. package/chunks/{server-63BRDBL5.js → server-S56IB4TT.js} +3 -3
  185. package/chunks/{session-XB6J4CZD.js → session-2CUVLZ4H.js} +1 -1
  186. package/chunks/{session-attachments-root-PFK475N2.js → session-attachments-root-FINBX7K5.js} +1 -1
  187. package/chunks/{session-execution-engine-selector-P6TJTCKR.js → session-execution-engine-selector-UGC7DGUN.js} +1 -1
  188. package/chunks/{session-pr-refresh-PM7VAQTV.js → session-pr-refresh-KQLQ4MZY.js} +1 -1
  189. package/chunks/{sessionService-PO3LLZIZ.js → sessionService-Q6N7LF7Z.js} +1 -1
  190. package/chunks/{settings-JDQSRXP3.js → settings-23I6H76E.js} +1 -1
  191. package/chunks/{shell-JCEX3HKM.js → shell-IUECEVVY.js} +1 -1
  192. package/chunks/{skill-JSZBONIZ.js → skill-YKUETMPC.js} +1 -1
  193. package/chunks/{skill-settings-YGFG6GPN.js → skill-settings-ODYXOPCA.js} +1 -1
  194. package/chunks/{spawnChannel-VIIWSWTL.js → spawnChannel-7XU2SRWZ.js} +1 -1
  195. package/chunks/{standalone-update-2UU6FQZL.js → standalone-update-SWI2RL3L.js} +1 -1
  196. package/chunks/{start-opentui-ui-OSZZNSLY.js → start-opentui-ui-T53QJGCH.js} +1 -1
  197. package/chunks/{startInteractiveUI-FFH66MYH.js → startInteractiveUI-USTZGQOE.js} +1 -1
  198. package/chunks/{team-create-TKGDJ3NU.js → team-create-4A2XUE3D.js} +1 -1
  199. package/chunks/{team-plan-approval-3VJF4G6Z.js → team-plan-approval-4TS5CYN6.js} +1 -1
  200. package/chunks/{terminal-image-renderer-T3VJRZGP.js → terminal-image-renderer-C7553YV6.js} +1 -1
  201. package/chunks/{theme-manager-ZGUFLFUI.js → theme-manager-GTW75GOO.js} +1 -1
  202. package/chunks/{tool-call-3EQS5KSE.js → tool-call-YTUMWL3A.js} +1 -1
  203. package/chunks/{tool-result-media-7LFNVQ6E.js → tool-result-media-JYOYBX4J.js} +1 -1
  204. package/chunks/{tool-search-UDZ4S7T5.js → tool-search-Y4XTT2WF.js} +1 -1
  205. package/chunks/{total-session-admission-U4MII4RA.js → total-session-admission-EMJ5NRGL.js} +1 -1
  206. package/chunks/{trustedFolders-2NQJCIN3.js → trustedFolders-YG6WAVRE.js} +1 -1
  207. package/chunks/{update-relaunch-YKLWSCLC.js → update-relaunch-4QYQRCP4.js} +1 -1
  208. package/chunks/{updateCheck-YDLTQQRU.js → updateCheck-VRFPSX4G.js} +1 -1
  209. package/chunks/{upload-config-5QQKWF4O.js → upload-config-UCKGUYYQ.js} +1 -1
  210. package/chunks/{useAutoAcceptIndicator-AJS4WTU2.js → useAutoAcceptIndicator-2VGLKD7B.js} +1 -1
  211. package/chunks/{validateNonInterActiveAuth-AETOT7ZW.js → validateNonInterActiveAuth-GGMQXKKU.js} +1 -1
  212. package/chunks/{version-IB6DLRAG.js → version-Y46PG7II.js} +1 -1
  213. package/chunks/{web-fetch-LS3QARNR.js → web-fetch-7MPU555L.js} +1 -1
  214. package/chunks/{web-search-FGHRIVEB.js → web-search-HU2CL2X2.js} +1 -1
  215. package/chunks/{workflow-FX6XNETQ.js → workflow-U3D34QQX.js} +1 -1
  216. package/chunks/{workflow-ancestor-trust-5XXBGN6F.js → workflow-ancestor-trust-OWC4YTMR.js} +1 -1
  217. package/chunks/{workspace-agents-UJKLYPUK.js → workspace-agents-KHLAWSAR.js} +1 -1
  218. package/chunks/{workspace-providers-status-4JOHMTAW.js → workspace-providers-status-T57SE3YX.js} +1 -1
  219. package/chunks/{workspace-recovery-worker-XFEYQ4TP.js → workspace-recovery-worker-VYQ723ZE.js} +1 -1
  220. package/chunks/{workspace-registration-store-LWAPVNYC.js → workspace-registration-store-I7PR3A2Y.js} +1 -1
  221. package/chunks/{workspace-registry-M7OC376O.js → workspace-registry-YYUBXCLH.js} +1 -1
  222. package/chunks/{workspace-runtime-coordinator-CYHIL47L.js → workspace-runtime-coordinator-5ICAQO7W.js} +1 -1
  223. package/chunks/{workspace-service-43VZZ56B.js → workspace-service-YROWXOLQ.js} +1 -1
  224. package/chunks/{workspace-skills-status-V2TT6UJQ.js → workspace-skills-status-DKKQDTZJ.js} +1 -1
  225. package/chunks/{workspace-trust-reconciler-YZ4AG5ZW.js → workspace-trust-reconciler-3FPMUZDO.js} +1 -1
  226. package/chunks/{write-file-TGEH5MEZ.js → write-file-7QQVYFDT.js} +1 -1
  227. package/chunks/{zoom-image-TT6R7H2H.js → zoom-image-WL5EB6Q7.js} +1 -1
  228. package/cli.js +2 -2
  229. package/execution-worker.js +1 -1
  230. package/export-transcript-document.js +1 -1
  231. package/package.json +3 -3
  232. package/web-shell/assets/{PierreFilePreview-OsApm5-S.js → PierreFilePreview-BZ17f56_.js} +1 -1
  233. package/web-shell/assets/{SpreadsheetPreview-I1v1EzV7.js → SpreadsheetPreview-Bvkvr_5u.js} +1 -1
  234. package/web-shell/assets/{WorkspaceFileBrowser-BO6aug7i.js → WorkspaceFileBrowser-BJ_I4Uoz.js} +1 -1
  235. package/web-shell/assets/{abnfDiagram-VCTEODGH-DxuLMyN0.js → abnfDiagram-VCTEODGH-iuaBM15V.js} +1 -1
  236. package/web-shell/assets/{agents-route-CSJf6QPO.js → agents-route-CycwfNSC.js} +1 -1
  237. package/web-shell/assets/{arc-3--LekYQ.js → arc-C0lt8n55.js} +1 -1
  238. package/web-shell/assets/{architectureDiagram-5GKGNRK7-Dihq4uto.js → architectureDiagram-5GKGNRK7-Bw326d-A.js} +1 -1
  239. package/web-shell/assets/{blockDiagram-NRAW4CY4-BnaRPM2o.js → blockDiagram-NRAW4CY4-CHtFgBjV.js} +1 -1
  240. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BtC94eMa.js → c4Diagram-UCG6FXSJ-Bx66oJT9.js} +1 -1
  241. package/web-shell/assets/channel-CRJuO00u.js +1 -0
  242. package/web-shell/assets/{chunk-2Q5K7J3B-2ZTXWP6M.js → chunk-2Q5K7J3B-BIshvfa_.js} +1 -1
  243. package/web-shell/assets/{chunk-5VM5RSS4-DBh7DP1F.js → chunk-5VM5RSS4-BZeRS6uD.js} +1 -1
  244. package/web-shell/assets/{chunk-F27PBJKO-xzqbWXBw.js → chunk-F27PBJKO-El-CGY2R.js} +1 -1
  245. package/web-shell/assets/{chunk-G27WJ6UU-DxnCrpxK.js → chunk-G27WJ6UU-DO8ZfQL_.js} +1 -1
  246. package/web-shell/assets/{chunk-JWPE2WC7-BPjRsozm.js → chunk-JWPE2WC7-yYFrrKAj.js} +1 -1
  247. package/web-shell/assets/{chunk-LCL6LL3I-Q2HgB3lf.js → chunk-LCL6LL3I-BFGuOKN0.js} +1 -1
  248. package/web-shell/assets/{chunk-POPQ4Y6H-9tlPaKu-.js → chunk-POPQ4Y6H-GRHK6sdV.js} +1 -1
  249. package/web-shell/assets/{chunk-SVP7TREG-DkNdOHCU.js → chunk-SVP7TREG-DwDu6GqZ.js} +1 -1
  250. package/web-shell/assets/{chunk-XXDRQBXY-D0G-Dhfi.js → chunk-XXDRQBXY-RoNDjkIy.js} +1 -1
  251. package/web-shell/assets/classDiagram-DTDB5LWJ-pPPByLA7.js +1 -0
  252. package/web-shell/assets/classDiagram-v2-JRS7N3AN-pPPByLA7.js +1 -0
  253. package/web-shell/assets/{cose-bilkent-JH36ORCC-Ck0tHxul.js → cose-bilkent-JH36ORCC-CYNiiONE.js} +1 -1
  254. package/web-shell/assets/{cynefin-OW5HDTMX-a4-NTMHi.js → cynefin-OW5HDTMX-DC1_lDIG.js} +1 -1
  255. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Pg41Zbf2.js → cynefinDiagram-5FMLGOSQ-D2VxKm2n.js} +1 -1
  256. package/web-shell/assets/{dagre-3AP2YEHR-DT_ZmqkF.js → dagre-3AP2YEHR-C4_BHzpM.js} +1 -1
  257. package/web-shell/assets/{diagram-S7CK7UJ4-hapdMOl1.js → diagram-S7CK7UJ4-BpAO4-Gv.js} +1 -1
  258. package/web-shell/assets/{diagram-UQ7AKVKN-YZ0nbk56.js → diagram-UQ7AKVKN-DqUsFdsX.js} +1 -1
  259. package/web-shell/assets/{diagram-VSXAHHWV-DA_yNbWy.js → diagram-VSXAHHWV-DcMXIYMy.js} +1 -1
  260. package/web-shell/assets/{diagram-VX7I27RA-DoULuCLT.js → diagram-VX7I27RA-I3nr09ex.js} +1 -1
  261. package/web-shell/assets/{diagram-Z3DM3KII-B5c9o9zL.js → diagram-Z3DM3KII-CN-gvsTo.js} +1 -1
  262. package/web-shell/assets/{docx-preview-BulxdBjs.js → docx-preview-31J6RsS0.js} +1 -1
  263. package/web-shell/assets/{ebnfDiagram-PWID7BFC-B5hgIg3m.js → ebnfDiagram-PWID7BFC-DOQvLWlM.js} +1 -1
  264. package/web-shell/assets/{erDiagram-SSCWMZ5O-BEfEPozi.js → erDiagram-SSCWMZ5O-Cb5ijFZh.js} +1 -1
  265. package/web-shell/assets/{flowDiagram-A5DVABFB-CQHNk92v.js → flowDiagram-A5DVABFB-BecqqjnZ.js} +1 -1
  266. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-BabdVgIM.js → ganttDiagram-EL5Y4UJY-DWY5vzQl.js} +1 -1
  267. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-ujRZBFUo.js → gitGraphDiagram-WWUBYQGX-DqBnsZmZ.js} +1 -1
  268. package/web-shell/assets/{index-B9uXebIR.js → index-DDmiUW3b.js} +6 -6
  269. package/web-shell/assets/{index-DSZXdZnu.js → index-DabH7kHA.js} +1 -1
  270. package/web-shell/assets/{infoDiagram-RXCK75RN-CUHj9jJC.js → infoDiagram-RXCK75RN-MlotyOdT.js} +1 -1
  271. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-CulW_q81.js → ishikawaDiagram-5VMMS53U-Daq_85C7.js} +1 -1
  272. package/web-shell/assets/{journeyDiagram-EYS64GPL-BR46CvRQ.js → journeyDiagram-EYS64GPL-OipivCxL.js} +1 -1
  273. package/web-shell/assets/{kanban-definition-3QL26DDD-HAoUqzFy.js → kanban-definition-3QL26DDD-zqaz7dLu.js} +1 -1
  274. package/web-shell/assets/{layout-DYLl7fyA.js → layout-Bi3msQMQ.js} +1 -1
  275. package/web-shell/assets/{linear-DPXABjDZ.js → linear-D4gPORvD.js} +1 -1
  276. package/web-shell/assets/{mermaid.core-Bi30Gi0n.js → mermaid.core-BUnytF7a.js} +6 -6
  277. package/web-shell/assets/{mindmap-definition-FBJOCRG2-B1_lUq4o.js → mindmap-definition-FBJOCRG2-B_X4iChu.js} +1 -1
  278. package/web-shell/assets/{pegDiagram-XKGWAZYB-Cy8tjJJC.js → pegDiagram-XKGWAZYB-z4wYBoBW.js} +1 -1
  279. package/web-shell/assets/{pieDiagram-E7YTZNPT-D6waLVVi.js → pieDiagram-E7YTZNPT-Dvyg6FYo.js} +1 -1
  280. package/web-shell/assets/{quadrantDiagram-AXDQQJYC--6ehi_FI.js → quadrantDiagram-AXDQQJYC-CJBWU2Dk.js} +1 -1
  281. package/web-shell/assets/{railroadDiagram-O6MQD6OU-BhLy40X4.js → railroadDiagram-O6MQD6OU-Dl_An1O0.js} +1 -1
  282. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BVNXTgNP.js → requirementDiagram-EFPCY7ZU-Tw8FwaYU.js} +1 -1
  283. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BHgTytxV.js → sankeyDiagram-P5KCCOFB-BCPCkbR0.js} +1 -1
  284. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-CgOsTvhu.js → sequenceDiagram-WJ2MYXX4-DDj7uFTG.js} +1 -1
  285. package/web-shell/assets/{sizeCapture-X5ZJPWSS-vCQBQ5FI.js → sizeCapture-X5ZJPWSS-B9eVSpKb.js} +1 -1
  286. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DytMYRWJ.js → stateDiagram-HBIQ2CUA-Bf4BZP_V.js} +1 -1
  287. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BPJi6Gre.js +1 -0
  288. package/web-shell/assets/{swimlanes-XN3QIQJK-CTGnifOP.js → swimlanes-XN3QIQJK-dyTWsZFj.js} +1 -1
  289. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bw4NRtJQ.js +8 -0
  290. package/web-shell/assets/{timeline-definition-24CTP7MA-DEJ1cbn2.js → timeline-definition-24CTP7MA-DVl1A4uL.js} +1 -1
  291. package/web-shell/assets/{vennDiagram-4TSXK5OY-K1e4SjS0.js → vennDiagram-4TSXK5OY-Boosxy9D.js} +1 -1
  292. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DEX-GkRp.js → wardleyDiagram-VM6X3IG4-C6wlY8jy.js} +1 -1
  293. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-B6wYXreH.js → xychartDiagram-S5SC5T6Z-CkzZe3ro.js} +1 -1
  294. package/web-shell/index.html +1 -1
  295. package/web-shell/sw.js +1 -1
  296. package/web-shell/assets/channel-CLVrtVFX.js +0 -1
  297. package/web-shell/assets/classDiagram-DTDB5LWJ-Df2T70oB.js +0 -1
  298. package/web-shell/assets/classDiagram-v2-JRS7N3AN-Df2T70oB.js +0 -1
  299. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CcjUJGng.js +0 -1
  300. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dt8NvQfX.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{runExitCleanup}from"./chunk-UFTIUKD4.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var RELAUNCH_EXIT_CODE=42;var UPDATE_RELAUNCH_EXIT_CODE=43;var UPDATE_COMPLETE_EXIT_CODE=44;var SKIP_UPDATE_CHECK_ENV_VAR="QWEN_CODE_SKIP_UPDATE_CHECK_ONCE";var CUSTOM_SANDBOX_IMAGE_ENV_VAR="QWEN_CODE_CUSTOM_SANDBOX_IMAGE";var HOST_UPDATE_RELAUNCH_ENV_VAR="QWEN_CODE_HOST_UPDATE_RELAUNCH";var UPDATE_ON_EXIT_MESSAGE="qwen-code:update-on-exit";var inProcessUpdateRelaunch;var supervisedInProcess=false;var updateOnExitRequested=false;var updatingOnExit=false;function superviseInProcess(onUpdateRelaunch){supervisedInProcess=true;inProcessUpdateRelaunch=onUpdateRelaunch}__name(superviseInProcess,"superviseInProcess");function getRelaunchExecArgv(){const needsExposeGc=typeof globalThis.gc==="function"&&!process.execArgv.includes("--expose-gc");return needsExposeGc?[...process.execArgv,"--expose-gc"]:[...process.execArgv]}__name(getRelaunchExecArgv,"getRelaunchExecArgv");async function relaunchApp(){await runExitCleanup();const proc=process;if(supervisedInProcess&&proc.execve){proc.execve(process.execPath,[process.execPath,...getRelaunchExecArgv(),...process.argv.slice(1)])}process.exit(RELAUNCH_EXIT_CODE)}__name(relaunchApp,"relaunchApp");async function exitCleanly(code){if(updatingOnExit)return new Promise(()=>{});if(code===0&&updateOnExitRequested&&inProcessUpdateRelaunch){updateOnExitRequested=false;updatingOnExit=true;try{code=await inProcessUpdateRelaunch(false)}catch{code=1}}process.exit(code)}__name(exitCleanly,"exitCleanly");async function relaunchForUpdate(){await runExitCleanup();if(inProcessUpdateRelaunch){process.exit(await inProcessUpdateRelaunch(true))}process.exit(UPDATE_RELAUNCH_EXIT_CODE)}__name(relaunchForUpdate,"relaunchForUpdate");function requestUpdateOnExit(){if(inProcessUpdateRelaunch){updateOnExitRequested=true;return true}if(!process.send)return false;try{process.send({type:UPDATE_ON_EXIT_MESSAGE});return true}catch{return false}}__name(requestUpdateOnExit,"requestUpdateOnExit");export{RELAUNCH_EXIT_CODE,UPDATE_RELAUNCH_EXIT_CODE,UPDATE_COMPLETE_EXIT_CODE,SKIP_UPDATE_CHECK_ENV_VAR,CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,UPDATE_ON_EXIT_MESSAGE,superviseInProcess,getRelaunchExecArgv,relaunchApp,exitCleanly,relaunchForUpdate,requestUpdateOnExit};
3
+ import{runExitCleanup}from"./chunk-LGYXZJI3.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var RELAUNCH_EXIT_CODE=42;var UPDATE_RELAUNCH_EXIT_CODE=43;var UPDATE_COMPLETE_EXIT_CODE=44;var SKIP_UPDATE_CHECK_ENV_VAR="QWEN_CODE_SKIP_UPDATE_CHECK_ONCE";var CUSTOM_SANDBOX_IMAGE_ENV_VAR="QWEN_CODE_CUSTOM_SANDBOX_IMAGE";var HOST_UPDATE_RELAUNCH_ENV_VAR="QWEN_CODE_HOST_UPDATE_RELAUNCH";var UPDATE_ON_EXIT_MESSAGE="qwen-code:update-on-exit";var inProcessUpdateRelaunch;var supervisedInProcess=false;var updateOnExitRequested=false;var updatingOnExit=false;function superviseInProcess(onUpdateRelaunch){supervisedInProcess=true;inProcessUpdateRelaunch=onUpdateRelaunch}__name(superviseInProcess,"superviseInProcess");function getRelaunchExecArgv(){const needsExposeGc=typeof globalThis.gc==="function"&&!process.execArgv.includes("--expose-gc");return needsExposeGc?[...process.execArgv,"--expose-gc"]:[...process.execArgv]}__name(getRelaunchExecArgv,"getRelaunchExecArgv");async function relaunchApp(){await runExitCleanup();const proc=process;if(supervisedInProcess&&proc.execve){proc.execve(process.execPath,[process.execPath,...getRelaunchExecArgv(),...process.argv.slice(1)])}process.exit(RELAUNCH_EXIT_CODE)}__name(relaunchApp,"relaunchApp");async function exitCleanly(code){if(updatingOnExit)return new Promise(()=>{});if(code===0&&updateOnExitRequested&&inProcessUpdateRelaunch){updateOnExitRequested=false;updatingOnExit=true;try{code=await inProcessUpdateRelaunch(false)}catch{code=1}}process.exit(code)}__name(exitCleanly,"exitCleanly");async function relaunchForUpdate(){await runExitCleanup();if(inProcessUpdateRelaunch){process.exit(await inProcessUpdateRelaunch(true))}process.exit(UPDATE_RELAUNCH_EXIT_CODE)}__name(relaunchForUpdate,"relaunchForUpdate");function requestUpdateOnExit(){if(inProcessUpdateRelaunch){updateOnExitRequested=true;return true}if(!process.send)return false;try{process.send({type:UPDATE_ON_EXIT_MESSAGE});return true}catch{return false}}__name(requestUpdateOnExit,"requestUpdateOnExit");export{RELAUNCH_EXIT_CODE,UPDATE_RELAUNCH_EXIT_CODE,UPDATE_COMPLETE_EXIT_CODE,SKIP_UPDATE_CHECK_ENV_VAR,CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,UPDATE_ON_EXIT_MESSAGE,superviseInProcess,getRelaunchExecArgv,relaunchApp,exitCleanly,relaunchForUpdate,requestUpdateOnExit};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{MarkdownCommandDefSchema,parseMarkdownCommand}from"./chunk-QXYN3PTW.js";import{historyPath,parseHostedFileHistoryState,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryState}from"./chunk-47LP4MBD.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-XLCTS6G3.js";import{DAEMON_ACP_NDJSON_LIMITS,hasBoundedJsonStructure}from"./chunk-OBGX5CDE.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-LIIMQ4DI.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-TLROJH6O.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import{parseSkillContent}from"./chunk-4WFGJVTF.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{require_brace_expansion}from"./chunk-OBOU4ZZM.js";import{BaseDeclarativeTool,BaseToolInvocation,ToolConfirmationOutcome}from"./chunk-O5EKX7LG.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();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 object(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedRuntimeProviderProtocolError;return value}__name(object,"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=object(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"]);object(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=object(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=object(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=object(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=object(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=object(tool);id(descriptor["name"]);object(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;object(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")object(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-QXYN3PTW.js";import{historyPath,parseHostedFileHistoryState,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryState}from"./chunk-JKMGS2VD.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-XLCTS6G3.js";import{DAEMON_ACP_NDJSON_LIMITS,hasBoundedJsonStructure}from"./chunk-OBGX5CDE.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-LZNBHBAJ.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-TLROJH6O.js";import{isShellResultDisplay}from"./chunk-T7CHK6C2.js";import{parseSkillContent}from"./chunk-4WFGJVTF.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{require_brace_expansion}from"./chunk-OBOU4ZZM.js";import{BaseDeclarativeTool,BaseToolInvocation,ToolConfirmationOutcome}from"./chunk-O5EKX7LG.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();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 object(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedRuntimeProviderProtocolError;return value}__name(object,"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=object(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"]);object(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=object(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=object(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=object(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=object(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=object(tool);id(descriptor["name"]);object(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;object(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")object(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(text2){return Buffer.byteLength(JSON.stringify(text2),"utf8")-2}__name(jsonTextBytes,"jsonTextBytes");function cutProviderFitSlot(slot,targetBytes,budgetBytes){const text2=slot.get();const size=jsonTextBytes(text2);if(size<=targetBytes)return;const keep=Math.max(0,targetBytes-jsonTextBytes(providerFitNotice(text2.length,budgetBytes)));let head=0;let headBytes=0;while(head<text2.length){const codePoint=text2.codePointAt(head);const cost=jsonCodePointBytes(codePoint);if(headBytes+cost>Math.ceil(keep/2))break;headBytes+=cost;head+=codePoint>65535?2:1}let tail=text2.length;let tailBytes=0;while(tail>head){let start=tail-1;const unit=text2.charCodeAt(start);if(unit>=56320&&unit<=57343&&start>head){const previous=text2.charCodeAt(start-1);if(previous>=55296&&previous<=56319)start--}const cost=jsonCodePointBytes(text2.codePointAt(start));if(headBytes+tailBytes+cost>keep)break;tailBytes+=cost;tail=start}let omitted=0;for(const _ of text2.slice(head,tail))omitted++;const next=text2.slice(0,head)+providerFitNotice(omitted,budgetBytes)+text2.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 fields=hook;const reason=fields["stopReason"];const hookError=fields["hookError"];execution2["postHook"]={shouldStop:fields["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();var WORKSPACE_EXECUTION_PROFILE="managed-workspace-execution/1";var WORKSPACE_CONTEXT_CONFIG_REF="sha256:5fa15183dcfe582ce54c28bf25aff62801d19038a9ec649e9bfc67b06f2a389f";var WORKSPACE_CAPABILITY_DIGEST="sha256:7df3981fa14b397fe09f6ba84ed0c096c71902394da667bf47f3b315866e7f91";var RESIDENT_WORKSPACE_PROFILE="resident-workspace-files/1";var RESIDENT_WORKSPACE_CAPABILITY_DIGEST="sha256:2cbf6f3825230848a65a546ec70714fbb2a53d1862a6caba73ae4cebf307b4ad";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,...boot.managedExtensions?[MANAGED_EXTENSION_LINUX_CAPABILITY_DIGEST,MANAGED_EXTENSION_DEVELOPER_CAPABILITY_DIGEST]:[]].includes(boot.capabilityDigest)||request["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";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 text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text2,MANAGED_CSI_ACK_LIMIT_BYTES);return JSON.parse(text2,(_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 fields=request[key];if(!Object.entries(expected).every(([name,field])=>fields[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 fields=closed(response[key],Object.keys(expected).sort());if(!Object.entries(expected).every(([name,field])=>fields[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 text2=storage[key];if(typeof text2!=="string"||text2===""||/^[ \u1680\u2000-\u2006\u2008-\u200a\u2028\u2029\u205f\u3000]+$/u.test(text2)||text2.length>maximum||Array.from(text2).some(char=>char.charCodeAt(0)<=31||char.charCodeAt(0)>=127&&char.charCodeAt(0)<=159)||/[\ud800-\udfff]/u.test(text2))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 fields=Object.keys(value).sort();if(fields.length!==keys2.length||!fields.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 text2=new TextDecoder("utf-8",{fatal:true}).decode(bytes);parseManagedSessionRecordJson(text2,limit);return JSON.parse(text2,(_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||identity["profile"]!=="csi-files-retirement/1"||identity["capabilityDigest"]!==CSI_FILES_RETIREMENT_CAPABILITY_DIGEST||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 fields={type:"boot",managedCsi:MANAGED_CSI_FILE_PROTOCOL,identity:Object.freeze(identity),context:data.context,storage:data.storage};return finalizationBoot?Object.freeze({...fields,version:6,authority:readManagedCsiNativeAuthority(boot["authority"]),finalization:CSI_FILE_FINALIZATION_FORMAT}):authorityBoot?Object.freeze({...fields,version:5,authority:readManagedCsiNativeAuthority(boot["authority"])}):Object.freeze({...fields,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 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";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 object2(value,field){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedPackageCompatibilityError([`${field}: invalid object`]);return value}__name(object2,"object");function text(value,field,maxBytes=512*1024){if(typeof value!=="string"||!value.trim()||Buffer.byteLength(value)>maxBytes)throw new ManagedPackageCompatibilityError([`${field}: invalid text`]);return value}__name(text,"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,fields,source){const reasons=fields.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 filesUnder(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(filesUnder,"filesUnder");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 object2(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 strings(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(strings,"strings");async function compileManagedExtensionPackage(root,options){const files=await filesUnder(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=object2(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=text(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);const{metadata}=frontmatter(content);rejectFields(metadata,["allowedTools","allowed-tools","hooks","paths","arguments","args-file"],file);if(metadata["model"]!==void 0&&metadata["model"]!=="inherit")throw new ManagedPackageCompatibilityError([`${file}.model: unsupported`]);const skill=parseSkillContent(content,file);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:object2((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:text(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}:${text(metadata["name"]??path.posix.basename(file,".md"),file,128)}`,description:text(metadata["description"],`${file}.description`,4096),systemPrompt:text(body,file),...metadata["tools"]!==void 0?{tools:strings(metadata["tools"],file)}:{},...metadata["disallowedTools"]!==void 0?{disallowedTools:strings(metadata["disallowedTools"],file)}:{},...metadata["model"]!==void 0?{model:text(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=object2(mcp,"mcpServers");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=object2(hooks,"hooks");contributions.hooks=object2(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=object2(entry,"setting");const envVar=text(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:text(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=hydrate(contributions.mcpServers);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)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:text(config["version"]??"1.0.0","version",128),target:packageTarget,components,...config["managedSource"]?{sourceType:text(object2(config["managedSource"],"managedSource")["type"],"sourceType",64),sourceRevision:text(object2(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 filesUnder(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 filesUnder(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||text(config["version"]??"snapshot","version",128)};await fs.writeFile(path.join(root,"qwen-extension.json"),JSON.stringify(config));files=await filesUnder(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");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();var import_brace_expansion=__toESM(require_brace_expansion(),1);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();init_esbuild_shims();var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]};var braceEscape=__name(s=>s.replace(/[[\]\\-]/g,"\\$&"),"braceEscape");var regexpEscape=__name(s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regexpEscape");var rangesToString=__name(ranges=>ranges.join(""),"rangesToString");var parseClass=__name((glob,position)=>{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 uflag=false;let escaping=false;let negate=false;let endPos=pos;let rangeStart="";WHILE:while(i<glob.length){const c=glob.charAt(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,u,neg]]of Object.entries(posixClasses)){if(glob.startsWith(cls,i)){if(rangeStart){return["$.",false,glob.length-pos,true]}i+=cls.length;if(neg)negs.push(unip);else ranges.push(unip);uflag=uflag||u;continue WHILE}}}escaping=false;if(rangeStart){if(c>rangeStart){ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c))}else if(c===rangeStart){ranges.push(braceEscape(c))}rangeStart="";i++;continue}if(glob.startsWith("-]",i+1)){ranges.push(braceEscape(c+"-"));i+=2;continue}if(glob.startsWith("-",i+1)){rangeStart=c;i+=2;continue}ranges.push(braceEscape(c));i++}if(endPos<i){return["",false,0,false]}if(!ranges.length&&!negs.length){return["$.",false,glob.length-pos,true]}if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){const r=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r),false,endPos-pos,false]}const sranges="["+(negate?"^":"")+rangesToString(ranges)+"]";const snegs="["+(negate?"":"^")+rangesToString(negs)+"]";const comb=ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs;return[comb,uflag,endPos-pos,true]},"parseClass");init_esbuild_shims();var unescape=__name((s,{windowsPathsNoEscape=false}={})=>{return windowsPathsNoEscape?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")},"unescape");var _a;var types=new Set(["!","?","+","*","@"]);var isExtglobType=__name(c=>types.has(c),"isExtglobType");var isExtglobAST=__name(c=>isExtglobType(c.type),"isExtglobAST");var adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]);var adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]);var adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]);var usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]);var startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))";var startNoDot="(?!\\.)";var addPatternStart=new Set(["[","."]);var justDots=new Set(["..","."]);var reSpecials=new Set("().*{}+?[]^$\\!");var regExpEscape=__name(s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape");var qmark="[^/]";var star=qmark+"*?";var starNoEmpty=qmark+"+?";var AST=class{static{__name(this,"AST")}type;#root;#hasMagic;#uflag=false;#parts=[];#parent;#parentIndex;#negs;#filledNegs=false;#options;#toString;#emptyExt=false;constructor(type,parent,options={}){this.type=type;if(type)this.#hasMagic=true;this.#parent=parent;this.#root=this.#parent?this.#parent.#root:this;this.#options=this.#root===this?options:this.#root.#options;this.#negs=this.#root===this?[]:this.#root.#negs;if(type==="!"&&!this.#root.#filledNegs)this.#negs.push(this);this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(const p of this.#parts){if(typeof p==="string")continue;if(p.type||p.hasMagic)return this.#hasMagic=true}return this.#hasMagic}toString(){if(this.#toString!==void 0)return this.#toString;if(!this.type){return this.#toString=this.#parts.map(p=>String(p)).join("")}else{return this.#toString=this.type+"("+this.#parts.map(p=>String(p)).join("|")+")"}}#fillNegs(){if(this!==this.#root)throw new Error("should only call on root");if(this.#filledNegs)return this;this.toString();this.#filledNegs=true;let n;while(n=this.#negs.pop()){if(n.type!=="!")continue;let p=n;let pp=p.#parent;while(pp){for(let i=p.#parentIndex+1;!pp.type&&i<pp.#parts.length;i++){for(const part of n.#parts){if(typeof part==="string"){throw new Error("string part in extglob AST??")}part.copyIn(pp.#parts[i])}}p=pp;pp=p.#parent}}return this}push(...parts){for(const p of parts){if(p==="")continue;if(typeof p!=="string"&&!(p instanceof _a&&p.#parent===this)){throw new Error("invalid part: "+p)}this.#parts.push(p)}}toJSON(){const ret=this.type===null?this.#parts.slice().map(p=>typeof p==="string"?p:p.toJSON()):[this.type,...this.#parts.map(p=>p.toJSON())];if(this.isStart()&&!this.type)ret.unshift([]);if(this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type==="!")){ret.push({})}return ret}isStart(){if(this.#root===this)return true;if(!this.#parent?.isStart())return false;if(this.#parentIndex===0)return true;const p=this.#parent;for(let i=0;i<this.#parentIndex;i++){const pp=p.#parts[i];if(!(pp instanceof _a&&pp.type==="!")){return false}}return true}isEnd(){if(this.#root===this)return true;if(this.#parent?.type==="!")return true;if(!this.#parent?.isEnd())return false;if(!this.type)return this.#parent?.isEnd();const pl=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===pl-1}copyIn(part){if(typeof part==="string")this.push(part);else this.push(part.clone(this))}clone(parent){const c=new _a(this.type,parent);for(const p of this.#parts){c.copyIn(p)}return c}static#parseAST(str,ast,pos,opt,extDepth){const maxDepth=opt.maxExtglobRecursion??2;let escaping=false;let inBrace=false;let braceStart=-1;let braceNeg=false;if(ast.type===null){let i2=pos;let acc2="";while(i2<str.length){const c=str.charAt(i2++);if(escaping||c==="\\"){escaping=!escaping;acc2+=c;continue}if(inBrace){if(i2===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i2===braceStart+2&&braceNeg)){inBrace=false}acc2+=c;continue}else if(c==="["){inBrace=true;braceStart=i2;braceNeg=false;acc2+=c;continue}const doRecurse=!opt.noext&&isExtglobType(c)&&str.charAt(i2)==="("&&extDepth<=maxDepth;if(doRecurse){ast.push(acc2);acc2="";const ext2=new _a(c,ast);i2=_a.#parseAST(str,ext2,i2,opt,extDepth+1);ast.push(ext2);continue}acc2+=c}ast.push(acc2);return i2}let i=pos+1;let part=new _a(null,ast);const parts=[];let acc="";while(i<str.length){const c=str.charAt(i++);if(escaping||c==="\\"){escaping=!escaping;acc+=c;continue}if(inBrace){if(i===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i===braceStart+2&&braceNeg)){inBrace=false}acc+=c;continue}else if(c==="["){inBrace=true;braceStart=i;braceNeg=false;acc+=c;continue}const doRecurse=isExtglobType(c)&&str.charAt(i)==="("&&(extDepth<=maxDepth||ast&&ast.#canAdoptType(c));if(doRecurse){const depthAdd=ast&&ast.#canAdoptType(c)?0:1;part.push(acc);acc="";const ext2=new _a(c,part);part.push(ext2);i=_a.#parseAST(str,ext2,i,opt,extDepth+depthAdd);continue}if(c==="|"){part.push(acc);acc="";parts.push(part);part=new _a(null,ast);continue}if(c===")"){if(acc===""&&ast.#parts.length===0){ast.#emptyExt=true}part.push(acc);acc="";ast.push(...parts,part);return i}acc+=c}ast.type=null;ast.#hasMagic=void 0;ast.#parts=[str.substring(pos-1)];return i}#canAdoptWithSpace(child){return this.#canAdopt(child,adoptionWithSpaceMap)}#canAdopt(child,map=adoptionMap){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null){return false}const gc=child.#parts[0];if(!gc||typeof gc!=="object"||gc.type===null){return false}return this.#canAdoptType(gc.type,map)}#canAdoptType(c,map=adoptionAnyMap){return!!map.get(this.type)?.includes(c)}#adoptWithSpace(child,index){const gc=child.#parts[0];const blank=new _a(null,gc,this.options);blank.#parts.push("");gc.push(blank);this.#adopt(child,index)}#adopt(child,index){const gc=child.#parts[0];this.#parts.splice(index,1,...gc.#parts);for(const p of gc.#parts){if(typeof p==="object")p.#parent=this}this.#toString=void 0}#canUsurpType(c){const m=usurpMap.get(this.type);return!!m?.has(c)}#canUsurp(child){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null||this.#parts.length!==1){return false}const gc=child.#parts[0];if(!gc||typeof gc!=="object"||gc.type===null){return false}return this.#canUsurpType(gc.type)}#usurp(child){const m=usurpMap.get(this.type);const gc=child.#parts[0];const nt=m?.get(gc.type);if(!nt)return false;this.#parts=gc.#parts;for(const p of this.#parts){if(typeof p==="object")p.#parent=this}this.type=nt;this.#toString=void 0;this.#emptyExt=false}#flatten(){if(!isExtglobAST(this)){for(const p of this.#parts){if(typeof p==="object")p.#flatten()}}else{let iterations=0;let done=false;do{done=true;for(let i=0;i<this.#parts.length;i++){const c=this.#parts[i];if(typeof c==="object"){c.#flatten();if(this.#canAdopt(c)){done=false;this.#adopt(c,i)}else if(this.#canAdoptWithSpace(c)){done=false;this.#adoptWithSpace(c,i)}else if(this.#canUsurp(c)){done=false;this.#usurp(c)}}}}while(!done&&++iterations<10)}this.#toString=void 0}static fromGlob(pattern,options={}){const ast=new _a(null,void 0,options);_a.#parseAST(pattern,ast,0,options,0);return ast}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();const glob=this.toString();const[re,body,hasMagic,uflag]=this.toRegExpSource();const anyMagic=hasMagic||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase();if(!anyMagic){return body}const flags=(this.#options.nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags),{_src:re,_glob:glob})}get options(){return this.#options}toRegExpSource(allowDot){const dot=allowDot??!!this.#options.dot;if(this.#root===this){this.#flatten();this.#fillNegs()}if(!isExtglobAST(this)){const noEmpty=this.isStart()&&this.isEnd();const src=this.#parts.map(p=>{const[re,_,hasMagic,uflag]=typeof p==="string"?_a.#parseGlob(p,this.#hasMagic,noEmpty):p.toRegExpSource(allowDot);this.#hasMagic=this.#hasMagic||hasMagic;this.#uflag=this.#uflag||uflag;return re}).join("");let start2="";if(this.isStart()){if(typeof this.#parts[0]==="string"){const dotTravAllowed=this.#parts.length===1&&justDots.has(this.#parts[0]);if(!dotTravAllowed){const aps=addPatternStart;const needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4));const needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}}}let end="";if(this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type==="!"){end="(?:$|\\/)"}const final2=start2+src+end;return[final2,unescape(src),this.#hasMagic=!!this.#hasMagic,this.#uflag]}const repeated=this.type==="*"||this.type==="+";const start=this.type==="!"?"(?:(?!(?:":"(?:";let body=this.#partsToRegExp(dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){const s=this.toString();const me=this;me.#parts=[s];me.type=null;me.#hasMagic=void 0;return[s,unescape(this.toString()),false,false]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":this.#partsToRegExp(true);if(bodyDotAllowed===body){bodyDotAllowed=""}if(bodyDotAllowed){body=`(?:${body})(?:${bodyDotAllowed})*?`}let final="";if(this.type==="!"&&this.#emptyExt){final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty}else{const close=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?`)?`:`)${this.type}`;final=start+body+close}return[final,unescape(body),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#partsToRegExp(dot){return this.#parts.map(p=>{if(typeof p==="string"){throw new Error("string type in extglob ast??")}const[re,_,_hasMagic,uflag]=p.toRegExpSource(dot);this.#uflag=this.#uflag||uflag;return re}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")}static#parseGlob(glob,hasMagic,noEmpty=false){let escaping=false;let re="";let uflag=false;let inStar=false;for(let i=0;i<glob.length;i++){const c=glob.charAt(i);if(escaping){escaping=false;re+=(reSpecials.has(c)?"\\":"")+c;inStar=false;continue}if(c==="\\"){if(i===glob.length-1){re+="\\\\"}else{escaping=true}continue}if(c==="["){const[src,needUflag,consumed,magic]=parseClass(glob,i);if(consumed){re+=src;uflag=uflag||needUflag;i+=consumed-1;hasMagic=hasMagic||magic;inStar=false;continue}}if(c==="*"){if(inStar)continue;inStar=true;re+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star;hasMagic=true;continue}else{inStar=false}if(c==="?"){re+=qmark;hasMagic=true;continue}re+=regExpEscape(c)}return[re,unescape(glob),!!hasMagic,uflag]}};_a=AST;init_esbuild_shims();var escape=__name((s,{windowsPathsNoEscape=false}={})=>{return windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&")},"escape");var minimatch=__name((p,pattern,options={})=>{assertValidPattern(pattern);if(!options.nocomment&&pattern.charAt(0)==="#"){return false}return new Minimatch(pattern,options).match(p)},"minimatch");var starDotExtRE=/^\*+([^+@!?\*\[\(]*)$/;var starDotExtTest=__name(ext2=>f=>!f.startsWith(".")&&f.endsWith(ext2),"starDotExtTest");var starDotExtTestDot=__name(ext2=>f=>f.endsWith(ext2),"starDotExtTestDot");var starDotExtTestNocase=__name(ext2=>{ext2=ext2.toLowerCase();return f=>!f.startsWith(".")&&f.toLowerCase().endsWith(ext2)},"starDotExtTestNocase");var starDotExtTestNocaseDot=__name(ext2=>{ext2=ext2.toLowerCase();return f=>f.toLowerCase().endsWith(ext2)},"starDotExtTestNocaseDot");var starDotStarRE=/^\*+\.\*+$/;var starDotStarTest=__name(f=>!f.startsWith(".")&&f.includes("."),"starDotStarTest");var starDotStarTestDot=__name(f=>f!=="."&&f!==".."&&f.includes("."),"starDotStarTestDot");var dotStarRE=/^\.\*+$/;var dotStarTest=__name(f=>f!=="."&&f!==".."&&f.startsWith("."),"dotStarTest");var starRE=/^\*+$/;var starTest=__name(f=>f.length!==0&&!f.startsWith("."),"starTest");var starTestDot=__name(f=>f.length!==0&&f!=="."&&f!=="..","starTestDot");var qmarksRE=/^\?+([^+@!?\*\[\(]*)?$/;var qmarksTestNocase=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f=>noext(f)&&f.toLowerCase().endsWith(ext2)},"qmarksTestNocase");var qmarksTestNocaseDot=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f=>noext(f)&&f.toLowerCase().endsWith(ext2)},"qmarksTestNocaseDot");var qmarksTestDot=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);return!ext2?noext:f=>noext(f)&&f.endsWith(ext2)},"qmarksTestDot");var qmarksTest=__name(([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);return!ext2?noext:f=>noext(f)&&f.endsWith(ext2)},"qmarksTest");var qmarksTestNoExt=__name(([$0])=>{const len=$0.length;return f=>f.length===len&&!f.startsWith(".")},"qmarksTestNoExt");var qmarksTestNoExtDot=__name(([$0])=>{const len=$0.length;return f=>f.length===len&&f!=="."&&f!==".."},"qmarksTestNoExtDot");var defaultPlatform=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&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 qmark2="[^/]";var star2=qmark2+"*?";var twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?";var filter=__name((pattern,options={})=>p=>minimatch(p,pattern,options),"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}},AST:class AST extends orig.AST{static{__name(this,"AST")}constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},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"),makeRe:__name((pattern,options={})=>orig.makeRe(pattern,ext(def,options)),"makeRe"),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]}return(0,import_brace_expansion.default)(pattern)},"braceExpand");minimatch.braceExpand=braceExpand;var makeRe=__name((pattern,options={})=>new Minimatch(pattern,options).makeRe(),"makeRe");minimatch.makeRe=makeRe;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 regExpEscape2=__name(s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape");var Minimatch=class{static{__name(this,"Minimatch")}options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(pattern,options={}){assertValidPattern(pattern);options=options||{};this.options=options;this.maxGlobstarRecursion=options.maxGlobstarRecursion??200;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows=this.platform==="win32";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options.allowWindowsEscape===false;if(this.windowsPathsNoEscape){this.pattern=this.pattern.replace(/\\/g,"/")}this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;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.make()}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}debug(..._){}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.braceExpand())];if(options.debug){this.debug=(...args)=>console.error(...args)}this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set=this.globParts.map((s,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&!globMagic.test(s[3]);const isDrive=/^[a-z]:/i.test(s[0]);if(isUNC){return[...s.slice(0,4),...s.slice(4).map(ss=>this.parse(ss))]}else if(isDrive){return[s[0],...s.slice(1).map(ss=>this.parse(ss))]}}return s.map(ss=>this.parse(ss))});this.debug(this.pattern,set);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]==="?"&&typeof p[3]==="string"&&/^[a-z]:$/i.test(p[3])){p[2]="?"}}}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar){for(let i=0;i<globParts.length;i++){for(let j=0;j<globParts[i].length;j++){if(globParts[i][j]==="**"){globParts[i][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=>{parts=parts.reduce((set,part)=>{const prev=set[set.length-1];if(part==="**"&&prev==="**"){return set}if(part===".."){if(prev&&prev!==".."&&prev!=="."&&prev!=="**"){set.pop();return set}}set.push(part);return set},[]);return parts.length===0?[""]:parts})}levelTwoFileOptimize(parts){if(!Array.isArray(parts)){parts=this.slashSplit(parts)}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()}}let dd=0;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-=2}}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){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}didSomething=true;parts.splice(gs,1);const other=parts.slice(0);other[gs]="**";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()}}let dd=0;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-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i=0;i<globParts.length-1;i++){for(let j=i+1;j<globParts.length;j++){const matched=this.partsMatch(globParts[i],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i]=[];globParts[j]=matched;break}}}return globParts.filter(gs=>gs.length)}partsMatch(a,b,emptyGSMatch=false){let ai=0;let bi=0;let result=[];let which="";while(ai<a.length&&bi<b.length){if(a[ai]===b[bi]){result.push(which==="b"?b[bi]:a[ai]);ai++;bi++}else if(emptyGSMatch&&a[ai]==="**"&&b[bi]===a[ai+1]){result.push(a[ai]);ai++}else if(emptyGSMatch&&b[bi]==="**"&&a[ai]===b[bi+1]){result.push(b[bi]);bi++}else if(a[ai]==="*"&&b[bi]&&(this.options.dot||!b[bi].startsWith("."))&&b[bi]!=="**"){if(which==="b")return false;which="a";result.push(a[ai]);ai++;bi++}else if(b[bi]==="*"&&a[ai]&&(this.options.dot||!a[ai].startsWith("."))&&a[ai]!=="**"){if(which==="a")return false;which="b";result.push(b[bi]);ai++;bi++}else{return false}}return a.length===b.length&&result}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}matchOne(file,pattern,partial=false){let fileStartIndex=0;let patternStartIndex=0;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()){pattern[pdi]=fd;patternStartIndex=pdi;fileStartIndex=fdi}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){file=this.levelTwoFileOptimize(file)}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 firstgs=pattern.indexOf(GLOBSTAR,patternIndex);const lastgs=pattern.lastIndexOf(GLOBSTAR);const[head,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head.length){const fileHead=file.slice(fileIndex,fileIndex+head.length);if(!this.#matchOne(fileHead,head,partial,0,0))return false;fileIndex+=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 i2=fileIndex;i2<file.length-fileTailMatch;i2++){const f=String(file[i2]);sawSome=true;if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}}return partial||sawSome}const bodySegments=[[[],0]];let currentBody=bodySegments[0];let nonGsParts=0;const nonGsPartsSums=[0];for(const b of body){if(b===GLOBSTAR){nonGsPartsSums.push(nonGsParts);currentBody=[[],0];bodySegments.push(currentBody)}else{currentBody[0].push(b);nonGsParts++}}let i=bodySegments.length-1;const fileLength=file.length-fileTailMatch;for(const b of bodySegments){b[1]=fileLength-(nonGsPartsSums[i--]+b[0].length)}return!!this.#matchGlobStarBodySections(file,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)}#matchGlobStarBodySections(file,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){const bs=bodySegments[bodyIndex];if(!bs){for(let i=fileIndex;i<file.length;i++){sawTail=true;const f=file[i];if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}}return sawTail}const[body,after]=bs;while(fileIndex<=after){const m=this.#matchOne(file.slice(0,fileIndex+body.length),body,partial,fileIndex,0);if(m&&globStarDepth<this.maxGlobstarRecursion){const sub=this.#matchGlobStarBodySections(file,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(sub!==false)return sub}const f=file[fileIndex];if(f==="."||f===".."||!this.options.dot&&f.startsWith(".")){return false}fileIndex++}return partial||null}#matchOne(file,pattern,partial,fileIndex,patternIndex){let fi;let pi;let pl;let fl;for(fi=fileIndex,pi=patternIndex,fl=file.length,pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){this.debug("matchOne loop");let p=pattern[pi];let f=file[fi];this.debug(pattern,p,f);if(p===false||p===GLOBSTAR)return false;let hit;if(typeof p==="string"){hit=f===p;this.debug("string match",p,f,hit)}else{hit=p.test(f);this.debug("pattern match",p,f,hit)}if(!hit)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)}parse(pattern){assertValidPattern(pattern);const options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m;let fastTest=null;if(m=pattern.match(starRE)){fastTest=options.dot?starTestDot:starTest}else if(m=pattern.match(starDotExtRE)){fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1])}else if(m=pattern.match(qmarksRE)){fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m)}else if(m=pattern.match(starDotStarRE)){fastTest=options.dot?starDotStarTestDot:starDotStarTest}else if(m=pattern.match(dotStarRE)){fastTest=dotStarTest}const re=AST.fromGlob(pattern,this.options).toMMPattern();if(fastTest&&typeof re==="object"){Reflect.defineProperty(re,"test",{value:fastTest})}return re}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;const set=this.set;if(!set.length){this.regexp=false;return this.regexp}const options=this.options;const twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot;const flags=new Set(options.nocase?["i"]:[]);let re=set.map(pattern=>{const pp=pattern.map(p=>{if(p instanceof RegExp){for(const f of p.flags.split(""))flags.add(f)}return typeof p==="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp.forEach((p,i)=>{const next=pp[i+1];const prev=pp[i-1];if(p!==GLOBSTAR||prev===GLOBSTAR){return}if(prev===void 0){if(next!==void 0&&next!==GLOBSTAR){pp[i+1]="(?:\\/|"+twoStar+"\\/)?"+next}else{pp[i]=twoStar}}else if(next===void 0){pp[i-1]=prev+"(?:\\/|"+twoStar+")?"}else if(next!==GLOBSTAR){pp[i-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next;pp[i+1]=GLOBSTAR}});return pp.filter(p=>p!==GLOBSTAR).join("/")}).join("|");const[open,close]=set.length>1?["(?:",")"]:["",""];re="^"+open+re+close+"$";if(this.negate)re="^(?!"+re+").+$";try{this.regexp=new RegExp(re,[...flags].join(""))}catch(ex){this.regexp=false}return this.regexp}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){this.debug("match",f,this.pattern);if(this.comment){return false}if(this.empty){return f===""}if(f==="/"&&partial){return true}const options=this.options;if(this.isWindows){f=f.split("\\").join("/")}const ff=this.slashSplit(f);this.debug(this.pattern,"split",ff);const set=this.set;this.debug(this.pattern,"set",set);let filename=ff[ff.length-1];if(!filename){for(let i=ff.length-2;!filename&&i>=0;i--){filename=ff[i]}}for(let i=0;i<set.length;i++){const pattern=set[i];let file=ff;if(options.matchBase&&pattern.length===1){file=[filename]}const hit=this.matchOne(file,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.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;init_esbuild_shims();import path3 from"node:path";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(text2){let index=0;const limit=HOSTED_GLOB_MAX_ALTERNATIVES+1;const sequence2=__name(depth=>{let product=1;while(index<text2.length){const char=text2[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(text2[index]===","){index++;items.push(sequence2(depth))}if(text2[index]!=="}")return Infinity;const body=text2.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 range=SEQUENCE.exec(body);if(!range)return 1;if([range[1],range[2],range[5]].some(value=>value!==void 0&&!Number.isSafeInteger(Number(value))))return Infinity;const step=Math.max(Math.abs(Number(range[5]??1)),1);const span=range[1]!==void 0?Math.abs(Number(range[2])-Number(range[1])):Math.abs(range[4].charCodeAt(0)-range[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 text2=first&&typeof first==="object"&&"text"in first?first.text:void 0;if(typeof text2!=="string")return null;let parsed;try{parsed=JSON.parse(text2)}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(identity["profile"]==="csi-files-retirement/1"&&identity["capabilityDigest"]===CSI_FILES_RETIREMENT_CAPABILITY_DIGEST);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,...fields}=context;parseManagedContextBoot({...fields,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,prefix=false){ensure(typeof value==="string"&&(prefix?/^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"]==="csi-files-retirement/1"&&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{ManagedPackageCompatibilityError,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,RESIDENT_WORKSPACE_CAPABILITY_DIGEST,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,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
  /**
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{mapSkillConfigToStatus}from"./chunk-BJ5KZREO.js";import{resolveSkillSettings}from"./chunk-AVCBF5WL.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{loadSettings}from"./chunk-2B3W7IQY.js";import{resolveLanguage,resolveLanguageSetting}from"./chunk-EZMTX4EU.js";import{ExtensionManager,ExtensionStore,SkillManager,getExtensionDisplayName,isSafeModeEnv}from"./chunk-LIIMQ4DI.js";import{authoredSkillName,qualifySkillName}from"./chunk-CV2UAEZA.js";import{writeStderrLine}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";var VALID_SKILL_LEVELS=new Set(["project","user","extension","bundled"]);function createWorkspaceSkillsStatusProvider(options={}){const managers=new Map;const provider=__name((workspaceCwd=>buildWorkspaceSkillsStatus(workspaceCwd,managers,options.workspaceTrusted??true,options.includeUntrustedSkills??false)),"provider");provider.invalidate=workspaceCwd=>managers.delete(workspaceCwd);provider.snapshot=async workspaceCwd=>{if(options.workspaceTrusted===false)throw new Error("Skills snapshots require a trusted Workspace.");const freshManagers=new Map;const status=await buildWorkspaceSkillsStatus(workspaceCwd,freshManagers,true,false);const manager=freshManagers.get(workspaceCwd)?.skillManager;if(!status.initialized||status.errors?.length||!manager||manager.hasDiscoveryErrors())throw new Error("The enabled Skills could not be completely discovered.");const configured=new Map(manager.getCachedSkills().map(skill=>[skill.name,skill]));const skills=status.skills.filter(skill=>skill.status==="ok").map(entry=>{const skill=configured.get(entry.name);if(!skill)throw new Error("An enabled Skill is missing its instructions.");return{name:entry.name,description:entry.description,body:skill.body,...entry.modelInvocable?{}:{model_invocable:false},...entry.userInvocable===false?{user_invocable:false}:{}}});if(skills.length>256||skills.some(skill=>Buffer.byteLength(skill.body,"utf8")>512*1024)||Buffer.byteLength(JSON.stringify(skills),"utf8")>2*1024*1024)throw new Error("Enabled Skills exceed the 256-item, 512-KiB/body or 2-MiB catalog limit.");return{workspaceCwd,skills}};return provider}__name(createWorkspaceSkillsStatusProvider,"createWorkspaceSkillsStatusProvider");async function buildWorkspaceSkillsStatus(workspaceCwd,managers,workspaceTrusted,includeUntrustedSkills){try{const settings=loadSettings(workspaceCwd,{consumeCorruptionEnvVars:false,skipLoadEnvironment:true,skipWorkspaceSettings:!workspaceTrusted,workspaceTrusted});const rawLanguage=settings.merged.general?.language;const locale=resolveLanguage(resolveLanguageSetting(typeof rawLanguage==="string"?rawLanguage:void 0));let cached=managers.get(workspaceCwd);if(!cached){const rawLevels=!workspaceTrusted||isSafeModeEnv()?void 0:settings.merged.skills?.disabledLevels;const disabledLevels=new Set(Array.isArray(rawLevels)?rawLevels.filter(v=>typeof v==="string"&&VALID_SKILL_LEVELS.has(v)):[]);const safeMode=!workspaceTrusted&&!includeUntrustedSkills||isSafeModeEnv();let extensionManager2;const extensionSkillStates2=new Map;if(workspaceTrusted&&!safeMode){const directory=Storage.getUserExtensionsDir();const entry=await fs.lstat(directory).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(entry){await fs.readdir(directory);const extensionStore=new ExtensionStore;extensionManager2=new ExtensionManager({extensionStore,workspaceDir:workspaceCwd,isWorkspaceTrusted:workspaceTrusted,locale});const snapshot=await extensionManager2.refreshCacheWithSnapshot();for(const extension of extensionManager2.getLoadedExtensions()){const states=new Map;for(const skill of extension.skills??[]){const name=skill.name.trim().toLowerCase();const defaults=extension.config.skillStates;const defaultEnabled=defaults&&Object.hasOwn(defaults,name)?defaults[name]:true;states.set(name,extensionStore.getSkillWorkspaceOverride(snapshot,extension.id,workspaceCwd,name)??defaultEnabled)}extensionSkillStates2.set(extension,states)}}}const shim={isSafeMode:__name(()=>safeMode,"isSafeMode"),getBareMode:__name(()=>false,"getBareMode"),getProjectRoot:__name(()=>workspaceCwd,"getProjectRoot"),getActiveExtensions:__name(()=>extensionManager2?.getLoadedExtensions().filter(e=>e.isActive)??[],"getActiveExtensions"),getDisabledSkillLevels:__name(()=>disabledLevels,"getDisabledSkillLevels")};const skillManager2=new SkillManager(shim);if(!safeMode){for(const level of["project","user"]){if(disabledLevels.has(level))continue;for(const directory of skillManager2.getSkillsBaseDirs(level)){try{await fs.readdir(directory)}catch(error){if(error.code!=="ENOENT"){throw error}}}}}cached={skillManager:skillManager2,extensionManager:extensionManager2,extensionSkillStates:extensionSkillStates2};managers.set(workspaceCwd,cached)}const{disablements,enabledNames}=resolveSkillSettings(settings);const{skillManager,extensionManager,extensionSkillStates}=cached;const extensions=extensionManager?.getLoadedExtensions()??[];const skills=await skillManager.listSkills();const statuses=skills.map(skill=>{const extension=skill.level==="extension"?extensions.find(e=>e.name===skill.extensionName):void 0;const enabled=extension?extensionSkillStates.get(extension)?.get(authoredSkillName(skill).trim().toLowerCase()):void 0;const localizedSkill=extension?.displayName!==void 0?{...skill,extensionDisplayName:getExtensionDisplayName(extension,locale)}:skill;return mapSkillConfigToStatus(localizedSkill,disablements,{enabled:enabledNames.has(skill.name.trim().toLowerCase())||enabled!==false})});for(const extension of extensions){if(extension.isActive)continue;const seenNames=new Set;for(const skill of extension.skills??[]){if(seenNames.has(skill.name))continue;seenNames.add(skill.name);statuses.push(mapSkillConfigToStatus({...skill,name:qualifySkillName(extension.name,skill.name),authoredName:skill.name,level:"extension",extensionName:extension.name,extensionDisplayName:extension.displayName===void 0?void 0:getExtensionDisplayName(extension,locale)},disablements,{disabled:true}))}}return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:true,skills:statuses.sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const message=error instanceof Error?error.message:String(error);writeStderrLine(`qwen serve: daemon-local skills enumeration failed for ${workspaceCwd}: ${message}`);return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:false,skills:[],errors:[{kind:"skills",status:"error",error:message}]}}}__name(buildWorkspaceSkillsStatus,"buildWorkspaceSkillsStatus");export{createWorkspaceSkillsStatusProvider};
3
+ import{mapSkillConfigToStatus}from"./chunk-BJ5KZREO.js";import{resolveSkillSettings}from"./chunk-AVCBF5WL.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{loadSettings}from"./chunk-MVGQFFIK.js";import{resolveLanguage,resolveLanguageSetting}from"./chunk-EZMTX4EU.js";import{ExtensionManager,ExtensionStore,SkillManager,getExtensionDisplayName,isSafeModeEnv}from"./chunk-LZNBHBAJ.js";import{authoredSkillName,qualifySkillName}from"./chunk-CV2UAEZA.js";import{writeStderrLine}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";var VALID_SKILL_LEVELS=new Set(["project","user","extension","bundled"]);function createWorkspaceSkillsStatusProvider(options={}){const managers=new Map;const provider=__name((workspaceCwd=>buildWorkspaceSkillsStatus(workspaceCwd,managers,options.workspaceTrusted??true,options.includeUntrustedSkills??false)),"provider");provider.invalidate=workspaceCwd=>managers.delete(workspaceCwd);provider.snapshot=async workspaceCwd=>{if(options.workspaceTrusted===false)throw new Error("Skills snapshots require a trusted Workspace.");const freshManagers=new Map;const status=await buildWorkspaceSkillsStatus(workspaceCwd,freshManagers,true,false);const manager=freshManagers.get(workspaceCwd)?.skillManager;if(!status.initialized||status.errors?.length||!manager||manager.hasDiscoveryErrors())throw new Error("The enabled Skills could not be completely discovered.");const configured=new Map(manager.getCachedSkills().map(skill=>[skill.name,skill]));const skills=status.skills.filter(skill=>skill.status==="ok").map(entry=>{const skill=configured.get(entry.name);if(!skill)throw new Error("An enabled Skill is missing its instructions.");return{name:entry.name,description:entry.description,body:skill.body,...entry.modelInvocable?{}:{model_invocable:false},...entry.userInvocable===false?{user_invocable:false}:{}}});if(skills.length>256||skills.some(skill=>Buffer.byteLength(skill.body,"utf8")>512*1024)||Buffer.byteLength(JSON.stringify(skills),"utf8")>2*1024*1024)throw new Error("Enabled Skills exceed the 256-item, 512-KiB/body or 2-MiB catalog limit.");return{workspaceCwd,skills}};return provider}__name(createWorkspaceSkillsStatusProvider,"createWorkspaceSkillsStatusProvider");async function buildWorkspaceSkillsStatus(workspaceCwd,managers,workspaceTrusted,includeUntrustedSkills){try{const settings=loadSettings(workspaceCwd,{consumeCorruptionEnvVars:false,skipLoadEnvironment:true,skipWorkspaceSettings:!workspaceTrusted,workspaceTrusted});const rawLanguage=settings.merged.general?.language;const locale=resolveLanguage(resolveLanguageSetting(typeof rawLanguage==="string"?rawLanguage:void 0));let cached=managers.get(workspaceCwd);if(!cached){const rawLevels=!workspaceTrusted||isSafeModeEnv()?void 0:settings.merged.skills?.disabledLevels;const disabledLevels=new Set(Array.isArray(rawLevels)?rawLevels.filter(v=>typeof v==="string"&&VALID_SKILL_LEVELS.has(v)):[]);const safeMode=!workspaceTrusted&&!includeUntrustedSkills||isSafeModeEnv();let extensionManager2;const extensionSkillStates2=new Map;if(workspaceTrusted&&!safeMode){const directory=Storage.getUserExtensionsDir();const entry=await fs.lstat(directory).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(entry){await fs.readdir(directory);const extensionStore=new ExtensionStore;extensionManager2=new ExtensionManager({extensionStore,workspaceDir:workspaceCwd,isWorkspaceTrusted:workspaceTrusted,locale});const snapshot=await extensionManager2.refreshCacheWithSnapshot();for(const extension of extensionManager2.getLoadedExtensions()){const states=new Map;for(const skill of extension.skills??[]){const name=skill.name.trim().toLowerCase();const defaults=extension.config.skillStates;const defaultEnabled=defaults&&Object.hasOwn(defaults,name)?defaults[name]:true;states.set(name,extensionStore.getSkillWorkspaceOverride(snapshot,extension.id,workspaceCwd,name)??defaultEnabled)}extensionSkillStates2.set(extension,states)}}}const shim={isSafeMode:__name(()=>safeMode,"isSafeMode"),getBareMode:__name(()=>false,"getBareMode"),getProjectRoot:__name(()=>workspaceCwd,"getProjectRoot"),getActiveExtensions:__name(()=>extensionManager2?.getLoadedExtensions().filter(e=>e.isActive)??[],"getActiveExtensions"),getDisabledSkillLevels:__name(()=>disabledLevels,"getDisabledSkillLevels")};const skillManager2=new SkillManager(shim);if(!safeMode){for(const level of["project","user"]){if(disabledLevels.has(level))continue;for(const directory of skillManager2.getSkillsBaseDirs(level)){try{await fs.readdir(directory)}catch(error){if(error.code!=="ENOENT"){throw error}}}}}cached={skillManager:skillManager2,extensionManager:extensionManager2,extensionSkillStates:extensionSkillStates2};managers.set(workspaceCwd,cached)}const{disablements,enabledNames}=resolveSkillSettings(settings);const{skillManager,extensionManager,extensionSkillStates}=cached;const extensions=extensionManager?.getLoadedExtensions()??[];const skills=await skillManager.listSkills();const statuses=skills.map(skill=>{const extension=skill.level==="extension"?extensions.find(e=>e.name===skill.extensionName):void 0;const enabled=extension?extensionSkillStates.get(extension)?.get(authoredSkillName(skill).trim().toLowerCase()):void 0;const localizedSkill=extension?.displayName!==void 0?{...skill,extensionDisplayName:getExtensionDisplayName(extension,locale)}:skill;return mapSkillConfigToStatus(localizedSkill,disablements,{enabled:enabledNames.has(skill.name.trim().toLowerCase())||enabled!==false})});for(const extension of extensions){if(extension.isActive)continue;const seenNames=new Set;for(const skill of extension.skills??[]){if(seenNames.has(skill.name))continue;seenNames.add(skill.name);statuses.push(mapSkillConfigToStatus({...skill,name:qualifySkillName(extension.name,skill.name),authoredName:skill.name,level:"extension",extensionName:extension.name,extensionDisplayName:extension.displayName===void 0?void 0:getExtensionDisplayName(extension,locale)},disablements,{disabled:true}))}}return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:true,skills:statuses.sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const message=error instanceof Error?error.message:String(error);writeStderrLine(`qwen serve: daemon-local skills enumeration failed for ${workspaceCwd}: ${message}`);return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:false,skills:[],errors:[{kind:"skills",status:"error",error:message}]}}}__name(buildWorkspaceSkillsStatus,"buildWorkspaceSkillsStatus");export{createWorkspaceSkillsStatusProvider};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{checkTeamMemorySecrets}from"./chunk-UJP2MPBI.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-AKWYMQKU.js";import{CommitAttributionService,createPatchSmart,detectLineEnding,getDiffStat}from"./chunk-LIIMQ4DI.js";import{backgroundFixHolding}from"./chunk-2MB4ZSKF.js";import{getCurrentAgentId}from"./chunk-AGQBNWGY.js";import{FileOperationEvent,logFileOperation}from"./chunk-TNCN2JX2.js";import{findCellIndex,getCellDisplayId,getNotebookLanguage,getSpecificMimeType,hasStableCellIds,inferInsertedCellSourceArrayStyle,inferNotebookJsonFormat,isAmbiguousCellId,makeCellId,normalizeEditedCell,normalizeSource,parseNotebook,serializeNotebook,toNotebookSource}from"./chunk-Y6HHV4LC.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var debugLogger=createDebugLogger("NOTEBOOK_EDIT");function rejectNotebookPriorRead(notebookPath,reason,decision){debugLogger.debug("prior-read-rejected",{path:notebookPath,reason,type:decision.type,displayMessage:decision.displayMessage});return decision}__name(rejectNotebookPriorRead,"rejectNotebookPriorRead");var NotebookEditError=class extends Error{constructor(message,type){super(message);this.type=type;this.name="NotebookEditError"}static{__name(this,"NotebookEditError")}};function requireNotebookSource(source,mode){if(mode==="delete"){return""}if(typeof source!=="string"){throw new NotebookEditError(`new_source is required when edit_mode is "${mode}".`,"invalid_tool_params")}return source}__name(requireNotebookSource,"requireNotebookSource");function displayCellId(cell,index){return cell?getCellDisplayId(cell,index):`cell-${index}`}__name(displayCellId,"displayCellId");function resolveTargetIndex(notebook,cellId,mode){if(!cellId){if(mode==="insert"){return-1}throw new NotebookEditError("cell_id is required for replace and delete operations.","invalid_tool_params")}if(isAmbiguousCellId(notebook,cellId)){throw new NotebookEditError(`Cell ID "${cellId}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params")}const index=findCellIndex(notebook,cellId);if(index===-1){throw new NotebookEditError(`Cell with ID "${cellId}" not found in notebook.`,"notebook_cell_not_found")}return index}__name(resolveTargetIndex,"resolveTargetIndex");function createNotebookCell(notebook,cellType,source,preferSourceArray){const cell={cell_type:cellType,metadata:{},source:toNotebookSource(source,preferSourceArray)};const id=makeCellId(notebook);if(id){cell.id=id}normalizeEditedCell(cell,cellType);return cell}__name(createNotebookCell,"createNotebookCell");function applyNotebookEdit(rawContent,params){let notebook;try{notebook=parseNotebook(rawContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}const mode=params.edit_mode??"replace";const source=requireNotebookSource(params.new_source,mode);const originalHasStableCellIds=hasStableCellIds(notebook);const targetIndex=resolveTargetIndex(notebook,params.cell_id,mode);const language=getNotebookLanguage(notebook);const jsonFormat=inferNotebookJsonFormat(rawContent);const buildResult=__name((updatedNotebook,result)=>{const structuralEdit=mode==="insert"||mode==="delete";return{...result,updatedContent:serializeNotebook(updatedNotebook,jsonFormat),requiresReadAfterWrite:structuralEdit&&!(originalHasStableCellIds&&hasStableCellIds(updatedNotebook))}},"buildResult");switch(mode){case"insert":{const cellType=params.cell_type??"code";const insertAt=targetIndex===-1?0:targetIndex+1;const newCell=createNotebookCell(notebook,cellType,source,inferInsertedCellSourceArrayStyle(notebook,insertAt));notebook.cells.splice(insertAt,0,newCell);return buildResult(notebook,{editedCellId:displayCellId(newCell,insertAt),editedCellType:cellType,language,mode})}case"delete":{const[removed]=notebook.cells.splice(targetIndex,1);return buildResult(notebook,{editedCellId:displayCellId(removed,targetIndex),editedCellType:removed?.cell_type,language,mode})}case"replace":{const target=notebook.cells[targetIndex];if(!target){throw new NotebookEditError(`Cell index ${targetIndex} is out of range.`,"notebook_cell_not_found")}const finalType=params.cell_type??target.cell_type;target.source=toNotebookSource(source,Array.isArray(target.source));normalizeEditedCell(target,finalType);return buildResult(notebook,{editedCellId:displayCellId(target,targetIndex),editedCellType:finalType,language,mode})}default:throw new NotebookEditError(`Unsupported notebook edit mode: ${mode}`,"invalid_tool_params")}}__name(applyNotebookEdit,"applyNotebookEdit");function prepareModifiedNotebookContent(originalContent,modifiedContent,params){let notebook;let originalNotebook;try{notebook=parseNotebook(modifiedContent);originalNotebook=parseNotebook(originalContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}return{updatedContent:modifiedContent,editedCellId:params.cell_id??"user-modified-notebook",editedCellType:void 0,language:getNotebookLanguage(notebook),mode:params.edit_mode??"replace",requiresReadAfterWrite:!hasStableCellIds(originalNotebook)||!hasStableCellIds(notebook)}}__name(prepareModifiedNotebookContent,"prepareModifiedNotebookContent");async function checkPriorNotebookRead(config,notebookPath,options={}){if(config.getFileReadCacheDisabled()){return{ok:true}}let stats;try{stats=await fs.promises.stat(notebookPath)}catch(error){const code=error?.code;if(code==="ENOENT"){if(options.expectExisting){return rejectNotebookPriorRead(notebookPath,"missing-after-read",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} disappeared after it was read. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${ToolNames.READ_FILE} first.`})}return{ok:true}}return rejectNotebookPriorRead(notebookPath,"stat-failed",{ok:false,type:"prior_read_verification_failed",rawMessage:`Could not stat ${notebookPath} to verify prior notebook read (${code??"unknown error"}). Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${notebookPath}; re-run ${ToolNames.READ_FILE} before editing this notebook.`})}if(stats.isDirectory()){return rejectNotebookPriorRead(notebookPath,"target-is-directory",{ok:false,type:"target_is_directory",rawMessage:`${notebookPath} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."})}if(!stats.isFile()){return rejectNotebookPriorRead(notebookPath,"target-not-regular-file",{ok:false,type:"target_not_regular_file",rawMessage:`${notebookPath} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."})}const status=config.getFileReadCache().check(stats);if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&status.entry.lastReadWasFull){return{ok:true}}if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&!status.entry.lastReadWasFull){return rejectNotebookPriorRead(notebookPath,"truncated-cache-entry",{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."})}if(status.state==="stale"){return rejectNotebookPriorRead(notebookPath,"stale-cache-entry",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} has been modified since you last read it. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${ToolNames.READ_FILE} first.`})}if(status.state==="unverifiable"){return rejectNotebookPriorRead(notebookPath,"unverifiable-cache-entry",{ok:false,type:"prior_read_verification_failed",rawMessage:`Notebook ${notebookPath} is on a filesystem that does not provide a verifiable inode identity (ino=0), so NotebookEdit cannot safely confirm a prior read. Use a different mechanism to edit this notebook.`,displayMessage:`cannot verify prior read of ${notebookPath}; use a different mechanism to edit it.`})}return rejectNotebookPriorRead(notebookPath,`cache-${status.state}`,{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} has not been fully read in this session. Use the ${ToolNames.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${ToolNames.READ_FILE} required before editing this notebook.`})}__name(checkPriorNotebookRead,"checkPriorNotebookRead");var NotebookEditInvocation=class extends BaseToolInvocation{constructor(config,params,modifyMetadata){super(params);this.config=config;this.modifyMetadata=modifyMetadata}static{__name(this,"NotebookEditInvocation")}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){const relativePath=makeRelative(this.params.notebook_path,this.config.getTargetDir());const mode=this.params.edit_mode??"replace";const cell=this.params.cell_id??"beginning";return`${mode} notebook cell ${cell} in ${shortenPath(relativePath)}`}async getDefaultPermission(){return"ask"}requiresUserInteraction(){return backgroundFixHolding(this.params.notebook_path,getCurrentAgentId())!==void 0}async getConfirmationDetails(abortSignal){const prepared=await this.prepareEdit(abortSignal);const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Notebook Edit: ${shortenPath(makeRelative(this.params.notebook_path,this.config.getTargetDir()))}`,fileName,filePath:this.params.notebook_path,fileDiff,originalContent:prepared.originalContent,newContent:prepared.updatedContent,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async prepareEdit(abortSignal){const preDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path);if(!preDecision.ok){throw new StructuredToolError(preDecision.rawMessage,preDecision.type)}let originalContent;let bom=false;let encoding;let lineEnding="lf";try{const fileInfo=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});originalContent=fileInfo.content;bom=fileInfo._meta?.bom??false;encoding=fileInfo._meta?.encoding;lineEnding=fileInfo._meta?.lineEnding??detectLineEnding(fileInfo.content)}catch(error){if(abortSignal.aborted){throw error}const code=error?.code;if(code==="ENOENT"){throw new StructuredToolError(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found")}throw new StructuredToolError(`Error reading notebook: ${error instanceof Error?error.message:String(error)}`,"read_content_failure")}const postDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!postDecision.ok){throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}try{if(this.modifyMetadata?.modifiedNotebookContent!==void 0){return{...prepareModifiedNotebookContent(originalContent,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent,bom,encoding,lineEnding}}return{...applyNotebookEdit(originalContent,this.params),originalContent,bom,encoding,lineEnding}}catch(error){if(error instanceof NotebookEditError){throw new StructuredToolError(error.message,error.type)}throw error}}async execute(signal){let prepared;try{prepared=await this.prepareEdit(signal)}catch(error){if(signal.aborted){throw error}const errorType=error instanceof StructuredToolError?error.errorType:"notebook_edit_failure";const message=error instanceof Error?error.message:String(error);return{llmContent:message,returnDisplay:`Error: ${message}`,error:{message,type:errorType}}}const teamMemoryError=checkTeamMemorySecrets(this.params.notebook_path,prepared.updatedContent,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}const writeDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!writeDecision.ok){return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:prepared.updatedContent,toolWriteOrigin:"notebook_edit",_meta:{bom:prepared.bom,encoding:prepared.encoding,lineEnding:prepared.lineEnding}});if(!this.modifyMetadata?.modifiedByUser){CommitAttributionService.getInstance().recordEdit(this.params.notebook_path,prepared.originalContent,prepared.updatedContent)}let postWriteSizeBytes;try{const postWriteStats=fs.statSync(this.params.notebook_path);postWriteSizeBytes=postWriteStats.size;const cache=this.config.getFileReadCache();if(prepared.requiresReadAfterWrite){cache.invalidate(postWriteStats)}else{cache.recordWrite(this.params.notebook_path,postWriteStats,{cacheable:false})}}catch(error){debugLogger.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${error instanceof Error?error.message:String(error)}`)}const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const diffStat=getDiffStat(fileName,prepared.originalContent,this.modifyMetadata?.aiProposedContent??prepared.updatedContent,prepared.updatedContent);logFileOperation(this.config,new FileOperationEvent(NotebookEditTool.Name,"update",prepared.updatedContent.split("\n").length,getSpecificMimeType(this.params.notebook_path),".ipynb",prepared.language));const displayResult={fileDiff,fileName,filePath:this.params.notebook_path,originalContent:prepared.originalContent,newContent:prepared.updatedContent,diffStat};const artifact=buildWorkspaceArtifactCandidate(this.config,this.params.notebook_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});const reminder=artifact&&!artifact.updateOnly?` ${formatRecordArtifactReminder(artifact.workspacePath)}`:"";const llmContent=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated.${reminder} Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${prepared.mode} cell ${prepared.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated.${reminder} ${prepared.mode} cell ${prepared.editedCellId}.${prepared.mode==="delete"?"":`
3
+ import{checkTeamMemorySecrets}from"./chunk-UJP2MPBI.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-AKWYMQKU.js";import{CommitAttributionService,createPatchSmart,detectLineEnding,getDiffStat}from"./chunk-LZNBHBAJ.js";import{backgroundFixHolding}from"./chunk-2MB4ZSKF.js";import{getCurrentAgentId}from"./chunk-AGQBNWGY.js";import{FileOperationEvent,logFileOperation}from"./chunk-TNCN2JX2.js";import{findCellIndex,getCellDisplayId,getNotebookLanguage,getSpecificMimeType,hasStableCellIds,inferInsertedCellSourceArrayStyle,inferNotebookJsonFormat,isAmbiguousCellId,makeCellId,normalizeEditedCell,normalizeSource,parseNotebook,serializeNotebook,toNotebookSource}from"./chunk-Y6HHV4LC.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var debugLogger=createDebugLogger("NOTEBOOK_EDIT");function rejectNotebookPriorRead(notebookPath,reason,decision){debugLogger.debug("prior-read-rejected",{path:notebookPath,reason,type:decision.type,displayMessage:decision.displayMessage});return decision}__name(rejectNotebookPriorRead,"rejectNotebookPriorRead");var NotebookEditError=class extends Error{constructor(message,type){super(message);this.type=type;this.name="NotebookEditError"}static{__name(this,"NotebookEditError")}};function requireNotebookSource(source,mode){if(mode==="delete"){return""}if(typeof source!=="string"){throw new NotebookEditError(`new_source is required when edit_mode is "${mode}".`,"invalid_tool_params")}return source}__name(requireNotebookSource,"requireNotebookSource");function displayCellId(cell,index){return cell?getCellDisplayId(cell,index):`cell-${index}`}__name(displayCellId,"displayCellId");function resolveTargetIndex(notebook,cellId,mode){if(!cellId){if(mode==="insert"){return-1}throw new NotebookEditError("cell_id is required for replace and delete operations.","invalid_tool_params")}if(isAmbiguousCellId(notebook,cellId)){throw new NotebookEditError(`Cell ID "${cellId}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params")}const index=findCellIndex(notebook,cellId);if(index===-1){throw new NotebookEditError(`Cell with ID "${cellId}" not found in notebook.`,"notebook_cell_not_found")}return index}__name(resolveTargetIndex,"resolveTargetIndex");function createNotebookCell(notebook,cellType,source,preferSourceArray){const cell={cell_type:cellType,metadata:{},source:toNotebookSource(source,preferSourceArray)};const id=makeCellId(notebook);if(id){cell.id=id}normalizeEditedCell(cell,cellType);return cell}__name(createNotebookCell,"createNotebookCell");function applyNotebookEdit(rawContent,params){let notebook;try{notebook=parseNotebook(rawContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}const mode=params.edit_mode??"replace";const source=requireNotebookSource(params.new_source,mode);const originalHasStableCellIds=hasStableCellIds(notebook);const targetIndex=resolveTargetIndex(notebook,params.cell_id,mode);const language=getNotebookLanguage(notebook);const jsonFormat=inferNotebookJsonFormat(rawContent);const buildResult=__name((updatedNotebook,result)=>{const structuralEdit=mode==="insert"||mode==="delete";return{...result,updatedContent:serializeNotebook(updatedNotebook,jsonFormat),requiresReadAfterWrite:structuralEdit&&!(originalHasStableCellIds&&hasStableCellIds(updatedNotebook))}},"buildResult");switch(mode){case"insert":{const cellType=params.cell_type??"code";const insertAt=targetIndex===-1?0:targetIndex+1;const newCell=createNotebookCell(notebook,cellType,source,inferInsertedCellSourceArrayStyle(notebook,insertAt));notebook.cells.splice(insertAt,0,newCell);return buildResult(notebook,{editedCellId:displayCellId(newCell,insertAt),editedCellType:cellType,language,mode})}case"delete":{const[removed]=notebook.cells.splice(targetIndex,1);return buildResult(notebook,{editedCellId:displayCellId(removed,targetIndex),editedCellType:removed?.cell_type,language,mode})}case"replace":{const target=notebook.cells[targetIndex];if(!target){throw new NotebookEditError(`Cell index ${targetIndex} is out of range.`,"notebook_cell_not_found")}const finalType=params.cell_type??target.cell_type;target.source=toNotebookSource(source,Array.isArray(target.source));normalizeEditedCell(target,finalType);return buildResult(notebook,{editedCellId:displayCellId(target,targetIndex),editedCellType:finalType,language,mode})}default:throw new NotebookEditError(`Unsupported notebook edit mode: ${mode}`,"invalid_tool_params")}}__name(applyNotebookEdit,"applyNotebookEdit");function prepareModifiedNotebookContent(originalContent,modifiedContent,params){let notebook;let originalNotebook;try{notebook=parseNotebook(modifiedContent);originalNotebook=parseNotebook(originalContent)}catch(error){throw new NotebookEditError(error instanceof Error?error.message:String(error),"notebook_invalid_json")}return{updatedContent:modifiedContent,editedCellId:params.cell_id??"user-modified-notebook",editedCellType:void 0,language:getNotebookLanguage(notebook),mode:params.edit_mode??"replace",requiresReadAfterWrite:!hasStableCellIds(originalNotebook)||!hasStableCellIds(notebook)}}__name(prepareModifiedNotebookContent,"prepareModifiedNotebookContent");async function checkPriorNotebookRead(config,notebookPath,options={}){if(config.getFileReadCacheDisabled()){return{ok:true}}let stats;try{stats=await fs.promises.stat(notebookPath)}catch(error){const code=error?.code;if(code==="ENOENT"){if(options.expectExisting){return rejectNotebookPriorRead(notebookPath,"missing-after-read",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} disappeared after it was read. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${ToolNames.READ_FILE} first.`})}return{ok:true}}return rejectNotebookPriorRead(notebookPath,"stat-failed",{ok:false,type:"prior_read_verification_failed",rawMessage:`Could not stat ${notebookPath} to verify prior notebook read (${code??"unknown error"}). Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${notebookPath}; re-run ${ToolNames.READ_FILE} before editing this notebook.`})}if(stats.isDirectory()){return rejectNotebookPriorRead(notebookPath,"target-is-directory",{ok:false,type:"target_is_directory",rawMessage:`${notebookPath} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."})}if(!stats.isFile()){return rejectNotebookPriorRead(notebookPath,"target-not-regular-file",{ok:false,type:"target_not_regular_file",rawMessage:`${notebookPath} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."})}const status=config.getFileReadCache().check(stats);if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&status.entry.lastReadWasFull){return{ok:true}}if(status.state==="fresh"&&status.entry.lastReadAt!==void 0&&!status.entry.lastReadWasFull){return rejectNotebookPriorRead(notebookPath,"truncated-cache-entry",{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."})}if(status.state==="stale"){return rejectNotebookPriorRead(notebookPath,"stale-cache-entry",{ok:false,type:"file_changed_since_read",rawMessage:`Notebook ${notebookPath} has been modified since you last read it. Re-read it with the ${ToolNames.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${ToolNames.READ_FILE} first.`})}if(status.state==="unverifiable"){return rejectNotebookPriorRead(notebookPath,"unverifiable-cache-entry",{ok:false,type:"prior_read_verification_failed",rawMessage:`Notebook ${notebookPath} is on a filesystem that does not provide a verifiable inode identity (ino=0), so NotebookEdit cannot safely confirm a prior read. Use a different mechanism to edit this notebook.`,displayMessage:`cannot verify prior read of ${notebookPath}; use a different mechanism to edit it.`})}return rejectNotebookPriorRead(notebookPath,`cache-${status.state}`,{ok:false,type:"edit_requires_prior_read",rawMessage:`Notebook ${notebookPath} has not been fully read in this session. Use the ${ToolNames.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${ToolNames.READ_FILE} required before editing this notebook.`})}__name(checkPriorNotebookRead,"checkPriorNotebookRead");var NotebookEditInvocation=class extends BaseToolInvocation{constructor(config,params,modifyMetadata){super(params);this.config=config;this.modifyMetadata=modifyMetadata}static{__name(this,"NotebookEditInvocation")}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){const relativePath=makeRelative(this.params.notebook_path,this.config.getTargetDir());const mode=this.params.edit_mode??"replace";const cell=this.params.cell_id??"beginning";return`${mode} notebook cell ${cell} in ${shortenPath(relativePath)}`}async getDefaultPermission(){return"ask"}requiresUserInteraction(){return backgroundFixHolding(this.params.notebook_path,getCurrentAgentId())!==void 0}async getConfirmationDetails(abortSignal){const prepared=await this.prepareEdit(abortSignal);const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Notebook Edit: ${shortenPath(makeRelative(this.params.notebook_path,this.config.getTargetDir()))}`,fileName,filePath:this.params.notebook_path,fileDiff,originalContent:prepared.originalContent,newContent:prepared.updatedContent,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async prepareEdit(abortSignal){const preDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path);if(!preDecision.ok){throw new StructuredToolError(preDecision.rawMessage,preDecision.type)}let originalContent;let bom=false;let encoding;let lineEnding="lf";try{const fileInfo=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});originalContent=fileInfo.content;bom=fileInfo._meta?.bom??false;encoding=fileInfo._meta?.encoding;lineEnding=fileInfo._meta?.lineEnding??detectLineEnding(fileInfo.content)}catch(error){if(abortSignal.aborted){throw error}const code=error?.code;if(code==="ENOENT"){throw new StructuredToolError(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found")}throw new StructuredToolError(`Error reading notebook: ${error instanceof Error?error.message:String(error)}`,"read_content_failure")}const postDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!postDecision.ok){throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}try{if(this.modifyMetadata?.modifiedNotebookContent!==void 0){return{...prepareModifiedNotebookContent(originalContent,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent,bom,encoding,lineEnding}}return{...applyNotebookEdit(originalContent,this.params),originalContent,bom,encoding,lineEnding}}catch(error){if(error instanceof NotebookEditError){throw new StructuredToolError(error.message,error.type)}throw error}}async execute(signal){let prepared;try{prepared=await this.prepareEdit(signal)}catch(error){if(signal.aborted){throw error}const errorType=error instanceof StructuredToolError?error.errorType:"notebook_edit_failure";const message=error instanceof Error?error.message:String(error);return{llmContent:message,returnDisplay:`Error: ${message}`,error:{message,type:errorType}}}const teamMemoryError=checkTeamMemorySecrets(this.params.notebook_path,prepared.updatedContent,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}const writeDecision=await checkPriorNotebookRead(this.config,this.params.notebook_path,{expectExisting:true});if(!writeDecision.ok){return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:prepared.updatedContent,toolWriteOrigin:"notebook_edit",_meta:{bom:prepared.bom,encoding:prepared.encoding,lineEnding:prepared.lineEnding}});if(!this.modifyMetadata?.modifiedByUser){CommitAttributionService.getInstance().recordEdit(this.params.notebook_path,prepared.originalContent,prepared.updatedContent)}let postWriteSizeBytes;try{const postWriteStats=fs.statSync(this.params.notebook_path);postWriteSizeBytes=postWriteStats.size;const cache=this.config.getFileReadCache();if(prepared.requiresReadAfterWrite){cache.invalidate(postWriteStats)}else{cache.recordWrite(this.params.notebook_path,postWriteStats,{cacheable:false})}}catch(error){debugLogger.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${error instanceof Error?error.message:String(error)}`)}const fileName=path.basename(this.params.notebook_path);const fileDiff=createPatchSmart(fileName,prepared.originalContent,prepared.updatedContent,"Current","Proposed");const diffStat=getDiffStat(fileName,prepared.originalContent,this.modifyMetadata?.aiProposedContent??prepared.updatedContent,prepared.updatedContent);logFileOperation(this.config,new FileOperationEvent(NotebookEditTool.Name,"update",prepared.updatedContent.split("\n").length,getSpecificMimeType(this.params.notebook_path),".ipynb",prepared.language));const displayResult={fileDiff,fileName,filePath:this.params.notebook_path,originalContent:prepared.originalContent,newContent:prepared.updatedContent,diffStat};const artifact=buildWorkspaceArtifactCandidate(this.config,this.params.notebook_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});const reminder=artifact&&!artifact.updateOnly?` ${formatRecordArtifactReminder(artifact.workspacePath)}`:"";const llmContent=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated.${reminder} Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${prepared.mode} cell ${prepared.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated.${reminder} ${prepared.mode} cell ${prepared.editedCellId}.${prepared.mode==="delete"?"":`
4
4
 
5
5
  Updated source:
6
6