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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/chunks/{MaxSizedBox-XGJBXFET.js → MaxSizedBox-QRQEXRXW.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-BNFJWFLQ.js → StandaloneSessionPicker-X274Q6BX.js} +1 -1
  3. package/chunks/{acp-subagent-executor-P5FBYPD5.js → acp-subagent-executor-YIFQD4LJ.js} +1 -1
  4. package/chunks/{acpAgent-J6G57ZCE.js → acpAgent-NW4XNW7P.js} +3 -3
  5. package/chunks/{advisor-3O63GFOM.js → advisor-W7KCVPBR.js} +1 -1
  6. package/chunks/{agent-ALZEISY2.js → agent-FGDWPNXW.js} +1 -1
  7. package/chunks/{agent-headless-XAKKB6OT.js → agent-headless-7KA3VVAB.js} +1 -1
  8. package/chunks/{agent-host-client-DIV2XAL5.js → agent-host-client-YZJLSOLB.js} +1 -1
  9. package/chunks/{agent-host-connections-ZQUMCO2F.js → agent-host-connections-5JGDPG3L.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-ZE7TAQPO.js → anthropicContentGenerator-QUXJVJ3I.js} +1 -1
  11. package/chunks/{autofix-pr-RZ4PWQ46.js → autofix-pr-UDRPJC7L.js} +1 -1
  12. package/chunks/{batch-AIMBHUMX.js → batch-GCEHGR5P.js} +1 -1
  13. package/chunks/{bridge-A3RRGPEI.js → bridge-JY2JXNVV.js} +1 -1
  14. package/chunks/{channel-settings-store-P3KM5GTN.js → channel-settings-store-EX6ZU6R3.js} +1 -1
  15. package/chunks/{chunk-P22U5UQR.js → chunk-27MJJU2I.js} +1 -1
  16. package/chunks/{chunk-RYRMDOIX.js → chunk-2LDABIAY.js} +3 -3
  17. package/chunks/{chunk-MYPEVUKI.js → chunk-2QZDPMIH.js} +1 -1
  18. package/chunks/{chunk-TW2REHPX.js → chunk-2SGTJMSU.js} +1 -1
  19. package/chunks/{chunk-NCW3NPS5.js → chunk-3BHXPXCC.js} +1 -1
  20. package/chunks/{chunk-XUB4JKSR.js → chunk-3NR3JBMA.js} +6 -6
  21. package/chunks/{chunk-NRJOUWP4.js → chunk-3QCFMVI6.js} +1 -1
  22. package/chunks/{chunk-EGMV4S6D.js → chunk-3YOERSU5.js} +1 -1
  23. package/chunks/{chunk-WXKD4L4A.js → chunk-4NIUXYUF.js} +1 -1
  24. package/chunks/{chunk-YHC27L5W.js → chunk-5FS5OQHO.js} +1 -1
  25. package/chunks/{chunk-L76RFQKW.js → chunk-5MGG2BGT.js} +1 -1
  26. package/chunks/{chunk-HHDQ5JAA.js → chunk-66LFVQJP.js} +1 -1
  27. package/chunks/{chunk-RJPELYUW.js → chunk-6KU7LHBT.js} +1 -1
  28. package/chunks/{chunk-SKU5J7Q7.js → chunk-6O7CARPF.js} +1 -1
  29. package/chunks/{chunk-CPOFE42B.js → chunk-6Z3TBTUS.js} +1 -1
  30. package/chunks/{chunk-HRRQHZQE.js → chunk-73TSS7KS.js} +1 -1
  31. package/chunks/{chunk-BSGONILH.js → chunk-776L3HAN.js} +1 -1
  32. package/chunks/{chunk-MZNZYCAC.js → chunk-7BL2OTHX.js} +1 -1
  33. package/chunks/{chunk-5DPLJQUC.js → chunk-7GYFDPEP.js} +1 -1
  34. package/chunks/{chunk-OD44AOSX.js → chunk-7KGCNYE4.js} +1 -1
  35. package/chunks/{chunk-4JLLFT6S.js → chunk-7SX547WS.js} +1 -1
  36. package/chunks/{chunk-5Q6POUDM.js → chunk-7VIES3RW.js} +1 -1
  37. package/chunks/{chunk-NMK72ZA4.js → chunk-ABEBQNYK.js} +1 -1
  38. package/chunks/{chunk-QZ5JBF3E.js → chunk-AD7JBW6R.js} +2 -2
  39. package/chunks/{chunk-E6XRNALG.js → chunk-AEX3XSTE.js} +1 -1
  40. package/chunks/{chunk-B7CYUTAO.js → chunk-AKDODQCI.js} +1 -1
  41. package/chunks/{chunk-EEARSY3D.js → chunk-B3I5LFFK.js} +1 -1
  42. package/chunks/{chunk-YSGVX6LT.js → chunk-B5Y56PDI.js} +1 -1
  43. package/chunks/{chunk-MEFN5DY3.js → chunk-BEBKKJP3.js} +1 -1
  44. package/chunks/{chunk-GYCGVZ32.js → chunk-BFPP7X4E.js} +1 -1
  45. package/chunks/{chunk-GNWPYWGQ.js → chunk-BY5GX6DQ.js} +1 -1
  46. package/chunks/{chunk-6W5ZZSQF.js → chunk-CUX3C6QV.js} +1 -1
  47. package/chunks/{chunk-HXYHIEMH.js → chunk-CXPRHT3E.js} +1 -1
  48. package/chunks/{chunk-53CWA7N2.js → chunk-D5H5GARR.js} +1 -1
  49. package/chunks/{chunk-DV67DRNT.js → chunk-DLY7QJ5Y.js} +1 -1
  50. package/chunks/{chunk-SFDOJ2FF.js → chunk-DN4QKOFL.js} +1 -1
  51. package/chunks/{chunk-VOAIDOUV.js → chunk-DP4YE24V.js} +1 -1
  52. package/chunks/{chunk-D2X6A5FH.js → chunk-DQLI7HH7.js} +1 -1
  53. package/chunks/{chunk-ET7ADS4X.js → chunk-DS2FKATN.js} +1 -1
  54. package/chunks/{chunk-FRSSRLIO.js → chunk-E6EW43WZ.js} +1 -1
  55. package/chunks/{chunk-F4AWT5LV.js → chunk-EEBFFC76.js} +1 -1
  56. package/chunks/{chunk-B7PJ5TNK.js → chunk-EGKUF5NS.js} +2 -2
  57. package/chunks/{chunk-B2YLVSQE.js → chunk-ERMAKXS3.js} +2 -2
  58. package/chunks/{chunk-PEZZTKPM.js → chunk-FB73O3E5.js} +1 -1
  59. package/chunks/{chunk-36DBNBTF.js → chunk-FEIUMWFA.js} +1 -1
  60. package/chunks/{chunk-YE3LA3U4.js → chunk-FWJKQA2H.js} +1 -1
  61. package/chunks/{chunk-VDNPMX5W.js → chunk-FZQJOSHD.js} +1 -1
  62. package/chunks/{chunk-YYSMMFK7.js → chunk-GNI5J2ON.js} +1 -1
  63. package/chunks/{chunk-6OCKLRQC.js → chunk-H3VGRICV.js} +1 -1
  64. package/chunks/{chunk-OSLFWRV2.js → chunk-HRTWLOGK.js} +1 -1
  65. package/chunks/{chunk-XZYQKCTU.js → chunk-IGIZ6AZE.js} +1 -1
  66. package/chunks/{chunk-RIBVEHUG.js → chunk-IHB7CDQ2.js} +1 -1
  67. package/chunks/{chunk-LO6OFMFC.js → chunk-IHEGGZBE.js} +1 -1
  68. package/chunks/{chunk-N5S6SIRO.js → chunk-IMTHBYJP.js} +1 -1
  69. package/chunks/{chunk-I5F24CVP.js → chunk-IP3K5SRR.js} +1 -1
  70. package/chunks/{chunk-2FYWJVGW.js → chunk-ISA4MFNT.js} +1 -1
  71. package/chunks/{chunk-GV3E2RHX.js → chunk-JGF3ND5D.js} +1 -1
  72. package/chunks/{chunk-ASQ7BSJ4.js → chunk-JJ4UPR4A.js} +1 -1
  73. package/chunks/{chunk-HOCNE2LO.js → chunk-JTUWFGEB.js} +1 -1
  74. package/chunks/{chunk-FDQFJFO5.js → chunk-KAN5KUJD.js} +1 -1
  75. package/chunks/{chunk-K7GCWWTI.js → chunk-KU4F6SSJ.js} +2 -2
  76. package/chunks/{chunk-QDQQFQB4.js → chunk-LBAINHIN.js} +1 -1
  77. package/chunks/{chunk-BAPIZCC7.js → chunk-LTJLPYFS.js} +1 -1
  78. package/chunks/{chunk-ZOUMCSDW.js → chunk-MSNPEQ2I.js} +1 -1
  79. package/chunks/{chunk-MPDGSR2S.js → chunk-N3YWQWSR.js} +5 -5
  80. package/chunks/{chunk-VEVQB4CI.js → chunk-NDTPBVER.js} +1 -1
  81. package/chunks/{chunk-L4WG2XDS.js → chunk-NJ77L3GS.js} +1 -1
  82. package/chunks/{chunk-U2DX235N.js → chunk-NL62UQDW.js} +1 -1
  83. package/chunks/{chunk-QASJXL5B.js → chunk-NYXR2655.js} +1 -1
  84. package/chunks/{chunk-5SPQ5V35.js → chunk-OEPXWKZL.js} +1 -1
  85. package/chunks/{chunk-EOR7AP7Z.js → chunk-OIKWJN7E.js} +1 -1
  86. package/chunks/{chunk-BT7V3O75.js → chunk-OIQKVWR7.js} +1 -1
  87. package/chunks/{chunk-ESXBBANA.js → chunk-OPBSEVFC.js} +1 -1
  88. package/chunks/{chunk-NW3H676V.js → chunk-P5RBFVMP.js} +1 -1
  89. package/chunks/{chunk-F7KVMGGZ.js → chunk-QD4KNY2J.js} +1 -1
  90. package/chunks/{chunk-2ZE6CAZV.js → chunk-RSLBGXPB.js} +1 -1
  91. package/chunks/{chunk-3R7NEEW7.js → chunk-S542WTV7.js} +1 -1
  92. package/chunks/{chunk-KXAZ2Z5M.js → chunk-SEK234IM.js} +1 -1
  93. package/chunks/{chunk-5DPXLL3H.js → chunk-TM6IVXAM.js} +1 -1
  94. package/chunks/{chunk-KMJLEAS3.js → chunk-TPTV6HPU.js} +1 -1
  95. package/chunks/{chunk-DCUBMMWG.js → chunk-TQ6FKWSC.js} +1 -1
  96. package/chunks/{chunk-JK2S74SA.js → chunk-TUBHG6EI.js} +1 -1
  97. package/chunks/{chunk-FMZ5U7J5.js → chunk-UBPC3F32.js} +1 -1
  98. package/chunks/{chunk-XB7DJWOJ.js → chunk-UG5B4UOQ.js} +6 -6
  99. package/chunks/{chunk-36S57YYW.js → chunk-UGWTN5IK.js} +1 -1
  100. package/chunks/{chunk-SK2DTYBZ.js → chunk-URMRX2MG.js} +1 -1
  101. package/chunks/{chunk-VB4DB57C.js → chunk-UY6J5CHF.js} +1 -1
  102. package/chunks/{chunk-STQ3TEZW.js → chunk-VSTQT667.js} +2 -2
  103. package/chunks/{chunk-SGUUOXLH.js → chunk-WDO33SWR.js} +1 -1
  104. package/chunks/{chunk-IVXR5JO2.js → chunk-WFJHBU7B.js} +1 -1
  105. package/chunks/{chunk-BINJRUHZ.js → chunk-XSRHGC5R.js} +1 -1
  106. package/chunks/{chunk-HN7EGFIP.js → chunk-XVF3FMTM.js} +1 -1
  107. package/chunks/{chunk-C5X6K67T.js → chunk-XYRNYCRQ.js} +1 -1
  108. package/chunks/{chunk-HZOPWFFL.js → chunk-YAMLF3SM.js} +1 -1
  109. package/chunks/{chunk-CMW64XU2.js → chunk-ZEZCRRQC.js} +1 -1
  110. package/chunks/{chunk-J5W6P7QD.js → chunk-ZF56DRDP.js} +1 -1
  111. package/chunks/{chunk-LHIEE3A2.js → chunk-ZSPOFXP3.js} +1 -1
  112. package/chunks/{chunk-Q6CXEN4H.js → chunk-ZZXAOGUV.js} +1 -1
  113. package/chunks/{codex-subagent-executor-HB3MUCY4.js → codex-subagent-executor-7RAVQBYA.js} +1 -1
  114. package/chunks/{config-utils-F7OF5UR2.js → config-utils-JFD4RJK3.js} +1 -1
  115. package/chunks/{contextCommand-Y3KO2FY6.js → contextCommand-U6CD3CW7.js} +1 -1
  116. package/chunks/{core-runtime-D7DAA5NY.js → core-runtime-ORCZRJ4O.js} +1 -1
  117. package/chunks/{create-sub-session-2HTWYAP4.js → create-sub-session-57WMU2AE.js} +1 -1
  118. package/chunks/{cron-create-Y5I6E2X4.js → cron-create-V466MOUE.js} +1 -1
  119. package/chunks/{daemon-git-worktree-guard-UOBMXOUC.js → daemon-git-worktree-guard-ATD77XOF.js} +1 -1
  120. package/chunks/{daemon-status-provider-L2225KDS.js → daemon-status-provider-5FVRNMAZ.js} +1 -1
  121. package/chunks/{daemon-trust-policy-5D52N5GL.js → daemon-trust-policy-6YRQV4ZM.js} +1 -1
  122. package/chunks/{daemon-trust-policy-monitor-RUE25K7A.js → daemon-trust-policy-monitor-QRUOWZQP.js} +1 -1
  123. package/chunks/{deferred-core-runtime-6BO5DI5B.js → deferred-core-runtime-TXIXMDDH.js} +1 -1
  124. package/chunks/{edit-B6DKSK3O.js → edit-FNXBINJ3.js} +1 -1
  125. package/chunks/{enterPlanMode-WVJ3XC3P.js → enterPlanMode-YMLAOTTS.js} +1 -1
  126. package/chunks/{environment-7WMACN3E.js → environment-RFNJLRF7.js} +1 -1
  127. package/chunks/{errors-BN73QF2O.js → errors-NHGSZ2BV.js} +1 -1
  128. package/chunks/{execution-tool-IGDH3MQT.js → execution-tool-L2BF6ZKP.js} +1 -1
  129. package/chunks/{execution-worker-WWP3JZGV.js → execution-worker-F5B2BI2W.js} +1 -1
  130. package/chunks/{exitPlanMode-7WHKOTS7.js → exitPlanMode-ZZVBF5V4.js} +1 -1
  131. package/chunks/{fast-path-B37HGFQO.js → fast-path-TOJYOAD3.js} +1 -1
  132. package/chunks/{glob-ZRXU5G5X.js → glob-SYPMYU4V.js} +1 -1
  133. package/chunks/{goal-tools-DQ5IZXCM.js → goal-tools-NOXNXZFR.js} +1 -1
  134. package/chunks/{handleAutoUpdate-FD7QAG2R.js → handleAutoUpdate-RS6Y2IWS.js} +1 -1
  135. package/chunks/{i18n-TI3ZCEHR.js → i18n-WWZD25J5.js} +1 -1
  136. package/chunks/{initializer-SB7P3LRU.js → initializer-YGR4YXAM.js} +1 -1
  137. package/chunks/{installationInfo-B337C7R4.js → installationInfo-EPURVILN.js} +1 -1
  138. package/chunks/{interactive-mod-session-OWRMETPP.js → interactive-mod-session-2VSTTHPA.js} +1 -1
  139. package/chunks/{list-2QKQIEOB.js → list-6JAKVRMZ.js} +1 -1
  140. package/chunks/{llm-GQ76E4DL.js → llm-V272EOVL.js} +4 -4
  141. package/chunks/{llm-content-generator-2A23HFLD.js → llm-content-generator-EXMC3NYS.js} +1 -1
  142. package/chunks/{loadedSettingsAdapter-RGQOA5BG.js → loadedSettingsAdapter-T6W2CKFA.js} +1 -1
  143. package/chunks/{local-OEBLERSJ.js → local-NUBKA3T2.js} +1 -1
  144. package/chunks/{local-execution-environment-FT5J4SUH.js → local-execution-environment-WO62QDKJ.js} +1 -1
  145. package/chunks/{loggingContentGenerator-WC23RZYM.js → loggingContentGenerator-KHRN6S3S.js} +1 -1
  146. package/chunks/{loop-wakeup-GIIIDUNG.js → loop-wakeup-TTAZMOYH.js} +1 -1
  147. package/chunks/{manage-memory-E2OAR2RV.js → manage-memory-BKA7QM4N.js} +1 -1
  148. package/chunks/{managed-execution-engine-CYYNVVP5.js → managed-execution-engine-32BLALNC.js} +1 -1
  149. package/chunks/{managed-local-serve-TUVNNY7K.js → managed-local-serve-UTJFLZI6.js} +1 -1
  150. package/chunks/{managed-npm-update-IDRZ32UK.js → managed-npm-update-XPIRAQ47.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-HON7TGY2.js → managed-runtime-attestation-worker-DDU4HUGS.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-OMLX5CTV.js → managed-runtime-bootstrap-7TTCLDQJ.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-J3P7WMDW.js → managed-runtime-session-worker-WBYLRXU3.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-LPFPOBTL.js → managed-runtime-ssh-worker-X2U2OK2E.js} +1 -1
  155. package/chunks/{managed-session-authority-I5OHOM7N.js → managed-session-authority-U76OGS6U.js} +1 -1
  156. package/chunks/{mcp-CGDIDRDI.js → mcp-UROGTJ3U.js} +1 -1
  157. package/chunks/{memory-VKXOH5UM.js → memory-M4OF6FV7.js} +1 -1
  158. package/chunks/{model-call-collection-ZTYFDFBB.js → model-call-collection-TW6Q7SXP.js} +1 -1
  159. package/chunks/{model-configuration-EXLM4SD3.js → model-configuration-4PJUBAYR.js} +1 -1
  160. package/chunks/{modelConfigUtils-XDMB6XPY.js → modelConfigUtils-ARMBTDAK.js} +1 -1
  161. package/chunks/{monitor-LKKCC6MQ.js → monitor-URMSEGAJ.js} +1 -1
  162. package/chunks/{nonInteractiveCli-J3Z3IZIF.js → nonInteractiveCli-YHOC5KZF.js} +1 -1
  163. package/chunks/{nonInteractiveToolExecutor-UQTMGYN2.js → nonInteractiveToolExecutor-DM5IGBP7.js} +1 -1
  164. package/chunks/{notebook-edit-JFD2KDI6.js → notebook-edit-3YSG73BK.js} +1 -1
  165. package/chunks/{omni-CI5JTMPR.js → omni-J6YYWKII.js} +1 -1
  166. package/chunks/{openaiContentGenerator-YZOV2TQX.js → openaiContentGenerator-UIFSPMTE.js} +1 -1
  167. package/chunks/{openaiResponsesContentGenerator-AHL7V6TE.js → openaiResponsesContentGenerator-U6Q536RZ.js} +1 -1
  168. package/chunks/{pidfile-ULOUTG67.js → pidfile-WCZE5ONH.js} +1 -1
  169. package/chunks/{processUtils-XX62FVFO.js → processUtils-3CDEN2GV.js} +1 -1
  170. package/chunks/{prompt-terminal-ledger-L6CWXBAW.js → prompt-terminal-ledger-VAQC6TC3.js} +1 -1
  171. package/chunks/{qwenContentGenerator-ZDXJW7EM.js → qwenContentGenerator-RWBGMON6.js} +1 -1
  172. package/chunks/{reactive-degrade-4OJ7XKSJ.js → reactive-degrade-GOTSVZKO.js} +1 -1
  173. package/chunks/{read-file-H6I32UZS.js → read-file-WNNTTHL5.js} +1 -1
  174. package/chunks/{resumeHistoryUtils-CTRMXPKQ.js → resumeHistoryUtils-UAGV4TC3.js} +1 -1
  175. package/chunks/{review-7SV2M7EL.js → review-JETUJT7N.js} +1 -1
  176. package/chunks/{ripGrep-Y2TGCQH5.js → ripGrep-OJNMOYPD.js} +1 -1
  177. package/chunks/{run-qwen-serve-6SWKYY6I.js → run-qwen-serve-BVNSBOLL.js} +1 -1
  178. package/chunks/{runtime-ITZIIC6D.js → runtime-CERVMTEG.js} +1 -1
  179. package/chunks/{sandboxConfig-FF2YF3RY.js → sandboxConfig-ZHW3GTMH.js} +1 -1
  180. package/chunks/{scheduled-tasks-WWPWNM3Y.js → scheduled-tasks-AAB5OESY.js} +1 -1
  181. package/chunks/{scheduler-ELSUH4GZ.js → scheduler-4ZZA357S.js} +1 -1
  182. package/chunks/{search-memory-465ZSHKG.js → search-memory-USJ3D7WQ.js} +1 -1
  183. package/chunks/{send-message-M5JFT3VH.js → send-message-QE2YZZ6M.js} +1 -1
  184. package/chunks/{serve-VTR7PTK2.js → serve-SX2PK3OZ.js} +1 -1
  185. package/chunks/{server-5NHPPEPR.js → server-OGTIIX65.js} +3 -3
  186. package/chunks/{session-HZLRQKEB.js → session-DXORIQDK.js} +1 -1
  187. package/chunks/{session-attachments-root-LS5Q4OT3.js → session-attachments-root-VHH2OZF6.js} +1 -1
  188. package/chunks/{session-execution-engine-selector-GS4LJPUU.js → session-execution-engine-selector-5WKZ6WXX.js} +1 -1
  189. package/chunks/{session-pr-refresh-FKYCCTWD.js → session-pr-refresh-MHXNT44I.js} +1 -1
  190. package/chunks/{sessionService-XUBKN4CM.js → sessionService-QDDGXOB7.js} +1 -1
  191. package/chunks/{settings-BFTTGWJN.js → settings-W3ALYJZM.js} +1 -1
  192. package/chunks/{shell-YEUMIQVE.js → shell-YROF2KXZ.js} +1 -1
  193. package/chunks/{skill-2MJ7S5SK.js → skill-CBEQAUIQ.js} +1 -1
  194. package/chunks/{skill-settings-DP7A2GMB.js → skill-settings-YRN4SHJO.js} +1 -1
  195. package/chunks/{spawnChannel-3IZ7S6U7.js → spawnChannel-M7Q6URLT.js} +1 -1
  196. package/chunks/{standalone-update-NAI3OI3P.js → standalone-update-WIRHMWE6.js} +1 -1
  197. package/chunks/{start-opentui-ui-D6ETKJSG.js → start-opentui-ui-OLHWNKCY.js} +1 -1
  198. package/chunks/{startInteractiveUI-FR5ZT72L.js → startInteractiveUI-KCHCIQWO.js} +1 -1
  199. package/chunks/{subscription-content-generator-JHU5YG2L.js → subscription-content-generator-YQLQKG6S.js} +1 -1
  200. package/chunks/{team-create-ZW3NXJ2M.js → team-create-I432CHIX.js} +1 -1
  201. package/chunks/{team-plan-approval-GPFOKUEV.js → team-plan-approval-APMPMLXS.js} +1 -1
  202. package/chunks/{terminal-image-renderer-WTEEKRMJ.js → terminal-image-renderer-3BNICGAX.js} +1 -1
  203. package/chunks/{theme-manager-STF74SF2.js → theme-manager-6KY7Q4ZR.js} +1 -1
  204. package/chunks/{tool-call-TVX5UHRJ.js → tool-call-QGOVXOVJ.js} +1 -1
  205. package/chunks/{tool-result-media-QALAETZ4.js → tool-result-media-LRSYJOND.js} +1 -1
  206. package/chunks/{tool-search-ZGJEYTBI.js → tool-search-HXP25AWV.js} +1 -1
  207. package/chunks/{total-session-admission-BOYLCRYA.js → total-session-admission-ISTRHUQ7.js} +1 -1
  208. package/chunks/{trustedFolders-65OZWLQO.js → trustedFolders-5BXMWMYB.js} +1 -1
  209. package/chunks/{update-relaunch-4LJ3SY6L.js → update-relaunch-NYGYYLSC.js} +1 -1
  210. package/chunks/{updateCheck-2QOAKEIH.js → updateCheck-UBLS3LUD.js} +1 -1
  211. package/chunks/{upload-config-5N7UDWC6.js → upload-config-Y372LVXX.js} +1 -1
  212. package/chunks/{useAutoAcceptIndicator-V37CGGMF.js → useAutoAcceptIndicator-RXZJRU74.js} +1 -1
  213. package/chunks/{validateNonInterActiveAuth-6ZTVWZ6W.js → validateNonInterActiveAuth-2GJ4ICJ3.js} +1 -1
  214. package/chunks/{version-EO3VIRH6.js → version-XRSNVEB2.js} +1 -1
  215. package/chunks/{web-fetch-B6LNZ2YK.js → web-fetch-B4VFVGWW.js} +1 -1
  216. package/chunks/{web-search-VIPZWUJX.js → web-search-3DSQWMAV.js} +1 -1
  217. package/chunks/{workflow-W5QEAOGN.js → workflow-RCCH5FPV.js} +1 -1
  218. package/chunks/{workflow-ancestor-trust-VE7B4RD2.js → workflow-ancestor-trust-N3QYH3OL.js} +1 -1
  219. package/chunks/{workspace-agents-D32D3K5S.js → workspace-agents-KEV4VBZD.js} +1 -1
  220. package/chunks/{workspace-providers-status-BOH7RJPV.js → workspace-providers-status-HW4VI4T7.js} +1 -1
  221. package/chunks/{workspace-recovery-worker-53GJWYJ5.js → workspace-recovery-worker-C3SSJ64A.js} +1 -1
  222. package/chunks/{workspace-registration-store-BMX2NT45.js → workspace-registration-store-K7VEBHIU.js} +1 -1
  223. package/chunks/{workspace-registry-SS2NKLEL.js → workspace-registry-C5ZPYT4P.js} +1 -1
  224. package/chunks/{workspace-runtime-coordinator-7ZKVLJDC.js → workspace-runtime-coordinator-ALWOLW3N.js} +1 -1
  225. package/chunks/{workspace-service-GIUD3D25.js → workspace-service-TNZJAC7M.js} +1 -1
  226. package/chunks/{workspace-skills-status-36A76TDX.js → workspace-skills-status-TI763F5M.js} +1 -1
  227. package/chunks/{workspace-trust-reconciler-VKKSY2AR.js → workspace-trust-reconciler-6UQ7HSUG.js} +1 -1
  228. package/chunks/{write-file-43JOGU55.js → write-file-2XXEHBZR.js} +1 -1
  229. package/chunks/{zoom-image-USUXATDM.js → zoom-image-P3E3V6PQ.js} +1 -1
  230. package/cli.js +2 -2
  231. package/execution-worker.js +1 -1
  232. package/export-transcript-document.js +1 -1
  233. package/package.json +3 -3
  234. package/web-shell/assets/{PierreFilePreview-Dx075_VT.js → PierreFilePreview-DtTOu9VE.js} +1 -1
  235. package/web-shell/assets/{SpreadsheetPreview-l2R-Y1o6.js → SpreadsheetPreview-C21imJIX.js} +1 -1
  236. package/web-shell/assets/{WorkspaceFileBrowser-CGi_eR1a.js → WorkspaceFileBrowser-DIWHfhtl.js} +1 -1
  237. package/web-shell/assets/{abnfDiagram-VCTEODGH-DZPHyWbH.js → abnfDiagram-VCTEODGH-qffA9juk.js} +1 -1
  238. package/web-shell/assets/{agents-route-Bp0Yjhm4.js → agents-route-4f6fKJaY.js} +1 -1
  239. package/web-shell/assets/{arc-BAS_Ct0z.js → arc-BOZg4dn0.js} +1 -1
  240. package/web-shell/assets/{architectureDiagram-5GKGNRK7-C5a7ooE1.js → architectureDiagram-5GKGNRK7-BOYWC6dJ.js} +1 -1
  241. package/web-shell/assets/{blockDiagram-NRAW4CY4-D-Wzzi9Z.js → blockDiagram-NRAW4CY4-CiN_IMJ7.js} +1 -1
  242. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BiYnmYkI.js → c4Diagram-UCG6FXSJ-WYLA0JW0.js} +1 -1
  243. package/web-shell/assets/channel-DtcoR96T.js +1 -0
  244. package/web-shell/assets/{chunk-2Q5K7J3B-DHi3a_yf.js → chunk-2Q5K7J3B-BZUPB745.js} +1 -1
  245. package/web-shell/assets/{chunk-5VM5RSS4-DKgiHWPM.js → chunk-5VM5RSS4-BHfjsu8x.js} +1 -1
  246. package/web-shell/assets/{chunk-F27PBJKO-qvFMzdl_.js → chunk-F27PBJKO-DHtQsOyA.js} +1 -1
  247. package/web-shell/assets/{chunk-G27WJ6UU-C9Apl4Df.js → chunk-G27WJ6UU-DvEX_QHY.js} +1 -1
  248. package/web-shell/assets/{chunk-JWPE2WC7-ManrSgDL.js → chunk-JWPE2WC7-CwQJmw1a.js} +1 -1
  249. package/web-shell/assets/{chunk-LCL6LL3I-DNZqkjQu.js → chunk-LCL6LL3I-Cv7bRuRV.js} +1 -1
  250. package/web-shell/assets/{chunk-POPQ4Y6H-CxineRE8.js → chunk-POPQ4Y6H-zGw4PzDB.js} +1 -1
  251. package/web-shell/assets/{chunk-SVP7TREG-BzmCQ6Bh.js → chunk-SVP7TREG-DZMGVnJg.js} +1 -1
  252. package/web-shell/assets/{chunk-XXDRQBXY-Dm6Ascgd.js → chunk-XXDRQBXY-Dg5_qrTq.js} +1 -1
  253. package/web-shell/assets/classDiagram-DTDB5LWJ-CBq-DXYQ.js +1 -0
  254. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBq-DXYQ.js +1 -0
  255. package/web-shell/assets/{cose-bilkent-JH36ORCC-Cs-vIewG.js → cose-bilkent-JH36ORCC-D07aXZdD.js} +1 -1
  256. package/web-shell/assets/{cynefin-OW5HDTMX-CrxyzLrG.js → cynefin-OW5HDTMX-B4txjD0l.js} +1 -1
  257. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Bf7RdtX4.js → cynefinDiagram-5FMLGOSQ-zFtLauJ6.js} +1 -1
  258. package/web-shell/assets/{dagre-3AP2YEHR-jN7qDhRR.js → dagre-3AP2YEHR-CKZj9zbB.js} +1 -1
  259. package/web-shell/assets/{diagram-S7CK7UJ4-KcNQ38Ue.js → diagram-S7CK7UJ4-DIsLTku6.js} +1 -1
  260. package/web-shell/assets/{diagram-UQ7AKVKN-9VmCS0SV.js → diagram-UQ7AKVKN-60CC00CO.js} +1 -1
  261. package/web-shell/assets/{diagram-VSXAHHWV-D-MA8NCD.js → diagram-VSXAHHWV-BCfHqY7L.js} +1 -1
  262. package/web-shell/assets/{diagram-VX7I27RA-323tLIBS.js → diagram-VX7I27RA-BbTOx9qC.js} +1 -1
  263. package/web-shell/assets/{diagram-Z3DM3KII-C547h61H.js → diagram-Z3DM3KII-DLjgnodz.js} +1 -1
  264. package/web-shell/assets/{docx-preview-DHO0seXT.js → docx-preview-CfGqg6IJ.js} +1 -1
  265. package/web-shell/assets/{ebnfDiagram-PWID7BFC-DfB8wLF5.js → ebnfDiagram-PWID7BFC-Cf1IQbGo.js} +1 -1
  266. package/web-shell/assets/{erDiagram-SSCWMZ5O-tzqYkCjp.js → erDiagram-SSCWMZ5O-BTVNpu1y.js} +1 -1
  267. package/web-shell/assets/{flowDiagram-A5DVABFB-Dsw6uHjD.js → flowDiagram-A5DVABFB-BC404IkJ.js} +1 -1
  268. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-D1SaF3O0.js → ganttDiagram-EL5Y4UJY-BHP58V1Y.js} +1 -1
  269. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D0EzECMT.js → gitGraphDiagram-WWUBYQGX-s1PkjMd4.js} +1 -1
  270. package/web-shell/assets/{index-ob2Iut7D.js → index-DZnv4pXI.js} +6 -6
  271. package/web-shell/assets/{index-C-YHF5xI.js → index-YpdTDWts.js} +1 -1
  272. package/web-shell/assets/{infoDiagram-RXCK75RN-6NnYMmcC.js → infoDiagram-RXCK75RN-DDaQbbGu.js} +1 -1
  273. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BnxsfuuS.js → ishikawaDiagram-5VMMS53U-FpQWCzWS.js} +1 -1
  274. package/web-shell/assets/{journeyDiagram-EYS64GPL-DduswigY.js → journeyDiagram-EYS64GPL-CC5YG1zk.js} +1 -1
  275. package/web-shell/assets/{kanban-definition-3QL26DDD-D0trNRAQ.js → kanban-definition-3QL26DDD-CsitCmSH.js} +1 -1
  276. package/web-shell/assets/{layout-nP-pCdd_.js → layout-DR8LNzXS.js} +1 -1
  277. package/web-shell/assets/{linear-DCw4lqG9.js → linear-Dt61H2xY.js} +1 -1
  278. package/web-shell/assets/{mermaid.core-DYjTp4Sk.js → mermaid.core-C3SdL30W.js} +6 -6
  279. package/web-shell/assets/{mindmap-definition-FBJOCRG2-BK9iSa2V.js → mindmap-definition-FBJOCRG2-BjxTLs9R.js} +1 -1
  280. package/web-shell/assets/{pegDiagram-XKGWAZYB-Dg0TQ1Ty.js → pegDiagram-XKGWAZYB-eBurSwq6.js} +1 -1
  281. package/web-shell/assets/{pieDiagram-E7YTZNPT-DKeqeVkg.js → pieDiagram-E7YTZNPT-BFWkbtZz.js} +1 -1
  282. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-C4zBeQXd.js → quadrantDiagram-AXDQQJYC-SThzXP6T.js} +1 -1
  283. package/web-shell/assets/{railroadDiagram-O6MQD6OU-jDnAGU3z.js → railroadDiagram-O6MQD6OU-D73YId-T.js} +1 -1
  284. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-D0sIdHq4.js → requirementDiagram-EFPCY7ZU-YecInWjM.js} +1 -1
  285. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BFz_QzXx.js → sankeyDiagram-P5KCCOFB-D4Gl35cC.js} +1 -1
  286. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DhDmjiCT.js → sequenceDiagram-WJ2MYXX4-C1JdJSRH.js} +1 -1
  287. package/web-shell/assets/{sizeCapture-X5ZJPWSS-D8Ov3K_0.js → sizeCapture-X5ZJPWSS-D3mHX34v.js} +1 -1
  288. package/web-shell/assets/{stateDiagram-HBIQ2CUA-Bb4f1ILo.js → stateDiagram-HBIQ2CUA-BR05d7ll.js} +1 -1
  289. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BBhqVmOU.js +1 -0
  290. package/web-shell/assets/{swimlanes-XN3QIQJK-CQyilPoS.js → swimlanes-XN3QIQJK-CENq9EQ7.js} +1 -1
  291. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DI8ON7to.js +8 -0
  292. package/web-shell/assets/{timeline-definition-24CTP7MA-B_CntdLT.js → timeline-definition-24CTP7MA-DFhKdLgc.js} +1 -1
  293. package/web-shell/assets/{vennDiagram-4TSXK5OY-BbuHkADM.js → vennDiagram-4TSXK5OY-C-p5h-ue.js} +1 -1
  294. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-0mNKcB-T.js → wardleyDiagram-VM6X3IG4-BCWSjHZH.js} +1 -1
  295. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BL-rMOQs.js → xychartDiagram-S5SC5T6Z-DBvE_Y0y.js} +1 -1
  296. package/web-shell/index.html +1 -1
  297. package/web-shell/sw.js +1 -1
  298. package/web-shell/assets/channel-B31dxYCL.js +0 -1
  299. package/web-shell/assets/classDiagram-DTDB5LWJ-CxU_Ty2M.js +0 -1
  300. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CxU_Ty2M.js +0 -1
  301. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-xbht8Czs.js +0 -1
  302. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dz34bASJ.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{flushOutput}from"./chunk-VURTGFJP.js";import{cpLen,cpSlice,sanitizeTerminalLine,sanitizeTerminalText,stripUnsafeCharacters}from"./chunk-64CA3W6G.js";import{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,invalidRenderText,record,validModelResult,validateRenderTree,validateResult}from"./chunk-XWYUQMLN.js";import{stableJson}from"./chunk-FIXDX63I.js";import{openNoFollow}from"./chunk-PSKT6KWO.js";import{isZombie,readLocalBootId,readPidNamespaceId,readProcStartToken}from"./chunk-JB3XRNK7.js";import{buildModelIdContext,resolveModelId}from"./chunk-6XLIEJP5.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{runOutsideAgentContext}from"./chunk-WXQQVXYN.js";import{external_exports}from"./chunk-KZSUHQLD.js";import{isQuotaExhaustedError,isQwenQuotaExceededError}from"./chunk-A6LYTPBP.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-R5AA46IX.js";import{Mutex,Semaphore}from"./chunk-JEV36CS7.js";import{hasExplicitOutputLimit,tokenLimit}from"./chunk-AZ4Q2ZWQ.js";import{renameWithRetry}from"./chunk-2GF3E5MI.js";import{EVENT_API_RESPONSE}from"./chunk-UFRESHR3.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{require_semver}from"./chunk-73G3MZQR.js";import{registerCleanup}from"./chunk-LHIEE3A2.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorStatus,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";import path4 from"node:path";init_esbuild_shims();import{promises as fs}from"node:fs";import path from"node:path";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);var name=external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);var dependency=external_exports.union([external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:@[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/),external_exports.object({name,marketplace:name.optional(),version:external_exports.string().optional()}).strict()]);function parseModDependencies(value){const parsed=external_exports.array(dependency).safeParse(value===void 0?[]:value);if(!parsed.success)throw new Error("Invalid Mod dependencies declaration.");return parsed.data.map(item=>{if(typeof item==="string"){const[name2,marketplace]=item.split("@");return{name:name2,marketplace}}if(item.version!==void 0&&!(0,import_semver.validRange)(item.version)){throw new Error(`Invalid Mod dependency version range for ${item.name}.`)}return item})}__name(parseModDependencies,"parseModDependencies");function resolveModDependency(plugins,plugin,dependency2){const marketplace=dependency2.marketplace??plugin.marketplace;const local=plugins.filter(item=>item.name===dependency2.name&&!item.marketplace);const matches=local.length?local:plugins.filter(item=>item.name===dependency2.name&&item.marketplace===marketplace);if(matches.length!==1){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} must identify one installed, enabled plugin.`)}const target=matches[0];if(target.marketplace&&dependency2.version&&!(0,import_semver.satisfies)(target.version,dependency2.version)){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} has an incompatible installed version.`)}return target}__name(resolveModDependency,"resolveModDependency");function orderModPlugins(plugins){const edges=plugins.map(()=>new Set);const incoming=plugins.map(()=>0);for(const[index,plugin]of plugins.entries()){for(const dependency2 of plugin.dependencies){const targetIndex=plugins.indexOf(resolveModDependency(plugins,plugin,dependency2));if(!edges[index].has(targetIndex)){edges[index].add(targetIndex);incoming[targetIndex]++}}}const ordered=[];const remaining=new Set(plugins.map((_,index)=>index));while(remaining.size){const next=[...remaining].find(index=>incoming[index]===0);if(next===void 0)throw new Error("Mod dependency cycle: activation refused.");remaining.delete(next);ordered.push(plugins[next]);for(const target of edges[next])incoming[target]--}return ordered}__name(orderModPlugins,"orderModPlugins");function isContainedFile(root,file){const relative=path.relative(root,file);return Boolean(relative)&&!path.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path.sep}`)}__name(isContainedFile,"isContainedFile");async function readModFile(root,file){if(!isContainedFile(root,file)){throw new Error("Mod file must stay inside the installed extension.")}let current=root;for(const part of path.relative(root,file).split(path.sep)){current=path.join(current,part);const stat=await fs.lstat(current);if(stat.isSymbolicLink()){throw new Error("Mod files cannot be symbolic links.")}if(current===file&&!stat.isFile()){throw Object.assign(new Error("Mod input must be a regular file."),{code:stat.isDirectory()?"EISDIR":void 0})}}const entry=await fs.realpath(file);if(!isContainedFile(root,entry)){throw new Error("Mod file must stay inside the installed extension.")}const handle=await openNoFollow(entry);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>MOD_MAX_BYTES){throw new Error("Mod file exceeds the 256 KiB regular-file limit.")}const buffer=Buffer.alloc(MOD_MAX_BYTES+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>MOD_MAX_BYTES)throw new Error("Mod file is too large.");return{entry,source:buffer.subarray(0,bytesRead).toString("utf8")}}finally{await handle.close()}}__name(readModFile,"readModFile");async function readManifest(root,relative){try{if(path.isAbsolute(relative)){throw new Error("Mod manifest path must be relative to the extension.")}const value=JSON.parse((await readModFile(root,path.resolve(root,relative))).source);if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("Mod manifest must be a JSON object.")}return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(readManifest,"readManifest");async function loadModSource(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");if(typeof qwen?.["hooks"]==="string"&&(path.isAbsolute(qwen["hooks"])||!isContainedFile(root,path.resolve(root,qwen["hooks"])))){return void 0}const claude=await readManifest(root,".claude-plugin/plugin.json");const hooksPath=typeof qwen?.["hooks"]==="string"?qwen["hooks"]:typeof claude?.["hooks"]==="string"?claude["hooks"]:"hooks/hooks.json";if(path.isAbsolute(hooksPath)||!isContainedFile(root,path.resolve(root,hooksPath))){return void 0}const hooks=await readManifest(root,hooksPath);if(!hooks||!Object.hasOwn(hooks,"modules"))return void 0;const modules=hooks["modules"];if(!Array.isArray(modules)||modules.length!==1||typeof modules[0]!=="string"||path.isAbsolute(modules[0])||!/\.(?:[cm]?js|[cm]?ts|[jt]sx)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript, TypeScript or JSX module.")}const manifest={...claude,...qwen};const entry=path.resolve(root,path.dirname(hooksPath),modules[0]);return{root,...await readModFile(root,entry),userConfig:manifest["userConfig"],dependencies:parseModDependencies(manifest["dependencies"])}}__name(loadModSource,"loadModSource");async function loadModDependencies(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");const claude=await readManifest(root,".claude-plugin/plugin.json");return parseModDependencies({...claude,...qwen}["dependencies"])}__name(loadModDependencies,"loadModDependencies");init_esbuild_shims();var option=external_exports.union([external_exports.string(),external_exports.number().finite(),external_exports.boolean(),external_exports.array(external_exports.string())]);var field=external_exports.object({type:external_exports.enum(["string","number","boolean","directory","file"]),title:external_exports.string(),description:external_exports.string(),required:external_exports.boolean().optional(),default:option.optional(),multiple:external_exports.boolean().optional(),sensitive:external_exports.boolean().optional(),min:external_exports.number().finite().optional(),max:external_exports.number().finite().optional(),options:external_exports.array(external_exports.string().min(1).max(64)).nonempty().optional()}).strict().refine(value=>{if(!value.options)return true;return value.type==="string"&&!value.multiple&&!value.sensitive&&value.options.every(item=>item.trim()===item&&!/[\p{Cc}\p{Cf}]/u.test(item))&&new Set(value.options.map(item=>item.toLowerCase())).size===value.options.length&&(value.default===void 0?value.required===true:value.options.includes(value.default))});var schema=external_exports.record(external_exports.string().regex(/^[A-Za-z_]\w*$/),field);var storedOptions=external_exports.record(external_exports.string(),option);function*pluginConfigurations(scopes,name2,marketplace){const keys=marketplace?[`${name2}@${marketplace}`]:[name2,`${name2}@inline`];for(const scope of scopes){if(scope===void 0)continue;if(!scope||typeof scope!=="object"||Array.isArray(scope)){throw new Error("Invalid Mod pluginConfigs settings.")}for(const key of keys){if(!Object.hasOwn(scope,key))continue;const config=scope[key];if(!config||typeof config!=="object"||Array.isArray(config)){throw new Error("Invalid Mod pluginConfigs entry.")}yield config}}}__name(pluginConfigurations,"pluginConfigurations");function resolveModChoice(scopes,name2,marketplace,key,choices){let choice=choices[0];for(const config of pluginConfigurations(scopes,name2,marketplace)){const value=config[key];if(value===void 0)continue;if(!choices.includes(value))throw new Error(`Invalid Mod ${key}: expected ${choices.join(" or ")}.`);choice=value}return choice}__name(resolveModChoice,"resolveModChoice");function resolveModToolDialect(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"toolDialect",["native","claude"])}__name(resolveModToolDialect,"resolveModToolDialect");function resolveModUnsupportedEvents(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"unsupportedEvents",["skip","reject"])}__name(resolveModUnsupportedEvents,"resolveModUnsupportedEvents");function resolveModOptions(declaration,scopes,name2,marketplace){const parsed=schema.safeParse(declaration===void 0?{}:declaration);if(!parsed.success)throw new Error("Invalid Mod userConfig declaration.");const fields=Object.entries(parsed.data);if(!fields.length)return{};if(fields.some(([,value])=>value.sensitive)){throw new Error("Sensitive Mod userConfig is not supported yet.")}let stored={};for(const config of pluginConfigurations(scopes,name2,marketplace)){const options=config["options"];if(options===void 0)continue;const values=storedOptions.safeParse(options);if(!values.success)throw new Error(`Invalid Mod configured option: ${String(values.error.issues[0]?.path[0]??"").slice(0,64)}.`);stored={...stored,...values.data}}const result=Object.fromEntries(fields.filter(([,config])=>config.default!==void 0||!config.required).map(([key,config])=>[key,config.default??""]));for(const[key,value]of Object.entries(stored)){const choices=Object.hasOwn(parsed.data,key)?parsed.data[key].options:void 0;if(!choices||choices.includes(value))Object.defineProperty(result,key,{value,enumerable:true,writable:true,configurable:true})}for(const[key,config]of fields){const value=Object.hasOwn(result,key)?result[key]:void 0;if(value===void 0||value===""){if(config.required)throw new Error(`Missing required Mod option: ${key}.`)}else{const valid=config.type==="number"?typeof value==="number"&&(config.min===void 0||value>=config.min)&&(config.max===void 0||value<=config.max):config.type==="boolean"?typeof value==="boolean":typeof value==="string"||config.type==="string"&&config.multiple&&Array.isArray(value);if(!valid)throw new Error(`Invalid Mod option: ${key}.`)}}if(Buffer.byteLength(JSON.stringify(result))>MOD_MAX_BYTES){throw new Error("Mod options exceed the 256 KiB limit.")}return result}__name(resolveModOptions,"resolveModOptions");init_esbuild_shims();import{Worker}from"node:worker_threads";import{existsSync}from"node:fs";import path2 from"node:path";import{createRequire}from"node:module";import{pathToFileURL}from"node:url";function workerEntry(){if(import.meta.url.endsWith(".ts")){return new URL(`data:text/javascript,${encodeURIComponent(`import { register } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}; register(); await import(${JSON.stringify(new URL("./mod-worker.ts",import.meta.url).href)});`)}`)}const sibling=new URL("./mod-worker.js",import.meta.url);return existsSync(sibling)?sibling:path2.join(resolveBundleDir(import.meta.url),"mod-worker.js")}__name(workerEntry,"workerEntry");var ModRuntime=class _ModRuntime{constructor(log,facts,resolveTool,surface=null,abortTurn,renderHost,queuePrompt,completeModel,store){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;this.queuePrompt=queuePrompt;this.completeModel=completeModel;this.store=store;this.worker=new Worker(workerEntry(),{stdout:true,stderr:true,workerData:this.cancelled.buffer});this.worker.stdout?.resume();this.worker.stderr?.resume();this.worker.on("message",reply=>{const root=this.root;if(!root||reply.root!==root.id)return;if(reply.type==="host-call")this.executeHost(reply);else if(reply.type==="host-cancel"){for(const id of reply.ids){this.tool?.operations.get(id)?.controller.abort();root.models.get(id)?.abort();this.storeCalls.get(id)?.controller.abort()}}else if(reply.type==="model-complete")this.answerModel(reply,root);else if(reply.type==="check-result")this.tool?.checks.get(reply.id)?.(reply);else if(reply.type==="turn-abort")this.answerTurnAbort(reply,root.id);else if(reply.type==="prompt-queue")this.answerPromptQueue(reply,root.id);else if(reply.type==="store"){const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signals=[root.storeAbort.signal,controller.signal];if(Number.isFinite(remainingMs))signals.push(AbortSignal.timeout(Math.ceil(remainingMs)));const task=this.answerStore(reply,root.id,AbortSignal.any(signals));this.storeCalls.set(reply.id,{controller,task});void task.finally(()=>this.storeCalls.delete(reply.id))}else if(reply.type==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(Object.values(this.renders).some(names=>names.includes(reply.plugin)))this.renderHost?.invalidate(reply.plugin)}else if(reply.type==="activity"){if(reply.phase!==root.phase||reply.revision<=root.revision||reply.operation!==void 0&&reply.operation!==root.native&&!root.models.has(reply.operation))return;root.revision=reply.revision;root.idle=reply.operation===root.native&&this.tool?.checks.size?void 0:reply.operation;root.refresh()}else if(reply.type==="log"){if(this.failure)return;try{this.log({text:reply.text,to:reply.to},reply.plugin)}catch(error){this.fail(error instanceof Error?error:new Error(String(error)));void this.worker.terminate()}}else this.pending?.(reply)});this.worker.on("error",error=>this.fail(error));this.worker.on("exit",code=>this.fail(new Error(`Mod worker exited (${code}).`)))}static{__name(this,"ModRuntime")}worker;storeCalls=new Map;storeReadSlots=new Semaphore(4);failure;pending;commands=[];tools=false;turns={start:false,complete:[]};prompts=[];renders={};early=new Set;noted=new Set;sequence=0;root;tool;cancelled=new Int32Array(new SharedArrayBuffer(4));static async create(source,cwd,log,signal,options={}){return _ModRuntime.createGroup([{id:"mod",name:"mod",source,options}],cwd,log,signal)}static async createGroup(plugins,cwd,log,signal,resolveTool,surface=null,version="unknown",facts,abortTurn,render,prompts=false,queuePrompt,completeModel,store){if(plugins.length>32||new Set(plugins.map(p=>p.id)).size!==plugins.length)throw new Error("Invalid Mod plugin group.");const startedAt=Date.now();const runtime=new _ModRuntime(log,facts??(()=>({id:"",cwd,root:cwd,model:"",turns:0,usage:{startedAt,context:{tokens:0,window:0},rateLimits:[]}})),plugins.some(plugin=>plugin.toolDialect==="claude")?resolveTool:void 0,surface,abortTurn,render,queuePrompt,completeModel,store);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[],prompts,submits:queuePrompt!==void 0,models:completeModel!==void 0,stores:store!==void 0},signal,6e4);const names=__name(value=>Array.isArray(value)&&value.every(name2=>plugins.some(plugin=>plugin.name===name2)),"names");const turnComplete=record(result)?result["turnComplete"]:void 0;const renders=record(result)?result["render"]:void 0;const promptSubmit=record(result)?result["promptSubmit"]:void 0;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(promptSubmit)||!names(turnComplete)||!record(renders)||Object.entries(renders).some(([site,plugins2])=>!(render?.sites??[]).includes(site)||!names(plugins2)))throw new Error("Invalid Mod declarations.");const commands=result["commands"];if(!Array.isArray(commands)||commands.length>64||commands.some(command=>!command||!plugins.some(plugin=>plugin.id===command.plugin)||typeof command.name!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(command.name)||typeof command.description!=="string"||command.argumentHint!==void 0&&typeof command.argumentHint!=="string"))throw new Error("Invalid Mod command declarations.");runtime.commands=commands;runtime.tools=result["tools"];runtime.turns={start:result["turnStart"],complete:turnComplete};runtime.prompts=promptSubmit;runtime.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(Object.values(runtime.renders).some(plugins2=>plugins2.includes(plugin)))render?.invalidate(plugin);return runtime}catch(error){await runtime.dispose();throw error}}getCommands(plugin="mod"){return this.commands.filter(command=>command.plugin===plugin).map(({plugin:_plugin,...command})=>command)}get hasToolHooks(){return this.tools}get turnHooks(){return this.turns}get promptHooks(){return this.prompts}renderHooksFor(site){return this.renders[site]??[]}async render(input,signal){const answer=await this.request({type:"render",input},signal);let settled=answer;if(input.component==="AssistantMessage")settled=record(answer)?answer["tree"]:void 0;const hooks=this.renderHooksFor(input.component);const owner=hooks.length===1?hooks[0]:"hooks";const notes=[];const note=__name((line,key=line)=>{if(this.noted.has(key))return;this.noted.add(key);notes.push(`${owner}: ${line}`)},"note");try{validateRenderTree(settled)}catch(error){note(`ui.render (${input.component}) refused: ${error instanceof Error?error.message:String(error)}; nothing was drawn`);return{tree:ENGINE_NODE,notes}}if(input.component==="AssistantMessage"){if(!record(settled)||settled["type"]!=="engine"||settled["ref"]!==0){note(`ui.render (${input.component}) answered a tree; this host draws only a rewrite of the row's props, so the row was left as it was`);return{tree:ENGINE_NODE,notes,props:input.props}}const props=record(answer)?answer["props"]:void 0;const text=record(props)?props["text"]:void 0;if(!record(props)||typeof text!=="string"||text!==input.props.text&&invalidRenderText(text)!==void 0||props["isFirstOfReply"]!==input.props.isFirstOfReply)return{tree:ENGINE_NODE,notes,props:input.props};return{tree:ENGINE_NODE,notes,props:{...input.props,text}}}const adjusted=adjustRenderTree(settled,input.component);for(const{key,text}of adjusted.notes)note(text,`${input.component}\0${key}`);return{tree:adjusted.tree,notes}}async builtinTool(name2){if(!this.resolveTool)return void 0;let builtin=false;switch(name2){case ToolNames.SHELL:builtin=await this.resolveTool(name2)instanceof(await import("./shell-YEUMIQVE.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-B6DKSK3O.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-43JOGU55.js")).WriteFileTool;break;default:return void 0}return builtin?name2:void 0}async runTool(input,next,signal){if(this.tool||this.pending)throw new Error("A Mod dispatch is already running.");const owner={next,controller:new AbortController,operations:new Map,checks:new Map,tail:Promise.resolve()};this.tool=owner;try{const builtinTool=await this.builtinTool(input.tool);const result=await this.request({type:"tool",input,builtinTool},AbortSignal.any([signal,owner.controller.signal]));validateResult("tool.call",result);return result}finally{owner.controller.abort();await Promise.allSettled([...owner.operations.values()].map(operation=>operation.task));this.tool=void 0}}executeHost(reply){const owner=this.tool;const root=this.root;if(!owner||!root||owner.operations.size>=32||owner.operations.has(reply.id)){this.fail(new Error("Invalid Mod host operation."));return}const controller=new AbortController;const signal=AbortSignal.any([owner.controller.signal,controller.signal]);const task=owner.tail.then(async()=>{signal.throwIfAborted();root.native=reply.id;root.phase++;root.idle=void 0;root.refresh();this.post({type:"native",id:reply.id},root.id);const result=await owner.next(reply.input,signal,async(input,verdict,checkSignal)=>{const active=AbortSignal.any([signal,checkSignal]);active.throwIfAborted();const id=++this.sequence;let abort=__name(()=>{},"abort");try{return await new Promise((resolve,reject)=>{abort=__name(()=>reject(new Error("Mod permission check cancelled.")),"abort");owner.checks.set(id,response=>{if(response.error!==void 0)reject(new Error(response.error));else{try{validateResult("tool.check",response.result);resolve({...response.result,ceiling:input.ceiling})}catch(error){reject(error)}}});root.idle=void 0;root.phase++;root.refresh();active.addEventListener("abort",abort,{once:true});this.post({type:"tool-check",id,operation:reply.id,input,verdict},root.id)})}finally{active.removeEventListener("abort",abort);owner.checks.delete(id);root.refresh()}});root.native=void 0;root.phase++;root.idle=void 0;root.refresh();signal.throwIfAborted();this.post({type:"host-result",id:reply.id,result},root.id)}).catch(error=>{root.native=void 0;root.phase++;root.idle=void 0;root.refresh();if(!this.failure)this.post({type:"host-result",id:reply.id,error:String(error).slice(0,4e3)},root.id)}).finally(()=>{owner.operations.delete(reply.id)});owner.operations.set(reply.id,{controller,task});owner.tail=task}post(request,root){if(this.root?.id!==root)return;const json=JSON.stringify(request);if(Buffer.byteLength(json)>MOD_MAX_BYTES+8192)throw new Error("Mod host message is too large.");assertModDepth(json,"Mod host message");this.worker.postMessage({...request,root,phase:this.root.phase})}async runCommand(command,args,signal,presentation){if(!this.commands.some(item=>item.name===command))throw new Error("Unknown Mod command.");const result=await this.request({type:"command",command,args,...this.surface==="terminal"&&presentation?{presentation}:{}},signal);if(!result||typeof result!=="object"||Array.isArray(result)||Object.keys(result).some(key=>key!=="text")||"text"in result&&typeof result.text!=="string"){throw new Error("Invalid Mod command result.")}return"text"in result?result.text:""}async startTurn(input,signal){validateResult("turn.start",await this.request({type:"turn-start",input},signal))}async submitPrompt(input,signal){const result=await this.request({type:"prompt-submit",input},signal);if(record(result)&&(typeof result["drop"]==="string"?Object.keys(result).length===2&&typeof result["byHook"]==="boolean":typeof result["text"]==="string"&&Object.keys(result).every(key=>key==="text"||key==="context")&&(result["context"]===void 0||Array.isArray(result["context"])&&result["context"].every(item=>typeof item==="string"))))return result;throw new Error("Invalid Mod prompt.submit result.")}async completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}answerModel(reply,root){if(Atomics.load(this.cancelled,0)!==0||Atomics.load(reply.cancellation,0)!==0)return;const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signal=Number.isFinite(remainingMs)?AbortSignal.any([controller.signal,AbortSignal.timeout(Math.ceil(remainingMs))]):controller.signal;root.models.set(reply.id,controller);const answer=__name(async()=>{try{if(!this.completeModel)throw new Error("this host runs no Mod model calls");const result=await this.completeModel(reply.input,signal);if(!validModelResult(result))throw new Error("the host answered with an invalid model result");return{type:"model-result",id:reply.id,result}}catch(caught){const error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3);return{type:"model-result",id:reply.id,error}}},"answer");void answer().then(request=>{root.models.delete(reply.id);if(this.root!==root)return;if(!signal.aborted){try{this.post(request,root.id)}catch(caught){this.post({type:"model-result",id:reply.id,error:caught instanceof Error?caught.message:String(caught)},root.id)}}root.refresh()})}answerTurnAbort(reply,root){let error;try{if(!this.abortTurn)throw new Error(`$.turn.abort: no turn is running (asked for ${reply.turnId})`);this.abortTurn(reply.turnId)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"turn-abort-result",id:reply.id,error},root)}answerPromptQueue(reply,root){let refused;try{refused=this.queuePrompt?this.queuePrompt(reply.prompt):"this host does not run prompts a Mod submits"}catch(caught){refused=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"prompt-queue-result",id:reply.id,refused},root)}async answerStore(reply,root,signal){const{operation}=reply;let value;let error;try{signal.throwIfAborted();const store=this.store;if(!store)throw new Error("This host keeps no Mod store.");if(operation.method==="store.get"||operation.method==="store.keys"){value=await this.storeReadSlots.runExclusive(()=>{signal.throwIfAborted();return operation.method==="store.get"?store.get(operation.plugin,operation.key):store.keys(operation.plugin)})}else if(operation.method==="store.set")await store.set(operation.plugin,operation.key,operation.value,signal);else await store.delete(operation.plugin,operation.key,signal)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}if(signal.aborted)return;try{this.post({type:"store-result",id:reply.id,value,error},root)}catch(caught){this.post({type:"store-result",id:reply.id,error:(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)},root)}}async end(sessionId,reason,signal){await this.request({type:"end",sessionId,reason},signal,MOD_END_TIMEOUT_MS)}async dispose(){this.fail(new Error("Mod runtime is closed."));await this.worker.terminate();await Promise.allSettled([...[...this.tool?.operations.values()??[]].map(operation=>operation.task),...[...this.storeCalls.values()].map(({task})=>task)])}fail(error){this.failure??=error;this.tool?.controller.abort();this.root?.storeAbort.abort();this.pending?.({type:"error",message:this.failure.message})}async request(request,signal,timeoutMs=6e4){signal.throwIfAborted();if(this.failure)throw this.failure;if(this.pending)throw new Error("A Mod dispatch is already running.");const message={...request,facts:this.facts()};const json=JSON.stringify(message);if(Buffer.byteLength(json)>(request.type==="load"?32:1)*MOD_MAX_BYTES+8192)throw new Error("Mod request is too large.");assertModDepth(json,"Mod request");let timer;let cancelTimer;let aborted=false;const budget=new ModBudget(timeoutMs+250);const stop=__name(()=>{this.fail(new Error(aborted?"Mod dispatch cancelled.":"Mod dispatch timed out."));void this.worker.terminate()},"stop");const root={id:++this.sequence,revision:0,phase:0,models:new Map,storeAbort:new AbortController,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=root.idle!==void 0&&(request.type==="tool"&&root.idle===root.native&&!this.tool?.checks.size||root.models.has(root.idle))&&!budget.expired;if(lending!==budget.lending){if(lending)budget.pause();else budget.resume()}if(timer)clearTimeout(timer);if(!budget.lending)timer=setTimeout(stop,budget.remainingMs)},"refresh")};root.storeAbort.signal.addEventListener("abort",()=>this.storeReadSlots.cancel(),{once:true});this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort();for(const model of root.models.values())model.abort();root.storeAbort.abort();if(timer)clearTimeout(timer);cancelTimer=setTimeout(stop,250)},"onAbort");Atomics.store(this.cancelled,0,0);try{return await new Promise((resolve,reject)=>{this.pending=reply=>{if(this.failure)reject(this.failure);else if(aborted)reject(new Error("Mod dispatch cancelled."));else if(reply.type==="error")reject(new Error(reply.message));else if(reply.type==="result"){try{if(Buffer.byteLength(reply.json)>MOD_MAX_BYTES)throw new Error("Mod reply is too large.");resolve(JSON.parse(reply.json))}catch(error){reject(error)}}};signal.addEventListener("abort",onAbort,{once:true});root.refresh();this.worker.postMessage({...message,root:root.id,phase:root.phase})})}finally{this.root=void 0;root.storeAbort.abort();for(const model of root.models.values())model.abort();root.models.clear();if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};init_esbuild_shims();import{createHash,createHmac,randomUUID}from"node:crypto";import{closeSync,constants,openSync,readFileSync,statfsSync,statSync}from"node:fs";import*as fs2 from"node:fs/promises";import{hostname}from"node:os";import*as path3 from"node:path";import{setTimeout as delay}from"node:timers/promises";var MOD_STORE_MAX_BYTES=4*1024*1024;var MAX_KEY_LIST_BYTES=MOD_MAX_BYTES-64;var LOCK_WAIT_MS=8e3;var PROC_SUPER_MAGIC=40864;var BOOT_ID_PATH="/proc/sys/kernel/random/boot_id";var lockHost=hostname();var pidNamespace=readPidNamespaceId();var bootId=process.platform==="linux"?readLocalBootId():null;var startPrefix=pidNamespace===null?null:readStartPrefix();var lockScope=scopeForBoot(bootId);var machineScope=bootId!==null&&pidNamespace!==null&&hasKernelBootId(bootId)?readMachineScope():null;var fileLocks=new Map;function scopeForBoot(id){return createHash("sha256").update(JSON.stringify([lockHost,pidNamespace,id])).digest("hex").slice(0,16)}__name(scopeForBoot,"scopeForBoot");function hasKernelBootId(expected){try{const fd=openSync(BOOT_ID_PATH,constants.O_RDONLY|constants.O_NONBLOCK);try{return statfsSync(`/proc/self/fd/${fd}`).type===PROC_SUPER_MAGIC&&readFileSync(fd,"utf8").trim()===expected}finally{closeSync(fd)}}catch{return false}}__name(hasKernelBootId,"hasKernelBootId");function readMachineScope(){try{const id=readFileSync("/etc/machine-id","utf8").trim();if(!/^[a-f0-9]{32}$/i.test(id)||/^0+$/.test(id))return null;return createHmac("sha256","Qwen-Code/ModStore/lock-host").update(Buffer.from(id,"hex")).digest("hex").slice(0,32)}catch{return null}}__name(readMachineScope,"readMachineScope");function hasLocalProcPids(){if(pidNamespace===null)return false;try{const status=readFileSync("/proc/self/status","utf8");return/^NStgid:[ \t]+(\d+)[ \t]*$/m.exec(status)?.[1]===String(process.pid)}catch{return false}}__name(hasLocalProcPids,"hasLocalProcPids");function readStartPrefix(){try{return`${statSync("/proc/self/ns/time").ino}~`}catch{return null}}__name(readStartPrefix,"readStartPrefix");function processStart(pid){if(startPrefix===null)return"-";const token=readProcStartToken(pid);return token===null?"-":`${startPrefix}${Buffer.from(token).toString("base64url")}`}__name(processStart,"processStart");function deadOwner(owner){const identity=/^(?<scope>[a-f0-9]{16})\.(?<pid>[1-9]\d{0,9})\.(?<start>(?:\d+~)?[\w-]+)\.[a-f0-9-]{36}(?:(?<kernel>\.k)?\.(?<machine>[a-f0-9]{32})\.(?<boot>[a-f0-9-]+))?$/.exec(owner)?.groups;if(!identity)return false;const{scope,pid:rawPid,start:recordedStart,kernel,machine,boot}=identity;if(scope!==lockScope){return kernel!==void 0&&machineScope!==null&&machine===machineScope&&boot!==void 0&&boot!==bootId&&scope===scopeForBoot(boot)}if(process.platform==="linux"&&(pidNamespace===null||bootId===null))return false;const pid=Number(rawPid);if(pid>2147483647)return false;try{process.kill(pid,0)}catch(error){return isNodeError(error)&&error.code==="ESRCH"}if(!hasLocalProcPids())return false;if(isZombie(pid))return true;if(startPrefix===null||!recordedStart.startsWith(startPrefix))return false;const start=processStart(pid);return start!=="-"&&recordedStart!==start}__name(deadOwner,"deadOwner");async function removeLock(lock,owner){if(owner)await fs2.rm(path3.join(lock,owner),{recursive:true,force:true});try{await fs2.rmdir(lock)}catch(error){if(!isNodeError(error)||!["ENOENT","ENOTEMPTY","EEXIST"].includes(error.code??""))throw error}}__name(removeLock,"removeLock");async function acquireLock(lock,signal){signal?.throwIfAborted();const nonce=randomUUID();const staging=`${lock}.${nonce}`;const recovery=machineScope&&bootId?`.k.${machineScope}.${bootId}`:"";const start=hasLocalProcPids()?processStart(process.pid):"-";const owner=`${lockScope}.${process.pid}.${start}.${nonce}${recovery}`;await fs2.mkdir(staging,{mode:448});let acquired=false;try{await fs2.mkdir(path3.join(staging,owner));const deadline=performance.now()+LOCK_WAIT_MS;do{signal?.throwIfAborted();try{await fs2.rename(staging,lock);acquired=true;return path3.join(lock,owner)}catch(error){if(!isNodeError(error)||!["ENOTEMPTY","EEXIST","EPERM","EACCES"].includes(error.code??""))throw error;const owners=await fs2.lstat(lock).then(stat=>{if(!stat.isDirectory())throw error;return fs2.readdir(lock)}).catch(cause=>{if(isNodeError(cause)&&cause.code==="ENOENT")return[];throw cause});if(owners.length===0)await removeLock(lock);else if(owners.length===1&&deadOwner(owners[0]))await removeLock(lock,owners[0])}await delay(50,void 0,{signal})}while(performance.now()<deadline);throw new Error(`Mod store: timed out waiting for ${lock}.`)}finally{if(!acquired)await fs2.rm(staging,{recursive:true,force:true}).catch(()=>{})}}__name(acquireLock,"acquireLock");function acquireLocalLock(mutex,signal){if(!signal)return mutex.acquire();signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=__name(()=>reject(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});void mutex.acquire().then(release=>{signal.removeEventListener("abort",abort);if(signal.aborted)release();else resolve(release)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}__name(acquireLocalLock,"acquireLocalLock");var ModStore=class{constructor(dir){this.dir=dir}static{__name(this,"ModStore")}async get(plugin,key){return(await this.read(this.file(plugin))).get(key)}async keys(plugin){return[...(await this.read(this.file(plugin))).keys()]}async set(plugin,key,value,signal){await this.change(plugin,signal,entries=>{if(!entries.has(key)&&Buffer.byteLength(JSON.stringify([...entries.keys(),key]))>MAX_KEY_LIST_BYTES)throw new Error(`Mod store: the key list would be over ${MAX_KEY_LIST_BYTES} bytes of JSON.`);entries.set(key,value);return true})}async delete(plugin,key,signal){await this.change(plugin,signal,entries=>entries.delete(key))}file(plugin){const name2=plugin.toLowerCase();if(!/^[a-z0-9_.-]+$/.test(name2)||/^\.+$/.test(name2))throw new Error(`Mod store: no store for the plugin name "${plugin}".`);const stem=name2.length>128?`~${createHash("sha256").update(name2).digest("hex")}`:name2;return path3.join(this.dir,`${stem}.json`)}async read(file){let text;try{const handle=await openNoFollow(file,{nonBlocking:true}).catch(error=>{if(isNodeError(error)&&error.code==="ELOOP")return openNoFollow(file,{nonBlocking:true});throw error});try{if(!(await handle.stat()).isFile())throw new Error("The store is not a regular file.");text=await handle.readFile("utf8")}finally{await handle.close()}}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return new Map;throw new Error(`Mod store: cannot read ${file}: ${error instanceof Error?error.message:String(error)}`)}let parsed;try{parsed=JSON.parse(text)}catch{parsed=void 0}const stored=parsed;if(!stored||stored.version!==1||!Array.isArray(stored.entries)||!stored.entries.every(entry=>Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="string"))throw new Error(`Mod store: ${file} is not a store this version reads; it is left unchanged.`);return new Map(stored.entries)}async change(plugin,signal,apply){const file=this.file(plugin);let mutex=fileLocks.get(file);if(!mutex)fileLocks.set(file,mutex=new Mutex);const release=await acquireLocalLock(mutex,signal);try{signal?.throwIfAborted();await fs2.mkdir(this.dir,{recursive:true,mode:448});const lock=`${file}.lock`;const owner=await acquireLock(lock,signal);try{signal?.throwIfAborted();const entries=await this.read(file);if(!apply(entries))return;const stored={version:1,entries:[...entries]};const text=JSON.stringify(stored);if(Buffer.byteLength(text)>MOD_STORE_MAX_BYTES)throw new Error(`Mod store: the store would be over ${MOD_STORE_MAX_BYTES} bytes of JSON.`);const temporary=path3.join(owner,"store.json");await fs2.writeFile(temporary,text,{flag:"wx",mode:384,flush:true});await renameWithRetry(temporary,file,3,50)}finally{await removeLock(lock,path3.basename(owner))}}finally{release()}}};init_esbuild_shims();init_esbuild_shims();function classifyApiError(error){const status=error.status;const message=error.message?.toLowerCase()??"";if(status===429||message.includes("rate limit")){return"rate_limit"}if(status===401||message.includes("unauthorized")){return"authentication_failed"}if(status===402||status===403||message.includes("billing")||message.includes("quota")){return"billing_error"}if(status===400||message.includes("invalid")){return"invalid_request"}if(status!==void 0&&status>=500){return"server_error"}if(message.includes("max_tokens")||message.includes("token limit")){return"max_output_tokens"}return"unknown"}__name(classifyApiError,"classifyApiError");var MOD_MODEL_DEFAULT_MAX_TOKENS=1024;var ALIASES=new Map([["haiku","fast"],["sonnet","inherit"],["opus","inherit"]]);var NO_USAGE={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};function resolveModModel(config,name2){const modelName=name2.trim();const wanted=ALIASES.get(modelName)??modelName;const target=wanted==="fast"?config.getFastModel?.({requirePinnedEndpoint:true})??"inherit":wanted;const context=buildModelIdContext(config);const[modelSelector,endpoint,extra]=target.split("\0");if(!modelSelector?.trim()||endpoint===""||extra!==void 0){throw new Error(`invalid model endpoint selector ${JSON.stringify(name2)}`)}const resolved=resolveModelId(modelSelector,context);if(!resolved)throw new Error(`model ${JSON.stringify(name2)} is not available`);const isSession=resolved.modelId===context.currentModel&&(!resolved.authType||resolved.authType===context.currentAuthType)&&(endpoint===void 0||endpoint===config.getContentGeneratorConfig()?.baseUrl);const configured=config.getAllConfiguredModels(resolved.authType?[resolved.authType]:void 0).some(model=>model.id===resolved.modelId&&(endpoint===void 0||model.baseUrl===endpoint)&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly);if(!isSession&&!configured)throw new Error(`model ${JSON.stringify(name2)} is not configured`);const selector=resolved.authType?`${resolved.authType}:${resolved.modelId}`:resolved.modelId;return{selector:endpoint===void 0?selector:`${selector}\0${endpoint}`,modelId:resolved.modelId,...resolved.authType&&{authType:resolved.authType}}}__name(resolveModModel,"resolveModModel");function tokenCount(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):0}__name(tokenCount,"tokenCount");function modModelUsage(metadata,authType){if(!metadata)return{...NO_USAGE};const prompt=tokenCount(metadata.promptTokenCount);const read=tokenCount(metadata.cachedContentTokenCount);const written=tokenCount(getGenAiUsageProvenance(metadata)?.cacheCreationInputTokens);return{input_tokens:Math.max(0,prompt-read-written),output_tokens:outputTokenCount({input:prompt,output:tokenCount(metadata.candidatesTokenCount),thoughts:tokenCount(metadata.thoughtsTokenCount),total:tokenCount(metadata.totalTokenCount)},authType),cache_read_input_tokens:read,cache_creation_input_tokens:written}}__name(modModelUsage,"modModelUsage");function apiErrorKind(error,status){const message=error instanceof Error?error.message:String(error);if(status===529||/overloaded/i.test(message))return"overloaded";if(status===404||/model[^.]*not (found|exist)/i.test(message))return"model_not_found";if(isQuotaExhaustedError(error)||isQwenQuotaExceededError(error))return"billing_error";const kind=classifyApiError({message,status});return kind==="loop_detected"?"unknown":kind}__name(apiErrorKind,"apiErrorKind");async function completeModModel(config,input,signal){if(signal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const model=resolveModModel(config,input.model);const maxTokens=input.maxTokens??MOD_MODEL_DEFAULT_MAX_TOKENS;if(input.maxTokens!==void 0&&hasExplicitOutputLimit(model.modelId)&&maxTokens>tokenLimit(model.modelId,"output"))throw new Error(`maxTokens ${maxTokens} is over ${model.modelId}'s output limit of ${tokenLimit(model.modelId,"output")}`);const abortSignal=input.timeoutMs===void 0?signal:AbortSignal.any([signal,AbortSignal.timeout(input.timeoutMs)]);let onAbort;try{const request=Promise.resolve().then(()=>config.getBaseLlmClient().generateText({contents:[{role:"user",parts:[{text:input.prompt}]}],model:model.selector,...typeof input.system==="string"&&input.system&&{systemInstruction:input.system},abortSignal,promptId:"side-query:mod-model-complete",config:{maxOutputTokens:Math.min(maxTokens,hasExplicitOutputLimit(model.modelId)?tokenLimit(model.modelId,"output"):maxTokens),thinkingConfig:{includeThoughts:input.effort!==void 0}},isolatedRequest:true}));const cancelled=new Promise((_,reject)=>{onAbort=__name(()=>reject(abortSignal.reason),"onAbort");abortSignal.addEventListener("abort",onAbort,{once:true})});const result=await Promise.race([request,cancelled]);const usage=modModelUsage(result.usage,model.authType??config.getContentGeneratorConfig()?.authType);if(!result.text)return{isAnswered:false,reason:"empty-reply",usage};const text=projectJsonStringToByteBudget(result.text,MOD_MAX_BYTES/2,"\n[... truncated for Mods ...]\n");return{isAnswered:true,text,usage}}catch(error){if(abortSignal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const providerError=error instanceof Error?error.cause??error:error;let cause=providerError;let status=getErrorStatus(cause);for(let depth=0;depth<4&&status===void 0&&cause instanceof Error&&cause.cause!==void 0;depth++){cause=cause.cause;status=getErrorStatus(cause)}const providerStatus=status??getErrorStatus(error);return{isAnswered:false,reason:"api-error",status:providerStatus??null,error:apiErrorKind(status===void 0?providerError:cause,providerStatus),usage:{...NO_USAGE}}}finally{if(onAbort)abortSignal.removeEventListener("abort",onAbort)}}__name(completeModModel,"completeModModel");init_esbuild_shims();var KEPT_ROWS=1e3;var rowId=__name(input=>`${input.component}\0${input.requestId}`,"rowId");var rowKey=__name(input=>stableJson({...input,viewport:void 0}),"rowKey");var ModRows=class{constructor(schedule,render){this.schedule=schedule;this.render=render}static{__name(this,"ModRows")}rows=new Map;queue=[];running=false;watch(input,listener){const id=rowId(input);const key=rowKey(input);let row=this.rows.get(id);if(row){this.rows.delete(id);row.input=input;row.key=key}else row={input,key,queued:false,listeners:new Set};this.rows.set(id,row);row.listeners.add(listener);if(this.due(row))this.enqueue(id,row);this.prune();return()=>{row.listeners.delete(listener);if(!this.running)this.prune()}}get(input){const row=this.rows.get(rowId(input));return row?.answer&&row.answerKey===rowKey(input)?row.answer:void 0}invalidate(component){for(const[id,row]of this.rows){if(row.input.component!==component)continue;row.stale=true;if(row.listeners.size)this.enqueue(id,row)}}clear(){const rows=[...this.rows.values()];this.rows.clear();this.queue.length=0;for(const row of rows)if(row.answer)for(const listener of row.listeners)listener()}enqueue(id,row){if(row.queued)return;row.queued=true;this.queue.push(id);this.pump()}pump(){if(this.running)return;let id;let row;while((id=this.queue.shift())!==void 0){const next=this.rows.get(id);if(!next)continue;next.queued=false;if(next.listeners.size&&this.due(next)){row=next;break}}this.prune();if(!row||id===void 0)return;const ready=row;const readyId=id;this.running=true;this.schedule(async()=>{try{if(this.rows.get(readyId)!==ready||!ready.listeners.size)return;const{input,key}=ready;ready.stale=false;let answer;try{answer=await this.render(input)}catch{answer=void 0}if(this.rows.get(readyId)===ready){const changed=ready.answer!==answer;ready.answer=answer;ready.answerKey=key;if(this.due(ready)&&ready.listeners.size)this.enqueue(readyId,ready);if(changed)for(const listener of ready.listeners)listener()}}finally{this.running=false;this.pump()}})}due(row){return row.stale===true||row.answerKey!==row.key}prune(){if(this.rows.size<=KEPT_ROWS)return;for(const[id,row]of this.rows){if(this.rows.size<=KEPT_ROWS)break;if(!row.listeners.size&&!row.queued)this.rows.delete(id)}}};var logger=createDebugLogger("MODS");var MOD_PROMPT_TURN_LIMIT=8;var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;var ROW_RENDER_TIMEOUT_MS=3e4;var ModSession=class _ModSession{constructor(config,output,optionScopes=[]){this.config=config;this.output=output;this.optionScopes=optionScopes;this.sessionId=config.getSessionId();uiTelemetryService.on("update",this.observe);this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close().then(()=>this.flushOutput())},{first:Boolean(this.terminal)})}static{__name(this,"ModSession")}mods=[];runtime;toolQueue=Promise.resolve();lifetime=new AbortController;endLifetime=new AbortController;initialization;closing;logsReady=false;pendingLogs=[];notes=[];activeCommand;commandSignal;toolSignal;sessionId;adoptedAt=Date.now();startedAt;recorder;context={tokens:0,window:0};turn;submitted=[];modTurns=0;stopped=false;taken=new WeakMap;observe=__name(update=>runOutsideAgentContext(()=>{if(this.config.getSessionId()!==this.sessionId)return;this.recorder=this.config.getChatRecordingService();this.context={tokens:uiTelemetryService.getLastPromptTokenCount(),window:this.config.getContentGeneratorConfig()?.contextWindowSize||0};const event=update?.event;if(!this.turn||event?.["event.name"]!==EVENT_API_RESPONSE)return;const response=event;if(response.subagent_name===void 0&&!isInternalPromptId(response.prompt_id)&&(this.turn.promptId===void 0||response.prompt_id===this.turn.promptId))this.turn.model=response.model}),"observe");toolGeneration=new AbortController;sites=[];band={state:"idle",again:false,startedAt:-Infinity,steadyUntil:0};rows=new ModRows(task=>{this.toolQueue=this.toolQueue.then(task).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))},input=>this.renderRow(input));unregisterCleanup;static create(config,settings,output){return settings.merged.experimental?.mods?new _ModSession(config,output,[settings.systemDefaults.settings.pluginConfigs,settings.user.settings.pluginConfigs,settings.system.settings.pluginConfigs]):void 0}get terminal(){return"surface"in this.output?this.output:void 0}allowed(){return this.config.isInteractive()===Boolean(this.terminal)&&!this.config.getExperimentalZedIntegration()&&this.config.isTrustedFolder()&&!this.config.getDisableAllHooks()&&!this.config.getBareMode()&&!this.config.isSafeMode()&&!this.config.getExecutionEnvironment()&&!this.config.getExecutionEnvironmentFactory()&&!this.config.getHookSystem()?.isManaged()&&!this.config.getSandbox()&&!this.config.isSessionAgentSession()}async initialize(signal){if(this.closing)throw new Error("Mod session is closed.");if(!this.allowed()){if(this.mods.length){await this.close();throw new Error("Mods are no longer permitted in this session.")}return}this.initialization??=this.load(AbortSignal.any([signal,this.lifetime.signal]));await this.initialization}async load(signal){const sites=this.sites=this.terminal?.sites?.()??[];try{const candidates=[];for(const extension of this.config.getExtensions().filter(item=>item.isActive&&item.format!=="agent-plugins-v1")){signal.throwIfAborted();try{const source=await loadModSource(extension.path);const marketplace=extension.installMetadata?.marketplaceConfig?.name;candidates.push({extension,name:extension.name,version:extension.version,marketplace,source,dependencies:source?.dependencies??[],toolDialect:source?resolveModToolDialect(this.optionScopes,extension.name,marketplace):void 0,unsupportedEvents:source?resolveModUnsupportedEvents(this.optionScopes,extension.name,marketplace):void 0,options:source?resolveModOptions(source.userConfig,this.optionScopes,extension.name,marketplace):{}})}catch(error){throw new Error(`Mod ${extension.name}: ${error instanceof Error?error.message:String(error)}`)}}const pending=candidates.filter(item=>item.source);const reachable=new Set;while(pending.length){signal.throwIfAborted();const plugin=pending.shift();if(reachable.has(plugin))continue;reachable.add(plugin);if(!plugin.source){try{plugin.dependencies=await loadModDependencies(plugin.extension.path)}catch(error){throw new Error(`Mod dependency ${plugin.name}: ${error instanceof Error?error.message:String(error)}`)}}for(const dependency2 of plugin.dependencies){pending.push(resolveModDependency(candidates,plugin,dependency2))}}const selected=candidates.filter(item=>reachable.has(item));orderModPlugins(selected);const mods=selected.filter(item=>item.source).map(plugin=>({...plugin,dependencies:plugin.dependencies.filter(dependency2=>resolveModDependency(selected,plugin,dependency2).source)}));const ordered=orderModPlugins(mods);if(ordered.length){this.runtime=await ModRuntime.createGroup(ordered.map(({extension,source,options,toolDialect,unsupportedEvents})=>({id:extension.id,name:extension.name,source:{root:source.root,entry:source.entry,source:source.source},options,toolDialect,unsupportedEvents})),this.config.getTargetDir(),(entry,plugin)=>{if(this.commandSignal?.aborted||this.toolSignal?.aborted)return;this.pendingLogs.push({...entry,plugin,sessionId:this.sessionId});if(this.logsReady)this.flushLogs()},signal,name2=>this.config.getToolRegistry().ensureTool(name2),this.terminal?.surface??null,this.config.getCliVersion()||"unknown",()=>this.facts(),turnId=>this.abortTurn(turnId),sites.length?{sites,invalidate:__name(plugin=>this.invalidateRenders(plugin),"invalidate")}:void 0,this.terminal?this.terminal.prompts?.()===true:true,this.terminal&&this.terminal.runsPrompts?.()!==true?void 0:prompt=>this.queuePrompt(prompt),(input,modelSignal)=>completeModModel(this.config,input,this.sessionId===this.config.getSessionId()?modelSignal:AbortSignal.abort()),new ModStore(path4.join(Storage.getGlobalQwenDir(),"mods","store")));this.mods.push(...ordered.map(({extension})=>({id:extension.id,name:extension.name})));this.requestRender()}}catch(error){await this.runtime?.dispose();this.mods.length=0;throw error}}async loadCommands(signal){await this.initialize(signal);return this.mods.flatMap(mod=>this.runtime.getCommands(mod.id).map(command=>({name:command.name,description:this.terminal?sanitizeTerminalLine(command.description):command.description,kind:"file",source:"plugin-command",extensionName:this.terminal?sanitizeTerminalLine(mod.name):mod.name,supportedModes:[this.terminal?"interactive":"non_interactive"],argumentHint:this.terminal&&command.argumentHint!==void 0?sanitizeTerminalLine(command.argumentHint):command.argumentHint,modelInvocable:false,action:__name(async(context,args)=>{const active=AbortSignal.any([context.abortSignal??(this.terminal?this.lifetime.signal:signal),this.lifetime.signal]);const task=this.toolQueue.then(async()=>{active.throwIfAborted();if(!this.allowed()||!this.active()||this.closing){await this.runtime.dispose();throw new Error(`Mod ${mod.name} is disabled or its middleware chain changed.`)}if(this.sessionId!==this.config.getSessionId())throw new Error("The Mod command belongs to a previous session.");const controller=new AbortController;this.activeCommand=controller;const commandSignal=AbortSignal.any([active,controller.signal]);this.commandSignal=commandSignal;try{const content=await this.runtime.runCommand(command.name,args,commandSignal,this.terminal?.presentation());commandSignal.throwIfAborted();return{type:"message",messageType:"info",content:this.terminal?sanitizeTerminalText(stripUnsafeCharacters(content)):content}}finally{this.flushLogs();this.activeCommand=void 0;this.commandSignal=void 0}});this.toolQueue=task.catch(()=>{});return task},"action")})))}invalidateTools(){this.toolGeneration.abort();this.pendingLogs.length=0;this.activeCommand?.abort()}async restoreTools(){await this.toolQueue;if(!this.closing&&this.sessionId===this.config.getSessionId()){this.toolGeneration=new AbortController;this.requestRender();this.refreshRows()}}captureToolSignal(){return this.toolGeneration.signal}async syncSession(reason){const current=this.config.getSessionId();if(current===this.sessionId){if(this.toolGeneration.signal.aborted){this.toolGeneration=new AbortController;this.refreshRows()}return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;this.rows.clear();this.submitted.length=0;this.modTurns=0;this.stopped=false;this.adoptedAt=Date.now();this.startedAt=void 0;this.recorder=void 0;this.context={tokens:0,window:0};this.capture();this.toolGeneration=new AbortController;this.requestRender()});this.toolQueue=task.catch(()=>{});await task}get hasToolHooks(){return this.runtime?.hasToolHooks===true}setRenderInput(input){const band=this.band;const key=[input.viewport?.columns,input.viewport?.isFullscreen,stableJson(input.props)].join("\0");band.input=input;if(key===band.key)return;const size=`${input.viewport?.columns}\0${input.props.maxRows}`;const resized=band.size!==void 0&&size!==band.size;band.key=key;band.size=size;if(resized){clearTimeout(band.settle);band.settle=setTimeout(()=>{band.settle=void 0;this.requestRender()},RENDER_SETTLE_MS)}else this.requestRender()}requestRender(){const band=this.band;if(this.closing||!band.input||!this.sites.includes(band.input.component)||band.settle||band.wait||!this.runtime?.renderHooksFor("AbovePrompt").length||band.state==="waiting")return;if(band.state==="running"){band.again=true;return}const now=Date.now();const gap=(now<band.steadyUntil?RENDER_STEADY_MS:RENDER_LIVE_MS)-(now-band.startedAt);if(gap>0){band.wait=setTimeout(()=>{band.wait=void 0;this.requestRender()},gap);return}band.state="waiting";this.toolQueue=this.toolQueue.then(()=>this.render()).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))}async render(){const band=this.band;const runtime=this.runtime;const hooks=runtime.renderHooksFor("AbovePrompt");const owner=hooks.length===1?hooks[0]:"hooks";band.state="running";band.startedAt=Date.now();const signal=AbortSignal.any([this.lifetime.signal,this.toolGeneration.signal]);const isCurrent=__name(()=>!signal.aborted&&this.sessionId===this.config.getSessionId(),"isCurrent");try{if(this.closing||this.sessionId!==this.config.getSessionId())return;if(!this.allowed()||!this.active()){this.terminal?.draw?.(ENGINE_NODE,owner);return}const{tree,notes}=await runtime.render(band.input,signal);for(const note of notes)logger.debug(note);if(isCurrent())this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(isCurrent())this.terminal?.draw?.(ENGINE_NODE,owner)}finally{if(Date.now()-band.startedAt>RENDER_LIVE_MS)band.steadyUntil=Date.now()+RENDER_SLOW_MS;band.state="idle";if(band.again){band.again=false;this.requestRender()}this.flushLogs()}}watchRow(sessionId,input,listener){if(this.closing||sessionId!==this.sessionId||!this.sites.includes(input.component)||!this.runtime?.renderHooksFor(input.component).length||Buffer.byteLength(JSON.stringify(input))>MOD_MAX_BYTES/2)return void 0;return this.rows.watch(input,listener)}rowProps(sessionId,input){return sessionId===this.sessionId?this.rows.get(input):void 0}refreshRows(){for(const site of this.sites)if(site!=="AbovePrompt")this.rows.invalidate(site)}invalidateRenders(plugin){const runtime=this.runtime;if(!runtime)return;for(const site of this.sites){if(!runtime.renderHooksFor(site).includes(plugin))continue;if(site==="AbovePrompt")this.requestRender();else this.rows.invalidate(site)}}async renderRow(input){const runtime=this.runtime;const generation=this.toolGeneration.signal;if(!runtime||this.closing||generation.aborted||this.sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return void 0;const signal=AbortSignal.any([this.lifetime.signal,generation,AbortSignal.timeout(ROW_RENDER_TIMEOUT_MS)]);try{const{props,notes}=await runtime.render(input,signal);signal.throwIfAborted();for(const note of notes)logger.debug(note);return!props||stableJson(props)===stableJson(input.props)?void 0:props}finally{this.flushLogs()}}toolCall(onRepeat){if(!this.hasToolHooks)return void 0;return(input,next,signal)=>{const generation=this.toolGeneration;const sessionId=this.sessionId;const active=AbortSignal.any([signal,this.lifetime.signal,generation.signal]);const assertAllowed=__name(()=>{active.throwIfAborted();if(generation!==this.toolGeneration||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active()||this.closing)throw new Error("Mod tool middleware is disabled or its chain changed.")},"assertAllowed");const task=this.toolQueue.then(async()=>{assertAllowed();let attempts=0;this.toolSignal=active;try{return await this.runtime.runTool(input,async(changed,hostSignal,check)=>{assertAllowed();if(attempts++)onRepeat();active.throwIfAborted();return next(changed,hostSignal,async(question,verdict,checkSignal)=>{assertAllowed();const result=await check(question,verdict,checkSignal);assertAllowed();checkSignal.throwIfAborted();return result})},active)}finally{if(this.toolSignal===active)this.toolSignal=void 0}});this.toolQueue=task.catch(()=>{});return task}}queuePrompt(prompt){if(this.closing||this.sessionId!==this.config.getSessionId())return"the session is ending";const refused=this.stopped?"the person stopped a turn and has not sent a prompt since":this.modTurns+this.submitted.length>=MOD_PROMPT_TURN_LIMIT?`the Mods have started ${MOD_PROMPT_TURN_LIMIT} turns since the last prompt from the person`:void 0;if(refused){this.pendingLogs.push({text:`$.prompt.submit refused: ${refused}`,to:"transcript",plugin:prompt.plugin,sessionId:this.sessionId});this.flushLogs();return refused}this.submitted.push({...prompt,sessionId:this.sessionId});this.terminal?.promptQueued?.();return void 0}takeSubmittedPrompt(){const sessionId=this.config.getSessionId();let next=this.submitted.shift();while(next&&next.sessionId!==sessionId)next=this.submitted.shift();if(!next||this.closing)return void 0;this.modTurns++;const{sessionId:queuedFor,...prompt}=next;this.taken.set(prompt,queuedFor);return prompt}returnSubmittedPrompt(prompt){const sessionId=this.taken.get(prompt);this.taken.delete(prompt);if(sessionId===void 0||this.closing||this.stopped||sessionId!==this.config.getSessionId())return;this.modTurns=Math.max(0,this.modTurns-1);this.submitted.unshift({...prompt,sessionId})}get hasSubmittedPrompts(){const sessionId=this.config.getSessionId();return!this.closing&&this.submitted.some(prompt=>prompt.sessionId===sessionId)}notePersonPrompt(){this.modTurns=0;this.stopped=false}discardSubmittedPrompts(){this.submitted.length=0}stopSubmittedPrompts(){this.discardSubmittedPrompts();this.stopped=true}get hearsPrompts(){return!this.closing&&(this.runtime?.promptHooks.length??0)>0}async submitPrompt(text,signal){const plugins=this.runtime?.promptHooks??[];if(!plugins.length||this.closing)return{text};const input={text,wait:false,origin:{kind:this.terminal?"composer":"sdk"}};if(fitTurnText(text).truncated){this.pendingLogs.push({text:"prompt.submit hook skipped: the prompt is too long for a Mod payload",to:"transcript",plugin:plugins.join("+"),sessionId:this.sessionId});this.flushLogs();return{text}}const sessionId=this.sessionId;const task=this.toolQueue.then(async()=>{signal.throwIfAborted();if(this.closing||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return{text};try{return await this.runtime.submitPrompt(input,AbortSignal.any([signal,this.lifetime.signal]))}catch(error){signal.throwIfAborted();logger.debug(`Mod prompt.submit: ${String(error)}`);return{text}}finally{this.flushLogs()}});this.toolQueue=task.catch(()=>{});const result=await task;if(!("drop"in result)){if(!result.text.trim()&&text.trim())return{drop:"Prompt dropped by a hook: it left the prompt empty"};return result}if(!result.byHook)return{drop:`Prompt not submitted: ${result.drop}`};const reason=(this.terminal?sanitizeTerminalLine:stripAnsiAndControl)(result.drop.replace(/\r?\n/g," ").trim());if(cpLen(reason)>4096)logger.debug(`${plugins.join("+")}: prompt.submit hook: a drop of ${cpLen(reason)} characters, kept up to its first 4096`);return{drop:`Prompt dropped by a hook: ${cpLen(reason)>4096?`${cpSlice(reason,0,4096)}\u2026`:reason}`}}startTurn(text,signal,abort,promptId){const hooks=this.runtime?.turnHooks;if(!hooks||!hooks.start&&!hooks.complete.length||this.closing)return void 0;const turn={id:randomUUID2(),sessionId:this.sessionId,startedAt:Date.now(),abort,aborting:false,streaming:"",answer:"",failed:false,...promptId!==void 0&&{promptId}};this.turn=turn;if(hooks.start){const fitted=fitTurnText(text);const input={text:fitted.text,turnId:turn.id,...fitted.truncated&&{isTextTruncated:true}};void this.queueTurnEvent(turn,lifetime=>this.runtime.startTurn(input,AbortSignal.any([lifetime,signal])))}let ending;return{id:turn.id,saw:__name(event=>this.see(turn,event),"saw"),complete:__name(reason=>ending??=this.completeTurn(turn,reason),"complete")}}see(turn,event){if(turn.ended||!this.runtime?.turnHooks.complete.length)return;switch(event.type){case"content":turn.streaming+=event.value;break;case"finished":turn.answer=turn.streaming;turn.streaming="";turn.usage=addTurnUsage(turn.usage,event.value.usageMetadata,this.config.getContentGeneratorConfig()?.authType);break;case"retry":if(!event.isContinuation)turn.streaming="";else if(!turn.streaming)turn.streaming=turn.answer;break;case"model_fallback":turn.streaming="";break;case"error":case"loop_detected":case"max_session_turns":case"session_token_limit_exceeded":turn.failed=true;break;default:break}}completeTurn(turn,ending){if(turn.ended)return turn.ended;if(this.turn===turn)this.turn=void 0;const plugins=this.runtime?.turnHooks.complete??[];if(!plugins.length)return Promise.resolve();const reason=turn.aborting||ending==="aborted"?"aborted":ending==="error"||turn.failed?"error":"answer";const answer=fitTurnText((turn.streaming||turn.answer).trim());const input={answer:answer.text,durationMs:Date.now()-turn.startedAt,isAborted:reason==="aborted",turnId:turn.id,reason,...turn.usage?{usage:{...turn.usage,model:turn.model??runOutsideAgentContext(()=>this.config.getModel())}}:{},...answer.truncated&&{isAnswerTruncated:true}};const run=__name(async signal=>{const text=await this.runtime.completeTurn(input,signal);if(text===input.answer||!text.trim())return;const note={text:cpLen(text)>4096?`${cpSlice(text,0,4096)}\u2026`:text,to:"transcript",plugin:plugins.join("+"),sessionId:turn.sessionId,isTurnNote:true};if(!this.terminal&&this.config.getOutputFormat()==="text")this.notes.push(`[Mod ${note.plugin}] ${stripAnsiAndControl(note.text)}`);else this.pendingLogs.push(note)},"run");return turn.ended=this.queueTurnEvent(turn,run,true)}queueTurnEvent(turn,run,isEnd=false){const task=this.toolQueue.then(async()=>{if(this.closing&&!isEnd||turn.sessionId!==this.sessionId||!this.allowed()||!this.active())return;try{await run(isEnd?this.endLifetime.signal:this.lifetime.signal)}finally{this.flushLogs()}}).catch(error=>logger.debug(`Mod turn event: ${String(error)}`));this.toolQueue=task;return task}abortTurn(turnId){const turn=this.turn;if(!turn)throw new Error(`$.turn.abort: no turn is running (asked for ${turnId})`);if(turn.id!==turnId)throw new Error(`$.turn.abort: ${turnId} is not the running turn (${turn.id}); a hook ends the turn turn.start told it about`);if(turn.aborting)throw new Error(`$.turn.abort: ${turnId} is already ending`);turn.aborting=true;let cancelled=false;try{cancelled=turn.abort()}finally{turn.aborting=cancelled}if(!cancelled)throw new Error(`$.turn.abort: ${turnId} is already ending`);logger.debug(`$.turn.abort: cancelled turn ${turnId}`)}flushLogs(){this.logsReady=true;for(const entry of this.pendingLogs.splice(0)){logger.debug(`[${entry.plugin}] ${entry.text}`);if(entry.to==="debug")continue;const text=this.terminal?sanitizeTerminalText(stripUnsafeCharacters(entry.text)):stripAnsiAndControl(entry.text);if("surface"in this.output){const{isTurnNote,...log}=entry;this.output.log({...log,text:isTurnNote?text:cpSlice(text,0,2e3)},entry.plugin,entry.sessionId)}else if(this.config.getOutputFormat()==="text"){process.stderr.write(`[Mod ${entry.plugin}] ${text}
