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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/chunks/{MaxSizedBox-K6YUM3DX.js → MaxSizedBox-EGHZ2BPF.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-75IC33SN.js → StandaloneSessionPicker-UVCW6YW3.js} +1 -1
  3. package/chunks/{acp-subagent-executor-3NHBJRPL.js → acp-subagent-executor-AQ7AWSD4.js} +1 -1
  4. package/chunks/{acpAgent-JT6KQPTH.js → acpAgent-IV7JAGD7.js} +3 -3
  5. package/chunks/{advisor-TI2UVEZK.js → advisor-UZ4TF65D.js} +1 -1
  6. package/chunks/{agent-SWIZZZMY.js → agent-CNLVAWDD.js} +1 -1
  7. package/chunks/{agent-headless-USWEJ4GW.js → agent-headless-ZJUJLUJS.js} +1 -1
  8. package/chunks/{agent-host-client-ZFIMQX33.js → agent-host-client-SN5V2KBH.js} +1 -1
  9. package/chunks/{agent-host-connections-LOFD7O7Q.js → agent-host-connections-VKMAJIIU.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-HMLEI4FI.js → anthropicContentGenerator-QTJVPAMI.js} +1 -1
  11. package/chunks/{autofix-pr-NKR2VSLB.js → autofix-pr-U7GNSH27.js} +1 -1
  12. package/chunks/{batch-JQZ3TOHA.js → batch-MBEWETXN.js} +1 -1
  13. package/chunks/{bridge-EIWWT4P6.js → bridge-TEJLNYV3.js} +1 -1
  14. package/chunks/{channel-settings-store-FLRLUA67.js → channel-settings-store-QNCKWWBL.js} +1 -1
  15. package/chunks/{chunk-244YTFYD.js → chunk-23KDY7UW.js} +1 -1
  16. package/chunks/{chunk-7TDMQJTD.js → chunk-2DWWSMTV.js} +1 -1
  17. package/chunks/{chunk-UU2LTNSF.js → chunk-3IZMVLVZ.js} +1 -1
  18. package/chunks/{chunk-B6T4ESBM.js → chunk-3JI7IKJL.js} +1 -1
  19. package/chunks/{chunk-Y5TT2G3N.js → chunk-427MARCP.js} +1 -1
  20. package/chunks/{chunk-KX7JS2P7.js → chunk-4NNNGSQY.js} +3 -3
  21. package/chunks/{chunk-6TQS2WQO.js → chunk-4RM7KY3Z.js} +2 -2
  22. package/chunks/{chunk-YL3N2UGG.js → chunk-5X7S4AE6.js} +5 -5
  23. package/chunks/{chunk-K2HAY5PY.js → chunk-5XAECBED.js} +1 -1
  24. package/chunks/{chunk-VCHFBETO.js → chunk-66KKSLUO.js} +1 -1
  25. package/chunks/{chunk-BSJR2KEF.js → chunk-6CIIDUZW.js} +1 -1
  26. package/chunks/{chunk-22CLK7PK.js → chunk-7EBRMQYW.js} +1 -1
  27. package/chunks/{chunk-J4TFGZ4A.js → chunk-7FSC2NKA.js} +1 -1
  28. package/chunks/{chunk-6JFC5M6B.js → chunk-A5TAAMML.js} +1 -1
  29. package/chunks/{chunk-DHHACQVN.js → chunk-AOYSX44A.js} +1 -1
  30. package/chunks/{chunk-VFVZ2DY7.js → chunk-AZCMQ3DD.js} +2 -2
  31. package/chunks/{chunk-BQJXWIMR.js → chunk-B6F7CVBP.js} +1 -1
  32. package/chunks/{chunk-OVPEAKOQ.js → chunk-BDQOLT37.js} +1 -1
  33. package/chunks/{chunk-5SYUBQNO.js → chunk-BIWEUAKG.js} +1 -1
  34. package/chunks/{chunk-BZM66PQO.js → chunk-BJ5R7LOM.js} +1 -1
  35. package/chunks/{chunk-4R2OHBH3.js → chunk-BKUFRNME.js} +1 -1
  36. package/chunks/{chunk-NIYWNFVF.js → chunk-BNZSPX2I.js} +1 -1
  37. package/chunks/{chunk-FJV2ECNY.js → chunk-D2URRVOK.js} +1 -1
  38. package/chunks/{chunk-GT6CHVAI.js → chunk-DANP7CMW.js} +1 -1
  39. package/chunks/{chunk-FHFLD4DR.js → chunk-DBHLRZGI.js} +1 -1
  40. package/chunks/{chunk-Y2UXZJLM.js → chunk-DL7TKH2E.js} +2 -2
  41. package/chunks/{chunk-MCQE2U7N.js → chunk-DOWKH5OZ.js} +6 -6
  42. package/chunks/{chunk-UHRLBY3C.js → chunk-DPHQJPCU.js} +1 -1
  43. package/chunks/{chunk-PV2VT25U.js → chunk-DPNGBOI7.js} +1 -1
  44. package/chunks/{chunk-NCDNF7UJ.js → chunk-DXRXF4QD.js} +1 -1
  45. package/chunks/{chunk-OCVRMNEQ.js → chunk-DZ3GV34J.js} +1 -1
  46. package/chunks/{chunk-3QIAXWWW.js → chunk-EU2MKUK4.js} +1 -1
  47. package/chunks/{chunk-KMAVI6FB.js → chunk-EVBUXPGM.js} +1 -1
  48. package/chunks/{chunk-BVSTV4JM.js → chunk-F3ZRU2SA.js} +1 -1
  49. package/chunks/{chunk-TBZY477Y.js → chunk-FCZYH27X.js} +1 -1
  50. package/chunks/{chunk-JCOK67LT.js → chunk-FNDMWG43.js} +1 -1
  51. package/chunks/{chunk-5SF32OGU.js → chunk-GDXLJJSW.js} +1 -1
  52. package/chunks/{chunk-SO6FCPRI.js → chunk-GZYIXB7Y.js} +1 -1
  53. package/chunks/{chunk-WZPTWC7X.js → chunk-HHNAH4IH.js} +1 -1
  54. package/chunks/{chunk-7KCAOXNL.js → chunk-HOKROBQZ.js} +1 -1
  55. package/chunks/{chunk-34ZBUQJV.js → chunk-IGPAATQW.js} +1 -1
  56. package/chunks/{chunk-2ZTRKK2O.js → chunk-INFBJDWM.js} +1 -1
  57. package/chunks/{chunk-IEJ2CGRN.js → chunk-J3R7ZNSA.js} +1 -1
  58. package/chunks/{chunk-KT5MPRYB.js → chunk-JCRS367I.js} +1 -1
  59. package/chunks/{chunk-7JWJTRP6.js → chunk-JFVXZFMV.js} +1 -1
  60. package/chunks/{chunk-47LP4MBD.js → chunk-JKMGS2VD.js} +1 -1
  61. package/chunks/{chunk-WRJ3PMDZ.js → chunk-JUQ7T2MV.js} +1 -1
  62. package/chunks/{chunk-NZX3UWNF.js → chunk-KQ4TDFNE.js} +1 -1
  63. package/chunks/{chunk-X7D4VKMX.js → chunk-L6BKKN42.js} +1 -1
  64. package/chunks/{chunk-YG5HVFMY.js → chunk-L7Y6MOHS.js} +1 -1
  65. package/chunks/{chunk-UFTIUKD4.js → chunk-LGYXZJI3.js} +1 -1
  66. package/chunks/{chunk-JQGGILML.js → chunk-LPOEVTKD.js} +1 -1
  67. package/chunks/{chunk-5KI55A6S.js → chunk-LRXS7ZI2.js} +1 -1
  68. package/chunks/{chunk-CKVHEYXW.js → chunk-LYYVSCNL.js} +1 -1
  69. package/chunks/{chunk-LIIMQ4DI.js → chunk-LZNBHBAJ.js} +6 -6
  70. package/chunks/{chunk-H4GDEXMF.js → chunk-M3C6RDGC.js} +1 -1
  71. package/chunks/{chunk-KKKUB3RQ.js → chunk-MNVMHVQJ.js} +1 -1
  72. package/chunks/{chunk-2B3W7IQY.js → chunk-MVGQFFIK.js} +1 -1
  73. package/chunks/{chunk-Q35A2RGO.js → chunk-NC7BCZPQ.js} +1 -1
  74. package/chunks/{chunk-2ZOTG3NW.js → chunk-NE627MUW.js} +1 -1
  75. package/chunks/{chunk-W4P2EN3V.js → chunk-NZNRCPGE.js} +1 -1
  76. package/chunks/{chunk-YPDQJQ3S.js → chunk-P3M4WWRA.js} +1 -1
  77. package/chunks/{chunk-DVB36ASH.js → chunk-P534ONQN.js} +1 -1
  78. package/chunks/{chunk-EL5J4ESB.js → chunk-QF44NNSC.js} +1 -1
  79. package/chunks/{chunk-IQPJOBPI.js → chunk-QHGCDHNW.js} +1 -1
  80. package/chunks/{chunk-EVZC4KEQ.js → chunk-QWJX7NIP.js} +1 -1
  81. package/chunks/{chunk-J2TJL2F4.js → chunk-S53G54DW.js} +2 -2
  82. package/chunks/{chunk-3A6LFJJV.js → chunk-SMNFL3AD.js} +1 -1
  83. package/chunks/{chunk-WDO3K3P2.js → chunk-TOBNWST4.js} +1 -1
  84. package/chunks/{chunk-AVGJ4HE3.js → chunk-TQSBUHAM.js} +1 -1
  85. package/chunks/{chunk-ABUS7DNN.js → chunk-TW5QEP2J.js} +1 -1
  86. package/chunks/{chunk-WYM4Z4D5.js → chunk-UEB2F43V.js} +1 -1
  87. package/chunks/{chunk-FUUPMVD2.js → chunk-UPPE4I6H.js} +1 -1
  88. package/chunks/{chunk-UHBJVFZA.js → chunk-US42COBM.js} +1 -1
  89. package/chunks/{chunk-RMQNBSMK.js → chunk-UUY6XSQI.js} +1 -1
  90. package/chunks/{chunk-UVQUQNCA.js → chunk-UZI3IA27.js} +1 -1
  91. package/chunks/{chunk-SXJ2E33J.js → chunk-V6VMUJ47.js} +1 -1
  92. package/chunks/{chunk-5UFCNJGN.js → chunk-VG2ZINTO.js} +1 -1
  93. package/chunks/{chunk-JPPPJ2GN.js → chunk-VJI6MHWX.js} +1 -1
  94. package/chunks/{chunk-AUI7WVSU.js → chunk-VOBNHBCJ.js} +1 -1
  95. package/chunks/{chunk-3BNJDZHU.js → chunk-VUEZWMI4.js} +1 -1
  96. package/chunks/{chunk-LMNKCL55.js → chunk-W7ZX6WB3.js} +2 -2
  97. package/chunks/{chunk-HVS6V2UZ.js → chunk-WA2LKUVP.js} +1 -1
  98. package/chunks/{chunk-7APLU2XE.js → chunk-WFFCJ5PF.js} +1 -1
  99. package/chunks/{chunk-3TD4WAG5.js → chunk-WQY5GE65.js} +1 -1
  100. package/chunks/{chunk-3YWRMF6C.js → chunk-WSESLSKK.js} +1 -1
  101. package/chunks/{chunk-NILCQMZ7.js → chunk-XFJV5NYT.js} +1 -1
  102. package/chunks/{chunk-LGBGUITT.js → chunk-XIYLRIW4.js} +1 -1
  103. package/chunks/{chunk-KS74L67R.js → chunk-XQ2NYKJH.js} +1 -1
  104. package/chunks/{chunk-JB2NOB6W.js → chunk-Y3VRWG52.js} +1 -1
  105. package/chunks/{chunk-GVZ6D2NL.js → chunk-YBISME5B.js} +1 -1
  106. package/chunks/{chunk-2C2253QI.js → chunk-YJNWPSB3.js} +1 -1
  107. package/chunks/{chunk-O2T3GQ6F.js → chunk-YWVV5STA.js} +1 -1
  108. package/chunks/{chunk-MAQZSOHI.js → chunk-ZH4J3FL6.js} +1 -1
  109. package/chunks/{chunk-THNEKTPK.js → chunk-ZSKCF6DI.js} +1 -1
  110. package/chunks/{chunk-Z7BAHKO5.js → chunk-ZW6456SD.js} +1 -1
  111. package/chunks/{chunk-DMSZ2TB3.js → chunk-ZWM3LLT7.js} +1 -1
  112. package/chunks/{codex-subagent-executor-DQ5LQQWO.js → codex-subagent-executor-DWWT7246.js} +1 -1
  113. package/chunks/{config-utils-CY6HLKZ5.js → config-utils-NGZB522W.js} +1 -1
  114. package/chunks/{contextCommand-SGBWI7O6.js → contextCommand-7QCW2YNX.js} +1 -1
  115. package/chunks/{core-runtime-4DP27LCC.js → core-runtime-PSVNDJPD.js} +1 -1
  116. package/chunks/{create-sub-session-ECPDZMBX.js → create-sub-session-JTSEMEJE.js} +1 -1
  117. package/chunks/{cron-create-OO4OG3EI.js → cron-create-VGIDTUMX.js} +1 -1
  118. package/chunks/{daemon-git-worktree-guard-OYDNHT7P.js → daemon-git-worktree-guard-IQRGS7IH.js} +1 -1
  119. package/chunks/{daemon-status-provider-JGDLXPC6.js → daemon-status-provider-R4MYCYPG.js} +1 -1
  120. package/chunks/{daemon-trust-policy-5HRARS54.js → daemon-trust-policy-VAUKFZ2N.js} +1 -1
  121. package/chunks/{daemon-trust-policy-monitor-RM7FVIIC.js → daemon-trust-policy-monitor-E5HIO6RP.js} +1 -1
  122. package/chunks/{deferred-core-runtime-3CXBZIOG.js → deferred-core-runtime-FLOFQJPU.js} +1 -1
  123. package/chunks/{edit-DJPESAAY.js → edit-OOVQUGKV.js} +1 -1
  124. package/chunks/{enterPlanMode-IHBLRIF3.js → enterPlanMode-AUWVTQLT.js} +1 -1
  125. package/chunks/{environment-JN5SD347.js → environment-RM5OXYP4.js} +1 -1
  126. package/chunks/{errors-NUJCME3Y.js → errors-CLDJGHVD.js} +1 -1
  127. package/chunks/{execution-tool-I3SWG6I3.js → execution-tool-JFBVOKPW.js} +1 -1
  128. package/chunks/{execution-worker-62UZMAMJ.js → execution-worker-MNJZD72W.js} +1 -1
  129. package/chunks/{exitPlanMode-JIC4V3FE.js → exitPlanMode-PC6XG4TW.js} +1 -1
  130. package/chunks/{fast-path-NIOIL5YI.js → fast-path-V4DN3CRZ.js} +1 -1
  131. package/chunks/{glob-EQ4QNAHF.js → glob-DTZROBDS.js} +1 -1
  132. package/chunks/{goal-tools-DYTTSBQG.js → goal-tools-FUVGTY33.js} +1 -1
  133. package/chunks/{handleAutoUpdate-44BTG5L5.js → handleAutoUpdate-U4LVTHGU.js} +1 -1
  134. package/chunks/{i18n-FTHZAHCT.js → i18n-XOKNDFYP.js} +1 -1
  135. package/chunks/{initializer-MSGKXC75.js → initializer-XBR5J4CY.js} +1 -1
  136. package/chunks/{installationInfo-4XJMJJYU.js → installationInfo-4AOEOUI6.js} +1 -1
  137. package/chunks/{interactive-mod-session-DFLRYO2Q.js → interactive-mod-session-YGZK2JK2.js} +1 -1
  138. package/chunks/{list-ODZ7Z6VI.js → list-TCGKVPH4.js} +1 -1
  139. package/chunks/{llm-O64DHKP7.js → llm-SKFTN5UN.js} +4 -4
  140. package/chunks/{llm-content-generator-SK24I6QS.js → llm-content-generator-GWHXT3WS.js} +1 -1
  141. package/chunks/{loadedSettingsAdapter-6PEBUZT5.js → loadedSettingsAdapter-ZALZGZE7.js} +1 -1
  142. package/chunks/{local-ED3UEKWP.js → local-RWTWYS5Z.js} +1 -1
  143. package/chunks/{local-execution-environment-PUKES5LO.js → local-execution-environment-R6JWLD65.js} +1 -1
  144. package/chunks/{loggingContentGenerator-UHOJVSRR.js → loggingContentGenerator-UJV6QFOY.js} +1 -1
  145. package/chunks/{loop-wakeup-NSJQETPZ.js → loop-wakeup-BU2RRYHA.js} +1 -1
  146. package/chunks/{manage-memory-5RRB6FLH.js → manage-memory-XI57JN4T.js} +1 -1
  147. package/chunks/{managed-execution-engine-MZAP7SK6.js → managed-execution-engine-BA5PABMP.js} +1 -1
  148. package/chunks/{managed-local-serve-XMES3HXL.js → managed-local-serve-MFKN22K6.js} +1 -1
  149. package/chunks/{managed-npm-update-R5KGY7G2.js → managed-npm-update-ZGN43NUA.js} +1 -1
  150. package/chunks/{managed-runtime-attestation-worker-O2KNHHV6.js → managed-runtime-attestation-worker-YN2VBGYN.js} +1 -1
  151. package/chunks/{managed-runtime-bootstrap-HOTLM6DE.js → managed-runtime-bootstrap-SGQVMUJE.js} +1 -1
  152. package/chunks/{managed-runtime-session-worker-QZX44ZTD.js → managed-runtime-session-worker-4UMF3VBY.js} +1 -1
  153. package/chunks/{managed-runtime-ssh-worker-U425WQ65.js → managed-runtime-ssh-worker-7XA6KRBN.js} +1 -1
  154. package/chunks/{managed-session-authority-THHDHCBP.js → managed-session-authority-IJGYAOEL.js} +1 -1
  155. package/chunks/{mcp-AR7EK4WY.js → mcp-V3L7B5YK.js} +1 -1
  156. package/chunks/{memory-C2TSF6BK.js → memory-3T6FPNAK.js} +1 -1
  157. package/chunks/{model-call-collection-25WR55OH.js → model-call-collection-WTTITWWM.js} +1 -1
  158. package/chunks/{model-configuration-KC7DQGKV.js → model-configuration-T6SSGI4J.js} +1 -1
  159. package/chunks/{modelConfigUtils-QEHMVLSQ.js → modelConfigUtils-TQA25QJC.js} +1 -1
  160. package/chunks/{monitor-PDQUZD23.js → monitor-5ZAOJSEE.js} +1 -1
  161. package/chunks/{nonInteractiveCli-WY2YFONU.js → nonInteractiveCli-YFINLVA7.js} +1 -1
  162. package/chunks/{nonInteractiveToolExecutor-7RJZYPHJ.js → nonInteractiveToolExecutor-DE3WACL5.js} +1 -1
  163. package/chunks/{notebook-edit-P4ITXF5H.js → notebook-edit-UK6HBRO3.js} +1 -1
  164. package/chunks/{omni-AYUPB2QM.js → omni-65LF5QK4.js} +1 -1
  165. package/chunks/{openaiContentGenerator-V5IK4ITO.js → openaiContentGenerator-HX7NCSV5.js} +1 -1
  166. package/chunks/{openaiResponsesContentGenerator-DYDH6KWT.js → openaiResponsesContentGenerator-CFA6U6Y5.js} +1 -1
  167. package/chunks/{pidfile-INPBL2DK.js → pidfile-ZVKJUNTZ.js} +1 -1
  168. package/chunks/{processUtils-J4UDEDS4.js → processUtils-VS6CJT7E.js} +1 -1
  169. package/chunks/{prompt-terminal-ledger-QLOQWHYE.js → prompt-terminal-ledger-UF5RDB57.js} +1 -1
  170. package/chunks/{qwenContentGenerator-RU43XKKB.js → qwenContentGenerator-GM3ZSI7E.js} +1 -1
  171. package/chunks/{reactive-degrade-2Q3Z3KAR.js → reactive-degrade-TSAQWZ5F.js} +1 -1
  172. package/chunks/{read-file-472BQ25I.js → read-file-J267NT45.js} +1 -1
  173. package/chunks/{resumeHistoryUtils-7SUFKZDC.js → resumeHistoryUtils-IM46VFDV.js} +1 -1
  174. package/chunks/{review-WX52IWJR.js → review-4B64XTCL.js} +1 -1
  175. package/chunks/{ripGrep-4GPGLKAM.js → ripGrep-YLOSXO7P.js} +1 -1
  176. package/chunks/{run-qwen-serve-MXK4RBKL.js → run-qwen-serve-SAHEC44O.js} +1 -1
  177. package/chunks/{runtime-WHU3AGFT.js → runtime-SJDZHV6J.js} +1 -1
  178. package/chunks/{sandboxConfig-7DBXEQJH.js → sandboxConfig-47EXXMUA.js} +1 -1
  179. package/chunks/{scheduled-tasks-O5RV6G6U.js → scheduled-tasks-E6RCTUUS.js} +1 -1
  180. package/chunks/{scheduler-HLMS5LR5.js → scheduler-SE3IWIWA.js} +1 -1
  181. package/chunks/{search-memory-PYND7ZX3.js → search-memory-2W7VJC4Q.js} +1 -1
  182. package/chunks/{send-message-TMLYTQOI.js → send-message-63YGQP6G.js} +1 -1
  183. package/chunks/{serve-EBNBRAME.js → serve-F4ML2WNL.js} +1 -1
  184. package/chunks/{server-63BRDBL5.js → server-S56IB4TT.js} +3 -3
  185. package/chunks/{session-XB6J4CZD.js → session-2CUVLZ4H.js} +1 -1
  186. package/chunks/{session-attachments-root-PFK475N2.js → session-attachments-root-FINBX7K5.js} +1 -1
  187. package/chunks/{session-execution-engine-selector-P6TJTCKR.js → session-execution-engine-selector-UGC7DGUN.js} +1 -1
  188. package/chunks/{session-pr-refresh-PM7VAQTV.js → session-pr-refresh-KQLQ4MZY.js} +1 -1
  189. package/chunks/{sessionService-PO3LLZIZ.js → sessionService-Q6N7LF7Z.js} +1 -1
  190. package/chunks/{settings-JDQSRXP3.js → settings-23I6H76E.js} +1 -1
  191. package/chunks/{shell-JCEX3HKM.js → shell-IUECEVVY.js} +1 -1
  192. package/chunks/{skill-JSZBONIZ.js → skill-YKUETMPC.js} +1 -1
  193. package/chunks/{skill-settings-YGFG6GPN.js → skill-settings-ODYXOPCA.js} +1 -1
  194. package/chunks/{spawnChannel-VIIWSWTL.js → spawnChannel-7XU2SRWZ.js} +1 -1
  195. package/chunks/{standalone-update-2UU6FQZL.js → standalone-update-SWI2RL3L.js} +1 -1
  196. package/chunks/{start-opentui-ui-OSZZNSLY.js → start-opentui-ui-T53QJGCH.js} +1 -1
  197. package/chunks/{startInteractiveUI-FFH66MYH.js → startInteractiveUI-USTZGQOE.js} +1 -1
  198. package/chunks/{team-create-TKGDJ3NU.js → team-create-4A2XUE3D.js} +1 -1
  199. package/chunks/{team-plan-approval-3VJF4G6Z.js → team-plan-approval-4TS5CYN6.js} +1 -1
  200. package/chunks/{terminal-image-renderer-T3VJRZGP.js → terminal-image-renderer-C7553YV6.js} +1 -1
  201. package/chunks/{theme-manager-ZGUFLFUI.js → theme-manager-GTW75GOO.js} +1 -1
  202. package/chunks/{tool-call-3EQS5KSE.js → tool-call-YTUMWL3A.js} +1 -1
  203. package/chunks/{tool-result-media-7LFNVQ6E.js → tool-result-media-JYOYBX4J.js} +1 -1
  204. package/chunks/{tool-search-UDZ4S7T5.js → tool-search-Y4XTT2WF.js} +1 -1
  205. package/chunks/{total-session-admission-U4MII4RA.js → total-session-admission-EMJ5NRGL.js} +1 -1
  206. package/chunks/{trustedFolders-2NQJCIN3.js → trustedFolders-YG6WAVRE.js} +1 -1
  207. package/chunks/{update-relaunch-YKLWSCLC.js → update-relaunch-4QYQRCP4.js} +1 -1
  208. package/chunks/{updateCheck-YDLTQQRU.js → updateCheck-VRFPSX4G.js} +1 -1
  209. package/chunks/{upload-config-5QQKWF4O.js → upload-config-UCKGUYYQ.js} +1 -1
  210. package/chunks/{useAutoAcceptIndicator-AJS4WTU2.js → useAutoAcceptIndicator-2VGLKD7B.js} +1 -1
  211. package/chunks/{validateNonInterActiveAuth-AETOT7ZW.js → validateNonInterActiveAuth-GGMQXKKU.js} +1 -1
  212. package/chunks/{version-IB6DLRAG.js → version-Y46PG7II.js} +1 -1
  213. package/chunks/{web-fetch-LS3QARNR.js → web-fetch-7MPU555L.js} +1 -1
  214. package/chunks/{web-search-FGHRIVEB.js → web-search-HU2CL2X2.js} +1 -1
  215. package/chunks/{workflow-FX6XNETQ.js → workflow-U3D34QQX.js} +1 -1
  216. package/chunks/{workflow-ancestor-trust-5XXBGN6F.js → workflow-ancestor-trust-OWC4YTMR.js} +1 -1
  217. package/chunks/{workspace-agents-UJKLYPUK.js → workspace-agents-KHLAWSAR.js} +1 -1
  218. package/chunks/{workspace-providers-status-4JOHMTAW.js → workspace-providers-status-T57SE3YX.js} +1 -1
  219. package/chunks/{workspace-recovery-worker-XFEYQ4TP.js → workspace-recovery-worker-VYQ723ZE.js} +1 -1
  220. package/chunks/{workspace-registration-store-LWAPVNYC.js → workspace-registration-store-I7PR3A2Y.js} +1 -1
  221. package/chunks/{workspace-registry-M7OC376O.js → workspace-registry-YYUBXCLH.js} +1 -1
  222. package/chunks/{workspace-runtime-coordinator-CYHIL47L.js → workspace-runtime-coordinator-5ICAQO7W.js} +1 -1
  223. package/chunks/{workspace-service-43VZZ56B.js → workspace-service-YROWXOLQ.js} +1 -1
  224. package/chunks/{workspace-skills-status-V2TT6UJQ.js → workspace-skills-status-DKKQDTZJ.js} +1 -1
  225. package/chunks/{workspace-trust-reconciler-YZ4AG5ZW.js → workspace-trust-reconciler-3FPMUZDO.js} +1 -1
  226. package/chunks/{write-file-TGEH5MEZ.js → write-file-7QQVYFDT.js} +1 -1
  227. package/chunks/{zoom-image-TT6R7H2H.js → zoom-image-WL5EB6Q7.js} +1 -1
  228. package/cli.js +2 -2
  229. package/execution-worker.js +1 -1
  230. package/export-transcript-document.js +1 -1
  231. package/package.json +3 -3
  232. package/web-shell/assets/{PierreFilePreview-OsApm5-S.js → PierreFilePreview-BZ17f56_.js} +1 -1
  233. package/web-shell/assets/{SpreadsheetPreview-I1v1EzV7.js → SpreadsheetPreview-Bvkvr_5u.js} +1 -1
  234. package/web-shell/assets/{WorkspaceFileBrowser-BO6aug7i.js → WorkspaceFileBrowser-BJ_I4Uoz.js} +1 -1
  235. package/web-shell/assets/{abnfDiagram-VCTEODGH-DxuLMyN0.js → abnfDiagram-VCTEODGH-iuaBM15V.js} +1 -1
  236. package/web-shell/assets/{agents-route-CSJf6QPO.js → agents-route-CycwfNSC.js} +1 -1
  237. package/web-shell/assets/{arc-3--LekYQ.js → arc-C0lt8n55.js} +1 -1
  238. package/web-shell/assets/{architectureDiagram-5GKGNRK7-Dihq4uto.js → architectureDiagram-5GKGNRK7-Bw326d-A.js} +1 -1
  239. package/web-shell/assets/{blockDiagram-NRAW4CY4-BnaRPM2o.js → blockDiagram-NRAW4CY4-CHtFgBjV.js} +1 -1
  240. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BtC94eMa.js → c4Diagram-UCG6FXSJ-Bx66oJT9.js} +1 -1
  241. package/web-shell/assets/channel-CRJuO00u.js +1 -0
  242. package/web-shell/assets/{chunk-2Q5K7J3B-2ZTXWP6M.js → chunk-2Q5K7J3B-BIshvfa_.js} +1 -1
  243. package/web-shell/assets/{chunk-5VM5RSS4-DBh7DP1F.js → chunk-5VM5RSS4-BZeRS6uD.js} +1 -1
  244. package/web-shell/assets/{chunk-F27PBJKO-xzqbWXBw.js → chunk-F27PBJKO-El-CGY2R.js} +1 -1
  245. package/web-shell/assets/{chunk-G27WJ6UU-DxnCrpxK.js → chunk-G27WJ6UU-DO8ZfQL_.js} +1 -1
  246. package/web-shell/assets/{chunk-JWPE2WC7-BPjRsozm.js → chunk-JWPE2WC7-yYFrrKAj.js} +1 -1
  247. package/web-shell/assets/{chunk-LCL6LL3I-Q2HgB3lf.js → chunk-LCL6LL3I-BFGuOKN0.js} +1 -1
  248. package/web-shell/assets/{chunk-POPQ4Y6H-9tlPaKu-.js → chunk-POPQ4Y6H-GRHK6sdV.js} +1 -1
  249. package/web-shell/assets/{chunk-SVP7TREG-DkNdOHCU.js → chunk-SVP7TREG-DwDu6GqZ.js} +1 -1
  250. package/web-shell/assets/{chunk-XXDRQBXY-D0G-Dhfi.js → chunk-XXDRQBXY-RoNDjkIy.js} +1 -1
  251. package/web-shell/assets/classDiagram-DTDB5LWJ-pPPByLA7.js +1 -0
  252. package/web-shell/assets/classDiagram-v2-JRS7N3AN-pPPByLA7.js +1 -0
  253. package/web-shell/assets/{cose-bilkent-JH36ORCC-Ck0tHxul.js → cose-bilkent-JH36ORCC-CYNiiONE.js} +1 -1
  254. package/web-shell/assets/{cynefin-OW5HDTMX-a4-NTMHi.js → cynefin-OW5HDTMX-DC1_lDIG.js} +1 -1
  255. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Pg41Zbf2.js → cynefinDiagram-5FMLGOSQ-D2VxKm2n.js} +1 -1
  256. package/web-shell/assets/{dagre-3AP2YEHR-DT_ZmqkF.js → dagre-3AP2YEHR-C4_BHzpM.js} +1 -1
  257. package/web-shell/assets/{diagram-S7CK7UJ4-hapdMOl1.js → diagram-S7CK7UJ4-BpAO4-Gv.js} +1 -1
  258. package/web-shell/assets/{diagram-UQ7AKVKN-YZ0nbk56.js → diagram-UQ7AKVKN-DqUsFdsX.js} +1 -1
  259. package/web-shell/assets/{diagram-VSXAHHWV-DA_yNbWy.js → diagram-VSXAHHWV-DcMXIYMy.js} +1 -1
  260. package/web-shell/assets/{diagram-VX7I27RA-DoULuCLT.js → diagram-VX7I27RA-I3nr09ex.js} +1 -1
  261. package/web-shell/assets/{diagram-Z3DM3KII-B5c9o9zL.js → diagram-Z3DM3KII-CN-gvsTo.js} +1 -1
  262. package/web-shell/assets/{docx-preview-BulxdBjs.js → docx-preview-31J6RsS0.js} +1 -1
  263. package/web-shell/assets/{ebnfDiagram-PWID7BFC-B5hgIg3m.js → ebnfDiagram-PWID7BFC-DOQvLWlM.js} +1 -1
  264. package/web-shell/assets/{erDiagram-SSCWMZ5O-BEfEPozi.js → erDiagram-SSCWMZ5O-Cb5ijFZh.js} +1 -1
  265. package/web-shell/assets/{flowDiagram-A5DVABFB-CQHNk92v.js → flowDiagram-A5DVABFB-BecqqjnZ.js} +1 -1
  266. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-BabdVgIM.js → ganttDiagram-EL5Y4UJY-DWY5vzQl.js} +1 -1
  267. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-ujRZBFUo.js → gitGraphDiagram-WWUBYQGX-DqBnsZmZ.js} +1 -1
  268. package/web-shell/assets/{index-B9uXebIR.js → index-DDmiUW3b.js} +6 -6
  269. package/web-shell/assets/{index-DSZXdZnu.js → index-DabH7kHA.js} +1 -1
  270. package/web-shell/assets/{infoDiagram-RXCK75RN-CUHj9jJC.js → infoDiagram-RXCK75RN-MlotyOdT.js} +1 -1
  271. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-CulW_q81.js → ishikawaDiagram-5VMMS53U-Daq_85C7.js} +1 -1
  272. package/web-shell/assets/{journeyDiagram-EYS64GPL-BR46CvRQ.js → journeyDiagram-EYS64GPL-OipivCxL.js} +1 -1
  273. package/web-shell/assets/{kanban-definition-3QL26DDD-HAoUqzFy.js → kanban-definition-3QL26DDD-zqaz7dLu.js} +1 -1
  274. package/web-shell/assets/{layout-DYLl7fyA.js → layout-Bi3msQMQ.js} +1 -1
  275. package/web-shell/assets/{linear-DPXABjDZ.js → linear-D4gPORvD.js} +1 -1
  276. package/web-shell/assets/{mermaid.core-Bi30Gi0n.js → mermaid.core-BUnytF7a.js} +6 -6
  277. package/web-shell/assets/{mindmap-definition-FBJOCRG2-B1_lUq4o.js → mindmap-definition-FBJOCRG2-B_X4iChu.js} +1 -1
  278. package/web-shell/assets/{pegDiagram-XKGWAZYB-Cy8tjJJC.js → pegDiagram-XKGWAZYB-z4wYBoBW.js} +1 -1
  279. package/web-shell/assets/{pieDiagram-E7YTZNPT-D6waLVVi.js → pieDiagram-E7YTZNPT-Dvyg6FYo.js} +1 -1
  280. package/web-shell/assets/{quadrantDiagram-AXDQQJYC--6ehi_FI.js → quadrantDiagram-AXDQQJYC-CJBWU2Dk.js} +1 -1
  281. package/web-shell/assets/{railroadDiagram-O6MQD6OU-BhLy40X4.js → railroadDiagram-O6MQD6OU-Dl_An1O0.js} +1 -1
  282. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BVNXTgNP.js → requirementDiagram-EFPCY7ZU-Tw8FwaYU.js} +1 -1
  283. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BHgTytxV.js → sankeyDiagram-P5KCCOFB-BCPCkbR0.js} +1 -1
  284. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-CgOsTvhu.js → sequenceDiagram-WJ2MYXX4-DDj7uFTG.js} +1 -1
  285. package/web-shell/assets/{sizeCapture-X5ZJPWSS-vCQBQ5FI.js → sizeCapture-X5ZJPWSS-B9eVSpKb.js} +1 -1
  286. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DytMYRWJ.js → stateDiagram-HBIQ2CUA-Bf4BZP_V.js} +1 -1
  287. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BPJi6Gre.js +1 -0
  288. package/web-shell/assets/{swimlanes-XN3QIQJK-CTGnifOP.js → swimlanes-XN3QIQJK-dyTWsZFj.js} +1 -1
  289. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bw4NRtJQ.js +8 -0
  290. package/web-shell/assets/{timeline-definition-24CTP7MA-DEJ1cbn2.js → timeline-definition-24CTP7MA-DVl1A4uL.js} +1 -1
  291. package/web-shell/assets/{vennDiagram-4TSXK5OY-K1e4SjS0.js → vennDiagram-4TSXK5OY-Boosxy9D.js} +1 -1
  292. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DEX-GkRp.js → wardleyDiagram-VM6X3IG4-C6wlY8jy.js} +1 -1
  293. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-B6wYXreH.js → xychartDiagram-S5SC5T6Z-CkzZe3ro.js} +1 -1
  294. package/web-shell/index.html +1 -1
  295. package/web-shell/sw.js +1 -1
  296. package/web-shell/assets/channel-CLVrtVFX.js +0 -1
  297. package/web-shell/assets/classDiagram-DTDB5LWJ-Df2T70oB.js +0 -1
  298. package/web-shell/assets/classDiagram-v2-JRS7N3AN-Df2T70oB.js +0 -1
  299. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CcjUJGng.js +0 -1
  300. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dt8NvQfX.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{collectInlineImages,extractInlineContentRuns}from"./chunk-VRNYIKVL.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-LWJBPGIT.js";import{t}from"./chunk-EZMTX4EU.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-6JFC5M6B.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-LIIMQ4DI.js";import{projectUserTranscriptForDisplay}from"./chunk-DBA3F3D7.js";import{parseGoalStateRecordPayloadV2}from"./chunk-CMLAE3UB.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.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();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