3
+ import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{flushOutput}from"./chunk-VURTGFJP.js";import{cpLen,cpSlice,sanitizeTerminalLine,sanitizeTerminalText,stripUnsafeCharacters}from"./chunk-64CA3W6G.js";import{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,invalidRenderText,record,validModelResult,validateRenderTree,validateResult}from"./chunk-XWYUQMLN.js";import{stableJson}from"./chunk-FIXDX63I.js";import{openNoFollow}from"./chunk-PSKT6KWO.js";import{isZombie,readLocalBootId,readPidNamespaceId,readProcStartToken}from"./chunk-JB3XRNK7.js";import{buildModelIdContext,resolveModelId}from"./chunk-6XLIEJP5.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{runOutsideAgentContext}from"./chunk-WXQQVXYN.js";import{external_exports}from"./chunk-KZSUHQLD.js";import{isQuotaExhaustedError,isQwenQuotaExceededError}from"./chunk-A6LYTPBP.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-R5AA46IX.js";import{Mutex,Semaphore}from"./chunk-JEV36CS7.js";import{hasExplicitOutputLimit,tokenLimit}from"./chunk-AZ4Q2ZWQ.js";import{renameWithRetry}from"./chunk-2GF3E5MI.js";import{EVENT_API_RESPONSE}from"./chunk-UFRESHR3.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{require_semver}from"./chunk-73G3MZQR.js";import{registerCleanup}from"./chunk-ZSPOFXP3.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorStatus,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";import path4 from"node:path";init_esbuild_shims();import{promises as fs}from"node:fs";import path from"node:path";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);var name=external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);var dependency=external_exports.union([external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:@[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/),external_exports.object({name,marketplace:name.optional(),version:external_exports.string().optional()}).strict()]);function parseModDependencies(value){const parsed=external_exports.array(dependency).safeParse(value===void 0?[]:value);if(!parsed.success)throw new Error("Invalid Mod dependencies declaration.");return parsed.data.map(item=>{if(typeof item==="string"){const[name2,marketplace]=item.split("@");return{name:name2,marketplace}}if(item.version!==void 0&&!(0,import_semver.validRange)(item.version)){throw new Error(`Invalid Mod dependency version range for ${item.name}.`)}return item})}__name(parseModDependencies,"parseModDependencies");function resolveModDependency(plugins,plugin,dependency2){const marketplace=dependency2.marketplace??plugin.marketplace;const local=plugins.filter(item=>item.name===dependency2.name&&!item.marketplace);const matches=local.length?local:plugins.filter(item=>item.name===dependency2.name&&item.marketplace===marketplace);if(matches.length!==1){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} must identify one installed, enabled plugin.`)}const target=matches[0];if(target.marketplace&&dependency2.version&&!(0,import_semver.satisfies)(target.version,dependency2.version)){throw new Error(`Mod ${plugin.name}: dependency ${dependency2.name} has an incompatible installed version.`)}return target}__name(resolveModDependency,"resolveModDependency");function orderModPlugins(plugins){const edges=plugins.map(()=>new Set);const incoming=plugins.map(()=>0);for(const[index,plugin]of plugins.entries()){for(const dependency2 of plugin.dependencies){const targetIndex=plugins.indexOf(resolveModDependency(plugins,plugin,dependency2));if(!edges[index].has(targetIndex)){edges[index].add(targetIndex);incoming[targetIndex]++}}}const ordered=[];const remaining=new Set(plugins.map((_,index)=>index));while(remaining.size){const next=[...remaining].find(index=>incoming[index]===0);if(next===void 0)throw new Error("Mod dependency cycle: activation refused.");remaining.delete(next);ordered.push(plugins[next]);for(const target of edges[next])incoming[target]--}return ordered}__name(orderModPlugins,"orderModPlugins");function isContainedFile(root,file){const relative=path.relative(root,file);return Boolean(relative)&&!path.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path.sep}`)}__name(isContainedFile,"isContainedFile");async function readModFile(root,file){if(!isContainedFile(root,file)){throw new Error("Mod file must stay inside the installed extension.")}let current=root;for(const part of path.relative(root,file).split(path.sep)){current=path.join(current,part);const stat=await fs.lstat(current);if(stat.isSymbolicLink()){throw new Error("Mod files cannot be symbolic links.")}if(current===file&&!stat.isFile()){throw Object.assign(new Error("Mod input must be a regular file."),{code:stat.isDirectory()?"EISDIR":void 0})}}const entry=await fs.realpath(file);if(!isContainedFile(root,entry)){throw new Error("Mod file must stay inside the installed extension.")}const handle=await openNoFollow(entry);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>MOD_MAX_BYTES){throw new Error("Mod file exceeds the 256 KiB regular-file limit.")}const buffer=Buffer.alloc(MOD_MAX_BYTES+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>MOD_MAX_BYTES)throw new Error("Mod file is too large.");return{entry,source:buffer.subarray(0,bytesRead).toString("utf8")}}finally{await handle.close()}}__name(readModFile,"readModFile");async function readManifest(root,relative){try{if(path.isAbsolute(relative)){throw new Error("Mod manifest path must be relative to the extension.")}const value=JSON.parse((await readModFile(root,path.resolve(root,relative))).source);if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("Mod manifest must be a JSON object.")}return value}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(readManifest,"readManifest");async function loadModSource(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");if(typeof qwen?.["hooks"]==="string"&&(path.isAbsolute(qwen["hooks"])||!isContainedFile(root,path.resolve(root,qwen["hooks"])))){return void 0}const claude=await readManifest(root,".claude-plugin/plugin.json");const hooksPath=typeof qwen?.["hooks"]==="string"?qwen["hooks"]:typeof claude?.["hooks"]==="string"?claude["hooks"]:"hooks/hooks.json";if(path.isAbsolute(hooksPath)||!isContainedFile(root,path.resolve(root,hooksPath))){return void 0}const hooks=await readManifest(root,hooksPath);if(!hooks||!Object.hasOwn(hooks,"modules"))return void 0;const modules=hooks["modules"];if(!Array.isArray(modules)||modules.length!==1||typeof modules[0]!=="string"||path.isAbsolute(modules[0])||!/\.(?:[cm]?js|[cm]?ts|[jt]sx)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript, TypeScript or JSX module.")}const manifest={...claude,...qwen};const entry=path.resolve(root,path.dirname(hooksPath),modules[0]);return{root,...await readModFile(root,entry),userConfig:manifest["userConfig"],dependencies:parseModDependencies(manifest["dependencies"])}}__name(loadModSource,"loadModSource");async function loadModDependencies(extensionPath){const root=await fs.realpath(extensionPath);const qwen=await readManifest(root,"qwen-extension.json");const claude=await readManifest(root,".claude-plugin/plugin.json");return parseModDependencies({...claude,...qwen}["dependencies"])}__name(loadModDependencies,"loadModDependencies");init_esbuild_shims();var option=external_exports.union([external_exports.string(),external_exports.number().finite(),external_exports.boolean(),external_exports.array(external_exports.string())]);var field=external_exports.object({type:external_exports.enum(["string","number","boolean","directory","file"]),title:external_exports.string(),description:external_exports.string(),required:external_exports.boolean().optional(),default:option.optional(),multiple:external_exports.boolean().optional(),sensitive:external_exports.boolean().optional(),min:external_exports.number().finite().optional(),max:external_exports.number().finite().optional(),options:external_exports.array(external_exports.string().min(1).max(64)).nonempty().optional()}).strict().refine(value=>{if(!value.options)return true;return value.type==="string"&&!value.multiple&&!value.sensitive&&value.options.every(item=>item.trim()===item&&!/[\p{Cc}\p{Cf}]/u.test(item))&&new Set(value.options.map(item=>item.toLowerCase())).size===value.options.length&&(value.default===void 0?value.required===true:value.options.includes(value.default))});var schema=external_exports.record(external_exports.string().regex(/^[A-Za-z_]\w*$/),field);var storedOptions=external_exports.record(external_exports.string(),option);function*pluginConfigurations(scopes,name2,marketplace){const keys=marketplace?[`${name2}@${marketplace}`]:[name2,`${name2}@inline`];for(const scope of scopes){if(scope===void 0)continue;if(!scope||typeof scope!=="object"||Array.isArray(scope)){throw new Error("Invalid Mod pluginConfigs settings.")}for(const key of keys){if(!Object.hasOwn(scope,key))continue;const config=scope[key];if(!config||typeof config!=="object"||Array.isArray(config)){throw new Error("Invalid Mod pluginConfigs entry.")}yield config}}}__name(pluginConfigurations,"pluginConfigurations");function resolveModChoice(scopes,name2,marketplace,key,choices){let choice=choices[0];for(const config of pluginConfigurations(scopes,name2,marketplace)){const value=config[key];if(value===void 0)continue;if(!choices.includes(value))throw new Error(`Invalid Mod ${key}: expected ${choices.join(" or ")}.`);choice=value}return choice}__name(resolveModChoice,"resolveModChoice");function resolveModToolDialect(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"toolDialect",["native","claude"])}__name(resolveModToolDialect,"resolveModToolDialect");function resolveModUnsupportedEvents(scopes,name2,marketplace){return resolveModChoice(scopes,name2,marketplace,"unsupportedEvents",["skip","reject"])}__name(resolveModUnsupportedEvents,"resolveModUnsupportedEvents");function resolveModOptions(declaration,scopes,name2,marketplace){const parsed=schema.safeParse(declaration===void 0?{}:declaration);if(!parsed.success)throw new Error("Invalid Mod userConfig declaration.");const fields=Object.entries(parsed.data);if(!fields.length)return{};if(fields.some(([,value])=>value.sensitive)){throw new Error("Sensitive Mod userConfig is not supported yet.")}let stored={};for(const config of pluginConfigurations(scopes,name2,marketplace)){const options=config["options"];if(options===void 0)continue;const values=storedOptions.safeParse(options);if(!values.success)throw new Error(`Invalid Mod configured option: ${String(values.error.issues[0]?.path[0]??"").slice(0,64)}.`);stored={...stored,...values.data}}const result=Object.fromEntries(fields.filter(([,config])=>config.default!==void 0||!config.required).map(([key,config])=>[key,config.default??""]));for(const[key,value]of Object.entries(stored)){const choices=Object.hasOwn(parsed.data,key)?parsed.data[key].options:void 0;if(!choices||choices.includes(value))Object.defineProperty(result,key,{value,enumerable:true,writable:true,configurable:true})}for(const[key,config]of fields){const value=Object.hasOwn(result,key)?result[key]:void 0;if(value===void 0||value===""){if(config.required)throw new Error(`Missing required Mod option: ${key}.`)}else{const valid=config.type==="number"?typeof value==="number"&&(config.min===void 0||value>=config.min)&&(config.max===void 0||value<=config.max):config.type==="boolean"?typeof value==="boolean":typeof value==="string"||config.type==="string"&&config.multiple&&Array.isArray(value);if(!valid)throw new Error(`Invalid Mod option: ${key}.`)}}if(Buffer.byteLength(JSON.stringify(result))>MOD_MAX_BYTES){throw new Error("Mod options exceed the 256 KiB limit.")}return result}__name(resolveModOptions,"resolveModOptions");init_esbuild_shims();import{Worker}from"node:worker_threads";import{existsSync}from"node:fs";import path2 from"node:path";import{createRequire}from"node:module";import{pathToFileURL}from"node:url";function workerEntry(){if(import.meta.url.endsWith(".ts")){return new URL(`data:text/javascript,${encodeURIComponent(`import { register } from ${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}; register(); await import(${JSON.stringify(new URL("./mod-worker.ts",import.meta.url).href)});`)}`)}const sibling=new URL("./mod-worker.js",import.meta.url);return existsSync(sibling)?sibling:path2.join(resolveBundleDir(import.meta.url),"mod-worker.js")}__name(workerEntry,"workerEntry");var ModRuntime=class _ModRuntime{constructor(log,facts,resolveTool,surface=null,abortTurn,renderHost,queuePrompt,completeModel,store){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;this.queuePrompt=queuePrompt;this.completeModel=completeModel;this.store=store;this.worker=new Worker(workerEntry(),{stdout:true,stderr:true,workerData:this.cancelled.buffer});this.worker.stdout?.resume();this.worker.stderr?.resume();this.worker.on("message",reply=>{const root=this.root;if(!root||reply.root!==root.id)return;if(reply.type==="host-call")this.executeHost(reply);else if(reply.type==="host-cancel"){for(const id of reply.ids){this.tool?.operations.get(id)?.controller.abort();root.models.get(id)?.abort();this.storeCalls.get(id)?.controller.abort()}}else if(reply.type==="model-complete")this.answerModel(reply,root);else if(reply.type==="check-result")this.tool?.checks.get(reply.id)?.(reply);else if(reply.type==="turn-abort")this.answerTurnAbort(reply,root.id);else if(reply.type==="prompt-queue")this.answerPromptQueue(reply,root.id);else if(reply.type==="store"){const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signals=[root.storeAbort.signal,controller.signal];if(Number.isFinite(remainingMs))signals.push(AbortSignal.timeout(Math.ceil(remainingMs)));const task=this.answerStore(reply,root.id,AbortSignal.any(signals));this.storeCalls.set(reply.id,{controller,task});void task.finally(()=>this.storeCalls.delete(reply.id))}else if(reply.type==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(Object.values(this.renders).some(names=>names.includes(reply.plugin)))this.renderHost?.invalidate(reply.plugin)}else if(reply.type==="activity"){if(reply.phase!==root.phase||reply.revision<=root.revision||reply.operation!==void 0&&reply.operation!==root.native&&!root.models.has(reply.operation))return;root.revision=reply.revision;root.idle=reply.operation===root.native&&this.tool?.checks.size?void 0:reply.operation;root.refresh()}else if(reply.type==="log"){if(this.failure)return;try{this.log({text:reply.text,to:reply.to},reply.plugin)}catch(error){this.fail(error instanceof Error?error:new Error(String(error)));void this.worker.terminate()}}else this.pending?.(reply)});this.worker.on("error",error=>this.fail(error));this.worker.on("exit",code=>this.fail(new Error(`Mod worker exited (${code}).`)))}static{__name(this,"ModRuntime")}worker;storeCalls=new Map;storeReadSlots=new Semaphore(4);failure;pending;commands=[];tools=false;turns={start:false,complete:[]};prompts=[];renders={};early=new Set;noted=new Set;sequence=0;root;tool;cancelled=new Int32Array(new SharedArrayBuffer(4));static async create(source,cwd,log,signal,options={}){return _ModRuntime.createGroup([{id:"mod",name:"mod",source,options}],cwd,log,signal)}static async createGroup(plugins,cwd,log,signal,resolveTool,surface=null,version="unknown",facts,abortTurn,render,prompts=false,queuePrompt,completeModel,store){if(plugins.length>32||new Set(plugins.map(p=>p.id)).size!==plugins.length)throw new Error("Invalid Mod plugin group.");const startedAt=Date.now();const runtime=new _ModRuntime(log,facts??(()=>({id:"",cwd,root:cwd,model:"",turns:0,usage:{startedAt,context:{tokens:0,window:0},rateLimits:[]}})),plugins.some(plugin=>plugin.toolDialect==="claude")?resolveTool:void 0,surface,abortTurn,render,queuePrompt,completeModel,store);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[],prompts,submits:queuePrompt!==void 0,models:completeModel!==void 0,stores:store!==void 0},signal,6e4);const names=__name(value=>Array.isArray(value)&&value.every(name2=>plugins.some(plugin=>plugin.name===name2)),"names");const turnComplete=record(result)?result["turnComplete"]:void 0;const renders=record(result)?result["render"]:void 0;const promptSubmit=record(result)?result["promptSubmit"]:void 0;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(promptSubmit)||!names(turnComplete)||!record(renders)||Object.entries(renders).some(([site,plugins2])=>!(render?.sites??[]).includes(site)||!names(plugins2)))throw new Error("Invalid Mod declarations.");const commands=result["commands"];if(!Array.isArray(commands)||commands.length>64||commands.some(command=>!command||!plugins.some(plugin=>plugin.id===command.plugin)||typeof command.name!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(command.name)||typeof command.description!=="string"||command.argumentHint!==void 0&&typeof command.argumentHint!=="string"))throw new Error("Invalid Mod command declarations.");runtime.commands=commands;runtime.tools=result["tools"];runtime.turns={start:result["turnStart"],complete:turnComplete};runtime.prompts=promptSubmit;runtime.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(Object.values(runtime.renders).some(plugins2=>plugins2.includes(plugin)))render?.invalidate(plugin);return runtime}catch(error){await runtime.dispose();throw error}}getCommands(plugin="mod"){return this.commands.filter(command=>command.plugin===plugin).map(({plugin:_plugin,...command})=>command)}get hasToolHooks(){return this.tools}get turnHooks(){return this.turns}get promptHooks(){return this.prompts}renderHooksFor(site){return this.renders[site]??[]}async render(input,signal){const answer=await this.request({type:"render",input},signal);let settled=answer;if(input.component==="AssistantMessage")settled=record(answer)?answer["tree"]:void 0;const hooks=this.renderHooksFor(input.component);const owner=hooks.length===1?hooks[0]:"hooks";const notes=[];const note=__name((line,key=line)=>{if(this.noted.has(key))return;this.noted.add(key);notes.push(`${owner}: ${line}`)},"note");try{validateRenderTree(settled)}catch(error){note(`ui.render (${input.component}) refused: ${error instanceof Error?error.message:String(error)}; nothing was drawn`);return{tree:ENGINE_NODE,notes}}if(input.component==="AssistantMessage"){if(!record(settled)||settled["type"]!=="engine"||settled["ref"]!==0){note(`ui.render (${input.component}) answered a tree; this host draws only a rewrite of the row's props, so the row was left as it was`);return{tree:ENGINE_NODE,notes,props:input.props}}const props=record(answer)?answer["props"]:void 0;const text=record(props)?props["text"]:void 0;if(!record(props)||typeof text!=="string"||text!==input.props.text&&invalidRenderText(text)!==void 0||props["isFirstOfReply"]!==input.props.isFirstOfReply)return{tree:ENGINE_NODE,notes,props:input.props};return{tree:ENGINE_NODE,notes,props:{...input.props,text}}}const adjusted=adjustRenderTree(settled,input.component);for(const{key,text}of adjusted.notes)note(text,`${input.component}\0${key}`);return{tree:adjusted.tree,notes}}async builtinTool(name2){if(!this.resolveTool)return void 0;let builtin=false;switch(name2){case ToolNames.SHELL:builtin=await this.resolveTool(name2)instanceof(await import("./shell-YROF2KXZ.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-FNXBINJ3.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-2XXEHBZR.js")).WriteFileTool;break;default:return void 0}return builtin?name2:void 0}async runTool(input,next,signal){if(this.tool||this.pending)throw new Error("A Mod dispatch is already running.");const owner={next,controller:new AbortController,operations:new Map,checks:new Map,tail:Promise.resolve()};this.tool=owner;try{const builtinTool=await this.builtinTool(input.tool);const result=await this.request({type:"tool",input,builtinTool},AbortSignal.any([signal,owner.controller.signal]));validateResult("tool.call",result);return result}finally{owner.controller.abort();await Promise.allSettled([...owner.operations.values()].map(operation=>operation.task));this.tool=void 0}}executeHost(reply){const owner=this.tool;const root=this.root;if(!owner||!root||owner.operations.size>=32||owner.operations.has(reply.id)){this.fail(new Error("Invalid Mod host operation."));return}const controller=new AbortController;const signal=AbortSignal.any([owner.controller.signal,controller.signal]);const task=owner.tail.then(async()=>{signal.throwIfAborted();root.native=reply.id;root.phase++;root.idle=void 0;root.refresh();this.post({type:"native",id:reply.id},root.id);const result=await owner.next(reply.input,signal,async(input,verdict,checkSignal)=>{const active=AbortSignal.any([signal,checkSignal]);active.throwIfAborted();const id=++this.sequence;let abort=__name(()=>{},"abort");try{return await new Promise((resolve,reject)=>{abort=__name(()=>reject(new Error("Mod permission check cancelled.")),"abort");owner.checks.set(id,response=>{if(response.error!==void 0)reject(new Error(response.error));else{try{validateResult("tool.check",response.result);resolve({...response.result,ceiling:input.ceiling})}catch(error){reject(error)}}});root.idle=void 0;root.phase++;root.refresh();active.addEventListener("abort",abort,{once:true});this.post({type:"tool-check",id,operation:reply.id,input,verdict},root.id)})}finally{active.removeEventListener("abort",abort);owner.checks.delete(id);root.refresh()}});root.native=void 0;root.phase++;root.idle=void 0;root.refresh();signal.throwIfAborted();this.post({type:"host-result",id:reply.id,result},root.id)}).catch(error=>{root.native=void 0;root.phase++;root.idle=void 0;root.refresh();if(!this.failure)this.post({type:"host-result",id:reply.id,error:String(error).slice(0,4e3)},root.id)}).finally(()=>{owner.operations.delete(reply.id)});owner.operations.set(reply.id,{controller,task});owner.tail=task}post(request,root){if(this.root?.id!==root)return;const json=JSON.stringify(request);if(Buffer.byteLength(json)>MOD_MAX_BYTES+8192)throw new Error("Mod host message is too large.");assertModDepth(json,"Mod host message");this.worker.postMessage({...request,root,phase:this.root.phase})}async runCommand(command,args,signal,presentation){if(!this.commands.some(item=>item.name===command))throw new Error("Unknown Mod command.");const result=await this.request({type:"command",command,args,...this.surface==="terminal"&&presentation?{presentation}:{}},signal);if(!result||typeof result!=="object"||Array.isArray(result)||Object.keys(result).some(key=>key!=="text")||"text"in result&&typeof result.text!=="string"){throw new Error("Invalid Mod command result.")}return"text"in result?result.text:""}async startTurn(input,signal){validateResult("turn.start",await this.request({type:"turn-start",input},signal))}async submitPrompt(input,signal){const result=await this.request({type:"prompt-submit",input},signal);if(record(result)&&(typeof result["drop"]==="string"?Object.keys(result).length===2&&typeof result["byHook"]==="boolean":typeof result["text"]==="string"&&Object.keys(result).every(key=>key==="text"||key==="context")&&(result["context"]===void 0||Array.isArray(result["context"])&&result["context"].every(item=>typeof item==="string"))))return result;throw new Error("Invalid Mod prompt.submit result.")}async completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}answerModel(reply,root){if(Atomics.load(this.cancelled,0)!==0||Atomics.load(reply.cancellation,0)!==0)return;const remainingMs=reply.deadline-performance.now();if(remainingMs<=0)return;const controller=new AbortController;const signal=Number.isFinite(remainingMs)?AbortSignal.any([controller.signal,AbortSignal.timeout(Math.ceil(remainingMs))]):controller.signal;root.models.set(reply.id,controller);const answer=__name(async()=>{try{if(!this.completeModel)throw new Error("this host runs no Mod model calls");const result=await this.completeModel(reply.input,signal);if(!validModelResult(result))throw new Error("the host answered with an invalid model result");return{type:"model-result",id:reply.id,result}}catch(caught){const error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3);return{type:"model-result",id:reply.id,error}}},"answer");void answer().then(request=>{root.models.delete(reply.id);if(this.root!==root)return;if(!signal.aborted){try{this.post(request,root.id)}catch(caught){this.post({type:"model-result",id:reply.id,error:caught instanceof Error?caught.message:String(caught)},root.id)}}root.refresh()})}answerTurnAbort(reply,root){let error;try{if(!this.abortTurn)throw new Error(`$.turn.abort: no turn is running (asked for ${reply.turnId})`);this.abortTurn(reply.turnId)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"turn-abort-result",id:reply.id,error},root)}answerPromptQueue(reply,root){let refused;try{refused=this.queuePrompt?this.queuePrompt(reply.prompt):"this host does not run prompts a Mod submits"}catch(caught){refused=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}this.post({type:"prompt-queue-result",id:reply.id,refused},root)}async answerStore(reply,root,signal){const{operation}=reply;let value;let error;try{signal.throwIfAborted();const store=this.store;if(!store)throw new Error("This host keeps no Mod store.");if(operation.method==="store.get"||operation.method==="store.keys"){value=await this.storeReadSlots.runExclusive(()=>{signal.throwIfAborted();return operation.method==="store.get"?store.get(operation.plugin,operation.key):store.keys(operation.plugin)})}else if(operation.method==="store.set")await store.set(operation.plugin,operation.key,operation.value,signal);else await store.delete(operation.plugin,operation.key,signal)}catch(caught){error=(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)}if(signal.aborted)return;try{this.post({type:"store-result",id:reply.id,value,error},root)}catch(caught){this.post({type:"store-result",id:reply.id,error:(caught instanceof Error?caught.message:String(caught)).slice(0,4e3)},root)}}async end(sessionId,reason,signal){await this.request({type:"end",sessionId,reason},signal,MOD_END_TIMEOUT_MS)}async dispose(){this.fail(new Error("Mod runtime is closed."));await this.worker.terminate();await Promise.allSettled([...[...this.tool?.operations.values()??[]].map(operation=>operation.task),...[...this.storeCalls.values()].map(({task})=>task)])}fail(error){this.failure??=error;this.tool?.controller.abort();this.root?.storeAbort.abort();this.pending?.({type:"error",message:this.failure.message})}async request(request,signal,timeoutMs=6e4){signal.throwIfAborted();if(this.failure)throw this.failure;if(this.pending)throw new Error("A Mod dispatch is already running.");const message={...request,facts:this.facts()};const json=JSON.stringify(message);if(Buffer.byteLength(json)>(request.type==="load"?32:1)*MOD_MAX_BYTES+8192)throw new Error("Mod request is too large.");assertModDepth(json,"Mod request");let timer;let cancelTimer;let aborted=false;const budget=new ModBudget(timeoutMs+250);const stop=__name(()=>{this.fail(new Error(aborted?"Mod dispatch cancelled.":"Mod dispatch timed out."));void this.worker.terminate()},"stop");const root={id:++this.sequence,revision:0,phase:0,models:new Map,storeAbort:new AbortController,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=root.idle!==void 0&&(request.type==="tool"&&root.idle===root.native&&!this.tool?.checks.size||root.models.has(root.idle))&&!budget.expired;if(lending!==budget.lending){if(lending)budget.pause();else budget.resume()}if(timer)clearTimeout(timer);if(!budget.lending)timer=setTimeout(stop,budget.remainingMs)},"refresh")};root.storeAbort.signal.addEventListener("abort",()=>this.storeReadSlots.cancel(),{once:true});this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.abort();for(const model of root.models.values())model.abort();root.storeAbort.abort();if(timer)clearTimeout(timer);cancelTimer=setTimeout(stop,250)},"onAbort");Atomics.store(this.cancelled,0,0);try{return await new Promise((resolve,reject)=>{this.pending=reply=>{if(this.failure)reject(this.failure);else if(aborted)reject(new Error("Mod dispatch cancelled."));else if(reply.type==="error")reject(new Error(reply.message));else if(reply.type==="result"){try{if(Buffer.byteLength(reply.json)>MOD_MAX_BYTES)throw new Error("Mod reply is too large.");resolve(JSON.parse(reply.json))}catch(error){reject(error)}}};signal.addEventListener("abort",onAbort,{once:true});root.refresh();this.worker.postMessage({...message,root:root.id,phase:root.phase})})}finally{this.root=void 0;root.storeAbort.abort();for(const model of root.models.values())model.abort();root.models.clear();if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};init_esbuild_shims();import{createHash,createHmac,randomUUID}from"node:crypto";import{closeSync,constants,openSync,readFileSync,statfsSync,statSync}from"node:fs";import*as fs2 from"node:fs/promises";import{hostname}from"node:os";import*as path3 from"node:path";import{setTimeout as delay}from"node:timers/promises";var MOD_STORE_MAX_BYTES=4*1024*1024;var MAX_KEY_LIST_BYTES=MOD_MAX_BYTES-64;var LOCK_WAIT_MS=8e3;var PROC_SUPER_MAGIC=40864;var BOOT_ID_PATH="/proc/sys/kernel/random/boot_id";var lockHost=hostname();var pidNamespace=readPidNamespaceId();var bootId=process.platform==="linux"?readLocalBootId():null;var startPrefix=pidNamespace===null?null:readStartPrefix();var lockScope=scopeForBoot(bootId);var machineScope=bootId!==null&&pidNamespace!==null&&hasKernelBootId(bootId)?readMachineScope():null;var fileLocks=new Map;function scopeForBoot(id){return createHash("sha256").update(JSON.stringify([lockHost,pidNamespace,id])).digest("hex").slice(0,16)}__name(scopeForBoot,"scopeForBoot");function hasKernelBootId(expected){try{const fd=openSync(BOOT_ID_PATH,constants.O_RDONLY|constants.O_NONBLOCK);try{return statfsSync(`/proc/self/fd/${fd}`).type===PROC_SUPER_MAGIC&&readFileSync(fd,"utf8").trim()===expected}finally{closeSync(fd)}}catch{return false}}__name(hasKernelBootId,"hasKernelBootId");function readMachineScope(){try{const id=readFileSync("/etc/machine-id","utf8").trim();if(!/^[a-f0-9]{32}$/i.test(id)||/^0+$/.test(id))return null;return createHmac("sha256","Qwen-Code/ModStore/lock-host").update(Buffer.from(id,"hex")).digest("hex").slice(0,32)}catch{return null}}__name(readMachineScope,"readMachineScope");function hasLocalProcPids(){if(pidNamespace===null)return false;try{const status=readFileSync("/proc/self/status","utf8");return/^NStgid:[ \t]+(\d+)[ \t]*$/m.exec(status)?.[1]===String(process.pid)}catch{return false}}__name(hasLocalProcPids,"hasLocalProcPids");function readStartPrefix(){try{return`${statSync("/proc/self/ns/time").ino}~`}catch{return null}}__name(readStartPrefix,"readStartPrefix");function processStart(pid){if(startPrefix===null)return"-";const token=readProcStartToken(pid);return token===null?"-":`${startPrefix}${Buffer.from(token).toString("base64url")}`}__name(processStart,"processStart");function deadOwner(owner){const identity=/^(?<scope>[a-f0-9]{16})\.(?<pid>[1-9]\d{0,9})\.(?<start>(?:\d+~)?[\w-]+)\.[a-f0-9-]{36}(?:(?<kernel>\.k)?\.(?<machine>[a-f0-9]{32})\.(?<boot>[a-f0-9-]+))?$/.exec(owner)?.groups;if(!identity)return false;const{scope,pid:rawPid,start:recordedStart,kernel,machine,boot}=identity;if(scope!==lockScope){return kernel!==void 0&&machineScope!==null&&machine===machineScope&&boot!==void 0&&boot!==bootId&&scope===scopeForBoot(boot)}if(process.platform==="linux"&&(pidNamespace===null||bootId===null))return false;const pid=Number(rawPid);if(pid>2147483647)return false;try{process.kill(pid,0)}catch(error){return isNodeError(error)&&error.code==="ESRCH"}if(!hasLocalProcPids())return false;if(isZombie(pid))return true;if(startPrefix===null||!recordedStart.startsWith(startPrefix))return false;const start=processStart(pid);return start!=="-"&&recordedStart!==start}__name(deadOwner,"deadOwner");async function removeLock(lock,owner){if(owner)await fs2.rm(path3.join(lock,owner),{recursive:true,force:true});try{await fs2.rmdir(lock)}catch(error){if(!isNodeError(error)||!["ENOENT","ENOTEMPTY","EEXIST"].includes(error.code??""))throw error}}__name(removeLock,"removeLock");async function acquireLock(lock,signal){signal?.throwIfAborted();const nonce=randomUUID();const staging=`${lock}.${nonce}`;const recovery=machineScope&&bootId?`.k.${machineScope}.${bootId}`:"";const start=hasLocalProcPids()?processStart(process.pid):"-";const owner=`${lockScope}.${process.pid}.${start}.${nonce}${recovery}`;await fs2.mkdir(staging,{mode:448});let acquired=false;try{await fs2.mkdir(path3.join(staging,owner));const deadline=performance.now()+LOCK_WAIT_MS;do{signal?.throwIfAborted();try{await fs2.rename(staging,lock);acquired=true;return path3.join(lock,owner)}catch(error){if(!isNodeError(error)||!["ENOTEMPTY","EEXIST","EPERM","EACCES"].includes(error.code??""))throw error;const owners=await fs2.lstat(lock).then(stat=>{if(!stat.isDirectory())throw error;return fs2.readdir(lock)}).catch(cause=>{if(isNodeError(cause)&&cause.code==="ENOENT")return[];throw cause});if(owners.length===0)await removeLock(lock);else if(owners.length===1&&deadOwner(owners[0]))await removeLock(lock,owners[0])}await delay(50,void 0,{signal})}while(performance.now()<deadline);throw new Error(`Mod store: timed out waiting for ${lock}.`)}finally{if(!acquired)await fs2.rm(staging,{recursive:true,force:true}).catch(()=>{})}}__name(acquireLock,"acquireLock");function acquireLocalLock(mutex,signal){if(!signal)return mutex.acquire();signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=__name(()=>reject(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});void mutex.acquire().then(release=>{signal.removeEventListener("abort",abort);if(signal.aborted)release();else resolve(release)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}__name(acquireLocalLock,"acquireLocalLock");var ModStore=class{constructor(dir){this.dir=dir}static{__name(this,"ModStore")}async get(plugin,key){return(await this.read(this.file(plugin))).get(key)}async keys(plugin){return[...(await this.read(this.file(plugin))).keys()]}async set(plugin,key,value,signal){await this.change(plugin,signal,entries=>{if(!entries.has(key)&&Buffer.byteLength(JSON.stringify([...entries.keys(),key]))>MAX_KEY_LIST_BYTES)throw new Error(`Mod store: the key list would be over ${MAX_KEY_LIST_BYTES} bytes of JSON.`);entries.set(key,value);return true})}async delete(plugin,key,signal){await this.change(plugin,signal,entries=>entries.delete(key))}file(plugin){const name2=plugin.toLowerCase();if(!/^[a-z0-9_.-]+$/.test(name2)||/^\.+$/.test(name2))throw new Error(`Mod store: no store for the plugin name "${plugin}".`);const stem=name2.length>128?`~${createHash("sha256").update(name2).digest("hex")}`:name2;return path3.join(this.dir,`${stem}.json`)}async read(file){let text;try{const handle=await openNoFollow(file,{nonBlocking:true}).catch(error=>{if(isNodeError(error)&&error.code==="ELOOP")return openNoFollow(file,{nonBlocking:true});throw error});try{if(!(await handle.stat()).isFile())throw new Error("The store is not a regular file.");text=await handle.readFile("utf8")}finally{await handle.close()}}catch(error){if(isNodeError(error)&&error.code==="ENOENT")return new Map;throw new Error(`Mod store: cannot read ${file}: ${error instanceof Error?error.message:String(error)}`)}let parsed;try{parsed=JSON.parse(text)}catch{parsed=void 0}const stored=parsed;if(!stored||stored.version!==1||!Array.isArray(stored.entries)||!stored.entries.every(entry=>Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="string"))throw new Error(`Mod store: ${file} is not a store this version reads; it is left unchanged.`);return new Map(stored.entries)}async change(plugin,signal,apply){const file=this.file(plugin);let mutex=fileLocks.get(file);if(!mutex)fileLocks.set(file,mutex=new Mutex);const release=await acquireLocalLock(mutex,signal);try{signal?.throwIfAborted();await fs2.mkdir(this.dir,{recursive:true,mode:448});const lock=`${file}.lock`;const owner=await acquireLock(lock,signal);try{signal?.throwIfAborted();const entries=await this.read(file);if(!apply(entries))return;const stored={version:1,entries:[...entries]};const text=JSON.stringify(stored);if(Buffer.byteLength(text)>MOD_STORE_MAX_BYTES)throw new Error(`Mod store: the store would be over ${MOD_STORE_MAX_BYTES} bytes of JSON.`);const temporary=path3.join(owner,"store.json");await fs2.writeFile(temporary,text,{flag:"wx",mode:384,flush:true});await renameWithRetry(temporary,file,3,50)}finally{await removeLock(lock,path3.basename(owner))}}finally{release()}}};init_esbuild_shims();init_esbuild_shims();function classifyApiError(error){const status=error.status;const message=error.message?.toLowerCase()??"";if(status===429||message.includes("rate limit")){return"rate_limit"}if(status===401||message.includes("unauthorized")){return"authentication_failed"}if(status===402||status===403||message.includes("billing")||message.includes("quota")){return"billing_error"}if(status===400||message.includes("invalid")){return"invalid_request"}if(status!==void 0&&status>=500){return"server_error"}if(message.includes("max_tokens")||message.includes("token limit")){return"max_output_tokens"}return"unknown"}__name(classifyApiError,"classifyApiError");var MOD_MODEL_DEFAULT_MAX_TOKENS=1024;var ALIASES=new Map([["haiku","fast"],["sonnet","inherit"],["opus","inherit"]]);var NO_USAGE={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};function resolveModModel(config,name2){const modelName=name2.trim();const wanted=ALIASES.get(modelName)??modelName;const target=wanted==="fast"?config.getFastModel?.({requirePinnedEndpoint:true})??"inherit":wanted;const context=buildModelIdContext(config);const[modelSelector,endpoint,extra]=target.split("\0");if(!modelSelector?.trim()||endpoint===""||extra!==void 0){throw new Error(`invalid model endpoint selector ${JSON.stringify(name2)}`)}const resolved=resolveModelId(modelSelector,context);if(!resolved)throw new Error(`model ${JSON.stringify(name2)} is not available`);const isSession=resolved.modelId===context.currentModel&&(!resolved.authType||resolved.authType===context.currentAuthType)&&(endpoint===void 0||endpoint===config.getContentGeneratorConfig()?.baseUrl);const configured=config.getAllConfiguredModels(resolved.authType?[resolved.authType]:void 0).some(model=>model.id===resolved.modelId&&(endpoint===void 0||model.baseUrl===endpoint)&&!model.voiceOnly&&!model.imageOnly&&!model.visionOnly);if(!isSession&&!configured)throw new Error(`model ${JSON.stringify(name2)} is not configured`);const selector=resolved.authType?`${resolved.authType}:${resolved.modelId}`:resolved.modelId;return{selector:endpoint===void 0?selector:`${selector}\0${endpoint}`,modelId:resolved.modelId,...resolved.authType&&{authType:resolved.authType}}}__name(resolveModModel,"resolveModModel");function tokenCount(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):0}__name(tokenCount,"tokenCount");function modModelUsage(metadata,authType){if(!metadata)return{...NO_USAGE};const prompt=tokenCount(metadata.promptTokenCount);const read=tokenCount(metadata.cachedContentTokenCount);const written=tokenCount(getGenAiUsageProvenance(metadata)?.cacheCreationInputTokens);return{input_tokens:Math.max(0,prompt-read-written),output_tokens:outputTokenCount({input:prompt,output:tokenCount(metadata.candidatesTokenCount),thoughts:tokenCount(metadata.thoughtsTokenCount),total:tokenCount(metadata.totalTokenCount)},authType),cache_read_input_tokens:read,cache_creation_input_tokens:written}}__name(modModelUsage,"modModelUsage");function apiErrorKind(error,status){const message=error instanceof Error?error.message:String(error);if(status===529||/overloaded/i.test(message))return"overloaded";if(status===404||/model[^.]*not (found|exist)/i.test(message))return"model_not_found";if(isQuotaExhaustedError(error)||isQwenQuotaExceededError(error))return"billing_error";const kind=classifyApiError({message,status});return kind==="loop_detected"?"unknown":kind}__name(apiErrorKind,"apiErrorKind");async function completeModModel(config,input,signal){if(signal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const model=resolveModModel(config,input.model);const maxTokens=input.maxTokens??MOD_MODEL_DEFAULT_MAX_TOKENS;if(input.maxTokens!==void 0&&hasExplicitOutputLimit(model.modelId)&&maxTokens>tokenLimit(model.modelId,"output"))throw new Error(`maxTokens ${maxTokens} is over ${model.modelId}'s output limit of ${tokenLimit(model.modelId,"output")}`);const abortSignal=input.timeoutMs===void 0?signal:AbortSignal.any([signal,AbortSignal.timeout(input.timeoutMs)]);let onAbort;try{const request=Promise.resolve().then(()=>config.getBaseLlmClient().generateText({contents:[{role:"user",parts:[{text:input.prompt}]}],model:model.selector,...typeof input.system==="string"&&input.system&&{systemInstruction:input.system},abortSignal,promptId:"side-query:mod-model-complete",config:{maxOutputTokens:Math.min(maxTokens,hasExplicitOutputLimit(model.modelId)?tokenLimit(model.modelId,"output"):maxTokens),thinkingConfig:{includeThoughts:input.effort!==void 0}},isolatedRequest:true}));const cancelled=new Promise((_,reject)=>{onAbort=__name(()=>reject(abortSignal.reason),"onAbort");abortSignal.addEventListener("abort",onAbort,{once:true})});const result=await Promise.race([request,cancelled]);const usage=modModelUsage(result.usage,model.authType??config.getContentGeneratorConfig()?.authType);if(!result.text)return{isAnswered:false,reason:"empty-reply",usage};const text=projectJsonStringToByteBudget(result.text,MOD_MAX_BYTES/2,"\n[... truncated for Mods ...]\n");return{isAnswered:true,text,usage}}catch(error){if(abortSignal.aborted)return{isAnswered:false,reason:"aborted",usage:{...NO_USAGE}};const providerError=error instanceof Error?error.cause??error:error;let cause=providerError;let status=getErrorStatus(cause);for(let depth=0;depth<4&&status===void 0&&cause instanceof Error&&cause.cause!==void 0;depth++){cause=cause.cause;status=getErrorStatus(cause)}const providerStatus=status??getErrorStatus(error);return{isAnswered:false,reason:"api-error",status:providerStatus??null,error:apiErrorKind(status===void 0?providerError:cause,providerStatus),usage:{...NO_USAGE}}}finally{if(onAbort)abortSignal.removeEventListener("abort",onAbort)}}__name(completeModModel,"completeModModel");init_esbuild_shims();var KEPT_ROWS=1e3;var rowId=__name(input=>`${input.component}\0${input.requestId}`,"rowId");var rowKey=__name(input=>stableJson({...input,viewport:void 0}),"rowKey");var ModRows=class{constructor(schedule,render){this.schedule=schedule;this.render=render}static{__name(this,"ModRows")}rows=new Map;queue=[];running=false;watch(input,listener){const id=rowId(input);const key=rowKey(input);let row=this.rows.get(id);if(row){this.rows.delete(id);row.input=input;row.key=key}else row={input,key,queued:false,listeners:new Set};this.rows.set(id,row);row.listeners.add(listener);if(this.due(row))this.enqueue(id,row);this.prune();return()=>{row.listeners.delete(listener);if(!this.running)this.prune()}}get(input){const row=this.rows.get(rowId(input));return row?.answer&&row.answerKey===rowKey(input)?row.answer:void 0}invalidate(component){for(const[id,row]of this.rows){if(row.input.component!==component)continue;row.stale=true;if(row.listeners.size)this.enqueue(id,row)}}clear(){const rows=[...this.rows.values()];this.rows.clear();this.queue.length=0;for(const row of rows)if(row.answer)for(const listener of row.listeners)listener()}enqueue(id,row){if(row.queued)return;row.queued=true;this.queue.push(id);this.pump()}pump(){if(this.running)return;let id;let row;while((id=this.queue.shift())!==void 0){const next=this.rows.get(id);if(!next)continue;next.queued=false;if(next.listeners.size&&this.due(next)){row=next;break}}this.prune();if(!row||id===void 0)return;const ready=row;const readyId=id;this.running=true;this.schedule(async()=>{try{if(this.rows.get(readyId)!==ready||!ready.listeners.size)return;const{input,key}=ready;ready.stale=false;let answer;try{answer=await this.render(input)}catch{answer=void 0}if(this.rows.get(readyId)===ready){const changed=ready.answer!==answer;ready.answer=answer;ready.answerKey=key;if(this.due(ready)&&ready.listeners.size)this.enqueue(readyId,ready);if(changed)for(const listener of ready.listeners)listener()}}finally{this.running=false;this.pump()}})}due(row){return row.stale===true||row.answerKey!==row.key}prune(){if(this.rows.size<=KEPT_ROWS)return;for(const[id,row]of this.rows){if(this.rows.size<=KEPT_ROWS)break;if(!row.listeners.size&&!row.queued)this.rows.delete(id)}}};var logger=createDebugLogger("MODS");var MOD_PROMPT_TURN_LIMIT=8;var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;var ROW_RENDER_TIMEOUT_MS=3e4;var ModSession=class _ModSession{constructor(config,output,optionScopes=[]){this.config=config;this.output=output;this.optionScopes=optionScopes;this.sessionId=config.getSessionId();uiTelemetryService.on("update",this.observe);this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close().then(()=>this.flushOutput())},{first:Boolean(this.terminal)})}static{__name(this,"ModSession")}mods=[];runtime;toolQueue=Promise.resolve();lifetime=new AbortController;endLifetime=new AbortController;initialization;closing;logsReady=false;pendingLogs=[];notes=[];activeCommand;commandSignal;toolSignal;sessionId;adoptedAt=Date.now();startedAt;recorder;context={tokens:0,window:0};turn;submitted=[];modTurns=0;stopped=false;taken=new WeakMap;observe=__name(update=>runOutsideAgentContext(()=>{if(this.config.getSessionId()!==this.sessionId)return;this.recorder=this.config.getChatRecordingService();this.context={tokens:uiTelemetryService.getLastPromptTokenCount(),window:this.config.getContentGeneratorConfig()?.contextWindowSize||0};const event=update?.event;if(!this.turn||event?.["event.name"]!==EVENT_API_RESPONSE)return;const response=event;if(response.subagent_name===void 0&&!isInternalPromptId(response.prompt_id)&&(this.turn.promptId===void 0||response.prompt_id===this.turn.promptId))this.turn.model=response.model}),"observe");toolGeneration=new AbortController;sites=[];band={state:"idle",again:false,startedAt:-Infinity,steadyUntil:0};rows=new ModRows(task=>{this.toolQueue=this.toolQueue.then(task).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))},input=>this.renderRow(input));unregisterCleanup;static create(config,settings,output){return settings.merged.experimental?.mods?new _ModSession(config,output,[settings.systemDefaults.settings.pluginConfigs,settings.user.settings.pluginConfigs,settings.system.settings.pluginConfigs]):void 0}get terminal(){return"surface"in this.output?this.output:void 0}allowed(){return this.config.isInteractive()===Boolean(this.terminal)&&!this.config.getExperimentalZedIntegration()&&this.config.isTrustedFolder()&&!this.config.getDisableAllHooks()&&!this.config.getBareMode()&&!this.config.isSafeMode()&&!this.config.getExecutionEnvironment()&&!this.config.getExecutionEnvironmentFactory()&&!this.config.getHookSystem()?.isManaged()&&!this.config.getSandbox()&&!this.config.isSessionAgentSession()}async initialize(signal){if(this.closing)throw new Error("Mod session is closed.");if(!this.allowed()){if(this.mods.length){await this.close();throw new Error("Mods are no longer permitted in this session.")}return}this.initialization??=this.load(AbortSignal.any([signal,this.lifetime.signal]));await this.initialization}async load(signal){const sites=this.sites=this.terminal?.sites?.()??[];try{const candidates=[];for(const extension of this.config.getExtensions().filter(item=>item.isActive&&item.format!=="agent-plugins-v1")){signal.throwIfAborted();try{const source=await loadModSource(extension.path);const marketplace=extension.installMetadata?.marketplaceConfig?.name;candidates.push({extension,name:extension.name,version:extension.version,marketplace,source,dependencies:source?.dependencies??[],toolDialect:source?resolveModToolDialect(this.optionScopes,extension.name,marketplace):void 0,unsupportedEvents:source?resolveModUnsupportedEvents(this.optionScopes,extension.name,marketplace):void 0,options:source?resolveModOptions(source.userConfig,this.optionScopes,extension.name,marketplace):{}})}catch(error){throw new Error(`Mod ${extension.name}: ${error instanceof Error?error.message:String(error)}`)}}const pending=candidates.filter(item=>item.source);const reachable=new Set;while(pending.length){signal.throwIfAborted();const plugin=pending.shift();if(reachable.has(plugin))continue;reachable.add(plugin);if(!plugin.source){try{plugin.dependencies=await loadModDependencies(plugin.extension.path)}catch(error){throw new Error(`Mod dependency ${plugin.name}: ${error instanceof Error?error.message:String(error)}`)}}for(const dependency2 of plugin.dependencies){pending.push(resolveModDependency(candidates,plugin,dependency2))}}const selected=candidates.filter(item=>reachable.has(item));orderModPlugins(selected);const mods=selected.filter(item=>item.source).map(plugin=>({...plugin,dependencies:plugin.dependencies.filter(dependency2=>resolveModDependency(selected,plugin,dependency2).source)}));const ordered=orderModPlugins(mods);if(ordered.length){this.runtime=await ModRuntime.createGroup(ordered.map(({extension,source,options,toolDialect,unsupportedEvents})=>({id:extension.id,name:extension.name,source:{root:source.root,entry:source.entry,source:source.source},options,toolDialect,unsupportedEvents})),this.config.getTargetDir(),(entry,plugin)=>{if(this.commandSignal?.aborted||this.toolSignal?.aborted)return;this.pendingLogs.push({...entry,plugin,sessionId:this.sessionId});if(this.logsReady)this.flushLogs()},signal,name2=>this.config.getToolRegistry().ensureTool(name2),this.terminal?.surface??null,this.config.getCliVersion()||"unknown",()=>this.facts(),turnId=>this.abortTurn(turnId),sites.length?{sites,invalidate:__name(plugin=>this.invalidateRenders(plugin),"invalidate")}:void 0,this.terminal?this.terminal.prompts?.()===true:true,this.terminal&&this.terminal.runsPrompts?.()!==true?void 0:prompt=>this.queuePrompt(prompt),(input,modelSignal)=>completeModModel(this.config,input,this.sessionId===this.config.getSessionId()?modelSignal:AbortSignal.abort()),new ModStore(path4.join(Storage.getGlobalQwenDir(),"mods","store")));this.mods.push(...ordered.map(({extension})=>({id:extension.id,name:extension.name})));this.requestRender()}}catch(error){await this.runtime?.dispose();this.mods.length=0;throw error}}async loadCommands(signal){await this.initialize(signal);return this.mods.flatMap(mod=>this.runtime.getCommands(mod.id).map(command=>({name:command.name,description:this.terminal?sanitizeTerminalLine(command.description):command.description,kind:"file",source:"plugin-command",extensionName:this.terminal?sanitizeTerminalLine(mod.name):mod.name,supportedModes:[this.terminal?"interactive":"non_interactive"],argumentHint:this.terminal&&command.argumentHint!==void 0?sanitizeTerminalLine(command.argumentHint):command.argumentHint,modelInvocable:false,action:__name(async(context,args)=>{const active=AbortSignal.any([context.abortSignal??(this.terminal?this.lifetime.signal:signal),this.lifetime.signal]);const task=this.toolQueue.then(async()=>{active.throwIfAborted();if(!this.allowed()||!this.active()||this.closing){await this.runtime.dispose();throw new Error(`Mod ${mod.name} is disabled or its middleware chain changed.`)}if(this.sessionId!==this.config.getSessionId())throw new Error("The Mod command belongs to a previous session.");const controller=new AbortController;this.activeCommand=controller;const commandSignal=AbortSignal.any([active,controller.signal]);this.commandSignal=commandSignal;try{const content=await this.runtime.runCommand(command.name,args,commandSignal,this.terminal?.presentation());commandSignal.throwIfAborted();return{type:"message",messageType:"info",content:this.terminal?sanitizeTerminalText(stripUnsafeCharacters(content)):content}}finally{this.flushLogs();this.activeCommand=void 0;this.commandSignal=void 0}});this.toolQueue=task.catch(()=>{});return task},"action")})))}invalidateTools(){this.toolGeneration.abort();this.pendingLogs.length=0;this.activeCommand?.abort()}async restoreTools(){await this.toolQueue;if(!this.closing&&this.sessionId===this.config.getSessionId()){this.toolGeneration=new AbortController;this.requestRender();this.refreshRows()}}captureToolSignal(){return this.toolGeneration.signal}async syncSession(reason){const current=this.config.getSessionId();if(current===this.sessionId){if(this.toolGeneration.signal.aborted){this.toolGeneration=new AbortController;this.refreshRows()}return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;this.rows.clear();this.submitted.length=0;this.modTurns=0;this.stopped=false;this.adoptedAt=Date.now();this.startedAt=void 0;this.recorder=void 0;this.context={tokens:0,window:0};this.capture();this.toolGeneration=new AbortController;this.requestRender()});this.toolQueue=task.catch(()=>{});await task}get hasToolHooks(){return this.runtime?.hasToolHooks===true}setRenderInput(input){const band=this.band;const key=[input.viewport?.columns,input.viewport?.isFullscreen,stableJson(input.props)].join("\0");band.input=input;if(key===band.key)return;const size=`${input.viewport?.columns}\0${input.props.maxRows}`;const resized=band.size!==void 0&&size!==band.size;band.key=key;band.size=size;if(resized){clearTimeout(band.settle);band.settle=setTimeout(()=>{band.settle=void 0;this.requestRender()},RENDER_SETTLE_MS)}else this.requestRender()}requestRender(){const band=this.band;if(this.closing||!band.input||!this.sites.includes(band.input.component)||band.settle||band.wait||!this.runtime?.renderHooksFor("AbovePrompt").length||band.state==="waiting")return;if(band.state==="running"){band.again=true;return}const now=Date.now();const gap=(now<band.steadyUntil?RENDER_STEADY_MS:RENDER_LIVE_MS)-(now-band.startedAt);if(gap>0){band.wait=setTimeout(()=>{band.wait=void 0;this.requestRender()},gap);return}band.state="waiting";this.toolQueue=this.toolQueue.then(()=>this.render()).catch(error=>logger.debug(`Mod ui.render: ${String(error)}`))}async render(){const band=this.band;const runtime=this.runtime;const hooks=runtime.renderHooksFor("AbovePrompt");const owner=hooks.length===1?hooks[0]:"hooks";band.state="running";band.startedAt=Date.now();const signal=AbortSignal.any([this.lifetime.signal,this.toolGeneration.signal]);const isCurrent=__name(()=>!signal.aborted&&this.sessionId===this.config.getSessionId(),"isCurrent");try{if(this.closing||this.sessionId!==this.config.getSessionId())return;if(!this.allowed()||!this.active()){this.terminal?.draw?.(ENGINE_NODE,owner);return}const{tree,notes}=await runtime.render(band.input,signal);for(const note of notes)logger.debug(note);if(isCurrent())this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(isCurrent())this.terminal?.draw?.(ENGINE_NODE,owner)}finally{if(Date.now()-band.startedAt>RENDER_LIVE_MS)band.steadyUntil=Date.now()+RENDER_SLOW_MS;band.state="idle";if(band.again){band.again=false;this.requestRender()}this.flushLogs()}}watchRow(sessionId,input,listener){if(this.closing||sessionId!==this.sessionId||!this.sites.includes(input.component)||!this.runtime?.renderHooksFor(input.component).length||Buffer.byteLength(JSON.stringify(input))>MOD_MAX_BYTES/2)return void 0;return this.rows.watch(input,listener)}rowProps(sessionId,input){return sessionId===this.sessionId?this.rows.get(input):void 0}refreshRows(){for(const site of this.sites)if(site!=="AbovePrompt")this.rows.invalidate(site)}invalidateRenders(plugin){const runtime=this.runtime;if(!runtime)return;for(const site of this.sites){if(!runtime.renderHooksFor(site).includes(plugin))continue;if(site==="AbovePrompt")this.requestRender();else this.rows.invalidate(site)}}async renderRow(input){const runtime=this.runtime;const generation=this.toolGeneration.signal;if(!runtime||this.closing||generation.aborted||this.sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return void 0;const signal=AbortSignal.any([this.lifetime.signal,generation,AbortSignal.timeout(ROW_RENDER_TIMEOUT_MS)]);try{const{props,notes}=await runtime.render(input,signal);signal.throwIfAborted();for(const note of notes)logger.debug(note);return!props||stableJson(props)===stableJson(input.props)?void 0:props}finally{this.flushLogs()}}toolCall(onRepeat){if(!this.hasToolHooks)return void 0;return(input,next,signal)=>{const generation=this.toolGeneration;const sessionId=this.sessionId;const active=AbortSignal.any([signal,this.lifetime.signal,generation.signal]);const assertAllowed=__name(()=>{active.throwIfAborted();if(generation!==this.toolGeneration||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active()||this.closing)throw new Error("Mod tool middleware is disabled or its chain changed.")},"assertAllowed");const task=this.toolQueue.then(async()=>{assertAllowed();let attempts=0;this.toolSignal=active;try{return await this.runtime.runTool(input,async(changed,hostSignal,check)=>{assertAllowed();if(attempts++)onRepeat();active.throwIfAborted();return next(changed,hostSignal,async(question,verdict,checkSignal)=>{assertAllowed();const result=await check(question,verdict,checkSignal);assertAllowed();checkSignal.throwIfAborted();return result})},active)}finally{if(this.toolSignal===active)this.toolSignal=void 0}});this.toolQueue=task.catch(()=>{});return task}}queuePrompt(prompt){if(this.closing||this.sessionId!==this.config.getSessionId())return"the session is ending";const refused=this.stopped?"the person stopped a turn and has not sent a prompt since":this.modTurns+this.submitted.length>=MOD_PROMPT_TURN_LIMIT?`the Mods have started ${MOD_PROMPT_TURN_LIMIT} turns since the last prompt from the person`:void 0;if(refused){this.pendingLogs.push({text:`$.prompt.submit refused: ${refused}`,to:"transcript",plugin:prompt.plugin,sessionId:this.sessionId});this.flushLogs();return refused}this.submitted.push({...prompt,sessionId:this.sessionId});this.terminal?.promptQueued?.();return void 0}takeSubmittedPrompt(){const sessionId=this.config.getSessionId();let next=this.submitted.shift();while(next&&next.sessionId!==sessionId)next=this.submitted.shift();if(!next||this.closing)return void 0;this.modTurns++;const{sessionId:queuedFor,...prompt}=next;this.taken.set(prompt,queuedFor);return prompt}returnSubmittedPrompt(prompt){const sessionId=this.taken.get(prompt);this.taken.delete(prompt);if(sessionId===void 0||this.closing||this.stopped||sessionId!==this.config.getSessionId())return;this.modTurns=Math.max(0,this.modTurns-1);this.submitted.unshift({...prompt,sessionId})}get hasSubmittedPrompts(){const sessionId=this.config.getSessionId();return!this.closing&&this.submitted.some(prompt=>prompt.sessionId===sessionId)}notePersonPrompt(){this.modTurns=0;this.stopped=false}discardSubmittedPrompts(){this.submitted.length=0}stopSubmittedPrompts(){this.discardSubmittedPrompts();this.stopped=true}get hearsPrompts(){return!this.closing&&(this.runtime?.promptHooks.length??0)>0}async submitPrompt(text,signal){const plugins=this.runtime?.promptHooks??[];if(!plugins.length||this.closing)return{text};const input={text,wait:false,origin:{kind:this.terminal?"composer":"sdk"}};if(fitTurnText(text).truncated){this.pendingLogs.push({text:"prompt.submit hook skipped: the prompt is too long for a Mod payload",to:"transcript",plugin:plugins.join("+"),sessionId:this.sessionId});this.flushLogs();return{text}}const sessionId=this.sessionId;const task=this.toolQueue.then(async()=>{signal.throwIfAborted();if(this.closing||sessionId!==this.config.getSessionId()||!this.allowed()||!this.active())return{text};try{return await this.runtime.submitPrompt(input,AbortSignal.any([signal,this.lifetime.signal]))}catch(error){signal.throwIfAborted();logger.debug(`Mod prompt.submit: ${String(error)}`);return{text}}finally{this.flushLogs()}});this.toolQueue=task.catch(()=>{});const result=await task;if(!("drop"in result)){if(!result.text.trim()&&text.trim())return{drop:"Prompt dropped by a hook: it left the prompt empty"};return result}if(!result.byHook)return{drop:`Prompt not submitted: ${result.drop}`};const reason=(this.terminal?sanitizeTerminalLine:stripAnsiAndControl)(result.drop.replace(/\r?\n/g," ").trim());if(cpLen(reason)>4096)logger.debug(`${plugins.join("+")}: prompt.submit hook: a drop of ${cpLen(reason)} characters, kept up to its first 4096`);return{drop:`Prompt dropped by a hook: ${cpLen(reason)>4096?`${cpSlice(reason,0,4096)}\u2026`:reason}`}}startTurn(text,signal,abort,promptId){const hooks=this.runtime?.turnHooks;if(!hooks||!hooks.start&&!hooks.complete.length||this.closing)return void 0;const turn={id:randomUUID2(),sessionId:this.sessionId,startedAt:Date.now(),abort,aborting:false,streaming:"",answer:"",failed:false,...promptId!==void 0&&{promptId}};this.turn=turn;if(hooks.start){const fitted=fitTurnText(text);const input={text:fitted.text,turnId:turn.id,...fitted.truncated&&{isTextTruncated:true}};void this.queueTurnEvent(turn,lifetime=>this.runtime.startTurn(input,AbortSignal.any([lifetime,signal])))}let ending;return{id:turn.id,saw:__name(event=>this.see(turn,event),"saw"),complete:__name(reason=>ending??=this.completeTurn(turn,reason),"complete")}}see(turn,event){if(turn.ended||!this.runtime?.turnHooks.complete.length)return;switch(event.type){case"content":turn.streaming+=event.value;break;case"finished":turn.answer=turn.streaming;turn.streaming="";turn.usage=addTurnUsage(turn.usage,event.value.usageMetadata,this.config.getContentGeneratorConfig()?.authType);break;case"retry":if(!event.isContinuation)turn.streaming="";else if(!turn.streaming)turn.streaming=turn.answer;break;case"model_fallback":turn.streaming="";break;case"error":case"loop_detected":case"max_session_turns":case"session_token_limit_exceeded":turn.failed=true;break;default:break}}completeTurn(turn,ending){if(turn.ended)return turn.ended;if(this.turn===turn)this.turn=void 0;const plugins=this.runtime?.turnHooks.complete??[];if(!plugins.length)return Promise.resolve();const reason=turn.aborting||ending==="aborted"?"aborted":ending==="error"||turn.failed?"error":"answer";const answer=fitTurnText((turn.streaming||turn.answer).trim());const input={answer:answer.text,durationMs:Date.now()-turn.startedAt,isAborted:reason==="aborted",turnId:turn.id,reason,...turn.usage?{usage:{...turn.usage,model:turn.model??runOutsideAgentContext(()=>this.config.getModel())}}:{},...answer.truncated&&{isAnswerTruncated:true}};const run=__name(async signal=>{const text=await this.runtime.completeTurn(input,signal);if(text===input.answer||!text.trim())return;const note={text:cpLen(text)>4096?`${cpSlice(text,0,4096)}\u2026`:text,to:"transcript",plugin:plugins.join("+"),sessionId:turn.sessionId,isTurnNote:true};if(!this.terminal&&this.config.getOutputFormat()==="text")this.notes.push(`[Mod ${note.plugin}] ${stripAnsiAndControl(note.text)}`);else this.pendingLogs.push(note)},"run");return turn.ended=this.queueTurnEvent(turn,run,true)}queueTurnEvent(turn,run,isEnd=false){const task=this.toolQueue.then(async()=>{if(this.closing&&!isEnd||turn.sessionId!==this.sessionId||!this.allowed()||!this.active())return;try{await run(isEnd?this.endLifetime.signal:this.lifetime.signal)}finally{this.flushLogs()}}).catch(error=>logger.debug(`Mod turn event: ${String(error)}`));this.toolQueue=task;return task}abortTurn(turnId){const turn=this.turn;if(!turn)throw new Error(`$.turn.abort: no turn is running (asked for ${turnId})`);if(turn.id!==turnId)throw new Error(`$.turn.abort: ${turnId} is not the running turn (${turn.id}); a hook ends the turn turn.start told it about`);if(turn.aborting)throw new Error(`$.turn.abort: ${turnId} is already ending`);turn.aborting=true;let cancelled=false;try{cancelled=turn.abort()}finally{turn.aborting=cancelled}if(!cancelled)throw new Error(`$.turn.abort: ${turnId} is already ending`);logger.debug(`$.turn.abort: cancelled turn ${turnId}`)}flushLogs(){this.logsReady=true;for(const entry of this.pendingLogs.splice(0)){logger.debug(`[${entry.plugin}] ${entry.text}`);if(entry.to==="debug")continue;const text=this.terminal?sanitizeTerminalText(stripUnsafeCharacters(entry.text)):stripAnsiAndControl(entry.text);if("surface"in this.output){const{isTurnNote,...log}=entry;this.output.log({...log,text:isTurnNote?text:cpSlice(text,0,2e3)},entry.plugin,entry.sessionId)}else if(this.config.getOutputFormat()==="text"){process.stderr.write(`[Mod ${entry.plugin}] ${text}
4
4
  `)}else{this.output.emitSystemMessage("ui_log",{plugin:entry.plugin,text})}}}async flushOutput(){if(this.notes.length&&!this.terminal)await flushOutput(process.stdout,AbortSignal.timeout(1500));for(const note of this.notes.splice(0))process.stderr.write(`${note}
5
5
  `);await this.flushStreams()}async flushStreams(){if(this.terminal)return;const signal=AbortSignal.timeout(1500);await Promise.allSettled([flushOutput(process.stdout,signal),flushOutput(process.stderr,signal)])}capture(){this.observe();if(this.startedAt!==void 0)return this.startedAt;const resumed=this.config.getResumedSessionData()?.conversation;const first=resumed?.sessionId===this.sessionId?Date.parse(resumed.startTime):NaN;return this.startedAt=Number.isFinite(first)?first:this.adoptedAt}facts(){return runOutsideAgentContext(()=>this.readFacts())}readFacts(){const startedAt=this.capture();const{tokens,window}=this.context;return{id:this.sessionId,cwd:this.config.getTargetDir(),root:this.config.getProjectRoot(),model:this.config.getModel(),turns:this.recorder?.getUserTurnCount()??0,usage:{startedAt,context:{tokens,window,...window>0?{percent:Math.min(100,Math.round(tokens/window*100))}:{}},rateLimits:[]}}}active(){const extensions=this.config.getExtensions();return this.mods.every(mod=>extensions.some(extension=>extension.id===mod.id&&extension.isActive))}async end(reason){if(!this.allowed()||!this.active())return;try{await this.runtime?.end(this.sessionId,reason,AbortSignal.timeout(MOD_END_TIMEOUT_MS))}catch(error){logger.warn(`Mod session.end: ${String(error)}`)}}close(){this.closing??=(async()=>{this.unregisterCleanup();uiTelemetryService.off("update",this.observe);clearTimeout(this.band.settle);clearTimeout(this.band.wait);if(this.turn)void this.completeTurn(this.turn,"aborted");const endBudget=setTimeout(()=>this.endLifetime.abort(),MOD_END_TIMEOUT_MS);this.lifetime.abort();this.invalidateTools();await this.initialization?.catch(()=>{});try{await this.toolQueue;clearTimeout(endBudget);await this.end("other")}finally{clearTimeout(endBudget);this.endLifetime.abort();this.lifetime.abort();await this.runtime?.dispose();await this.flushStreams()}})();return this.closing}};function addTurnUsage(usage,metadata,authType){if(!metadata)return usage;const added=modModelUsage(metadata,authType);return{input_tokens:(usage?.input_tokens??0)+added.input_tokens,output_tokens:(usage?.output_tokens??0)+added.output_tokens,cache_read_input_tokens:(usage?.cache_read_input_tokens??0)+added.cache_read_input_tokens,cache_creation_input_tokens:(usage?.cache_creation_input_tokens??0)+added.cache_creation_input_tokens}}__name(addTurnUsage,"addTurnUsage");function fitTurnText(text){const fitted=projectJsonStringToByteBudget(text,MOD_MAX_BYTES/2,"\n[... truncated for Mods ...]\n");return{text:fitted,truncated:fitted!==text}}__name(fitTurnText,"fitTurnText");var sessions=new WeakMap;var MODS_FAILED_TO_INITIALIZE="Mods failed to initialize. Fix the Mod configuration and restart. /help and /quit remain available.";function isModRecoveryCommand(command){return command?.kind==="built-in"&&(command.name==="help"||command.name==="quit")}__name(isModRecoveryCommand,"isModRecoveryCommand");function createInteractiveModSession(config,settings){if(!settings.merged.experimental?.mods||!config.isInteractive())return;let session=sessions.get(config);if(!session){session=new InteractiveModSession(config,settings);sessions.set(config,session)}return session}__name(createInteractiveModSession,"createInteractiveModSession");function getInteractiveModSession(config){return config?sessions.get(config):void 0}__name(getInteractiveModSession,"getInteractiveModSession");var InteractiveModSession=class{constructor(config,settings){this.config=config;this.startup.catch(()=>{});this.session=ModSession.create(config,settings,{surface:"terminal",presentation:__name(()=>this.presentation,"presentation"),sites:__name(()=>this.sites,"sites"),prompts:__name(()=>this.prompts,"prompts"),runsPrompts:__name(()=>this.runsPrompts,"runsPrompts"),promptQueued:__name(()=>{for(const listener of this.promptListeners)listener()},"promptQueued"),draw:__name((tree,owner)=>{const band=tree.type==="engine"?void 0:{tree,owner,revision:++this.revision};if(!band&&!this.band)return;this.band=band;for(const listener of this.bandListeners)listener()},"draw"),log:__name((entry,plugin,sessionId)=>this.emit(`[Mod ${sanitizeTerminalLine(plugin)}] ${entry.text}`,sessionId),"log")});this.unregisterCleanup=registerCleanup(()=>{this.unregisterCleanup=()=>{};return this.close()})}static{__name(this,"InteractiveModSession")}session;lifetime=new AbortController;resolveStartup;rejectStartup;startup=new Promise((resolve,reject)=>{this.resolveStartup=resolve;this.rejectStartup=reject});initialization;started=false;startupFailed=false;closing;listener;logs=[];presentation={isFullscreen:false,columns:80};sites=[];prompts=false;runsPrompts=false;promptListeners=new Set;band;revision=0;bandListeners=new Set;unregisterCleanup;initialize(sites=[],{prompts=false,runsPrompts=false}={}){if(!this.initialization){this.sites=sites;this.prompts=prompts;this.runsPrompts=runsPrompts}this.initialization??=this.session.initialize(this.lifetime.signal).then(()=>{this.session.flushLogs();this.started=true;this.resolveStartup()},error=>{this.started=true;this.startupFailed=true;this.emit(`Mods failed to initialize: ${sanitizeTerminalLine(String(error)).slice(0,2e3)}`,this.config.getSessionId());this.rejectStartup(error);throw error});return this.initialization}get ready(){return this.startup}get starting(){return!this.closing&&!this.started}get failed(){return!this.closing&&this.startupFailed}failStartup(error){if(this.initialization)return;this.initialization=this.startup;this.started=true;this.rejectStartup(error)}async loadCommands(signal){await this.startup;signal.throwIfAborted();return this.session.loadCommands(this.lifetime.signal)}setPresentation(presentation){this.presentation={...presentation}}setRenderInput(input){if(!this.closing)this.session.setRenderInput(input)}watchRow(sessionId,input,listener){return this.closing||!this.started||this.startupFailed?void 0:this.session.watchRow(sessionId,input,listener)}rowProps(sessionId,input){return this.closing?void 0:this.session.rowProps(sessionId,input)}subscribeBand=__name(listener=>{this.bandListeners.add(listener);return()=>this.bandListeners.delete(listener)},"subscribeBand");getBand=__name(()=>this.band,"getBand");subscribe(listener){this.listener=listener;for(const entry of this.logs.splice(0))this.emit(entry.text,entry.sessionId);return()=>{if(this.listener===listener)this.listener=void 0}}emit(text,sessionId){if(this.closing||sessionId!==this.config.getSessionId())return;if(this.listener)this.listener(text);else{if(this.logs.length===100)this.logs.shift();this.logs.push({text,sessionId})}}captureToolSignal(){return AbortSignal.any([this.lifetime.signal,this.session.captureToolSignal()])}restoreTools(){return this.session.restoreTools()}invalidateTools(){this.session.invalidateTools()}toolCall(){return this.session.toolCall(()=>{})}syncSession(reason){return this.session.syncSession(reason)}get hearsPrompts(){return!this.closing&&this.session.hearsPrompts}submitPrompt(text,signal){return this.closing?Promise.resolve({text}):this.session.submitPrompt(text,signal)}subscribePrompts=__name(listener=>{this.promptListeners.add(listener);return()=>this.promptListeners.delete(listener)},"subscribePrompts");get hasSubmittedPrompts(){return!this.closing&&this.session.hasSubmittedPrompts}takeSubmittedPrompt(){return this.closing?void 0:this.session.takeSubmittedPrompt()}returnSubmittedPrompt(prompt){if(!this.closing)this.session.returnSubmittedPrompt(prompt)}notePersonPrompt(){this.session.notePersonPrompt()}stopSubmittedPrompts(){this.session.stopSubmittedPrompts()}startTurn(text,signal,abort,promptId){return this.closing?void 0:this.session.startTurn(text,signal,abort,promptId)}close(){this.closing??=(async()=>{this.unregisterCleanup();this.lifetime.abort();this.rejectStartup(new Error("Interactive Mod session is closed."));try{await this.session.close()}finally{this.listener=void 0;this.logs.length=0;this.band=void 0;for(const listener of this.bandListeners)listener();this.promptListeners.clear();if(sessions.get(this.config)===this)sessions.delete(this.config)}})();return this.closing}};export{classifyApiError,ModSession,MODS_FAILED_TO_INITIALIZE,isModRecoveryCommand,createInteractiveModSession,getInteractiveModSession,InteractiveModSession};
6
6
  /**
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{t}from"./chunk-HRRQHZQE.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-XUB4JKSR.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{DiscoveredMCPTool,uiTelemetryService}from"./chunk-R5AA46IX.js";import{getAllMemoryFilenames}from"./chunk-TQGZS3WN.js";import{DEFAULT_TOKEN_LIMIT}from"./chunk-AZ4Q2ZWQ.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,buildAvailableSkillsReminder,getStartupContextLength,isSkillListingReminder}from"./chunk-AAMQ5CMG.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{isSubpath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();import*as fs from"node:fs/promises";var EXTENSION_REF_PREFIX="ext:";var EXTENSION_CONTEXT_BUDGET=2e5;var EXTENSION_CONTEXT_FILE_CAP=5e4;function parseExtensionRef(pathName){if(!pathName.startsWith(EXTENSION_REF_PREFIX))return null;const name=pathName.slice(EXTENSION_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseExtensionRef,"parseExtensionRef");function buildExtensionRef(extensionName){return`${EXTENSION_REF_PREFIX}${extensionName}`}__name(buildExtensionRef,"buildExtensionRef");function matchExtensionByRef(name,extensions){const lower=name.toLowerCase();return extensions.find(ext=>ext.name.toLowerCase()===lower||ext.config.name.toLowerCase()===lower)}__name(matchExtensionByRef,"matchExtensionByRef");var BIDI_CONTROL_RE=/[‎‏؜⁦⁧⁨⁩‪‫‬‭‮]/g;function sanitizeDisplayText(raw){const stripped=stripTerminalControlSequences(raw).replace(BIDI_CONTROL_RE,"").replace(/\s+/g," ").trim();return stripped.length>0?stripped:null}__name(sanitizeDisplayText,"sanitizeDisplayText");function getSanitizedExtensionDisplayName(extension){return sanitizeDisplayText(extension.displayName||extension.name)||extension.name}__name(getSanitizedExtensionDisplayName,"getSanitizedExtensionDisplayName");function buildExtensionContextText(extension){const displayName=getSanitizedExtensionDisplayName(extension);const lines=[];lines.push(`--- Extension: ${displayName} (untrusted third-party content) ---`);if(extension.config.description){const desc=sanitizeDisplayText(extension.config.description);if(desc){lines.push(desc);lines.push("")}}const capabilities=[];if(extension.skills&&extension.skills.length>0){const skillNames=extension.skills.map(s=>sanitizeDisplayText(qualifySkillName(extension.name,s.name))||s.name).join(", ");capabilities.push(`- Skills: ${skillNames} (invoke via /<skill-name>)`)}if(extension.mcpServers&&Object.keys(extension.mcpServers).length>0){const serverNames=Object.keys(extension.mcpServers).map(n=>sanitizeDisplayText(n)||n).join(", ");capabilities.push(`- MCP Servers: ${serverNames}`)}if(extension.agents&&extension.agents.length>0){const agentNames=extension.agents.map(a=>sanitizeDisplayText(a.name)||a.name).join(", ");capabilities.push(`- Agents: ${agentNames}`)}if(capabilities.length>0){lines.push("Available capabilities from this extension:");lines.push(...capabilities);lines.push("")}lines.push(`--- End Extension: ${displayName} ---`);return lines.join("\n")}__name(buildExtensionContextText,"buildExtensionContextText");async function buildExtensionMentionContext(extension,options){let contextText=buildExtensionContextText(extension);let remainingBudget=options.remainingBudget;if(extension.contextFiles.length===0){return{text:contextText,remainingBudget}}const fileReads=await Promise.allSettled(extension.contextFiles.map(async contextFilePath=>{let realPath;let realExtPath;try{realPath=await fs.realpath(contextFilePath);realExtPath=await fs.realpath(extension.path)}catch{options.onDebugMessage?.(`Skipping unreadable context file: ${contextFilePath}`);return null}if(!isSubpath(realExtPath,realPath)){options.onDebugMessage?.(`Skipping context file outside extension directory: ${contextFilePath}`);return null}return fs.readFile(realPath,{encoding:"utf-8",signal:options.signal})}));for(let i=0;i<fileReads.length;i++){const outcome=fileReads[i];if(outcome.status==="rejected"){options.onDebugMessage?.(`Failed to read extension context file ${extension.contextFiles[i]}: ${getErrorMessage(outcome.reason)}`);continue}const content=outcome.value;if(!content||!content.trim())continue;if(remainingBudget<=0){options.onDebugMessage?.("Extension context budget exhausted, skipping remaining files.");break}const cap=Math.min(EXTENSION_CONTEXT_FILE_CAP,remainingBudget);const cappedContent=content.length>cap?content.slice(0,cap)+"\n... (truncated)":content;contextText+=`
3
+ import{t}from"./chunk-73TSS7KS.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-3NR3JBMA.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{DiscoveredMCPTool,uiTelemetryService}from"./chunk-R5AA46IX.js";import{getAllMemoryFilenames}from"./chunk-TQGZS3WN.js";import{DEFAULT_TOKEN_LIMIT}from"./chunk-AZ4Q2ZWQ.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,buildAvailableSkillsReminder,getStartupContextLength,isSkillListingReminder}from"./chunk-AAMQ5CMG.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{isSubpath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();import*as fs from"node:fs/promises";var EXTENSION_REF_PREFIX="ext:";var EXTENSION_CONTEXT_BUDGET=2e5;var EXTENSION_CONTEXT_FILE_CAP=5e4;function parseExtensionRef(pathName){if(!pathName.startsWith(EXTENSION_REF_PREFIX))return null;const name=pathName.slice(EXTENSION_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseExtensionRef,"parseExtensionRef");function buildExtensionRef(extensionName){return`${EXTENSION_REF_PREFIX}${extensionName}`}__name(buildExtensionRef,"buildExtensionRef");function matchExtensionByRef(name,extensions){const lower=name.toLowerCase();return extensions.find(ext=>ext.name.toLowerCase()===lower||ext.config.name.toLowerCase()===lower)}__name(matchExtensionByRef,"matchExtensionByRef");var BIDI_CONTROL_RE=/[‎‏؜⁦⁧⁨⁩‪‫‬‭‮]/g;function sanitizeDisplayText(raw){const stripped=stripTerminalControlSequences(raw).replace(BIDI_CONTROL_RE,"").replace(/\s+/g," ").trim();return stripped.length>0?stripped:null}__name(sanitizeDisplayText,"sanitizeDisplayText");function getSanitizedExtensionDisplayName(extension){return sanitizeDisplayText(extension.displayName||extension.name)||extension.name}__name(getSanitizedExtensionDisplayName,"getSanitizedExtensionDisplayName");function buildExtensionContextText(extension){const displayName=getSanitizedExtensionDisplayName(extension);const lines=[];lines.push(`--- Extension: ${displayName} (untrusted third-party content) ---`);if(extension.config.description){const desc=sanitizeDisplayText(extension.config.description);if(desc){lines.push(desc);lines.push("")}}const capabilities=[];if(extension.skills&&extension.skills.length>0){const skillNames=extension.skills.map(s=>sanitizeDisplayText(qualifySkillName(extension.name,s.name))||s.name).join(", ");capabilities.push(`- Skills: ${skillNames} (invoke via /<skill-name>)`)}if(extension.mcpServers&&Object.keys(extension.mcpServers).length>0){const serverNames=Object.keys(extension.mcpServers).map(n=>sanitizeDisplayText(n)||n).join(", ");capabilities.push(`- MCP Servers: ${serverNames}`)}if(extension.agents&&extension.agents.length>0){const agentNames=extension.agents.map(a=>sanitizeDisplayText(a.name)||a.name).join(", ");capabilities.push(`- Agents: ${agentNames}`)}if(capabilities.length>0){lines.push("Available capabilities from this extension:");lines.push(...capabilities);lines.push("")}lines.push(`--- End Extension: ${displayName} ---`);return lines.join("\n")}__name(buildExtensionContextText,"buildExtensionContextText");async function buildExtensionMentionContext(extension,options){let contextText=buildExtensionContextText(extension);let remainingBudget=options.remainingBudget;if(extension.contextFiles.length===0){return{text:contextText,remainingBudget}}const fileReads=await Promise.allSettled(extension.contextFiles.map(async contextFilePath=>{let realPath;let realExtPath;try{realPath=await fs.realpath(contextFilePath);realExtPath=await fs.realpath(extension.path)}catch{options.onDebugMessage?.(`Skipping unreadable context file: ${contextFilePath}`);return null}if(!isSubpath(realExtPath,realPath)){options.onDebugMessage?.(`Skipping context file outside extension directory: ${contextFilePath}`);return null}return fs.readFile(realPath,{encoding:"utf-8",signal:options.signal})}));for(let i=0;i<fileReads.length;i++){const outcome=fileReads[i];if(outcome.status==="rejected"){options.onDebugMessage?.(`Failed to read extension context file ${extension.contextFiles[i]}: ${getErrorMessage(outcome.reason)}`);continue}const content=outcome.value;if(!content||!content.trim())continue;if(remainingBudget<=0){options.onDebugMessage?.("Extension context budget exhausted, skipping remaining files.");break}const cap=Math.min(EXTENSION_CONTEXT_FILE_CAP,remainingBudget);const cappedContent=content.length>cap?content.slice(0,cap)+"\n... (truncated)":content;contextText+=`
4
4
 
5
5
  ${cappedContent}`;remainingBudget-=cappedContent.length}return{text:contextText,remainingBudget}}__name(buildExtensionMentionContext,"buildExtensionMentionContext");function currentTier(tokens,thresholds){if(tokens>=thresholds.hard)return"hard";if(tokens>=thresholds.auto)return"auto";if(tokens>=thresholds.warn)return"warn";return"safe"}__name(currentTier,"currentTier");function extensionContextFileOwners(config,workingDir){const owners=new Map;for(const extension of config.getActiveExtensions?.()??[]){const displayName=getSanitizedExtensionDisplayName(extension);for(const contextFile of extension.contextFiles??[]){const absolutePath=path.resolve(workingDir,contextFile);const fileLabel=formatContextFileDisplayPath(absolutePath,extension.path);owners.set(absolutePath,`${t("Extension")}: ${displayName} \xB7 ${fileLabel}`)}}return owners}__name(extensionContextFileOwners,"extensionContextFileOwners");function parseMemoryFiles(memoryContent,workingDir,extensionOwners=new Map,admissionRoot=workingDir){if(!memoryContent||memoryContent.trim().length===0)return[];const results=[];const root=path.resolve(admissionRoot);const globalDir=path.resolve(Storage.getGlobalQwenDir());const memoryFilenames=new Set(getAllMemoryFilenames());const openablePath=__name(absolutePath=>isSubpath(root,absolutePath)||path.resolve(path.dirname(absolutePath))===globalDir&&memoryFilenames.has(path.basename(absolutePath))?absolutePath:void 0,"openablePath");const regex=/--- Context from: (.+?) ---\n([\s\S]*?)--- End of Context from: \1 ---/g;let match;while((match=regex.exec(memoryContent))!==null){const filePath=match[1];const content=match[2];const absolutePath=path.resolve(workingDir,filePath);const owner=extensionOwners.get(absolutePath);const openPath=openablePath(absolutePath);results.push({path:owner??formatContextFileDisplayPath(absolutePath,workingDir),tokens:estimateContextTextTokens(content),...openPath!==void 0?{absolutePath:openPath}:{}})}if(results.length===0&&memoryContent.trim().length>0){results.push({path:t("memory"),tokens:estimateContextTextTokens(memoryContent)})}return results}__name(parseMemoryFiles,"parseMemoryFiles");function unescapeXml(text){return text.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&")}__name(unescapeXml,"unescapeXml");var SKILL_LISTING_ENTRY=/<skill>\n<name>\n([\s\S]*?)\n<\/name>[\s\S]*?<\/skill>/g;function measureSkillListing(text){const byName=new Map;for(const match of text.matchAll(SKILL_LISTING_ENTRY)){const name=unescapeXml(match[1]);byName.set(name.toLowerCase(),{name,tokens:estimateContextTextTokens(match[0])})}return{tokens:estimateContextTextTokens(text),byName}}__name(measureSkillListing,"measureSkillListing");function mergeSkillListing(into,from){into.tokens+=from.tokens;for(const[name,entry]of from.byName){into.byName.set(name,entry)}}__name(mergeSkillListing,"mergeSkillListing");function measureTailSkillListings(conversation){const listing={tokens:0,byName:new Map};const billedTexts=new Set;for(const content of conversation){for(const part of content.parts??[]){const text=part.text;if(typeof text!=="string"||!isSkillListingReminder(text))continue;const measured=measureSkillListing(text);if(measured.byName.size===0)continue;mergeSkillListing(listing,measured);billedTexts.add(text)}}return{listing,billedTexts}}__name(measureTailSkillListings,"measureTailSkillListings");function measureStartupPrelude(prelude){const skillListing={tokens:0,byName:new Map};let startupContextTokens=0;for(const content of prelude){for(const part of content.parts??[]){if(typeof part.text!=="string")continue;if(isSkillListingReminder(part.text)){mergeSkillListing(skillListing,measureSkillListing(part.text))}else{startupContextTokens+=estimateContextTextTokens(part.text)}}}return{skillListing,startupContextTokens}}__name(measureStartupPrelude,"measureStartupPrelude");function estimateFunctionResponseTokens(part,imageTokenEstimate){const response=part.functionResponse;let tokens=estimateContextTextTokens(JSON.stringify({id:response.id,name:response.name,response:response.response}));const nested=response.parts;if(Array.isArray(nested)){for(const inner of nested){if(inner.inlineData||inner.fileData){tokens+=imageTokenEstimate}else if(typeof inner.text==="string"){tokens+=estimateContextTextTokens(inner.text)}}}return tokens}__name(estimateFunctionResponseTokens,"estimateFunctionResponseTokens");function consumeBilledSkillBody(part,billedSkillBodies){if(billedSkillBodies.size===0)return false;const output=part.functionResponse?.response?.output;if(typeof output!=="string")return false;if(billedSkillBodies.delete(output))return true;for(const body of billedSkillBodies){if(output.startsWith(`${body}
6
6
  `)){billedSkillBodies.delete(body);return true}}return false}__name(consumeBilledSkillBody,"consumeBilledSkillBody");function estimateConversationTokens(conversation,billing){let tokens=0;const remainingSkillBodies=new Set(billing.billedSkillBodies);for(const content of conversation){for(const part of content.parts??[]){if(typeof part.text==="string"){if(billing.billedListingTexts.has(part.text))continue;tokens+=estimateContextTextTokens(part.text)}else if(part.inlineData||part.fileData){tokens+=billing.imageTokenEstimate}else if(part.functionCall){tokens+=estimateContextTextTokens(JSON.stringify(part.functionCall))}else if(part.functionResponse){if(part.functionResponse.name===ToolNames.SKILL&&consumeBilledSkillBody(part,remainingSkillBodies)){continue}tokens+=estimateFunctionResponseTokens(part,billing.imageTokenEstimate)}}}return tokens}__name(estimateConversationTokens,"estimateConversationTokens");async function collectContextData(config,showDetails){const modelName=config.getModel()||"unknown";const contentGeneratorConfig=config.getContentGeneratorConfig();const contextWindowSize=contentGeneratorConfig.contextWindowSize??DEFAULT_TOKEN_LIMIT;const llmClient=config.getLlmClient?.();const activeChat=llmClient?.isInitialized?.()?llmClient.getChat():void 0;const apiTotalTokens=activeChat?activeChat.getLastPromptTokenCount():uiTelemetryService.getLastPromptTokenCount();const apiCachedTokens=activeChat?.getLastCachedContentTokenCount?.()??uiTelemetryService.getLastCachedContentTokenCount();const history=activeChat?.getHistoryShallow?.()??activeChat?.getHistory?.()??[];const preludeLength=getStartupContextLength(history);const prelude=measureStartupPrelude(withoutAutoMemorySnapshots(history.slice(0,preludeLength)));const conversationHistory=withoutAutoMemorySnapshots(history.slice(preludeLength));const tailSkillListings=measureTailSkillListings(conversationHistory);let conversationTokens=0;const systemPromptText=getMainSessionBaseSystemPrompt(config);const systemPromptTokens=estimateContextTextTokens(systemPromptText);const toolRegistry=config.getToolRegistry();const allTools=toolRegistry?toolRegistry.getAllTools():[];const toolDeclarations=toolRegistry?toolRegistry.getFunctionDeclarations():[];const toolsJsonStr=JSON.stringify(toolDeclarations);const allToolsTokens=estimateContextTextTokens(toolsJsonStr);const builtinTools=[];const mcpTools=[];for(const declaration of toolDeclarations){const tool=allTools.find(tool2=>tool2.name===declaration.name);const toolJsonStr=JSON.stringify(declaration);const tokens=estimateContextTextTokens(toolJsonStr);if(tool instanceof DiscoveredMCPTool){mcpTools.push({name:`${tool.serverName}__${tool.serverToolName||tool.name}`,tokens})}else if(declaration.name!==ToolNames.SKILL){builtinTools.push({name:declaration.name,tokens})}}const memoryContent=config.getUserMemory();const instructionFiles=parseMemoryFiles(memoryContent,config.getWorkingDir(),extensionContextFileOwners(config,config.getWorkingDir()),config.storage.getProjectRoot());const memoryFiles=[];const instructionFilesTokens=instructionFiles.reduce((sum,f)=>sum+f.tokens,0);const catalog=config.getAutoMemoryContext?.()??"";const snapshots=catalog?history.flatMap(content=>(content.parts??[]).filter(part=>part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true)):[];const pendingSnapshot=getAutoMemorySnapshot(history,catalog);if(pendingSnapshot)snapshots.push(pendingSnapshot);const autoMemoryTokens=estimateContextTextTokens(config.getAutoMemoryPrompt())+snapshots.reduce((sum,part)=>sum+estimateContextTextTokens(part.text??""),0);if(autoMemoryTokens>0){memoryFiles.push({path:t("auto memory"),tokens:autoMemoryTokens})}const memoryFilesTokens=memoryFiles.reduce((sum,f)=>sum+f.tokens,0);const skillTool=allTools.find(tool=>tool.name===ToolNames.SKILL);const skillDeclaration=toolDeclarations.find(declaration=>declaration.name===ToolNames.SKILL);const skillToolDefinitionTokens=skillDeclaration?estimateContextTextTokens(JSON.stringify(skillDeclaration)):0;const loadedContentNames=skillTool&&"getLoadedSkillContentNames"in skillTool?skillTool.getLoadedSkillContentNames():new Map;const bodyTokensByName=new Map;for(const[content,name]of loadedContentNames){bodyTokensByName.set(name,(bodyTokensByName.get(name)??0)+estimateContextTextTokens(content))}const loadedBodiesTokens=[...bodyTokensByName.values()].reduce((sum,tokens)=>sum+tokens,0);const skillManager=config.getSkillManager();const skillConfigs=skillManager?await skillManager.listSkills():[];const enabledSkillNames=new Set(skillConfigs.filter(skill=>config.isSkillEnabled(skill)).map(skill=>skill.name.toLowerCase()));let skillListing=prelude.skillListing;if(!activeChat){const reminder=await buildAvailableSkillsReminder(config);if(reminder){skillListing=measureSkillListing(reminder.reminder)}}mergeSkillListing(skillListing,tailSkillListings.listing);const billedSkillBodies=new Set(loadedContentNames.keys());const skills=skillConfigs.map(skill=>{const listingTokens=skillListing.byName.get(skill.name.toLowerCase())?.tokens??0;const bodyTokens=bodyTokensByName.get(skill.name);const isLoaded=bodyTokens!==void 0;return{name:skill.name,tokens:listingTokens,loaded:isLoaded,bodyTokens}});const discoveredNames=new Set(skillConfigs.map(skill=>skill.name));for(const[name,bodyTokens]of bodyTokensByName){if(!discoveredNames.has(name)){skills.push({name,tokens:skillListing.byName.get(name.toLowerCase())?.tokens??0,loaded:true,bodyTokens})}}const rowedNames=new Set(skills.map(s=>s.name.toLowerCase()));for(const[key,entry]of skillListing.byName){enabledSkillNames.add(key);if(rowedNames.has(key))continue;rowedNames.add(key);skills.push({name:entry.name,tokens:entry.tokens,loaded:false})}conversationTokens=estimateConversationTokens(conversationHistory,{imageTokenEstimate:resolveSlimmingConfig(config.getChatCompression?.()).imageTokenEstimate,billedSkillBodies,billedListingTexts:tailSkillListings.billedTexts});const skillsTokens=skillToolDefinitionTokens+skillListing.tokens+loadedBodiesTokens;const startupContextTokens=prelude.startupContextTokens;const thresholds=computeThresholds(contextWindowSize,config.getAutoCompactThreshold());const autocompactBuffer=Math.max(0,Math.round(contextWindowSize-thresholds.auto));const rawOverhead=systemPromptTokens+allToolsTokens+instructionFilesTokens+memoryFilesTokens+skillListing.tokens+loadedBodiesTokens+startupContextTokens;const rawContent=rawOverhead+conversationTokens;const hasTokenCount=apiTotalTokens>0;const isEstimated=!hasTokenCount||activeChat?.isLastPromptTokenCountEstimated()===true;const mcpToolsTotalTokens=mcpTools.reduce((sum,tool)=>sum+tool.tokens,0);const totalTokens=hasTokenCount?apiTotalTokens:0;const clampDeficit=Math.max(0,skillToolDefinitionTokens+mcpToolsTotalTokens-allToolsTokens);const clampedMcpTools=Math.max(0,mcpToolsTotalTokens-clampDeficit);const clampedSkills=skillsTokens-Math.max(0,clampDeficit-mcpToolsTotalTokens);const clampedBuiltinTools=Math.max(0,allToolsTokens-skillToolDefinitionTokens-clampedMcpTools);const mcpDetailShare=mcpToolsTotalTokens>0?clampedMcpTools/mcpToolsTotalTokens:1;const detailMcpTools=mcpDetailShare<1?mcpTools.map(item=>({...item,tokens:Math.round(item.tokens*mcpDetailShare)})):mcpTools;const tierTokens=hasTokenCount?apiTotalTokens:rawContent;const freeSpace=Math.max(0,contextWindowSize-tierTokens-autocompactBuffer);const breakdown={systemPrompt:systemPromptTokens,builtinTools:clampedBuiltinTools,mcpTools:clampedMcpTools,instructionFiles:instructionFilesTokens,memoryFiles:memoryFilesTokens,skills:clampedSkills,startupContext:startupContextTokens,messages:conversationTokens,cachedTokens:hasTokenCount?apiCachedTokens:0,freeSpace,autocompactBuffer,thresholds,currentTier:currentTier(tierTokens,thresholds)};return{type:"context_usage",modelName,totalTokens,contextWindowSize,breakdown,builtinTools:showDetails?builtinTools:[],mcpTools:showDetails?detailMcpTools:[],instructionFiles:showDetails?instructionFiles:[],memoryFiles:showDetails?memoryFiles:[],skills:showDetails?skills.filter(skill=>skill.loaded||enabledSkillNames.has(skill.name.toLowerCase())):[],isEstimated,showDetails}}__name(collectContextData,"collectContextData");function fmtTokens(tokens){if(tokens>=999950){return`${(tokens/1e6).toFixed(1)}m`}if(tokens>=1e3){return`${(tokens/1e3).toFixed(1)}k`}return`${tokens}`}__name(fmtTokens,"fmtTokens");function fmtCategoryRow(label,tokens,contextWindowSize,indent=" "){const percentage=contextWindowSize>0?(tokens/contextWindowSize*100).toFixed(1):"0.0";const right=`${fmtTokens(tokens)} tokens (${percentage}%)`;const leftPart=`${indent}${label}`;const totalWidth=56;const dots=Math.max(1,totalWidth-leftPart.length-right.length);return`${leftPart}${" ".repeat(dots)}${right}`}__name(fmtCategoryRow,"fmtCategoryRow");function formatNum(n){return Math.round(n).toLocaleString("en-US")}__name(formatNum,"formatNum");function formatContextUsageText(data){const{modelName,totalTokens,contextWindowSize,breakdown,builtinTools,mcpTools,instructionFiles=[],memoryFiles,skills,isEstimated,showDetails}=data;const hasTokenCount=totalTokens>0;const memoryLabel=breakdown.instructionFiles===void 0?"Memory files":"Auto memory";const lines=[];lines.push("## Context Usage");lines.push("");if(!hasTokenCount){const includesConversation=breakdown.messages>0;lines.push(includesConversation?"*No provider usage yet. These are local estimates, including the conversation.*":"*No API response yet. Send a message to see actual usage.*");lines.push("");lines.push(includesConversation?"**Estimated usage, including the conversation**":"**Estimated pre-conversation overhead**");lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("")}else{lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("");if(isEstimated){lines.push("*Token usage is estimated until provider usage is received.*");lines.push("")}lines.push(fmtCategoryRow("Used",totalTokens,contextWindowSize));if((breakdown.cachedTokens??0)>0){lines.push(fmtCategoryRow("Cached prefix",breakdown.cachedTokens,contextWindowSize," \u2514 "))}lines.push(fmtCategoryRow("Free",breakdown.freeSpace,contextWindowSize));lines.push("");lines.push("**Compaction thresholds**");lines.push(` Effective window: ${formatNum(breakdown.thresholds.effectiveWindow)} (window \u2212 ${formatNum(contextWindowSize-breakdown.thresholds.effectiveWindow)} reserve)`);lines.push(` Warn threshold: ${formatNum(breakdown.thresholds.warn)}`);lines.push(` Auto threshold: ${formatNum(breakdown.thresholds.auto)}`);lines.push(` Hard threshold: ${formatNum(breakdown.thresholds.hard)}`);lines.push(` Current tier: ${breakdown.currentTier}`);lines.push("");lines.push("**Usage by category**")}lines.push(fmtCategoryRow("System prompt",breakdown.systemPrompt,contextWindowSize));lines.push(fmtCategoryRow("Built-in tools",breakdown.builtinTools,contextWindowSize));if(breakdown.mcpTools>0){lines.push(fmtCategoryRow("MCP tools",breakdown.mcpTools,contextWindowSize))}if(breakdown.instructionFiles!==void 0){lines.push(fmtCategoryRow("Instruction files",breakdown.instructionFiles,contextWindowSize))}lines.push(fmtCategoryRow(memoryLabel,breakdown.memoryFiles,contextWindowSize));lines.push(fmtCategoryRow("Skills",breakdown.skills,contextWindowSize));if((breakdown.startupContext??0)>0){lines.push(fmtCategoryRow("Startup context",breakdown.startupContext,contextWindowSize))}if(hasTokenCount||breakdown.messages>0){lines.push(fmtCategoryRow("Messages",breakdown.messages,contextWindowSize))}if(showDetails){const sortedBuiltin=[...builtinTools].sort((a,b)=>b.tokens-a.tokens);const sortedMcp=[...mcpTools].sort((a,b)=>b.tokens-a.tokens);const sortedMemory=[...memoryFiles].sort((a,b)=>b.tokens-a.tokens);const sortedSkills=[...skills].sort((a,b)=>{if(!a.loaded!==!b.loaded)return a.loaded?-1:1;return b.tokens+(b.bodyTokens??0)-(a.tokens+(a.bodyTokens??0))});if(sortedBuiltin.length>0){lines.push("");lines.push("**Built-in tools**");for(const tool of sortedBuiltin){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(sortedMcp.length>0){lines.push("");lines.push("**MCP tools**");for(const tool of sortedMcp){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(instructionFiles.length>0){lines.push("","**Instruction files**");for(const file of[...instructionFiles].sort((a,b)=>b.tokens-a.tokens)){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedMemory.length>0){lines.push("");lines.push("**"+memoryLabel+"**");for(const file of sortedMemory){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedSkills.length>0){lines.push("");lines.push("**Skills**");for(const skill of sortedSkills){lines.push(fmtCategoryRow(skill.name,skill.tokens,contextWindowSize," \u2514 "));if(skill.loaded&&skill.bodyTokens&&skill.bodyTokens>0){lines.push(fmtCategoryRow("body loaded",skill.bodyTokens,contextWindowSize," \u2514 "))}}}}else{lines.push("");lines.push("*Run /context detail for per-item breakdown.*")}return lines.join("\n")}__name(formatContextUsageText,"formatContextUsageText");var contextCommand={name:"context",get description(){return t('Show context window usage breakdown. Use "/context detail" for per-item breakdown.')},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,args)=>{const normalizedArgs=args?.trim().toLowerCase();const showDetails=normalizedArgs==="detail"||normalizedArgs==="-d";const executionMode=context.executionMode??"interactive";const{config}=context.services;if(!config){if(executionMode==="interactive"){context.ui.addItem({type:"error",text:t("Config not loaded.")},Date.now());return}return{type:"message",messageType:"error",content:t("Config not loaded.")}}const contextUsageItem=await collectContextData(config,showDetails);if(executionMode==="interactive"){context.ui.addItem(contextUsageItem,Date.now());return}return{type:"message",messageType:"info",content:formatContextUsageText(contextUsageItem)}},"action"),subCommands:[{name:"detail",get description(){return t("Show per-item context usage breakdown.")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async context=>{await contextCommand.action(context,"detail")},"action")}]};export{EXTENSION_CONTEXT_BUDGET,parseExtensionRef,buildExtensionRef,matchExtensionByRef,sanitizeDisplayText,getSanitizedExtensionDisplayName,buildExtensionMentionContext,collectContextData,formatContextUsageText,contextCommand};