3
+ import{collectInlineImages,extractInlineContentRuns}from"./chunk-VRNYIKVL.js";import{formatHistoryGapNotice,indexGapsByChild}from"./chunk-LWJBPGIT.js";import{t}from"./chunk-EZMTX4EU.js";import{isGoalCheckpointBookkeepingRecord}from"./chunk-A5TAAMML.js";import{GoalPersistenceUnavailableError,computeInitialTurnFromHistory,getRecordRewindId,getToolResponseDisplayText}from"./chunk-LZNBHBAJ.js";import{projectUserTranscriptForDisplay}from"./chunk-DBA3F3D7.js";import{parseGoalStateRecordPayloadV2}from"./chunk-CMLAE3UB.js";import{ToolDisplayNames}from"./chunk-SBZFGYYS.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();init_esbuild_shims();var EstimatedArtWidth=59;var BoxBorderWidth=1;var BOX_PADDING_X=1;var UI_WIDTH=EstimatedArtWidth+BOX_PADDING_X*2+BoxBorderWidth*2;var SHELL_COMMAND_NAME="Shell Command";var SHELL_NAME="Shell";var TOOL_STATUS={SUCCESS:"\u2713",PENDING:"o",EXECUTING:"\u22B7",CONFIRMING:"?",CANCELED:"-",ERROR:"x"};var _VS15="\uFE0E";var ICON={DIAMOND:`\u25C6${_VS15}`,CIRCLE_FILLED:`\u25CF${_VS15}`,TRIANGLE:`\u25B3${_VS15}`,CIRCLE_EMPTY:`\u25CB${_VS15}`,BULLSEYE:`\u25CE${_VS15}`,REFERENCE:`\u203B${_VS15}`,THEREFORE:`\u2234${_VS15}`,BECAUSE:`\u2235${_VS15}`,STAR:`\u2605${_VS15}`,SPARKLE:`\u2733${_VS15}`,RADIO_FILLED:`\u25C9${_VS15}`,CIRCLE_LEFT_HALF:`\u25D0${_VS15}`,CHECK:`\u2713${_VS15}`,CROSS:`\u2716${_VS15}`};var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var SPINNER_INTERVAL_MS=80;var WAITING_SPINNER_FRAME="\u280F";var TOOL_NAME_TO_CATEGORY={[ToolDisplayNames.READ_FILE]:"read",[ToolDisplayNames.EDIT]:"edit",[ToolDisplayNames.WRITE_FILE]:"write",[ToolDisplayNames.NOTEBOOK_EDIT]:"edit",[ToolDisplayNames.GREP]:"search",[ToolDisplayNames.GLOB]:"search",[ToolDisplayNames.LS]:"list",[ToolDisplayNames.SHELL]:"command",[SHELL_COMMAND_NAME]:"command",[ToolDisplayNames.AGENT]:"agent",[ToolDisplayNames.WORKFLOW]:"agent",[ToolDisplayNames.SEND_MESSAGE]:"agent","Read File":"read","Read File(s)":"read","Read Directory":"list",SearchFiles:"search",FindFiles:"search",ReadFolder:"list",Task:"agent",TodoWrite:"other"};var CATEGORY_TEMPLATES={read:{past:{one:"Read {{count}} file",many:"Read {{count}} files"},active:{one:"Reading {{count}} file",many:"Reading {{count}} files"},pastVerb:"Read",activeVerb:"Reading"},edit:{past:{one:"Edited {{count}} file",many:"Edited {{count}} files"},active:{one:"Editing {{count}} file",many:"Editing {{count}} files"},pastVerb:"Edited",activeVerb:"Editing"},write:{past:{one:"Wrote {{count}} file",many:"Wrote {{count}} files"},active:{one:"Writing {{count}} file",many:"Writing {{count}} files"},pastVerb:"Wrote",activeVerb:"Writing"},search:{past:{one:"Searched {{count}} pattern",many:"Searched {{count}} patterns"},active:{one:"Searching {{count}} pattern",many:"Searching {{count}} patterns"},pastVerb:"Searched",activeVerb:"Searching"},list:{past:{one:"Listed {{count}} directory",many:"Listed {{count}} directories"},active:{one:"Listing {{count}} directory",many:"Listing {{count}} directories"},pastVerb:"Listed",activeVerb:"Listing"},command:{past:{one:"Ran {{count}} command",many:"Ran {{count}} commands"},active:{one:"Running {{count}} command",many:"Running {{count}} commands"},pastVerb:"Ran",activeVerb:"Running"},agent:{past:{one:"Ran {{count}} agent",many:"Ran {{count}} agents"},active:{one:"Running {{count}} agent",many:"Running {{count}} agents"},pastVerb:"Ran",activeVerb:"Running"},other:{past:{one:"Used {{count}} tool",many:"Used {{count}} tools"},active:{one:"Using {{count}} tool",many:"Using {{count}} tools"},pastVerb:"Used",activeVerb:"Using"}};var CATEGORY_ORDER=["search","read","list","command","edit","write","agent","other"];var COLLAPSIBLE_CATEGORIES=new Set(["read","search","list"]);function getToolCategory(toolName){return TOOL_NAME_TO_CATEGORY[toolName]??"other"}__name(getToolCategory,"getToolCategory");function isCollapsibleTool(toolName){return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName))}__name(isCollapsibleTool,"isCollapsibleTool");function safeDescription(raw){if(!raw)return void 0;const stripped=raw.replace(/\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]|\x1b\[[0-9;]*[a-zA-Z]|\x1b./g,"");const cleaned=stripped.replace(/[\x00-\x1f\x7f]/g," ").trim();if(cleaned.startsWith("{")||cleaned.startsWith("[")){try{const parsed=JSON.parse(cleaned);if(typeof parsed==="object"&&parsed!==null)return void 0}catch{}}return cleaned||void 0}__name(safeDescription,"safeDescription");function categoryShowsDescriptionsInline(toolCalls,category){const sameCategory=toolCalls.filter(tc=>getToolCategory(tc.name)===category);if(sameCategory.length>DESCRIPTION_INLINE_LIMIT)return false;return sameCategory.every(tc=>safeDescription(tc.description)!==void 0)}__name(categoryShowsDescriptionsInline,"categoryShowsDescriptionsInline");function getActiveToolHint(toolCalls){if(toolCalls.length<2)return void 0;const statuses=["Confirming","Executing","Pending"];for(const status of statuses){for(let index=toolCalls.length-1;index>=0;index--){const tool=toolCalls[index];if(tool.status===status){const category=getToolCategory(tool.name);const hasCategoryPeers=toolCalls.some((candidate,candidateIndex)=>candidateIndex!==index&&getToolCategory(candidate.name)===category);if(!hasCategoryPeers)return void 0;if(categoryShowsDescriptionsInline(toolCalls,category))return void 0;return safeDescription(tool.description)}}}return void 0}__name(getActiveToolHint,"getActiveToolHint");var DESCRIPTION_INLINE_LIMIT=3;var DESCRIPTION_PREVIEW_COUNT=2;function buildToolSummary(toolCalls,isActive){if(toolCalls.length===0)return"";const toolsByCategory=new Map;for(const tool of toolCalls){const cat=getToolCategory(tool.name);const arr=toolsByCategory.get(cat)??[];arr.push(tool);toolsByCategory.set(cat,arr)}const parts=[];for(const cat of CATEGORY_ORDER){const tools=toolsByCategory.get(cat);if(!tools||tools.length===0)continue;const template=CATEGORY_TEMPLATES[cat];const verb=isActive?template.activeVerb:template.pastVerb;let part;if(tools.length===1){const safeDesc=safeDescription(tools[0].description);if(safeDesc!==void 0){part=`${verb} ${safeDesc}`}else{part=t(isActive?template.active.one:template.past.one,{count:"1"})}}else if(tools.length<=DESCRIPTION_INLINE_LIMIT){const descriptions=tools.map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(descriptions.length===tools.length){part=`${verb} ${descriptions.join(", ")}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}else{const previewDescs=tools.slice(0,DESCRIPTION_PREVIEW_COUNT).map(tc=>safeDescription(tc.description)).filter(d=>d!==void 0);if(previewDescs.length===DESCRIPTION_PREVIEW_COUNT){const remaining=tools.length-DESCRIPTION_PREVIEW_COUNT;const morePhrase=t("... and {{count}} more",{count:String(remaining)});part=`${verb} ${previewDescs.join(", ")}, ${morePhrase}`}else{const forms=isActive?template.active:template.past;part=t(forms.many,{count:String(tools.length)})}}if(parts.length>0){part=part.charAt(0).toLowerCase()+part.slice(1)}parts.push(part)}return parts.join(", ")}__name(buildToolSummary,"buildToolSummary");function isSubagentToolEntry(tool){const rd=tool.resultDisplay;return typeof rd==="object"&&rd!==null&&"type"in rd&&rd.type==="task_execution"}__name(isSubagentToolEntry,"isSubagentToolEntry");init_esbuild_shims();var SUPERSEDED_FINDINGS_MESSAGE="(findings replaced by a later report_findings call)";function isFindingsListDisplay(value){return typeof value==="object"&&value!==null&&"type"in value&&value.type==="findings_list"}__name(isFindingsListDisplay,"isFindingsListDisplay");function coalesceFindingsHistoryItems(items){let lastItem=-1;let lastTool=-1;for(let i=items.length-1;i>=0&&lastItem===-1;i-=1){const item=items[i];if(item.type!=="tool_group")continue;for(let j=item.tools.length-1;j>=0;j-=1){if(isFindingsListDisplay(item.tools[j].resultDisplay)){lastItem=i;lastTool=j;break}}}if(lastItem===-1)return items;let changed=false;const next=items.map((item,i)=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map((tool,j)=>{if(i===lastItem&&j===lastTool)return tool;if(!isFindingsListDisplay(tool.resultDisplay))return tool;toolsChanged=true;return{...tool,resultDisplay:SUPERSEDED_FINDINGS_MESSAGE,supersededFindingsDisplay:tool.supersededFindingsDisplay??tool.resultDisplay}});if(!toolsChanged)return item;changed=true;return{...item,tools}});return changed?next:items}__name(coalesceFindingsHistoryItems,"coalesceFindingsHistoryItems");function recoalesceFindingsHistoryItems(items){let restored=false;const next=items.map(item=>{if(item.type!=="tool_group")return item;let toolsChanged=false;const tools=item.tools.map(tool=>{if(tool.resultDisplay!==SUPERSEDED_FINDINGS_MESSAGE||!tool.supersededFindingsDisplay){return tool}toolsChanged=true;return{...tool,resultDisplay:tool.supersededFindingsDisplay,supersededFindingsDisplay:void 0}});if(!toolsChanged)return item;restored=true;return{...item,tools}});return coalesceFindingsHistoryItems(restored?next:items)}__name(recoalesceFindingsHistoryItems,"recoalesceFindingsHistoryItems");init_esbuild_shims();function shouldDisplayGoalStateCause(cause){switch(cause){case"turn_finished":case"checkpoint":case"verifier_accept":return false;case"verifier_reject":case"create":case"replace":case"edit":case"pause":case"resume":case"complete":case"blocked":case"usage_limited":case"clear":case"migrated":return true;default:{const exhaustive=cause;return exhaustive}}}__name(shouldDisplayGoalStateCause,"shouldDisplayGoalStateCause");async function waitForGoalRuntime(config,options={}){const awaitReady=__name(async()=>{try{await config.getGoalRuntimeReady()}catch(error){if(!(error instanceof GoalPersistenceUnavailableError))throw error}},"awaitReady");const{timeoutMs}=options;if(timeoutMs==null||timeoutMs<=0){await awaitReady();return true}let timer;const timeout=new Promise(resolve=>{timer=setTimeout(()=>resolve("timeout"),timeoutMs);timer.unref?.()});try{const winner=await Promise.race([awaitReady(),timeout]);return winner!=="timeout"}finally{if(timer)clearTimeout(timer)}}__name(waitForGoalRuntime,"waitForGoalRuntime");function extractTextFromParts(parts){if(!parts)return"";const textParts=[];for(const part of parts){if("text"in part&&part.text){if(!("thought"in part&&part.thought)){textParts.push(part.text)}}}return textParts.join("\n")}__name(extractTextFromParts,"extractTextFromParts");function extractThoughtTextFromParts(parts){if(!parts)return"";const thoughtParts=[];for(const part of parts){if("text"in part&&part.text&&"thought"in part&&part.thought){thoughtParts.push(part.text)}}return thoughtParts.join("\n")}__name(extractThoughtTextFromParts,"extractThoughtTextFromParts");function extractFunctionCalls(parts){if(!parts)return[];const calls=[];for(const part of parts){if("functionCall"in part&&part.functionCall){const fc=part.functionCall;calls.push({id:fc.id||`call-${calls.length}`,name:fc.name||"unknown",args:fc.args||{}})}}return calls}__name(extractFunctionCalls,"extractFunctionCalls");function getTool(config,name){if(!config)return void 0;const toolRegistry=config.getToolRegistry();return toolRegistry.getTool(name)}__name(getTool,"getTool");function formatToolDescription(tool,args){try{const invocation=tool.build(args);return invocation.getDescription()}catch{if(typeof args["description"]==="string"){return args["description"]}return""}}__name(formatToolDescription,"formatToolDescription");function restoreHistoryItem(raw){if(!raw||typeof raw!=="object"){return}const clone={...raw};if("timestamp"in clone){const ts=clone["timestamp"];if(typeof ts==="string"||typeof ts==="number"){clone["timestamp"]=new Date(ts)}}if(typeof clone["type"]!=="string"){return}return clone}__name(restoreHistoryItem,"restoreHistoryItem");function createHistoryGapItem(gap){return{type:"info",text:formatHistoryGapNotice(gap)}}__name(createHistoryGapItem,"createHistoryGapItem");function convertToHistoryItems(conversation,config,historyGaps){const items=[];const gapByChildUuid=indexGapsByChild(historyGaps);const pendingAtCommands=[];let atCommandCounter=0;let lastGoalStateSnapshot;let lastGoalStateCause;const pendingToolCalls=new Map;let currentToolGroup=[];const buildAtCommandDisplays=__name(payload=>{if(payload.status==="error"){atCommandCounter+=1;const filesLabel=payload.filesRead?.length?payload.filesRead.join(", "):"files";return[{callId:`at-command-${atCommandCounter}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:payload.message||`Error reading files (${filesLabel})`,confirmationDetails:void 0}]}if(!payload.filesRead?.length){atCommandCounter+=1;return[{callId:`at-command-${atCommandCounter}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}]}return payload.filesRead.map(filePath=>{atCommandCounter+=1;const isDir=filePath.endsWith("/");return{callId:`at-command-${atCommandCounter}`,name:isDir?"Read Directory":"Read File",description:isDir?`Read directory ${path.basename(filePath)}`:`Read file ${path.basename(filePath)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})},"buildAtCommandDisplays");for(const record of conversation.messages){const promptId=typeof record.promptId==="string"&&record.promptId.length>0?record.promptId:void 0;const rewindId=promptId?void 0:getRecordRewindId(record);const gap=gapByChildUuid.get(record.uuid);if(gap){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}pendingAtCommands.length=0;lastGoalStateSnapshot=void 0;lastGoalStateCause=void 0;items.push(createHistoryGapItem(gap))}if(record.type==="system"){if(record.subtype==="goal_state"){const payload=parseGoalStateRecordPayloadV2(record.systemPayload);if(payload){const bookkeepingOnly=isGoalCheckpointBookkeepingRecord({cause:payload.cause,previousCause:lastGoalStateCause,previous:lastGoalStateSnapshot,next:payload.snapshot});lastGoalStateCause=payload.cause;lastGoalStateSnapshot=payload.snapshot;if(shouldDisplayGoalStateCause(payload.cause)&&!bookkeepingOnly){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"goal_state",snapshot:payload.snapshot,cause:payload.cause})}}continue}if(record.subtype==="slash_command"){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload=record.systemPayload;if(!payload)continue;if(payload.phase==="invocation"&&payload.rawCommand&&!payload.hiddenInvocation){const sentToModel=typeof payload.sentToModel==="boolean"?payload.sentToModel:void 0;items.push({type:"user",text:payload.rawCommand,...promptId?{promptId}:{},...sentToModel===void 0?{}:{sentToModel}})}if(payload.phase==="result"){const outputs=payload.outputHistoryItems??[];for(const raw of outputs){const restored=restoreHistoryItem(raw);if(restored){items.push(restored)}}}}if(record.subtype==="at_command"){const payload=record.systemPayload;if(!payload)continue;pendingAtCommands.push(payload)}if(record.subtype==="rewind"){items.push({type:"info",text:"Conversation rewound."})}continue}switch(record.type){case"user":{if(record.subtype==="goal_runtime")break;if(record.subtype==="notification"||record.subtype==="cron"){const payload2=record.systemPayload;const fallback=record.subtype==="cron"?"Cron job fired":"Background agent completed";const text2=payload2?.displayText||extractTextFromParts(record.message?.parts)||fallback;items.push({type:"notification",text:text2});break}if(record.subtype==="agent_mention"||record.subtype==="agent_message"){const payload2=record.systemPayload;const text2=payload2?.displayText;if(text2){if(record.subtype==="agent_mention"&&!payload2?.author){items.push({type:"user",text:text2,sentToModel:false})}else{const name=payload2?.author?.name??record.agentName;items.push({type:"notification",text:name?`${name}: ${text2}`:text2})}}break}if(record.subtype==="mid_turn_user_message"){const payload2=record.systemPayload;const hasAttachmentReferences2=Array.isArray(payload2?.attachmentReferences)&&payload2.attachmentReferences.length>0;const text2=payload2?.displayText||(hasAttachmentReferences2?"[User message with attachments]":extractTextFromParts(record.message?.parts));if(text2){items.push({type:"user",text:text2,sentToModel:false})}break}if(pendingAtCommands.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const payload2=pendingAtCommands.shift();const projection2=projectUserTranscriptForDisplay(record);const text2=payload2.userText||(projection2.displayText??extractTextFromParts(projection2.parts));if(text2){items.push({type:"user",text:text2,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}const toolDisplays=buildAtCommandDisplays(payload2);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}break}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const projection=projectUserTranscriptForDisplay(record);const payload=record.systemPayload;const hasAttachmentReferences=Array.isArray(payload?.attachmentReferences)&&payload.attachmentReferences.length>0;const text=projection.displayText||(hasAttachmentReferences?"[User message with attachments]":extractTextFromParts(projection.parts));if(text){items.push({type:"user",text,...promptId?{promptId}:{},...rewindId?{rewindId}:{}})}break}case"assistant":{const parts=record.message?.parts;const thoughtText=!config?extractThoughtTextFromParts(parts):"";const displayRuns=extractInlineContentRuns(parts,"\n");const functionCalls=extractFunctionCalls(parts);if(thoughtText){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}items.push({type:"gemini_thought",text:thoughtText})}if(displayRuns.length>0){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}for(const[index,run]of displayRuns.entries()){const type=index===0?"gemini":"gemini_content";const timestamp=index===0?{timestamp:new Date(record.timestamp).getTime()}:{};if(run.kind==="text"){items.push({type,text:run.text,...timestamp})}else if(run.kind==="image"){items.push({type,text:"",images:[run.image],...timestamp})}else{items.push({type,text:"",omittedImageCount:run.count,...timestamp})}}}for(const fc of functionCalls){const tool=getTool(config,fc.name);pendingToolCalls.set(fc.id,{name:fc.name,args:fc.args});currentToolGroup.push({callId:fc.id,name:tool?.displayName||fc.name,description:tool?formatToolDescription(tool,fc.args):"",args:fc.args,resultDisplay:void 0,status:"Error",confirmationDetails:void 0})}break}case"tool_result":{if(record.toolCallResult){const callId=record.toolCallResult.callId;const toolCall=currentToolGroup.find(t2=>t2.callId===callId);if(toolCall){const responseParts=record.toolCallResult.responseParts??record.message?.parts;const rawDisplay=record.toolCallResult.resultDisplay;toolCall.resultDisplay=rawDisplay;if(record.toolCallResult.visionBridgeNotice!==void 0){toolCall.visionBridgeNotice=record.toolCallResult.visionBridgeNotice}const rawStatus=record.toolCallResult["status"];toolCall.status=rawStatus==="error"?"Error":rawStatus==="cancelled"?"Canceled":"Success";const{images,omittedImageCount}=collectInlineImages(responseParts);if(images.length>0){toolCall.images=images}if(omittedImageCount>0){toolCall.omittedImageCount=omittedImageCount}if(toolCall.status==="Success"&&isCollapsibleTool(toolCall.name)){toolCall.detailedDisplay=getToolResponseDisplayText(responseParts)}}pendingToolCalls.delete(callId||"")}break}default:break}}if(pendingAtCommands.length>0){for(const payload of pendingAtCommands){if(currentToolGroup.length>0){items.push({type:"tool_group",tools:[...currentToolGroup]});currentToolGroup=[]}const text=payload.userText;if(text){items.push({type:"user",text})}const toolDisplays=buildAtCommandDisplays(payload);if(toolDisplays.length>0){items.push({type:"tool_group",tools:toolDisplays})}}}if(currentToolGroup.length>0){items.push({type:"tool_group",tools:currentToolGroup})}return coalesceFindingsHistoryItems(items)}__name(convertToHistoryItems,"convertToHistoryItems");function buildResumedHistoryItems(sessionData,config,baseTimestamp=Date.now()){const items=[];let idCounter=1;const getNextId=__name(()=>baseTimestamp+idCounter++,"getNextId");const historyItems=convertToHistoryItems(sessionData.conversation,config,sessionData.historyGaps);for(const item of historyItems){items.push({...item,id:getNextId()})}return items}__name(buildResumedHistoryItems,"buildResumedHistoryItems");function applyResumeDisplayPolicy(items){return items.map(item=>({...item,display:{...item.display,suppressOnRestore:true}}))}__name(applyResumeDisplayPolicy,"applyResumeDisplayPolicy");function createHistoryCollapseSummaryItem(messageCount){const n=String(messageCount);return{type:"info",text:t("History collapsed: {{n}} messages hidden. Use /history expand-now to show.",{n}),display:{kind:"collapse-summary"}}}__name(createHistoryCollapseSummaryItem,"createHistoryCollapseSummaryItem");function stripSuppressOnRestore(item){if(!item.display?.suppressOnRestore)return item;const{suppressOnRestore:_,...rest}=item.display;return{...item,display:Object.keys(rest).length>0?rest:void 0}}__name(stripSuppressOnRestore,"stripSuppressOnRestore");function computeResumedPromptCountSeed(records,sessionId){const userTurnCount=records.filter(m=>m.type==="user"&&m.subtype!=="mid_turn_user_message"&&m.subtype!=="realtime_message").length;if(records.length===0){return 0}return Math.max(userTurnCount,computeInitialTurnFromHistory(records,sessionId)+1)}__name(computeResumedPromptCountSeed,"computeResumedPromptCountSeed");function expandCollapsedHistory(items){return items.filter(item=>item.display?.kind!=="collapse-summary").map(stripSuppressOnRestore)}__name(expandCollapsedHistory,"expandCollapsedHistory");function applyCollapsePolicyAndSummary(rawItems,collapseOnResume,collapsePreviewCount=0){if(!collapseOnResume)return rawItems;if(collapsePreviewCount===-1)return rawItems;let boundary=rawItems.length;if(collapsePreviewCount>0){let userTurnCount=0;for(let i=rawItems.length-1;i>=0;i--){const item=rawItems[i];if(item.type==="user"&&item.sentToModel!==false){userTurnCount++;if(userTurnCount===collapsePreviewCount){boundary=i;break}}}if(userTurnCount<collapsePreviewCount){boundary=0}}const hiddenItems=applyResumeDisplayPolicy(rawItems.slice(0,boundary));const visibleItems=rawItems.slice(boundary);const uiHistoryItems=[...hiddenItems,...visibleItems];if(boundary>0){const nextId=rawItems[rawItems.length-1].id+1;return[...uiHistoryItems,{id:nextId,...createHistoryCollapseSummaryItem(boundary)}]}return uiHistoryItems}__name(applyCollapsePolicyAndSummary,"applyCollapsePolicyAndSummary");export{SHELL_COMMAND_NAME,SHELL_NAME,TOOL_STATUS,ICON,SPINNER_FRAMES,SPINNER_INTERVAL_MS,WAITING_SPINNER_FRAME,isCollapsibleTool,getActiveToolHint,buildToolSummary,isSubagentToolEntry,isFindingsListDisplay,coalesceFindingsHistoryItems,recoalesceFindingsHistoryItems,shouldDisplayGoalStateCause,waitForGoalRuntime,buildResumedHistoryItems,stripSuppressOnRestore,computeResumedPromptCountSeed,expandCollapsedHistory,applyCollapsePolicyAndSummary};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{flushOutput}from"./chunk-VURTGFJP.js";import{cpLen,cpSlice,sanitizeTerminalLine,sanitizeTerminalText,stripUnsafeCharacters}from"./chunk-64CA3W6G.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,record,validateRenderTree,validateResult}from"./chunk-ZZJXFLVM.js";import{stableJson}from"./chunk-FIXDX63I.js";import{external_exports}from"./chunk-TWP72VRH.js";import{openNoFollow}from"./chunk-QXQGUM3Y.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{runOutsideAgentContext}from"./chunk-AGQBNWGY.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-TNCN2JX2.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{EVENT_API_RESPONSE}from"./chunk-XHV5HLJS.js";import{registerCleanup}from"./chunk-UFTIUKD4.js";import{stripAnsiAndControl}from"./chunk-4YLXNRRH.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID}from"node:crypto";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)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript or TypeScript 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(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){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;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()}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==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(this.renders.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)return;root.revision=reply.revision;root.idle=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;failure;pending;commands=[];tools=false;turns={start:false,complete:[]};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){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);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[]},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;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(turnComplete)||!names(renders))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.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(renders.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 renderHooks(){return this.renders}async render(input,signal){const settled=await this.request({type:"render",input},signal);const owner=this.renders.length===1?this.renders[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}}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-JCEX3HKM.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-DJPESAAY.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-TGEH5MEZ.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 completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}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)}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))}fail(error){this.failure??=error;this.tool?.controller.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,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=request.type==="tool"&&root.native!==void 0&&root.idle===root.native&&!this.tool?.checks.size&&!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")};this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.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;if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};var logger=createDebugLogger("MODS");var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;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;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};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(()=>this.requestRender(),"invalidate")}:void 0);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}}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;return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;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?.renderHooks.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 owner=runtime.renderHooks.length===1?runtime.renderHooks[0]:"hooks";band.state="running";band.startedAt=Date.now();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,this.lifetime.signal);for(const note of notes)logger.debug(note);if(!this.closing)this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(!this.closing)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()}}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}}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:randomUUID(),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{require_semver}from"./chunk-YZUKMJW7.js";import{ENGINE_NODE,MOD_END_TIMEOUT_MS,MOD_MAX_BYTES,ModBudget,adjustRenderTree,assertModDepth,record,validateRenderTree,validateResult}from"./chunk-ZZJXFLVM.js";import{stableJson}from"./chunk-FIXDX63I.js";import{external_exports}from"./chunk-TWP72VRH.js";import{openNoFollow}from"./chunk-QXQGUM3Y.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{runOutsideAgentContext}from"./chunk-AGQBNWGY.js";import{isInternalPromptId,uiTelemetryService}from"./chunk-TNCN2JX2.js";import{getGenAiUsageProvenance,outputTokenCount}from"./chunk-4DIWAQ5G.js";import{EVENT_API_RESPONSE}from"./chunk-XHV5HLJS.js";import{registerCleanup}from"./chunk-LGYXZJI3.js";import{stripAnsiAndControl}from"./chunk-4YLXNRRH.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{randomUUID}from"node:crypto";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)$/.test(modules[0])){throw new Error("Mods require one relative JavaScript or TypeScript 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(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){this.log=log;this.facts=facts;this.resolveTool=resolveTool;this.surface=surface;this.abortTurn=abortTurn;this.renderHost=renderHost;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()}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==="invalidate"){if(reply.event!=="ui.render"||this.failure)return;if(this.early)this.early.add(reply.plugin);else if(this.renders.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)return;root.revision=reply.revision;root.idle=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;failure;pending;commands=[];tools=false;turns={start:false,complete:[]};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){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);try{const result=await runtime.request({type:"load",plugins,cwd,surface,version,sites:render?.sites??[]},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;if(!record(result)||typeof result["tools"]!=="boolean"||typeof result["turnStart"]!=="boolean"||!names(turnComplete)||!names(renders))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.renders=renders;const early=runtime.early;runtime.early=void 0;for(const plugin of early)if(renders.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 renderHooks(){return this.renders}async render(input,signal){const settled=await this.request({type:"render",input},signal);const owner=this.renders.length===1?this.renders[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}}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-IUECEVVY.js")).ShellTool;break;case ToolNames.EDIT:builtin=await this.resolveTool(name2)instanceof(await import("./edit-OOVQUGKV.js")).EditTool;break;case ToolNames.WRITE_FILE:builtin=await this.resolveTool(name2)instanceof(await import("./write-file-7QQVYFDT.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 completeTurn(input,signal){const result=await this.request({type:"turn-complete",input},signal);validateResult("turn.complete",result);return result.text}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)}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))}fail(error){this.failure??=error;this.tool?.controller.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,refresh:__name(()=>{if(aborted||this.root!==root)return;const lending=request.type==="tool"&&root.native!==void 0&&root.idle===root.native&&!this.tool?.checks.size&&!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")};this.root=root;const onAbort=__name(()=>{aborted=true;Atomics.store(this.cancelled,0,1);this.tool?.controller.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;if(timer)clearTimeout(timer);if(cancelTimer)clearTimeout(cancelTimer);signal.removeEventListener("abort",onAbort);this.pending=void 0}}};var logger=createDebugLogger("MODS");var RENDER_SETTLE_MS=150;var RENDER_LIVE_MS=34;var RENDER_STEADY_MS=100;var RENDER_SLOW_MS=1e3;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;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};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(()=>this.requestRender(),"invalidate")}:void 0);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}}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;return}this.invalidateTools();const task=this.toolQueue.then(async()=>{if(current===this.sessionId||this.closing)return;await this.end(reason);this.sessionId=current;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?.renderHooks.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 owner=runtime.renderHooks.length===1?runtime.renderHooks[0]:"hooks";band.state="running";band.startedAt=Date.now();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,this.lifetime.signal);for(const note of notes)logger.debug(note);if(!this.closing)this.terminal?.draw?.(tree,owner)}catch(error){logger.debug(`Mod ui.render: ${String(error)}`);if(!this.closing)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()}}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}}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:randomUUID(),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 tokenCount(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):0}__name(tokenCount,"tokenCount");function addTurnUsage(usage,metadata,authType){if(!metadata)return usage;const prompt=tokenCount(metadata.promptTokenCount);const read=tokenCount(metadata.cachedContentTokenCount);const written=tokenCount(getGenAiUsageProvenance(metadata)?.cacheCreationInputTokens);const output=outputTokenCount({input:prompt,output:tokenCount(metadata.candidatesTokenCount),thoughts:tokenCount(metadata.thoughtsTokenCount),total:tokenCount(metadata.totalTokenCount)},authType);return{input_tokens:(usage?.input_tokens??0)+Math.max(0,prompt-read-written),output_tokens:(usage?.output_tokens??0)+output,cache_read_input_tokens:(usage?.cache_read_input_tokens??0)+read,cache_creation_input_tokens:(usage?.cache_creation_input_tokens??0)+written}}__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;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"),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;closing;listener;logs=[];presentation={isFullscreen:false,columns:80};sites=[];band;revision=0;bandListeners=new Set;unregisterCleanup;initialize(sites=[]){if(!this.initialization)this.sites=sites;this.initialization??=this.session.initialize(this.lifetime.signal).then(()=>{this.session.flushLogs();this.resolveStartup()},error=>{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}failStartup(error){if(this.initialization)return;this.initialization=this.startup;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)}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)}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();if(sessions.get(this.config)===this)sessions.delete(this.config)}})();return this.closing}};export{ModSession,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{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-LIIMQ4DI.js";import{scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments}from"./chunk-LO76B6GW.js";import{getAutoMemoryRoot,getUserAutoMemoryRoot}from"./chunk-KVA6DHHF.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import path from"node:path";var debugLogger=createDebugLogger("AUTO_MEMORY_REMEMBER");function buildManagedRememberPrompt(fact,projectRoot,options={}){const trimmed=fact.trim();const projectDir=projectRoot?getAutoMemoryRoot(projectRoot):void 0;const userDir=getUserAutoMemoryRoot();const dirHint=projectDir===void 0?"":options.scope==="project"?` Store this memory only in PROJECT memory at \`${projectDir}\`. This explicit project target overrides the memory type's default destination; do not read or write USER memory at \`${userDir}\`.`:options.scope==="user"?` Store this memory only in USER memory at \`${userDir}\`. This explicit user target overrides the memory type's default destination; do not read or write PROJECT memory at \`${projectDir}\`.`:` Choose the destination directory by the type's \`<scope>\`: USER memory at \`${userDir}\` for cross-project facts, PROJECT memory at \`${projectDir}\` for this-project-only facts.`;const content=options.wrapUserContent?`<user-content>
3
+ import{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-LZNBHBAJ.js";import{scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments}from"./chunk-LO76B6GW.js";import{getAutoMemoryRoot,getUserAutoMemoryRoot}from"./chunk-KVA6DHHF.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import path from"node:path";var debugLogger=createDebugLogger("AUTO_MEMORY_REMEMBER");function buildManagedRememberPrompt(fact,projectRoot,options={}){const trimmed=fact.trim();const projectDir=projectRoot?getAutoMemoryRoot(projectRoot):void 0;const userDir=getUserAutoMemoryRoot();const dirHint=projectDir===void 0?"":options.scope==="project"?` Store this memory only in PROJECT memory at \`${projectDir}\`. This explicit project target overrides the memory type's default destination; do not read or write USER memory at \`${userDir}\`.`:options.scope==="user"?` Store this memory only in USER memory at \`${userDir}\`. This explicit user target overrides the memory type's default destination; do not read or write PROJECT memory at \`${projectDir}\`.`:` Choose the destination directory by the type's \`<scope>\`: USER memory at \`${userDir}\` for cross-project facts, PROJECT memory at \`${projectDir}\` for this-project-only facts.`;const content=options.wrapUserContent?`<user-content>
4
4
  ${trimmed}
5
5
  </user-content>`:trimmed;return`Please save the following to your memory system.${dirHint} Choose the most appropriate memory type (user, feedback, project, or reference) based on the content:
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-LIIMQ4DI.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-TLROJH6O.js";import{getMemoryBaseDir}from"./chunk-KVA6DHHF.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-5DTFN37U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
3
+ import{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-LZNBHBAJ.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-TLROJH6O.js";import{getMemoryBaseDir}from"./chunk-KVA6DHHF.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-5DTFN37U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team