@qwen-code/qwen-code 0.25.2-preview.1 → 0.25.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/chunks/{MaxSizedBox-CF4NN4Y7.js → MaxSizedBox-CGJP7S5S.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-Q23KTB6U.js → StandaloneSessionPicker-H6NONKPP.js} +1 -1
  3. package/chunks/{acp-subagent-executor-LXOLDTFY.js → acp-subagent-executor-7OCKCTA5.js} +1 -1
  4. package/chunks/{acpAgent-QRKZVQAG.js → acpAgent-VCKTBLFO.js} +3 -3
  5. package/chunks/{advisor-VZZJU7BR.js → advisor-UQJ45FLG.js} +1 -1
  6. package/chunks/{agent-LP66VBC4.js → agent-KMSCVRSG.js} +1 -1
  7. package/chunks/{agent-headless-W5P4KPX4.js → agent-headless-3FWQ5QNO.js} +1 -1
  8. package/chunks/{agent-host-client-OW4HBXRL.js → agent-host-client-PXIIFCCS.js} +1 -1
  9. package/chunks/{agent-host-connections-D7IC6WWL.js → agent-host-connections-QUYGQNJX.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-6I25Q3Y6.js → anthropicContentGenerator-MDETV5LU.js} +1 -1
  11. package/chunks/{batch-7E5KJ625.js → batch-RQO2HWFV.js} +1 -1
  12. package/chunks/{bridge-BITC2AVN.js → bridge-OA3GEU2I.js} +1 -1
  13. package/chunks/{channel-settings-store-VAVG6ONF.js → channel-settings-store-YN23NP2H.js} +1 -1
  14. package/chunks/{chunk-4NCTKE4Z.js → chunk-2PQ5ZRTI.js} +1 -1
  15. package/chunks/{chunk-OJHTHXBC.js → chunk-32UFT5HU.js} +1 -1
  16. package/chunks/{chunk-2HJZ3OYW.js → chunk-3C34EMBZ.js} +1 -1
  17. package/chunks/{chunk-UXFLNZNB.js → chunk-3FPPMGVC.js} +1 -1
  18. package/chunks/{chunk-74YXI5IJ.js → chunk-445NIH5T.js} +1 -1
  19. package/chunks/{chunk-MXXYBMBZ.js → chunk-45EKBDFD.js} +1 -1
  20. package/chunks/{chunk-JV5FCFG4.js → chunk-4WFWZWR3.js} +1 -1
  21. package/chunks/{chunk-AAOAX46J.js → chunk-56NX3ASC.js} +1 -1
  22. package/chunks/{chunk-IBS4PHD2.js → chunk-5FY6TL3Z.js} +1 -1
  23. package/chunks/{chunk-UGI3XPRM.js → chunk-5GJPVNHI.js} +1 -1
  24. package/chunks/{chunk-7BZGY7AH.js → chunk-5XAVUYY6.js} +6 -6
  25. package/chunks/{chunk-V3WNU4F5.js → chunk-655XEN5H.js} +1 -1
  26. package/chunks/{chunk-APX7ODYT.js → chunk-6PHAGUA6.js} +1 -1
  27. package/chunks/{chunk-CD6C4OHZ.js → chunk-7YX6LW5H.js} +1 -1
  28. package/chunks/{chunk-C2NFZSGI.js → chunk-AAVRYR5T.js} +1 -1
  29. package/chunks/{chunk-EO35BRIG.js → chunk-ANUAITTH.js} +1 -1
  30. package/chunks/{chunk-CNQ6AOFN.js → chunk-AZ5GFEKG.js} +1 -1
  31. package/chunks/{chunk-KAEW65QP.js → chunk-B5XDGUAK.js} +1 -1
  32. package/chunks/{chunk-X6QHNKUW.js → chunk-BCNBZOGV.js} +1 -1
  33. package/chunks/{chunk-W5DIWPQB.js → chunk-BDXWLZJD.js} +1 -1
  34. package/chunks/{chunk-ZASVUARY.js → chunk-BPX4A433.js} +1 -1
  35. package/chunks/{chunk-CDSI44GJ.js → chunk-BUI6W6CU.js} +1 -1
  36. package/chunks/{chunk-ZEYCGUHI.js → chunk-BVARURDD.js} +1 -1
  37. package/chunks/{chunk-PZ5UPKIG.js → chunk-BW5CHWEJ.js} +2 -2
  38. package/chunks/{chunk-7TUP75C2.js → chunk-C4DSH4A3.js} +1 -1
  39. package/chunks/{chunk-R4KMBENY.js → chunk-CCBWBPJL.js} +1 -1
  40. package/chunks/{chunk-TU6DWKVI.js → chunk-CKJ3OUIV.js} +2 -2
  41. package/chunks/{chunk-SG5P4CK4.js → chunk-CRZ7QRFB.js} +1 -1
  42. package/chunks/{chunk-UYFL7K4Z.js → chunk-CTEBIP2S.js} +1 -1
  43. package/chunks/{chunk-WSIDVWGO.js → chunk-DBOWUORN.js} +1 -1
  44. package/chunks/{chunk-NAHKSVYI.js → chunk-DPBXGGQX.js} +1 -1
  45. package/chunks/{chunk-BMOJDKDZ.js → chunk-DSSSLNXD.js} +3 -3
  46. package/chunks/{chunk-FP2RLPWJ.js → chunk-EKGFFEH4.js} +1 -1
  47. package/chunks/{chunk-L7W3J427.js → chunk-EMEQR2LX.js} +1 -1
  48. package/chunks/{chunk-YRYMLJAC.js → chunk-ENUYA7BO.js} +1 -1
  49. package/chunks/{chunk-4CWBH6LP.js → chunk-EORORGZC.js} +1 -1
  50. package/chunks/{chunk-RBH3BOVF.js → chunk-EUK64V6Z.js} +1 -1
  51. package/chunks/{chunk-AII4DN7M.js → chunk-FBV4LUUL.js} +1 -1
  52. package/chunks/{chunk-YVEPPENZ.js → chunk-FFLFTXO7.js} +1 -1
  53. package/chunks/{chunk-2HSFO66N.js → chunk-FHXH3GSI.js} +1 -1
  54. package/chunks/{chunk-RH6PMH32.js → chunk-FVBDVZD7.js} +1 -1
  55. package/chunks/{chunk-Y2HLDUZG.js → chunk-I2D2ZUKF.js} +1 -1
  56. package/chunks/{chunk-6PUZWUMQ.js → chunk-I3FZ733S.js} +1 -1
  57. package/chunks/{chunk-GG7RNHZW.js → chunk-IFAUFERF.js} +5 -5
  58. package/chunks/{chunk-JQ7BCB3L.js → chunk-IYFUH3JB.js} +1 -1
  59. package/chunks/{chunk-VAMQAYF3.js → chunk-JB5I5QAD.js} +1 -1
  60. package/chunks/{chunk-Z3UZTCKY.js → chunk-JD3QDS7D.js} +1 -1
  61. package/chunks/{chunk-TFVPY43T.js → chunk-JG2UNQOW.js} +1 -1
  62. package/chunks/{chunk-E4MRBL4O.js → chunk-JSXHTTFE.js} +1 -1
  63. package/chunks/{chunk-QTYA6TES.js → chunk-LJLS3MDJ.js} +1 -1
  64. package/chunks/{chunk-RZISIEQL.js → chunk-MEIW5WVJ.js} +1 -1
  65. package/chunks/{chunk-ZD4U3GR4.js → chunk-MGL36H3B.js} +1 -1
  66. package/chunks/{chunk-HXA3X4PB.js → chunk-MJUFVFH3.js} +1 -1
  67. package/chunks/{chunk-SYIDPXVT.js → chunk-MSR6LYHS.js} +1 -1
  68. package/chunks/{chunk-4MJ67O5W.js → chunk-MTXJRB7G.js} +2 -2
  69. package/chunks/{chunk-F5P3BWS7.js → chunk-MXFBSMIM.js} +1 -1
  70. package/chunks/{chunk-W6TNBCKX.js → chunk-MYHJ4WUH.js} +1 -1
  71. package/chunks/{chunk-CWU5NJOB.js → chunk-NHXKNS7F.js} +1 -1
  72. package/chunks/{chunk-6OIJIF6G.js → chunk-NT74NPQT.js} +1 -1
  73. package/chunks/{chunk-O47FCWNF.js → chunk-NWXW4UNC.js} +1 -1
  74. package/chunks/{chunk-JASL4RZR.js → chunk-O77LM4EW.js} +1 -1
  75. package/chunks/{chunk-ZDNTENP2.js → chunk-OB7T2MDO.js} +1 -1
  76. package/chunks/{chunk-L7WFW57T.js → chunk-PODFLAH7.js} +1 -1
  77. package/chunks/{chunk-R3ZMQ7WR.js → chunk-Q2G675WT.js} +1 -1
  78. package/chunks/{chunk-H3QROVUO.js → chunk-QT27SK62.js} +1 -1
  79. package/chunks/{chunk-UELAXFT7.js → chunk-QZPNBV4F.js} +1 -1
  80. package/chunks/{chunk-B3L4LODR.js → chunk-RV54BGL2.js} +1 -1
  81. package/chunks/{chunk-KLXL3FSI.js → chunk-SFETIBPP.js} +1 -1
  82. package/chunks/{chunk-F3YGAXZ5.js → chunk-SGKINIQB.js} +1 -1
  83. package/chunks/{chunk-MBPT3YYO.js → chunk-SHJNP7OV.js} +1 -1
  84. package/chunks/{chunk-U3YSYIQE.js → chunk-SPFRORFN.js} +1 -1
  85. package/chunks/{chunk-S3B4TZVJ.js → chunk-SPLINFM7.js} +1 -1
  86. package/chunks/{chunk-ORIS5AVH.js → chunk-SYO5FPHL.js} +1 -1
  87. package/chunks/{chunk-AGHGPOH6.js → chunk-TEE4MM5S.js} +1 -1
  88. package/chunks/{chunk-WHF3HYZI.js → chunk-TPZTO4K3.js} +1 -1
  89. package/chunks/{chunk-KJO757RN.js → chunk-UY2CSL5W.js} +1 -1
  90. package/chunks/{chunk-VCTZRPKP.js → chunk-W7QYXFWW.js} +1 -1
  91. package/chunks/{chunk-T3ECMT6I.js → chunk-WQOZJ6V7.js} +2 -2
  92. package/chunks/{chunk-INEI2ZW2.js → chunk-WZK7RC36.js} +1 -1
  93. package/chunks/{chunk-Y5JLH3SN.js → chunk-X22435IN.js} +4 -4
  94. package/chunks/{chunk-WHNAY3QQ.js → chunk-X2KF6AUQ.js} +1 -1
  95. package/chunks/{chunk-MUEIZGTI.js → chunk-YHPHQX6M.js} +1 -1
  96. package/chunks/{chunk-5OOO3YIH.js → chunk-YL7QMYOX.js} +1 -1
  97. package/chunks/{chunk-43E3XC2W.js → chunk-YQEOEO5V.js} +1 -1
  98. package/chunks/{chunk-624P32LD.js → chunk-YZ374XTK.js} +1 -1
  99. package/chunks/{codex-subagent-executor-2MPLWNLD.js → codex-subagent-executor-MC3QB2AN.js} +1 -1
  100. package/chunks/{config-utils-MJEEBLQW.js → config-utils-FYT7PUIC.js} +1 -1
  101. package/chunks/{contextCommand-BP566QVE.js → contextCommand-DXMSMSR7.js} +1 -1
  102. package/chunks/{core-runtime-BOAIFYAZ.js → core-runtime-ZLB6QZ3Z.js} +1 -1
  103. package/chunks/{create-sub-session-HJVK7AXV.js → create-sub-session-YUI3G5AF.js} +1 -1
  104. package/chunks/{daemon-git-worktree-guard-KA2Y6FHL.js → daemon-git-worktree-guard-5PYZMC6T.js} +1 -1
  105. package/chunks/{daemon-status-provider-JGR5JT2T.js → daemon-status-provider-GC567FVE.js} +1 -1
  106. package/chunks/{daemon-trust-policy-EP4DHXOW.js → daemon-trust-policy-LLD2UMPF.js} +1 -1
  107. package/chunks/{daemon-trust-policy-monitor-W3VZRKOK.js → daemon-trust-policy-monitor-MRMB2CRJ.js} +1 -1
  108. package/chunks/{deferred-core-runtime-Q3JH7XDL.js → deferred-core-runtime-4HLTINJ6.js} +1 -1
  109. package/chunks/{edit-S7DCBMAL.js → edit-CZ6FEXDU.js} +1 -1
  110. package/chunks/{enterPlanMode-UX7B6KWX.js → enterPlanMode-O3CJ3I2J.js} +1 -1
  111. package/chunks/{environment-ZBW6HDG3.js → environment-OJWH4FYL.js} +1 -1
  112. package/chunks/{errors-7ZRLUHEB.js → errors-NWKSQVL3.js} +1 -1
  113. package/chunks/{execution-tool-R244Q3GW.js → execution-tool-7UCADALN.js} +1 -1
  114. package/chunks/{execution-worker-JR44JTC4.js → execution-worker-LWHQMPBV.js} +1 -1
  115. package/chunks/{exitPlanMode-2PTTZXGO.js → exitPlanMode-JDM6ZZWI.js} +1 -1
  116. package/chunks/{fast-path-NQQ42XUR.js → fast-path-4WHPMNMD.js} +1 -1
  117. package/chunks/{glob-4JP6RQNK.js → glob-LAU4YJ6J.js} +1 -1
  118. package/chunks/{goal-tools-MO7NIH7B.js → goal-tools-AF2FQO3H.js} +1 -1
  119. package/chunks/{handleAutoUpdate-STUVMCIU.js → handleAutoUpdate-WBWK4775.js} +1 -1
  120. package/chunks/{i18n-UTIILRKE.js → i18n-O4Q2KHOA.js} +1 -1
  121. package/chunks/{initializer-YI2WT6LZ.js → initializer-2AH3EKBL.js} +1 -1
  122. package/chunks/{installationInfo-PW2JHHJV.js → installationInfo-77WYXG4W.js} +1 -1
  123. package/chunks/{list-SAOL2OZI.js → list-RAU3ZJQS.js} +1 -1
  124. package/chunks/{llm-LMY62H6Z.js → llm-MJMQ34KB.js} +4 -4
  125. package/chunks/{llm-content-generator-6RPOZ2YR.js → llm-content-generator-MJPR2TWC.js} +1 -1
  126. package/chunks/{loadedSettingsAdapter-RNXWDDE2.js → loadedSettingsAdapter-WRWWNGHZ.js} +1 -1
  127. package/chunks/{local-execution-environment-GIWY2LO6.js → local-execution-environment-VVJ7OYBT.js} +1 -1
  128. package/chunks/{loggingContentGenerator-AOKEDXK6.js → loggingContentGenerator-722BJL7T.js} +1 -1
  129. package/chunks/{manage-memory-WKPWLYDD.js → manage-memory-GN56UQHG.js} +1 -1
  130. package/chunks/{managed-npm-update-LFFWFATA.js → managed-npm-update-5VE662JS.js} +1 -1
  131. package/chunks/{managed-runtime-attestation-worker-IV6ZNIAK.js → managed-runtime-attestation-worker-ASGGZMFM.js} +1 -1
  132. package/chunks/{managed-runtime-session-worker-3NU4FOXD.js → managed-runtime-session-worker-YUSO7WFB.js} +1 -1
  133. package/chunks/{mcp-RDDGN4JK.js → mcp-6D236MEH.js} +1 -1
  134. package/chunks/{model-call-collection-JARTJD6S.js → model-call-collection-UAE2W6VV.js} +1 -1
  135. package/chunks/{model-configuration-7H6PEOLY.js → model-configuration-VHPSBCQI.js} +1 -1
  136. package/chunks/{modelConfigUtils-Q63ZZTXY.js → modelConfigUtils-XKDXYQRJ.js} +1 -1
  137. package/chunks/{monitor-HLO366TQ.js → monitor-JIKXBXDK.js} +1 -1
  138. package/chunks/{nonInteractiveCli-JO5EG6OK.js → nonInteractiveCli-IXTK5V4Q.js} +1 -1
  139. package/chunks/{nonInteractiveToolExecutor-T7AKBX25.js → nonInteractiveToolExecutor-3MSROJV5.js} +1 -1
  140. package/chunks/{notebook-edit-XKULPMG7.js → notebook-edit-VDWBIBMG.js} +1 -1
  141. package/chunks/{omni-H3GFC6KR.js → omni-MEUE65XC.js} +1 -1
  142. package/chunks/{openaiContentGenerator-RT4S6OYR.js → openaiContentGenerator-KNZTYVNK.js} +1 -1
  143. package/chunks/{openaiResponsesContentGenerator-JD4ZBCAL.js → openaiResponsesContentGenerator-G7GRJXES.js} +1 -1
  144. package/chunks/{pidfile-JXCPPGC6.js → pidfile-HMEKKPWO.js} +1 -1
  145. package/chunks/{processUtils-FF7LHGHW.js → processUtils-KHWNT3KU.js} +1 -1
  146. package/chunks/{prompt-terminal-ledger-VLIEJ5BB.js → prompt-terminal-ledger-EY72RU3D.js} +1 -1
  147. package/chunks/{qwenContentGenerator-6SGQI4ES.js → qwenContentGenerator-A7WREYLV.js} +1 -1
  148. package/chunks/{reactive-degrade-2UJPX4AU.js → reactive-degrade-O6WBGQ5X.js} +1 -1
  149. package/chunks/{read-file-27DWTM5N.js → read-file-A4MQWC6T.js} +1 -1
  150. package/chunks/{resumeHistoryUtils-KRF2LD7T.js → resumeHistoryUtils-KNUVMH5J.js} +1 -1
  151. package/chunks/{review-IPFFTVGV.js → review-OC76PLQ4.js} +1 -1
  152. package/chunks/{ripGrep-75QL35XD.js → ripGrep-JR6DHTIW.js} +1 -1
  153. package/chunks/{run-qwen-serve-WW74NSUL.js → run-qwen-serve-NFPGPJJ2.js} +2 -2
  154. package/chunks/{runtime-Z2NIOF6Y.js → runtime-BPHFAZOP.js} +1 -1
  155. package/chunks/{sandboxConfig-WMQAKX7Q.js → sandboxConfig-KXTV3QBG.js} +1 -1
  156. package/chunks/{scheduled-tasks-LMJJ5ZM7.js → scheduled-tasks-2GNFZH4N.js} +1 -1
  157. package/chunks/{scheduler-KHWWXW6H.js → scheduler-CKLZCETX.js} +1 -1
  158. package/chunks/{search-memory-WEO3M674.js → search-memory-ICNU2EJA.js} +1 -1
  159. package/chunks/{send-message-E2EVXDU4.js → send-message-T32PFXX5.js} +1 -1
  160. package/chunks/{serve-E7ZGE7PD.js → serve-O7XBFM36.js} +1 -1
  161. package/chunks/{server-SSHP5IO4.js → server-7H2EGX7C.js} +3 -3
  162. package/chunks/{session-UWUQU3NV.js → session-SO4TKKO3.js} +1 -1
  163. package/chunks/{session-attachments-root-I35OUD7P.js → session-attachments-root-QPBJB3Y2.js} +1 -1
  164. package/chunks/{session-execution-engine-selector-S7HXLYKG.js → session-execution-engine-selector-73JQ7AG6.js} +1 -1
  165. package/chunks/{session-pr-refresh-34FLQB2Z.js → session-pr-refresh-XPDBRBQV.js} +1 -1
  166. package/chunks/{sessionService-BBC2563F.js → sessionService-DDLWVLNC.js} +1 -1
  167. package/chunks/{settings-BXCTAYMU.js → settings-TUEKBNAX.js} +1 -1
  168. package/chunks/{shell-ORZNRZKX.js → shell-SXSN7UYK.js} +1 -1
  169. package/chunks/{skill-3MJ6V2VQ.js → skill-XAYT7HGV.js} +1 -1
  170. package/chunks/{skill-settings-A7TTYJGH.js → skill-settings-X3O75XUN.js} +1 -1
  171. package/chunks/{spawnChannel-UPHPUPIJ.js → spawnChannel-3523LPUW.js} +1 -1
  172. package/chunks/{standalone-update-GGHQ54QB.js → standalone-update-T7AUODLV.js} +1 -1
  173. package/chunks/{start-opentui-ui-O6WMWLGS.js → start-opentui-ui-IKBADQQS.js} +1 -1
  174. package/chunks/{startInteractiveUI-N3ZPR2FK.js → startInteractiveUI-PV2JETB4.js} +1 -1
  175. package/chunks/{team-create-EYLFAQVU.js → team-create-ZKTBFE7Z.js} +1 -1
  176. package/chunks/{team-plan-approval-2WFSX4XE.js → team-plan-approval-SCTAN2HM.js} +1 -1
  177. package/chunks/{terminal-image-renderer-A5HEJZTW.js → terminal-image-renderer-EDBYTK3B.js} +1 -1
  178. package/chunks/{theme-manager-TQHNJSKQ.js → theme-manager-ZLXHLO2Y.js} +1 -1
  179. package/chunks/{tool-call-UBLAA45C.js → tool-call-ULUE3W3P.js} +1 -1
  180. package/chunks/{tool-result-media-53AD3EHK.js → tool-result-media-VXS7QTX7.js} +1 -1
  181. package/chunks/{tool-search-D6PSBDDZ.js → tool-search-VWM6VCVU.js} +1 -1
  182. package/chunks/{total-session-admission-CUMMWSM2.js → total-session-admission-FZDBG232.js} +1 -1
  183. package/chunks/{trustedFolders-TERXKVJ6.js → trustedFolders-VIPEDZNB.js} +1 -1
  184. package/chunks/{update-relaunch-PXCI66U2.js → update-relaunch-N6TNUHQE.js} +1 -1
  185. package/chunks/{updateCheck-2P4ANPL7.js → updateCheck-367IR3FW.js} +1 -1
  186. package/chunks/{upload-config-G2WZG4DM.js → upload-config-5W4WTLML.js} +1 -1
  187. package/chunks/{useAutoAcceptIndicator-H7I7JP34.js → useAutoAcceptIndicator-SGT7EBCJ.js} +1 -1
  188. package/chunks/{validateNonInterActiveAuth-VLRV5LCK.js → validateNonInterActiveAuth-7WEBPZ4S.js} +1 -1
  189. package/chunks/{version-AOKDKXXZ.js → version-3OKRQ6LC.js} +1 -1
  190. package/chunks/{web-fetch-OUJS56AV.js → web-fetch-BV7BK5NT.js} +1 -1
  191. package/chunks/{web-search-3S4ZIGLP.js → web-search-DFQ74G7V.js} +1 -1
  192. package/chunks/{workflow-6W4WB4L5.js → workflow-EXSCHLQK.js} +1 -1
  193. package/chunks/{workspace-agents-7GB2RLY5.js → workspace-agents-HPOPFXKJ.js} +1 -1
  194. package/chunks/{workspace-providers-status-OMD57CUW.js → workspace-providers-status-UQCSR2PB.js} +1 -1
  195. package/chunks/{workspace-registration-store-WKLFVMQ2.js → workspace-registration-store-Q5U4WD5M.js} +1 -1
  196. package/chunks/{workspace-registry-6WJOPYIS.js → workspace-registry-I2O2LXTZ.js} +1 -1
  197. package/chunks/{workspace-runtime-coordinator-XG7G7DG3.js → workspace-runtime-coordinator-MVVDZYYX.js} +1 -1
  198. package/chunks/{workspace-service-YLX46RJM.js → workspace-service-CFJ2EUB7.js} +1 -1
  199. package/chunks/{workspace-skills-status-JZZR7QHN.js → workspace-skills-status-LLNIK3NS.js} +1 -1
  200. package/chunks/{workspace-trust-reconciler-AO3I5KYO.js → workspace-trust-reconciler-VLGJXLCZ.js} +1 -1
  201. package/chunks/{write-file-MGYLC32T.js → write-file-RG7HHIYP.js} +1 -1
  202. package/chunks/{zoom-image-TZ527ASZ.js → zoom-image-AKW6CA4K.js} +1 -1
  203. package/cli.js +2 -2
  204. package/execution-worker.js +1 -1
  205. package/export-transcript-document.js +1 -1
  206. package/package.json +3 -3
  207. package/web-shell/assets/{PierreFilePreview-Cq9imG0c.js → PierreFilePreview-Cij36lF-.js} +1 -1
  208. package/web-shell/assets/{SpreadsheetPreview-Blho0kkO.js → SpreadsheetPreview-kDlHrK21.js} +1 -1
  209. package/web-shell/assets/{WorkspaceFileBrowser-DjeX-ArR.js → WorkspaceFileBrowser-DBXW9l-s.js} +1 -1
  210. package/web-shell/assets/{abnfDiagram-VCTEODGH-mEfLgGao.js → abnfDiagram-VCTEODGH-DBrfOx4O.js} +1 -1
  211. package/web-shell/assets/{agents-route-Bg4_tLdL.js → agents-route-6E_3XRjk.js} +1 -1
  212. package/web-shell/assets/{arc-DEVpMJqB.js → arc-RwrvKU6y.js} +1 -1
  213. package/web-shell/assets/{architectureDiagram-5GKGNRK7-CGhqKvd1.js → architectureDiagram-5GKGNRK7-B2_hfNn6.js} +1 -1
  214. package/web-shell/assets/{blockDiagram-NRAW4CY4-DxpWdCdl.js → blockDiagram-NRAW4CY4-C755qTFO.js} +1 -1
  215. package/web-shell/assets/{c4Diagram-UCG6FXSJ-CE1W0_yu.js → c4Diagram-UCG6FXSJ-CARC2uHQ.js} +1 -1
  216. package/web-shell/assets/channel-U9JRrjem.js +1 -0
  217. package/web-shell/assets/{chunk-2Q5K7J3B-ibHTXjoH.js → chunk-2Q5K7J3B-BS1ldEp9.js} +1 -1
  218. package/web-shell/assets/{chunk-5VM5RSS4-BEZ2-gCE.js → chunk-5VM5RSS4-DckOEd3N.js} +1 -1
  219. package/web-shell/assets/{chunk-F27PBJKO-CKyPZ7Jh.js → chunk-F27PBJKO-fZstOLLL.js} +1 -1
  220. package/web-shell/assets/{chunk-G27WJ6UU-WHNRb7iQ.js → chunk-G27WJ6UU-Bf4QkrJ7.js} +1 -1
  221. package/web-shell/assets/{chunk-JWPE2WC7-Dm4G-fLP.js → chunk-JWPE2WC7-uBW51XO_.js} +1 -1
  222. package/web-shell/assets/{chunk-LCL6LL3I-BvTm39E-.js → chunk-LCL6LL3I-D2MYZdE_.js} +1 -1
  223. package/web-shell/assets/{chunk-POPQ4Y6H-C0zAbzIo.js → chunk-POPQ4Y6H-CzTHTST7.js} +1 -1
  224. package/web-shell/assets/{chunk-SVP7TREG-B36K-VPq.js → chunk-SVP7TREG-fL48tjL5.js} +1 -1
  225. package/web-shell/assets/{chunk-XXDRQBXY-D1opdtZ1.js → chunk-XXDRQBXY-R1jjDz-e.js} +1 -1
  226. package/web-shell/assets/classDiagram-DTDB5LWJ-r255RW6f.js +1 -0
  227. package/web-shell/assets/classDiagram-v2-JRS7N3AN-r255RW6f.js +1 -0
  228. package/web-shell/assets/{cose-bilkent-JH36ORCC-S_IO4ZW5.js → cose-bilkent-JH36ORCC-DTK6Alrt.js} +1 -1
  229. package/web-shell/assets/{cynefin-OW5HDTMX-CGUKfurr.js → cynefin-OW5HDTMX-C1JYDjN4.js} +1 -1
  230. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-BqUpO_VD.js → cynefinDiagram-5FMLGOSQ-C3bR18IM.js} +1 -1
  231. package/web-shell/assets/{dagre-3AP2YEHR-CiKqZpUi.js → dagre-3AP2YEHR-D4oUlW7g.js} +1 -1
  232. package/web-shell/assets/{diagram-S7CK7UJ4-B3CQED4o.js → diagram-S7CK7UJ4-m-a-vk_2.js} +1 -1
  233. package/web-shell/assets/{diagram-UQ7AKVKN-BewunX5H.js → diagram-UQ7AKVKN-CVGSVvpJ.js} +1 -1
  234. package/web-shell/assets/{diagram-VSXAHHWV-C5j1hiVn.js → diagram-VSXAHHWV-DcLovKfd.js} +1 -1
  235. package/web-shell/assets/{diagram-VX7I27RA-CWDIIA61.js → diagram-VX7I27RA-DAwY09qQ.js} +1 -1
  236. package/web-shell/assets/{diagram-Z3DM3KII-COa1V8UD.js → diagram-Z3DM3KII-D4BWV8Yb.js} +1 -1
  237. package/web-shell/assets/{ebnfDiagram-PWID7BFC-CP33EIO8.js → ebnfDiagram-PWID7BFC-AhqQLlAR.js} +1 -1
  238. package/web-shell/assets/{erDiagram-SSCWMZ5O-V2pL2JAp.js → erDiagram-SSCWMZ5O-DcIpsPuK.js} +1 -1
  239. package/web-shell/assets/{flowDiagram-A5DVABFB-CF-YQlR_.js → flowDiagram-A5DVABFB-Cdu3v56D.js} +1 -1
  240. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-TXUid-Q2.js → ganttDiagram-EL5Y4UJY-D8o98Muo.js} +1 -1
  241. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-QNcIYsgn.js → gitGraphDiagram-WWUBYQGX-fIAd56jC.js} +1 -1
  242. package/web-shell/assets/{index-CKa6aZMZ.js → index-CJmvuO8Q.js} +1 -1
  243. package/web-shell/assets/{index-N9F4X44H.js → index-DSh5Yfsf.js} +5 -5
  244. package/web-shell/assets/{infoDiagram-RXCK75RN-Dn1biwuc.js → infoDiagram-RXCK75RN-dPnP0Koe.js} +1 -1
  245. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-iBYO7WCt.js → ishikawaDiagram-5VMMS53U-f9Oq8YH7.js} +1 -1
  246. package/web-shell/assets/{journeyDiagram-EYS64GPL-D98LzO4k.js → journeyDiagram-EYS64GPL-CqwSlUQ1.js} +1 -1
  247. package/web-shell/assets/{kanban-definition-3QL26DDD-lQMIgDSM.js → kanban-definition-3QL26DDD-Bh_KTp2S.js} +1 -1
  248. package/web-shell/assets/{layout-BgOy6tFo.js → layout-0e-hGnuM.js} +1 -1
  249. package/web-shell/assets/{linear-En8RXsBs.js → linear-BtxWFISv.js} +1 -1
  250. package/web-shell/assets/{mermaid.core-BneKXyZr.js → mermaid.core-Dik4l-jM.js} +6 -6
  251. package/web-shell/assets/{mindmap-definition-FBJOCRG2-NkP_9BC4.js → mindmap-definition-FBJOCRG2-B7gext3e.js} +1 -1
  252. package/web-shell/assets/{pegDiagram-XKGWAZYB-B0ie-nkt.js → pegDiagram-XKGWAZYB-BfyKzGY0.js} +1 -1
  253. package/web-shell/assets/{pieDiagram-E7YTZNPT-Qa86cFZc.js → pieDiagram-E7YTZNPT-vfeVyHgh.js} +1 -1
  254. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-CkjUzR0e.js → quadrantDiagram-AXDQQJYC-DGAZmngq.js} +1 -1
  255. package/web-shell/assets/{railroadDiagram-O6MQD6OU-mN7KpgJG.js → railroadDiagram-O6MQD6OU-Dgxiy8W5.js} +1 -1
  256. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-Bmn2z6x2.js → requirementDiagram-EFPCY7ZU-D7TFokdR.js} +1 -1
  257. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CYWnwpoW.js → sankeyDiagram-P5KCCOFB-BZU_UYd-.js} +1 -1
  258. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BFyWlR1P.js → sequenceDiagram-WJ2MYXX4-Bz94qtvq.js} +1 -1
  259. package/web-shell/assets/{sizeCapture-X5ZJPWSS-BwCPrn2w.js → sizeCapture-X5ZJPWSS-DVlzIShY.js} +1 -1
  260. package/web-shell/assets/{stateDiagram-HBIQ2CUA-oqL3E0Ws.js → stateDiagram-HBIQ2CUA-CE9Il33j.js} +1 -1
  261. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BVL1rIGD.js +1 -0
  262. package/web-shell/assets/{swimlanes-XN3QIQJK-C3FAVL8g.js → swimlanes-XN3QIQJK-Cr2CyF9L.js} +1 -1
  263. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-BeWJAUmf.js +8 -0
  264. package/web-shell/assets/{timeline-definition-24CTP7MA-BdwxFsPJ.js → timeline-definition-24CTP7MA-DWbRlUDe.js} +1 -1
  265. package/web-shell/assets/{vennDiagram-4TSXK5OY-j_G2AbSj.js → vennDiagram-4TSXK5OY-Bp5BiaRL.js} +1 -1
  266. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-Dy_fHHBq.js → wardleyDiagram-VM6X3IG4-DoQIUrT8.js} +1 -1
  267. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-CnLgG50x.js → xychartDiagram-S5SC5T6Z-BTO308Vv.js} +1 -1
  268. package/web-shell/index.html +1 -1
  269. package/web-shell/sw.js +1 -1
  270. package/web-shell/assets/channel-CHCXOu89.js +0 -1
  271. package/web-shell/assets/classDiagram-DTDB5LWJ-DXIqcod_.js +0 -1
  272. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DXIqcod_.js +0 -1
  273. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-Cmho6gw2.js +0 -1
  274. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-D9Sfkn7b.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{reportChatRecordingFailureToAdapter}from"./chunk-ULEYDXOX.js";import{StreamJsonOutputAdapter}from"./chunk-JQ7BCB3L.js";import{fireSessionDeleteHook}from"./chunk-F64AWDLW.js";import{MAX_SUGGESTIONS_TO_SHOW,SESSION_MENTION_PREFIX,buildMcpResourceRef,buildMcpServerRef,buildSessionRef,getExtensionSuggestions,matchMcpServerPrefix,normalizeDescription}from"./chunk-TU6DWKVI.js";import{getTranslatedSourceDisplayMap}from"./chunk-BMOJDKDZ.js";import{BaseSelectionList,Colors,RadioButtonSelect,RowMouseController,TextInput,dist_default,findElementAtMouseEvent,useMouseEvents,useTerminalSize}from"./chunk-SYIDPXVT.js";import{useKeypress}from"./chunk-KNGCIWWH.js";import{ICON,SHELL_COMMAND_NAME}from"./chunk-CDSI44GJ.js";import{theme}from"./chunk-OWCYARAS.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{Box_default,Text}from"./chunk-XZQH4UBR.js";import{themeManager}from"./chunk-W3YCOEIP.js";import{require_react}from"./chunk-5QKDV4CD.js";import{appEvents}from"./chunk-Y5JLH3SN.js";import{getCachedStringWidth,toCodePoints}from"./chunk-MOH67CDU.js";import{AGENT_HOST_SESSION_SOURCE_TYPE,AGENT_SESSION_SOURCE_TYPE}from"./chunk-DHYCGKLG.js";import{createLoadedSettingsAdapter}from"./chunk-4CWBH6LP.js";import{loadMcpApprovals}from"./chunk-C2NFZSGI.js";import{SettingScope,settingExistsInScope}from"./chunk-JV5FCFG4.js";import{getCurrentLanguage,t,ta}from"./chunk-4IE26CIN.js";import{FileSearchFactory,INITIAL_FOLLOWUP_STATE,Logger,createFollowupController,discoverProviderModels,generateSessionRecap,preserveModelProviderPlaceholders}from"./chunk-B3L4LODR.js";import{SessionService,allowEditorTypeInSandbox,checkHasEditorType,compactToolResultDisplayForHistory,executeRuntimeShell,isGatedMcpScope}from"./chunk-GG7RNHZW.js";import{TERMINAL_CSI_REGEX,TERMINAL_OSC_REGEX,TERMINAL_SHIFT_DCS_REGEX,stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{resolveBranchName,watchRepoBranch}from"./chunk-LLX4BCWK.js";import{isSignalTermination}from"./chunk-AH64K6DM.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{qwenOAuth2Events,sanitizeForOsc}from"./chunk-I5TFTKQS.js";import{applyProviderInstallPlan,buildInstallPlan,getDefaultBaseUrlForProtocol,getDefaultModelIds,getModelsForProviderProtocol,resolveBaseUrl,shouldShowStep}from"./chunk-KAEW65QP.js";import{AuthEvent,PromptSuggestionEvent,logAuth,logPromptSuggestion}from"./chunk-KBPIYGHG.js";import{REASONING_EFFORT_TIERS}from"./chunk-TAAJ7TDB.js";import{isBinary}from"./chunk-4YLXNRRH.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{escapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var DEFAULT_WINDOW_TITLE="qwen";var MULTIPLEXER_ENV_KEYS=["TMUX","STY","ZELLIJ","DVTM"];function sanitizeWindowTitle(title){return sanitizeForOsc(title)}__name(sanitizeWindowTitle,"sanitizeWindowTitle");function computeWindowTitle(folderName){return sanitizeWindowTitle(process.env["CLI_TITLE"]||`Qwen - ${folderName||DEFAULT_WINDOW_TITLE}`)}__name(computeWindowTitle,"computeWindowTitle");function writeTerminalTitle(write,title){const clean=sanitizeWindowTitle(title);if(process.platform==="win32"){process.title=clean}const inMultiplexer=MULTIPLEXER_ENV_KEYS.some(k=>!!process.env[k]);if(clean.length===0){if(inMultiplexer){write("\x1B]2;\x07")}else{write("\x1B]0;\x07\x1B]2;\x07")}return}if(inMultiplexer){write(`\x1B]2;${clean}\x07`)}else{const padded=clean.substring(0,80).padEnd(80," ");write(`\x1B]0;${padded}\x07\x1B]2;${padded}\x07`)}}__name(writeTerminalTitle,"writeTerminalTitle");function formatSessionWindowTitle(sessionName,folderName,statusPrefix=""){const base=sessionName?sanitizeWindowTitle(sessionName):computeWindowTitle(folderName);return sanitizeWindowTitle(statusPrefix+base)}__name(formatSessionWindowTitle,"formatSessionWindowTitle");function titleStatusPrefix(streamingState){switch(streamingState){case"responding":return`${ICON.CIRCLE_LEFT_HALF} `;case"waiting_for_confirmation":return`${ICON.SPARKLE} `;default:return""}}__name(titleStatusPrefix,"titleStatusPrefix");init_esbuild_shims();var import_react=__toESM(require_react(),1);var useLogger=__name((storage,sessionId)=>{const[logger,setLogger]=(0,import_react.useState)(null);(0,import_react.useEffect)(()=>{if(!sessionId){return}let cancelled=false;const newLogger=new Logger(sessionId,storage);newLogger.initialize().then(()=>{if(!cancelled){setLogger(newLogger)}}).catch(()=>{});return()=>{cancelled=true}},[storage,sessionId]);return logger},"useLogger");init_esbuild_shims();var import_react2=__toESM(require_react(),1);var DEFAULT_AWAY_THRESHOLD_MINUTES=5;var MIN_USER_MESSAGES_TO_FIRE=3;var MIN_USER_MESSAGES_SINCE_LAST_RECAP=2;function shouldFireRecap(history){let userMessageCount=0;let lastRecapIndex=-1;for(let i=0;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userMessageCount++;if(item.type==="away_recap")lastRecapIndex=i}if(userMessageCount<MIN_USER_MESSAGES_TO_FIRE)return false;if(lastRecapIndex===-1)return true;let userSinceLast=0;for(let i=lastRecapIndex+1;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userSinceLast++}return userSinceLast>=MIN_USER_MESSAGES_SINCE_LAST_RECAP}__name(shouldFireRecap,"shouldFireRecap");function useAwaySummary(options){const{enabled,config,isFocused,isIdle,addItem,history,awayThresholdMinutes}=options;const blurredAtRef=(0,import_react2.useRef)(null);const recapPendingRef=(0,import_react2.useRef)(false);const inFlightRef=(0,import_react2.useRef)(null);const isIdleRef=(0,import_react2.useRef)(isIdle);isIdleRef.current=isIdle;const historyRef=(0,import_react2.useRef)(history);historyRef.current=history;const thresholdMs=(awayThresholdMinutes&&awayThresholdMinutes>0?awayThresholdMinutes:DEFAULT_AWAY_THRESHOLD_MINUTES)*60*1e3;(0,import_react2.useEffect)(()=>{if(!enabled||!config){inFlightRef.current?.abort();inFlightRef.current=null;blurredAtRef.current=null;return}if(!isFocused){if(blurredAtRef.current===null){blurredAtRef.current=Date.now()}return}const blurredAt=blurredAtRef.current;if(blurredAt===null)return;if(Date.now()-blurredAt<thresholdMs){blurredAtRef.current=null;return}if(recapPendingRef.current)return;if(!isIdleRef.current)return;if(!shouldFireRecap(historyRef.current)){blurredAtRef.current=null;return}blurredAtRef.current=null;recapPendingRef.current=true;const controller=new AbortController;inFlightRef.current=controller;void generateSessionRecap(config,controller.signal).then(recap=>{if(controller.signal.aborted||!recap)return;if(!isIdleRef.current)return;const item={type:"away_recap",text:recap};addItem(item,Date.now());try{config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/recap",outputHistoryItems:[{...item}]})}catch{}}).finally(()=>{if(inFlightRef.current===controller){inFlightRef.current=null}recapPendingRef.current=false})},[enabled,config,isFocused,isIdle,addItem,thresholdMs]);(0,import_react2.useEffect)(()=>()=>{inFlightRef.current?.abort()},[])}__name(useAwaySummary,"useAwaySummary");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var BRANCH_POLL_INTERVAL_MS=5e3;var primedBranchNames=new Map;async function primeGitBranchName(cwd){primedBranchNames.set(cwd,await resolveBranchName(cwd))}__name(primeGitBranchName,"primeGitBranchName");function useGitBranchName(cwd){const[branchName,setBranchName]=(0,import_react3.useState)(()=>primedBranchNames.get(cwd));const branchNameRef=(0,import_react3.useRef)(branchName);branchNameRef.current=branchName;(0,import_react3.useEffect)(()=>{let cancelled=false;let dispose;let pollTimer;let refreshGeneration=0;const refresh=__name(async()=>{const generation=++refreshGeneration;const name=await resolveBranchName(cwd);if(!cancelled&&generation===refreshGeneration&&name!==branchNameRef.current){setBranchName(name)}},"refresh");const init=__name(async()=>{await refresh();if(cancelled)return;const disposer=await watchRepoBranch(cwd,()=>{void refresh().catch(()=>{})});if(cancelled){disposer()}else{dispose=disposer}if(!cancelled){pollTimer=setInterval(()=>{void refresh().catch(()=>{})},BRANCH_POLL_INTERVAL_MS);pollTimer.unref?.()}},"init");void init().catch(()=>{});return()=>{cancelled=true;dispose?.();if(pollTimer)clearInterval(pollTimer)}},[cwd]);return branchName}__name(useGitBranchName,"useGitBranchName");init_esbuild_shims();import{createWriteStream,fstatSync,openSync,constants}from"node:fs";init_esbuild_shims();var debugLogger=createDebugLogger("DUAL_OUTPUT");var SUPPORTED_EVENTS=["system","user","assistant","stream_event","result","control_request","control_response"];var DUAL_OUTPUT_PROTOCOL_VERSION=2;var MAX_BUFFERED_BYTES=1024*1024;var DualOutputBridge=class{static{__name(this,"DualOutputBridge")}adapter;stream;sessionId;active=true;shutdownPromise=null;unsubscribeRecordingFailure;constructor(config,target,options={}){this.sessionId=config.getSessionId();if("fd"in target){if(target.fd<=2){throw new Error(`--json-fd ${target.fd}: file descriptors 0 (stdin), 1 (stdout), and 2 (stderr) are reserved. Use fd 3 or higher.`)}try{fstatSync(target.fd)}catch{throw new Error(`--json-fd ${target.fd}: file descriptor is not open. The caller must provide this fd via spawn stdio configuration or shell redirection (e.g., 3>/tmp/events.jsonl).`)}this.stream=createWriteStream("",{fd:target.fd})}else{try{const fd=openSync(target.filePath,constants.O_WRONLY|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(err){const code=err.code;if(code==="ENXIO"){try{const fd=openSync(target.filePath,constants.O_RDWR|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(retryErr){if(retryErr.code==="EACCES"){throw new Error(`--json-file "${target.filePath}": permission denied opening FIFO for read-write. Check read/write permissions on the file and its parent directories, or start a reader before launching Qwen Code.`)}throw retryErr}}else if(code==="ENOENT"){this.stream=createWriteStream(target.filePath,{flags:"w"})}else{throw err}}}this.stream.on("error",err=>{const code=err.code;if(code==="EPIPE"||code==="ERR_STREAM_DESTROYED"){debugLogger.warn("DualOutput: consumer disconnected, disabling")}else if(code==="ERR_SYSTEM_ERROR"){debugLogger.warn("DualOutput: system error on stream, disabling:",err.message)}else{debugLogger.error("DualOutput stream error:",err)}this.active=false});this.adapter=new StreamJsonOutputAdapter(config,true,this.stream);this.unsubscribeRecordingFailure=typeof config.onChatRecordingFailure==="function"?config.onChatRecordingFailure(event=>{this.emitRecordingFailure(event)}):()=>{};try{this.adapter.emitSystemMessage("session_start",{session_id:this.sessionId,cwd:process.cwd(),protocol_version:DUAL_OUTPUT_PROTOCOL_VERSION,version:options.version,supported_events:[...SUPPORTED_EVENTS]})}catch(err){debugLogger.error("DualOutput session_start error:",err);this.active=false}}processEvent(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.processEvent(event)}catch(err){debugLogger.error("DualOutput processEvent error:",err);this.active=false}}startAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.startAssistantMessage()}catch(err){debugLogger.error("DualOutput startAssistantMessage error:",err);this.active=false}}finalizeAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.finalizeAssistantMessage()}catch(err){debugLogger.error("DualOutput finalizeAssistantMessage error:",err);this.active=false}}emitUserMessage(parts){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitUserMessage(parts)}catch(err){debugLogger.error("DualOutput emitUserMessage error:",err);this.active=false}}emitToolResult(request,response){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitToolResult(request,response)}catch(err){debugLogger.error("DualOutput emitToolResult error:",err);this.active=false}}get isConnected(){return this.active}disableIfBufferOverflowed(){if(this.stream.writableLength>MAX_BUFFERED_BYTES){debugLogger.warn("DualOutput: buffered data exceeds limit, disabling (no consumer draining?)");this.active=false;this.stream.destroy()}}emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath=null,permissionSuggestions=null){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath,permissionSuggestions)}catch(err){debugLogger.error("DualOutput emitPermissionRequest error:",err);this.active=false}}emitControlResponse(requestId,allowed){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlResponse(requestId,allowed)}catch(err){debugLogger.error("DualOutput emitControlResponse error:",err);this.active=false}}emitControlError(requestId,message){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlError(requestId,message)}catch(err){debugLogger.error("DualOutput emitControlError error:",err);this.active=false}}emitSystemMessage(subtype,data){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitSystemMessage(subtype,data)}catch(err){debugLogger.error("DualOutput emitSystemMessage error:",err);this.active=false}}emitRecordingFailure(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{reportChatRecordingFailureToAdapter(this.adapter,event)}catch(err){debugLogger.error("DualOutput recording failure output error:",err);this.active=false}}shutdown(){if(this.shutdownPromise)return this.shutdownPromise;this.unsubscribeRecordingFailure();if(this.active){try{this.adapter.emitSystemMessage("session_end",{session_id:this.sessionId})}catch{}}this.active=false;this.shutdownPromise=new Promise(resolve2=>{if(this.stream.closed||this.stream.destroyed){resolve2();return}const cleanup=__name(()=>{this.stream.off("close",onClose);this.stream.off("error",onError)},"cleanup");const onClose=__name(()=>{cleanup();resolve2()},"onClose");const onError=__name(err=>{debugLogger.debug("DualOutput: stream error during shutdown:",err)},"onError");this.stream.once("close",onClose);this.stream.once("error",onError);try{this.stream.end()}catch(err){cleanup();debugLogger.debug("DualOutput: stream end error during shutdown:",err);resolve2()}});return this.shutdownPromise}};init_esbuild_shims();import{createHash}from"node:crypto";import{closeSync,createReadStream,openSync as openSync2,readSync,statSync,unwatchFile,watchFile}from"node:fs";import{createInterface}from"node:readline";var debugLogger2=createDebugLogger("REMOTE_INPUT");var RemoteInputWatcher=class{static{__name(this,"RemoteInputWatcher")}submitFn=null;confirmationHandler=null;queue=[];processing=false;active=true;bytesRead=0;consumedPrefixHash=null;reading=false;filePath;retryTimer=null;pollIntervalMs;constructor(filePath,options){this.filePath=filePath;this.pollIntervalMs=options?.pollIntervalMs??500;this.startWatching()}setSubmitFn(fn){this.submitFn=fn;this.processQueue()}setConfirmationHandler(fn){this.confirmationHandler=fn}notifyIdle(){if(this.queue.length>0&&!this.processing){this.processQueue()}}startWatching(){try{const stat=statSync(this.filePath);this.bytesRead=stat.size;this.consumedPrefixHash=this.hashFilePrefix(this.bytesRead)}catch{this.bytesRead=0;this.consumedPrefixHash=null}watchFile(this.filePath,{interval:this.pollIntervalMs},()=>{if(!this.active)return;this.readNewLines()});debugLogger2.debug(`RemoteInput: watching ${this.filePath}`)}checkForNewInput(){return this.readNewLines()}readNewLines(){if(!this.active||this.reading)return Promise.resolve();let currentSize;try{const stat=statSync(this.filePath);currentSize=stat.size}catch{return Promise.resolve()}if(currentSize<this.bytesRead){debugLogger2.debug("RemoteInput: input file shrank, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}else if(this.hasConsumedPrefixChanged()){debugLogger2.debug("RemoteInput: input file prefix changed, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}if(currentSize<=this.bytesRead)return Promise.resolve();const consumeUntil=this.findLastCompleteRecordEnd(this.bytesRead,currentSize);if(consumeUntil===null){return Promise.resolve()}const nextConsumedPrefixHash=this.hashFilePrefix(consumeUntil);this.reading=true;const stream=createReadStream(this.filePath,{start:this.bytesRead,end:consumeUntil-1,encoding:"utf-8"});const rl=createInterface({input:stream,crlfDelay:Infinity});rl.on("line",line=>{const trimmed=line.trim();if(!trimmed)return;try{const cmd=JSON.parse(trimmed);if(cmd&&cmd.type==="confirmation_response"&&typeof cmd.request_id==="string"&&typeof cmd.allowed==="boolean"){debugLogger2.debug(`RemoteInput: confirmation_response for ${cmd.request_id} (allowed=${cmd.allowed})`);this.confirmationHandler?.(cmd.request_id,cmd.allowed)}else if(cmd&&cmd.type==="submit"&&typeof cmd.text==="string"){debugLogger2.debug(`RemoteInput: queued command: ${cmd.text.slice(0,50)}...`);this.queue.push(cmd)}else{debugLogger2.warn(`RemoteInput: unknown command type: ${String(cmd?.type)}`)}}catch(_err){debugLogger2.warn(`RemoteInput: failed to parse line: ${trimmed}`)}});return new Promise(resolve2=>{rl.on("close",()=>{this.bytesRead=consumeUntil;if(nextConsumedPrefixHash!==null){this.consumedPrefixHash=nextConsumedPrefixHash}this.reading=false;this.processQueue();resolve2()})})}findLastCompleteRecordEnd(start,end){if(end<=start)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const buffer=Buffer.allocUnsafe(Math.min(64*1024,end-start));let remaining=end-start;let position=start;let lastLineBreak=-1;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)break;for(let i=0;i<bytesRead;i++){if(buffer[i]===10){lastLineBreak=position+i}}remaining-=bytesRead;position+=bytesRead}return lastLineBreak>=start?lastLineBreak+1:null}catch(err){debugLogger2.warn("RemoteInput: failed to scan complete records:",err);return null}finally{if(fd!==null){closeSync(fd)}}}hasConsumedPrefixChanged(){if(this.bytesRead===0){return false}if(this.consumedPrefixHash===null){debugLogger2.warn("RemoteInput: missing consumed prefix hash, resetting read offset");return true}const currentHash=this.hashFilePrefix(this.bytesRead);if(currentHash===null){debugLogger2.warn("RemoteInput: failed to hash consumed prefix, resetting read offset");return true}return currentHash!==this.consumedPrefixHash}hashFilePrefix(size){if(size<=0)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const hash=createHash("sha256");const buffer=Buffer.allocUnsafe(Math.min(64*1024,size));let remaining=size;let position=0;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)return null;hash.update(buffer.subarray(0,bytesRead));remaining-=bytesRead;position+=bytesRead}return hash.digest("base64")}catch(err){debugLogger2.warn("RemoteInput: failed to hash file prefix:",err);return null}finally{if(fd!==null){closeSync(fd)}}}async processQueue(){if(this.processing||!this.submitFn||this.queue.length===0)return;this.processing=true;if(this.retryTimer){clearTimeout(this.retryTimer);this.retryTimer=null}try{while(this.queue.length>0&&this.active){if(!this.submitFn)break;const cmd=this.queue[0];debugLogger2.debug(`RemoteInput: submitting: ${cmd.text.slice(0,50)}...`);try{const result=await this.submitFn(cmd.text);if(result===false){debugLogger2.debug("RemoteInput: TUI busy, will retry on idle");this.scheduleRetry();break}this.queue.shift()}catch(err){debugLogger2.error("RemoteInput: submit failed:",err);this.queue.shift()}if(this.queue.length>0){await new Promise(r=>setTimeout(r,500))}}}finally{this.processing=false}}scheduleRetry(){if(this.retryTimer)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null;if(this.queue.length>0&&!this.processing){this.processQueue()}},2e3)}shutdown(){this.active=false;unwatchFile(this.filePath);if(this.retryTimer)clearTimeout(this.retryTimer);this.queue.length=0;debugLogger2.debug("RemoteInput: shut down")}};init_esbuild_shims();var calculatePromptWidths=__name(terminalWidth=>{const widthFraction=.9;const FRAME_PADDING_AND_BORDER=4;const PROMPT_PREFIX_WIDTH=2;const MIN_CONTENT_WIDTH=2;const innerContentWidth=Math.floor(terminalWidth*widthFraction)-FRAME_PADDING_AND_BORDER-PROMPT_PREFIX_WIDTH;const inputWidth=Math.max(MIN_CONTENT_WIDTH,innerContentWidth);const FRAME_OVERHEAD=FRAME_PADDING_AND_BORDER+PROMPT_PREFIX_WIDTH;const containerWidth=inputWidth+FRAME_OVERHEAD;const suggestionsWidth=Math.max(20,Math.floor(terminalWidth*1));return{inputWidth,containerWidth,suggestionsWidth,frameOverhead:FRAME_OVERHEAD}},"calculatePromptWidths");var MAIN_CONTENT_HEIGHT_RESERVATION=2;var STATIC_EXTRA_HEIGHT=3;var clampDialogHeight=__name(height=>height===void 0?void 0:Math.max(1,Math.floor(height)),"clampDialogHeight");var getDialogMaxHeight=__name((terminalHeight,staticExtraHeight)=>Math.max(1,terminalHeight-staticExtraHeight-MAIN_CONTENT_HEIGHT_RESERVATION),"getDialogMaxHeight");init_esbuild_shims();var import_react5=__toESM(require_react(),1);init_esbuild_shims();var import_react4=__toESM(require_react(),1);var useQwenAuth=__name((pendingAuthType,isAuthenticating)=>{const[qwenAuthState,setQwenAuthState]=(0,import_react4.useState)({deviceAuth:null,authStatus:"idle",authMessage:null});const isQwenAuth=pendingAuthType==="qwen-oauth";(0,import_react4.useEffect)(()=>{if(!isQwenAuth||!isAuthenticating){setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null});return}setQwenAuthState(prev=>({...prev,authStatus:"idle"}));const handleDeviceAuth=__name(deviceAuth=>{setQwenAuthState(prev=>({...prev,deviceAuth:{verification_uri:deviceAuth.verification_uri,verification_uri_complete:deviceAuth.verification_uri_complete,user_code:deviceAuth.user_code,expires_in:deviceAuth.expires_in,device_code:deviceAuth.device_code},authStatus:"polling"}))},"handleDeviceAuth");const handleAuthProgress=__name((status,message)=>{setQwenAuthState(prev=>({...prev,authStatus:status,authMessage:message||null}))},"handleAuthProgress");qwenOAuth2Events.on("auth-uri",handleDeviceAuth);qwenOAuth2Events.on("auth-progress",handleAuthProgress);return()=>{qwenOAuth2Events.off("auth-uri",handleDeviceAuth);qwenOAuth2Events.off("auth-progress",handleAuthProgress)}},[isQwenAuth,isAuthenticating]);const cancelQwenAuth=(0,import_react4.useCallback)(()=>{qwenOAuth2Events.emit("auth-cancel");setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null})},[]);return{qwenAuthState,cancelQwenAuth}},"useQwenAuth");function normalizeModelIds(modelIdsInput){return modelIdsInput.split(",").map(id=>id.trim()).filter((id,index,array)=>id.length>0&&array.indexOf(id)===index)}__name(normalizeModelIds,"normalizeModelIds");function maskApiKey(apiKey){const trimmed=apiKey.trim();if(trimmed.length===0)return"(not set)";if(trimmed.length<=6)return"***";return`${trimmed.slice(0,3)}...${trimmed.slice(-4)}`}__name(maskApiKey,"maskApiKey");var useAuthCommand=__name((settings,config,addItem,onAuthChange)=>{const unAuthenticated=config.getAuthType()===void 0;const[authState,setAuthState]=(0,import_react5.useState)(unAuthenticated?"updating":"unauthenticated");const[authError,setAuthError]=(0,import_react5.useState)(null);const[isAuthenticating,setIsAuthenticating]=(0,import_react5.useState)(false);const[isAuthDialogOpen,setIsAuthDialogOpen]=(0,import_react5.useState)(unAuthenticated);const[pendingAuthType,setPendingAuthType]=(0,import_react5.useState)(void 0);const[externalAuthState,setExternalAuthState]=(0,import_react5.useState)(null);const{qwenAuthState,cancelQwenAuth}=useQwenAuth(pendingAuthType,isAuthenticating);const openedViaCommandRef=(0,import_react5.useRef)(false);const onAuthError=(0,import_react5.useCallback)(error=>{setAuthError(error);if(error){setAuthState("updating");setIsAuthDialogOpen(true)}},[setAuthError,setAuthState]);const handleAuthFailure=(0,import_react5.useCallback)((error,protocolForTelemetry)=>{setIsAuthenticating(false);setExternalAuthState(null);const msg=t("Failed to authenticate. Message: {{message}}",{message:getErrorMessage(error)});onAuthError(msg);const effectiveProtocol=protocolForTelemetry??pendingAuthType;if(effectiveProtocol){logAuth(config,new AuthEvent(effectiveProtocol,"manual","error",msg))}},[onAuthError,pendingAuthType,config]);const completeAuthentication=(0,import_react5.useCallback)(()=>{setAuthError(null);setAuthState("authenticated");setPendingAuthType(void 0);setIsAuthDialogOpen(false);setIsAuthenticating(false);onAuthChange?.()},[onAuthChange]);const handleProviderSubmit=(0,import_react5.useCallback)(async(providerConfig,inputs)=>{let protocol=inputs.protocol??providerConfig.protocol;try{setPendingAuthType(protocol);setIsAuthenticating(true);setAuthError(null);const plan=buildInstallPlan(providerConfig,inputs,getModelsForProviderProtocol(settings.merged.modelProviders,inputs.protocol??providerConfig.protocol,settings.merged.providerProtocol),{authType:settings.merged.security?.auth?.selectedType,id:settings.merged.model?.name,baseUrl:settings.merged.model?.baseUrl});protocol=plan.authType;setPendingAuthType(protocol);await applyProviderInstallPlan(plan,{settings:createLoadedSettingsAdapter(settings),reloadModelProviders:__name(mp=>config.reloadModelProvidersConfig(mp),"reloadModelProviders"),syncAuthState:__name((authType,modelId,baseUrl)=>config.syncModelSelection(authType,modelId,baseUrl),"syncAuthState"),refreshAuth:__name(authType=>config.refreshAuth(authType),"refreshAuth")});if(!plan.modelSelection&&!config.getAuthType()){setIsAuthenticating(false);setPendingAuthType(void 0);onAuthError(t("Service models saved. Configure a conversation model to start chatting."));return}completeAuthentication();const feedbackItem={type:"info",text:!plan.modelSelection?t("Service models saved."):t("Successfully configured {{provider}}. Use /model to switch models.",{provider:providerConfig.label})};addItem(feedbackItem,Date.now());if(openedViaCommandRef.current){openedViaCommandRef.current=false;config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/auth",outputHistoryItems:[feedbackItem]})}if(plan.modelSelection)logAuth(config,new AuthEvent(protocol,"manual","success"))}catch(error){handleAuthFailure(error,protocol)}},[settings,config,completeAuthentication,addItem,handleAuthFailure,onAuthError]);const openAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=true;setIsAuthDialogOpen(true)},[]);const closeAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=false;setIsAuthDialogOpen(false);setAuthError(null)},[]);const cancelAuthentication=(0,import_react5.useCallback)(()=>{if(isAuthenticating&&pendingAuthType==="qwen-oauth"){cancelQwenAuth()}if(isAuthenticating&&pendingAuthType){logAuth(config,new AuthEvent(pendingAuthType,"manual","cancelled"))}setIsAuthenticating(false);setExternalAuthState(null);setIsAuthDialogOpen(true);setAuthError(null)},[isAuthenticating,pendingAuthType,cancelQwenAuth,config]);(0,import_react5.useEffect)(()=>{const val=process.env["QWEN_DEFAULT_AUTH_TYPE"];const valid=["qwen-oauth","openai","openai-responses","anthropic","gemini","vertex-ai"];if(val&&!valid.includes(val)){onAuthError(t('Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}',{value:val,validValues:valid.join(", ")}))}},[onAuthError]);const state=(0,import_react5.useMemo)(()=>({authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState}),[authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState]);const actions=(0,import_react5.useMemo)(()=>({setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication}),[setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication]);return{authState,setAuthState,authError,onAuthError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication,state,actions}},"useAuthCommand");init_esbuild_shims();var import_react6=__toESM(require_react(),1);function useDeleteCommand(options){const[isDeleteDialogOpen,setIsDeleteDialogOpen]=(0,import_react6.useState)(false);const openDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(true)},[]);const closeDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(false)},[]);const{config,addItem,logger}=options??{};const isDeletingManyRef=(0,import_react6.useRef)(false);const purgeSessionLogs=(0,import_react6.useCallback)(sessionIds=>{if(sessionIds.length===0)return;void logger?.removeSessionsMessages(sessionIds).catch(error=>{console.error("Failed to purge deleted sessions from log:",error)})},[logger]);const handleDelete=(0,import_react6.useCallback)(async sessionId=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}closeDeleteDialog();if(sessionId===config.getSessionId()){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}try{const sessionService=config.getSessionService();const success=await sessionService.removeSession(sessionId);if(success){purgeSessionLogs([sessionId]);fireSessionDeleteHook(config,sessionId);addItem?.({type:"info",text:t("Session deleted successfully.")},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete session. Session not found.")},Date.now())}}catch(error){console.error("handleDelete failed:",error);addItem?.({type:"error",text:t("Failed to delete session.")},Date.now())}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);const handleDeleteMany=(0,import_react6.useCallback)(async sessionIds=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}try{closeDeleteDialog();isDeletingManyRef.current=true;const currentId=config.getSessionId();const filtered=sessionIds.filter(id=>id!==currentId);if(filtered.length===0){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}if(filtered.length<sessionIds.length){addItem?.({type:"info",text:t("Current active session skipped.")},Date.now())}addItem?.({type:"info",text:t("Deleting {{count}} session(s)...",{count:String(filtered.length)})},Date.now());const sessionService=config.getSessionService();const result=await sessionService.removeSessions(filtered);purgeSessionLogs(result.removed);for(const sessionId of result.removed){fireSessionDeleteHook(config,sessionId)}const removedCount=result.removed.length;const failedIds=[...result.notFound,...result.errors.map(e=>e.sessionId)];const failedCount=failedIds.length;const sampleIds=failedIds.slice(0,3).map(id=>id.slice(0,8)).join(", ");const overflow=failedCount>3?`, +${failedCount-3} more`:"";const firstError=result.errors[0]?.error.message;const reason=firstError?` \u2014 ${firstError}`:"";if(removedCount>0&&failedCount===0){addItem?.({type:"info",text:t("Deleted {{count}} session(s).",{count:String(removedCount)})},Date.now())}else if(removedCount>0&&failedCount>0){addItem?.({type:"error",text:t("Deleted {{removed}} session(s); {{failed}} could not be deleted ({{ids}}{{overflow}}){{reason}}.",{removed:String(removedCount),failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete {{failed}} session(s) ({{ids}}{{overflow}}){{reason}}.",{failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}}catch(error){console.error("handleDeleteMany failed:",error);const detail=error instanceof Error?error.message:String(error);addItem?.({type:"error",text:t("Failed to delete sessions: {{error}}",{error:detail})},Date.now())}finally{isDeletingManyRef.current=false}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);return{isDeleteDialogOpen,openDeleteDialog,closeDeleteDialog,handleDelete,handleDeleteMany}}__name(useDeleteCommand,"useDeleteCommand");init_esbuild_shims();var import_react7=__toESM(require_react(),1);function sourceLabel(scope){switch(scope){case"workspace":return".qwen/settings.json";case"project":default:return".mcp.json"}}__name(sourceLabel,"sourceLabel");function summarize(config){let summary;if(config.httpUrl){summary=`${config.httpUrl} (http)`}else if(config.url){summary=`${config.url} (sse)`}else if(config.command){summary=`${config.command} ${config.args?.join(" ")??""} (stdio)`.replace(/\s+\(/," (")}else{summary="(unknown transport)"}const details=[];if(config.env&&Object.keys(config.env).length>0){details.push(`env: ${Object.keys(config.env).join(", ")}`)}if(config.headers&&Object.keys(config.headers).length>0){details.push(`headers: ${Object.keys(config.headers).join(", ")}`)}return details.length>0?`${summary} [${details.join("; ")}]`:summary}__name(summarize,"summarize");var useMcpApproval=__name(config=>{const[queue,setQueue]=(0,import_react7.useState)([]);const computePending=(0,import_react7.useCallback)(()=>{if(config.getApprovalMode()==="yolo")return[];const servers=config.getMcpServers()??{};const approvals=loadMcpApprovals();const root=config.getWorkingDir();return Object.entries(servers).filter(([,c])=>isGatedMcpScope(c.scope)).filter(([name,c])=>approvals.getState(root,name,c)==="pending").map(([name,c])=>({name,config:c,summary:summarize(c),source:sourceLabel(c.scope)}))},[config]);(0,import_react7.useEffect)(()=>{setQueue(computePending())},[computePending]);(0,import_react7.useEffect)(()=>{const onPendingChanged=__name(()=>{setQueue(computePending())},"onPendingChanged");appEvents.on("mcp-pending-approval-changed",onPendingChanged);return()=>{appEvents.off("mcp-pending-approval-changed",onPendingChanged)}},[computePending]);const reconnect=(0,import_react7.useCallback)(name=>{config.approveMcpServerForSession(name);const registry=config.getToolRegistry();void registry?.discoverToolsForServer?.(name)?.catch?.(error=>{if(process.env["DEBUG"]){console.error(`MCP reconnect failed for ${name}:`,error)}})},[config]);const handleMcpApprovalSelect=(0,import_react7.useCallback)(async choice=>{const approvals=loadMcpApprovals();const root=config.getWorkingDir();const current=queue[0];if(!current){return}if(choice==="approve_all"){for(const server of queue){await approvals.setState(root,server.name,server.config,"approved");reconnect(server.name)}setQueue([]);return}if(choice==="approve"){await approvals.setState(root,current.name,current.config,"approved");reconnect(current.name)}else{await approvals.setState(root,current.name,current.config,"rejected")}setQueue(q=>q.slice(1))},[config,queue,reconnect]);return{isMcpApprovalDialogOpen:queue.length>0,currentMcpApproval:queue[0],pendingMcpApprovals:queue,mcpApprovalRemaining:Math.max(0,queue.length-1),handleMcpApprovalSelect}},"useMcpApproval");init_esbuild_shims();var import_react8=__toESM(require_react(),1);import crypto from"node:crypto";import path from"node:path";import os from"node:os";import fs from"node:fs";var OUTPUT_UPDATE_INTERVAL_MS=1e3;var MAX_OUTPUT_LENGTH=1e4;var debugLogger3=createDebugLogger("SHELL_COMMAND_PROCESSOR");function copyString(value){return value.split("").join("")}__name(copyString,"copyString");function addShellCommandToLlmHistory(llmClient,rawQuery,resultText){const modelContent=resultText.length>MAX_OUTPUT_LENGTH?copyString(resultText.substring(0,MAX_OUTPUT_LENGTH))+"\n... (truncated)":resultText;llmClient.addHistory({role:"user",parts:[{text:`I ran the following shell command:
3
+ import{reportChatRecordingFailureToAdapter}from"./chunk-ULEYDXOX.js";import{StreamJsonOutputAdapter}from"./chunk-IYFUH3JB.js";import{fireSessionDeleteHook}from"./chunk-F64AWDLW.js";import{MAX_SUGGESTIONS_TO_SHOW,SESSION_MENTION_PREFIX,buildMcpResourceRef,buildMcpServerRef,buildSessionRef,getExtensionSuggestions,matchMcpServerPrefix,normalizeDescription}from"./chunk-CKJ3OUIV.js";import{getTranslatedSourceDisplayMap}from"./chunk-DSSSLNXD.js";import{BaseSelectionList,Colors,RadioButtonSelect,RowMouseController,TextInput,dist_default,findElementAtMouseEvent,useMouseEvents,useTerminalSize}from"./chunk-MSR6LYHS.js";import{useKeypress}from"./chunk-KNGCIWWH.js";import{ICON,SHELL_COMMAND_NAME}from"./chunk-BUI6W6CU.js";import{theme}from"./chunk-OWCYARAS.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{Box_default,Text}from"./chunk-XZQH4UBR.js";import{themeManager}from"./chunk-W3YCOEIP.js";import{require_react}from"./chunk-5QKDV4CD.js";import{appEvents}from"./chunk-X22435IN.js";import{getCachedStringWidth,toCodePoints}from"./chunk-MOH67CDU.js";import{AGENT_HOST_SESSION_SOURCE_TYPE,AGENT_SESSION_SOURCE_TYPE}from"./chunk-DHYCGKLG.js";import{createLoadedSettingsAdapter}from"./chunk-EORORGZC.js";import{loadMcpApprovals}from"./chunk-AAVRYR5T.js";import{SettingScope,settingExistsInScope}from"./chunk-4WFWZWR3.js";import{getCurrentLanguage,t,ta}from"./chunk-4IE26CIN.js";import{FileSearchFactory,INITIAL_FOLLOWUP_STATE,Logger,createFollowupController,discoverProviderModels,generateSessionRecap,preserveModelProviderPlaceholders}from"./chunk-RV54BGL2.js";import{SessionService,allowEditorTypeInSandbox,checkHasEditorType,compactToolResultDisplayForHistory,executeRuntimeShell,isGatedMcpScope}from"./chunk-IFAUFERF.js";import{TERMINAL_CSI_REGEX,TERMINAL_OSC_REGEX,TERMINAL_SHIFT_DCS_REGEX,stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{resolveBranchName,watchRepoBranch}from"./chunk-LLX4BCWK.js";import{isSignalTermination}from"./chunk-AH64K6DM.js";import{formatMemoryUsage}from"./chunk-NTRFETZB.js";import{qwenOAuth2Events,sanitizeForOsc}from"./chunk-I5TFTKQS.js";import{applyProviderInstallPlan,buildInstallPlan,getDefaultBaseUrlForProtocol,getDefaultModelIds,getModelsForProviderProtocol,resolveBaseUrl,shouldShowStep}from"./chunk-B5XDGUAK.js";import{AuthEvent,PromptSuggestionEvent,logAuth,logPromptSuggestion}from"./chunk-KBPIYGHG.js";import{REASONING_EFFORT_TIERS}from"./chunk-TAAJ7TDB.js";import{isBinary}from"./chunk-4YLXNRRH.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{escapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var DEFAULT_WINDOW_TITLE="qwen";var MULTIPLEXER_ENV_KEYS=["TMUX","STY","ZELLIJ","DVTM"];function sanitizeWindowTitle(title){return sanitizeForOsc(title)}__name(sanitizeWindowTitle,"sanitizeWindowTitle");function computeWindowTitle(folderName){return sanitizeWindowTitle(process.env["CLI_TITLE"]||`Qwen - ${folderName||DEFAULT_WINDOW_TITLE}`)}__name(computeWindowTitle,"computeWindowTitle");function writeTerminalTitle(write,title){const clean=sanitizeWindowTitle(title);if(process.platform==="win32"){process.title=clean}const inMultiplexer=MULTIPLEXER_ENV_KEYS.some(k=>!!process.env[k]);if(clean.length===0){if(inMultiplexer){write("\x1B]2;\x07")}else{write("\x1B]0;\x07\x1B]2;\x07")}return}if(inMultiplexer){write(`\x1B]2;${clean}\x07`)}else{const padded=clean.substring(0,80).padEnd(80," ");write(`\x1B]0;${padded}\x07\x1B]2;${padded}\x07`)}}__name(writeTerminalTitle,"writeTerminalTitle");function formatSessionWindowTitle(sessionName,folderName,statusPrefix=""){const base=sessionName?sanitizeWindowTitle(sessionName):computeWindowTitle(folderName);return sanitizeWindowTitle(statusPrefix+base)}__name(formatSessionWindowTitle,"formatSessionWindowTitle");function titleStatusPrefix(streamingState){switch(streamingState){case"responding":return`${ICON.CIRCLE_LEFT_HALF} `;case"waiting_for_confirmation":return`${ICON.SPARKLE} `;default:return""}}__name(titleStatusPrefix,"titleStatusPrefix");init_esbuild_shims();var import_react=__toESM(require_react(),1);var useLogger=__name((storage,sessionId)=>{const[logger,setLogger]=(0,import_react.useState)(null);(0,import_react.useEffect)(()=>{if(!sessionId){return}let cancelled=false;const newLogger=new Logger(sessionId,storage);newLogger.initialize().then(()=>{if(!cancelled){setLogger(newLogger)}}).catch(()=>{});return()=>{cancelled=true}},[storage,sessionId]);return logger},"useLogger");init_esbuild_shims();var import_react2=__toESM(require_react(),1);var DEFAULT_AWAY_THRESHOLD_MINUTES=5;var MIN_USER_MESSAGES_TO_FIRE=3;var MIN_USER_MESSAGES_SINCE_LAST_RECAP=2;function shouldFireRecap(history){let userMessageCount=0;let lastRecapIndex=-1;for(let i=0;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userMessageCount++;if(item.type==="away_recap")lastRecapIndex=i}if(userMessageCount<MIN_USER_MESSAGES_TO_FIRE)return false;if(lastRecapIndex===-1)return true;let userSinceLast=0;for(let i=lastRecapIndex+1;i<history.length;i++){const item=history[i];if(item.type==="user"&&item.sentToModel!==false)userSinceLast++}return userSinceLast>=MIN_USER_MESSAGES_SINCE_LAST_RECAP}__name(shouldFireRecap,"shouldFireRecap");function useAwaySummary(options){const{enabled,config,isFocused,isIdle,addItem,history,awayThresholdMinutes}=options;const blurredAtRef=(0,import_react2.useRef)(null);const recapPendingRef=(0,import_react2.useRef)(false);const inFlightRef=(0,import_react2.useRef)(null);const isIdleRef=(0,import_react2.useRef)(isIdle);isIdleRef.current=isIdle;const historyRef=(0,import_react2.useRef)(history);historyRef.current=history;const thresholdMs=(awayThresholdMinutes&&awayThresholdMinutes>0?awayThresholdMinutes:DEFAULT_AWAY_THRESHOLD_MINUTES)*60*1e3;(0,import_react2.useEffect)(()=>{if(!enabled||!config){inFlightRef.current?.abort();inFlightRef.current=null;blurredAtRef.current=null;return}if(!isFocused){if(blurredAtRef.current===null){blurredAtRef.current=Date.now()}return}const blurredAt=blurredAtRef.current;if(blurredAt===null)return;if(Date.now()-blurredAt<thresholdMs){blurredAtRef.current=null;return}if(recapPendingRef.current)return;if(!isIdleRef.current)return;if(!shouldFireRecap(historyRef.current)){blurredAtRef.current=null;return}blurredAtRef.current=null;recapPendingRef.current=true;const controller=new AbortController;inFlightRef.current=controller;void generateSessionRecap(config,controller.signal).then(recap=>{if(controller.signal.aborted||!recap)return;if(!isIdleRef.current)return;const item={type:"away_recap",text:recap};addItem(item,Date.now());try{config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/recap",outputHistoryItems:[{...item}]})}catch{}}).finally(()=>{if(inFlightRef.current===controller){inFlightRef.current=null}recapPendingRef.current=false})},[enabled,config,isFocused,isIdle,addItem,thresholdMs]);(0,import_react2.useEffect)(()=>()=>{inFlightRef.current?.abort()},[])}__name(useAwaySummary,"useAwaySummary");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var BRANCH_POLL_INTERVAL_MS=5e3;var primedBranchNames=new Map;async function primeGitBranchName(cwd){primedBranchNames.set(cwd,await resolveBranchName(cwd))}__name(primeGitBranchName,"primeGitBranchName");function useGitBranchName(cwd){const[branchName,setBranchName]=(0,import_react3.useState)(()=>primedBranchNames.get(cwd));const branchNameRef=(0,import_react3.useRef)(branchName);branchNameRef.current=branchName;(0,import_react3.useEffect)(()=>{let cancelled=false;let dispose;let pollTimer;let refreshGeneration=0;const refresh=__name(async()=>{const generation=++refreshGeneration;const name=await resolveBranchName(cwd);if(!cancelled&&generation===refreshGeneration&&name!==branchNameRef.current){setBranchName(name)}},"refresh");const init=__name(async()=>{await refresh();if(cancelled)return;const disposer=await watchRepoBranch(cwd,()=>{void refresh().catch(()=>{})});if(cancelled){disposer()}else{dispose=disposer}if(!cancelled){pollTimer=setInterval(()=>{void refresh().catch(()=>{})},BRANCH_POLL_INTERVAL_MS);pollTimer.unref?.()}},"init");void init().catch(()=>{});return()=>{cancelled=true;dispose?.();if(pollTimer)clearInterval(pollTimer)}},[cwd]);return branchName}__name(useGitBranchName,"useGitBranchName");init_esbuild_shims();import{createWriteStream,fstatSync,openSync,constants}from"node:fs";init_esbuild_shims();var debugLogger=createDebugLogger("DUAL_OUTPUT");var SUPPORTED_EVENTS=["system","user","assistant","stream_event","result","control_request","control_response"];var DUAL_OUTPUT_PROTOCOL_VERSION=2;var MAX_BUFFERED_BYTES=1024*1024;var DualOutputBridge=class{static{__name(this,"DualOutputBridge")}adapter;stream;sessionId;active=true;shutdownPromise=null;unsubscribeRecordingFailure;constructor(config,target,options={}){this.sessionId=config.getSessionId();if("fd"in target){if(target.fd<=2){throw new Error(`--json-fd ${target.fd}: file descriptors 0 (stdin), 1 (stdout), and 2 (stderr) are reserved. Use fd 3 or higher.`)}try{fstatSync(target.fd)}catch{throw new Error(`--json-fd ${target.fd}: file descriptor is not open. The caller must provide this fd via spawn stdio configuration or shell redirection (e.g., 3>/tmp/events.jsonl).`)}this.stream=createWriteStream("",{fd:target.fd})}else{try{const fd=openSync(target.filePath,constants.O_WRONLY|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(err){const code=err.code;if(code==="ENXIO"){try{const fd=openSync(target.filePath,constants.O_RDWR|constants.O_NONBLOCK);this.stream=createWriteStream("",{fd})}catch(retryErr){if(retryErr.code==="EACCES"){throw new Error(`--json-file "${target.filePath}": permission denied opening FIFO for read-write. Check read/write permissions on the file and its parent directories, or start a reader before launching Qwen Code.`)}throw retryErr}}else if(code==="ENOENT"){this.stream=createWriteStream(target.filePath,{flags:"w"})}else{throw err}}}this.stream.on("error",err=>{const code=err.code;if(code==="EPIPE"||code==="ERR_STREAM_DESTROYED"){debugLogger.warn("DualOutput: consumer disconnected, disabling")}else if(code==="ERR_SYSTEM_ERROR"){debugLogger.warn("DualOutput: system error on stream, disabling:",err.message)}else{debugLogger.error("DualOutput stream error:",err)}this.active=false});this.adapter=new StreamJsonOutputAdapter(config,true,this.stream);this.unsubscribeRecordingFailure=typeof config.onChatRecordingFailure==="function"?config.onChatRecordingFailure(event=>{this.emitRecordingFailure(event)}):()=>{};try{this.adapter.emitSystemMessage("session_start",{session_id:this.sessionId,cwd:process.cwd(),protocol_version:DUAL_OUTPUT_PROTOCOL_VERSION,version:options.version,supported_events:[...SUPPORTED_EVENTS]})}catch(err){debugLogger.error("DualOutput session_start error:",err);this.active=false}}processEvent(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.processEvent(event)}catch(err){debugLogger.error("DualOutput processEvent error:",err);this.active=false}}startAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.startAssistantMessage()}catch(err){debugLogger.error("DualOutput startAssistantMessage error:",err);this.active=false}}finalizeAssistantMessage(){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.finalizeAssistantMessage()}catch(err){debugLogger.error("DualOutput finalizeAssistantMessage error:",err);this.active=false}}emitUserMessage(parts){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitUserMessage(parts)}catch(err){debugLogger.error("DualOutput emitUserMessage error:",err);this.active=false}}emitToolResult(request,response){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitToolResult(request,response)}catch(err){debugLogger.error("DualOutput emitToolResult error:",err);this.active=false}}get isConnected(){return this.active}disableIfBufferOverflowed(){if(this.stream.writableLength>MAX_BUFFERED_BYTES){debugLogger.warn("DualOutput: buffered data exceeds limit, disabling (no consumer draining?)");this.active=false;this.stream.destroy()}}emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath=null,permissionSuggestions=null){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath,permissionSuggestions)}catch(err){debugLogger.error("DualOutput emitPermissionRequest error:",err);this.active=false}}emitControlResponse(requestId,allowed){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlResponse(requestId,allowed)}catch(err){debugLogger.error("DualOutput emitControlResponse error:",err);this.active=false}}emitControlError(requestId,message){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitControlError(requestId,message)}catch(err){debugLogger.error("DualOutput emitControlError error:",err);this.active=false}}emitSystemMessage(subtype,data){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{this.adapter.emitSystemMessage(subtype,data)}catch(err){debugLogger.error("DualOutput emitSystemMessage error:",err);this.active=false}}emitRecordingFailure(event){if(!this.active)return;this.disableIfBufferOverflowed();if(!this.active)return;try{reportChatRecordingFailureToAdapter(this.adapter,event)}catch(err){debugLogger.error("DualOutput recording failure output error:",err);this.active=false}}shutdown(){if(this.shutdownPromise)return this.shutdownPromise;this.unsubscribeRecordingFailure();if(this.active){try{this.adapter.emitSystemMessage("session_end",{session_id:this.sessionId})}catch{}}this.active=false;this.shutdownPromise=new Promise(resolve2=>{if(this.stream.closed||this.stream.destroyed){resolve2();return}const cleanup=__name(()=>{this.stream.off("close",onClose);this.stream.off("error",onError)},"cleanup");const onClose=__name(()=>{cleanup();resolve2()},"onClose");const onError=__name(err=>{debugLogger.debug("DualOutput: stream error during shutdown:",err)},"onError");this.stream.once("close",onClose);this.stream.once("error",onError);try{this.stream.end()}catch(err){cleanup();debugLogger.debug("DualOutput: stream end error during shutdown:",err);resolve2()}});return this.shutdownPromise}};init_esbuild_shims();import{createHash}from"node:crypto";import{closeSync,createReadStream,openSync as openSync2,readSync,statSync,unwatchFile,watchFile}from"node:fs";import{createInterface}from"node:readline";var debugLogger2=createDebugLogger("REMOTE_INPUT");var RemoteInputWatcher=class{static{__name(this,"RemoteInputWatcher")}submitFn=null;confirmationHandler=null;queue=[];processing=false;active=true;bytesRead=0;consumedPrefixHash=null;reading=false;filePath;retryTimer=null;pollIntervalMs;constructor(filePath,options){this.filePath=filePath;this.pollIntervalMs=options?.pollIntervalMs??500;this.startWatching()}setSubmitFn(fn){this.submitFn=fn;this.processQueue()}setConfirmationHandler(fn){this.confirmationHandler=fn}notifyIdle(){if(this.queue.length>0&&!this.processing){this.processQueue()}}startWatching(){try{const stat=statSync(this.filePath);this.bytesRead=stat.size;this.consumedPrefixHash=this.hashFilePrefix(this.bytesRead)}catch{this.bytesRead=0;this.consumedPrefixHash=null}watchFile(this.filePath,{interval:this.pollIntervalMs},()=>{if(!this.active)return;this.readNewLines()});debugLogger2.debug(`RemoteInput: watching ${this.filePath}`)}checkForNewInput(){return this.readNewLines()}readNewLines(){if(!this.active||this.reading)return Promise.resolve();let currentSize;try{const stat=statSync(this.filePath);currentSize=stat.size}catch{return Promise.resolve()}if(currentSize<this.bytesRead){debugLogger2.debug("RemoteInput: input file shrank, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}else if(this.hasConsumedPrefixChanged()){debugLogger2.debug("RemoteInput: input file prefix changed, resetting read offset");this.bytesRead=0;this.consumedPrefixHash=null}if(currentSize<=this.bytesRead)return Promise.resolve();const consumeUntil=this.findLastCompleteRecordEnd(this.bytesRead,currentSize);if(consumeUntil===null){return Promise.resolve()}const nextConsumedPrefixHash=this.hashFilePrefix(consumeUntil);this.reading=true;const stream=createReadStream(this.filePath,{start:this.bytesRead,end:consumeUntil-1,encoding:"utf-8"});const rl=createInterface({input:stream,crlfDelay:Infinity});rl.on("line",line=>{const trimmed=line.trim();if(!trimmed)return;try{const cmd=JSON.parse(trimmed);if(cmd&&cmd.type==="confirmation_response"&&typeof cmd.request_id==="string"&&typeof cmd.allowed==="boolean"){debugLogger2.debug(`RemoteInput: confirmation_response for ${cmd.request_id} (allowed=${cmd.allowed})`);this.confirmationHandler?.(cmd.request_id,cmd.allowed)}else if(cmd&&cmd.type==="submit"&&typeof cmd.text==="string"){debugLogger2.debug(`RemoteInput: queued command: ${cmd.text.slice(0,50)}...`);this.queue.push(cmd)}else{debugLogger2.warn(`RemoteInput: unknown command type: ${String(cmd?.type)}`)}}catch(_err){debugLogger2.warn(`RemoteInput: failed to parse line: ${trimmed}`)}});return new Promise(resolve2=>{rl.on("close",()=>{this.bytesRead=consumeUntil;if(nextConsumedPrefixHash!==null){this.consumedPrefixHash=nextConsumedPrefixHash}this.reading=false;this.processQueue();resolve2()})})}findLastCompleteRecordEnd(start,end){if(end<=start)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const buffer=Buffer.allocUnsafe(Math.min(64*1024,end-start));let remaining=end-start;let position=start;let lastLineBreak=-1;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)break;for(let i=0;i<bytesRead;i++){if(buffer[i]===10){lastLineBreak=position+i}}remaining-=bytesRead;position+=bytesRead}return lastLineBreak>=start?lastLineBreak+1:null}catch(err){debugLogger2.warn("RemoteInput: failed to scan complete records:",err);return null}finally{if(fd!==null){closeSync(fd)}}}hasConsumedPrefixChanged(){if(this.bytesRead===0){return false}if(this.consumedPrefixHash===null){debugLogger2.warn("RemoteInput: missing consumed prefix hash, resetting read offset");return true}const currentHash=this.hashFilePrefix(this.bytesRead);if(currentHash===null){debugLogger2.warn("RemoteInput: failed to hash consumed prefix, resetting read offset");return true}return currentHash!==this.consumedPrefixHash}hashFilePrefix(size){if(size<=0)return null;let fd=null;try{fd=openSync2(this.filePath,"r");const hash=createHash("sha256");const buffer=Buffer.allocUnsafe(Math.min(64*1024,size));let remaining=size;let position=0;while(remaining>0){const bytesToRead=Math.min(buffer.length,remaining);const bytesRead=readSync(fd,buffer,0,bytesToRead,position);if(bytesRead<=0)return null;hash.update(buffer.subarray(0,bytesRead));remaining-=bytesRead;position+=bytesRead}return hash.digest("base64")}catch(err){debugLogger2.warn("RemoteInput: failed to hash file prefix:",err);return null}finally{if(fd!==null){closeSync(fd)}}}async processQueue(){if(this.processing||!this.submitFn||this.queue.length===0)return;this.processing=true;if(this.retryTimer){clearTimeout(this.retryTimer);this.retryTimer=null}try{while(this.queue.length>0&&this.active){if(!this.submitFn)break;const cmd=this.queue[0];debugLogger2.debug(`RemoteInput: submitting: ${cmd.text.slice(0,50)}...`);try{const result=await this.submitFn(cmd.text);if(result===false){debugLogger2.debug("RemoteInput: TUI busy, will retry on idle");this.scheduleRetry();break}this.queue.shift()}catch(err){debugLogger2.error("RemoteInput: submit failed:",err);this.queue.shift()}if(this.queue.length>0){await new Promise(r=>setTimeout(r,500))}}}finally{this.processing=false}}scheduleRetry(){if(this.retryTimer)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null;if(this.queue.length>0&&!this.processing){this.processQueue()}},2e3)}shutdown(){this.active=false;unwatchFile(this.filePath);if(this.retryTimer)clearTimeout(this.retryTimer);this.queue.length=0;debugLogger2.debug("RemoteInput: shut down")}};init_esbuild_shims();var calculatePromptWidths=__name(terminalWidth=>{const widthFraction=.9;const FRAME_PADDING_AND_BORDER=4;const PROMPT_PREFIX_WIDTH=2;const MIN_CONTENT_WIDTH=2;const innerContentWidth=Math.floor(terminalWidth*widthFraction)-FRAME_PADDING_AND_BORDER-PROMPT_PREFIX_WIDTH;const inputWidth=Math.max(MIN_CONTENT_WIDTH,innerContentWidth);const FRAME_OVERHEAD=FRAME_PADDING_AND_BORDER+PROMPT_PREFIX_WIDTH;const containerWidth=inputWidth+FRAME_OVERHEAD;const suggestionsWidth=Math.max(20,Math.floor(terminalWidth*1));return{inputWidth,containerWidth,suggestionsWidth,frameOverhead:FRAME_OVERHEAD}},"calculatePromptWidths");var MAIN_CONTENT_HEIGHT_RESERVATION=2;var STATIC_EXTRA_HEIGHT=3;var clampDialogHeight=__name(height=>height===void 0?void 0:Math.max(1,Math.floor(height)),"clampDialogHeight");var getDialogMaxHeight=__name((terminalHeight,staticExtraHeight)=>Math.max(1,terminalHeight-staticExtraHeight-MAIN_CONTENT_HEIGHT_RESERVATION),"getDialogMaxHeight");init_esbuild_shims();var import_react5=__toESM(require_react(),1);init_esbuild_shims();var import_react4=__toESM(require_react(),1);var useQwenAuth=__name((pendingAuthType,isAuthenticating)=>{const[qwenAuthState,setQwenAuthState]=(0,import_react4.useState)({deviceAuth:null,authStatus:"idle",authMessage:null});const isQwenAuth=pendingAuthType==="qwen-oauth";(0,import_react4.useEffect)(()=>{if(!isQwenAuth||!isAuthenticating){setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null});return}setQwenAuthState(prev=>({...prev,authStatus:"idle"}));const handleDeviceAuth=__name(deviceAuth=>{setQwenAuthState(prev=>({...prev,deviceAuth:{verification_uri:deviceAuth.verification_uri,verification_uri_complete:deviceAuth.verification_uri_complete,user_code:deviceAuth.user_code,expires_in:deviceAuth.expires_in,device_code:deviceAuth.device_code},authStatus:"polling"}))},"handleDeviceAuth");const handleAuthProgress=__name((status,message)=>{setQwenAuthState(prev=>({...prev,authStatus:status,authMessage:message||null}))},"handleAuthProgress");qwenOAuth2Events.on("auth-uri",handleDeviceAuth);qwenOAuth2Events.on("auth-progress",handleAuthProgress);return()=>{qwenOAuth2Events.off("auth-uri",handleDeviceAuth);qwenOAuth2Events.off("auth-progress",handleAuthProgress)}},[isQwenAuth,isAuthenticating]);const cancelQwenAuth=(0,import_react4.useCallback)(()=>{qwenOAuth2Events.emit("auth-cancel");setQwenAuthState({deviceAuth:null,authStatus:"idle",authMessage:null})},[]);return{qwenAuthState,cancelQwenAuth}},"useQwenAuth");function normalizeModelIds(modelIdsInput){return modelIdsInput.split(",").map(id=>id.trim()).filter((id,index,array)=>id.length>0&&array.indexOf(id)===index)}__name(normalizeModelIds,"normalizeModelIds");function maskApiKey(apiKey){const trimmed=apiKey.trim();if(trimmed.length===0)return"(not set)";if(trimmed.length<=6)return"***";return`${trimmed.slice(0,3)}...${trimmed.slice(-4)}`}__name(maskApiKey,"maskApiKey");var useAuthCommand=__name((settings,config,addItem,onAuthChange)=>{const unAuthenticated=config.getAuthType()===void 0;const[authState,setAuthState]=(0,import_react5.useState)(unAuthenticated?"updating":"unauthenticated");const[authError,setAuthError]=(0,import_react5.useState)(null);const[isAuthenticating,setIsAuthenticating]=(0,import_react5.useState)(false);const[isAuthDialogOpen,setIsAuthDialogOpen]=(0,import_react5.useState)(unAuthenticated);const[pendingAuthType,setPendingAuthType]=(0,import_react5.useState)(void 0);const[externalAuthState,setExternalAuthState]=(0,import_react5.useState)(null);const{qwenAuthState,cancelQwenAuth}=useQwenAuth(pendingAuthType,isAuthenticating);const openedViaCommandRef=(0,import_react5.useRef)(false);const onAuthError=(0,import_react5.useCallback)(error=>{setAuthError(error);if(error){setAuthState("updating");setIsAuthDialogOpen(true)}},[setAuthError,setAuthState]);const handleAuthFailure=(0,import_react5.useCallback)((error,protocolForTelemetry)=>{setIsAuthenticating(false);setExternalAuthState(null);const msg=t("Failed to authenticate. Message: {{message}}",{message:getErrorMessage(error)});onAuthError(msg);const effectiveProtocol=protocolForTelemetry??pendingAuthType;if(effectiveProtocol){logAuth(config,new AuthEvent(effectiveProtocol,"manual","error",msg))}},[onAuthError,pendingAuthType,config]);const completeAuthentication=(0,import_react5.useCallback)(()=>{setAuthError(null);setAuthState("authenticated");setPendingAuthType(void 0);setIsAuthDialogOpen(false);setIsAuthenticating(false);onAuthChange?.()},[onAuthChange]);const handleProviderSubmit=(0,import_react5.useCallback)(async(providerConfig,inputs)=>{let protocol=inputs.protocol??providerConfig.protocol;try{setPendingAuthType(protocol);setIsAuthenticating(true);setAuthError(null);const plan=buildInstallPlan(providerConfig,inputs,getModelsForProviderProtocol(settings.merged.modelProviders,inputs.protocol??providerConfig.protocol,settings.merged.providerProtocol),{authType:settings.merged.security?.auth?.selectedType,id:settings.merged.model?.name,baseUrl:settings.merged.model?.baseUrl});protocol=plan.authType;setPendingAuthType(protocol);await applyProviderInstallPlan(plan,{settings:createLoadedSettingsAdapter(settings),reloadModelProviders:__name(mp=>config.reloadModelProvidersConfig(mp),"reloadModelProviders"),syncAuthState:__name((authType,modelId,baseUrl)=>config.syncModelSelection(authType,modelId,baseUrl),"syncAuthState"),refreshAuth:__name(authType=>config.refreshAuth(authType),"refreshAuth")});if(!plan.modelSelection&&!config.getAuthType()){setIsAuthenticating(false);setPendingAuthType(void 0);onAuthError(t("Service models saved. Configure a conversation model to start chatting."));return}completeAuthentication();const feedbackItem={type:"info",text:!plan.modelSelection?t("Service models saved."):t("Successfully configured {{provider}}. Use /model to switch models.",{provider:providerConfig.label})};addItem(feedbackItem,Date.now());if(openedViaCommandRef.current){openedViaCommandRef.current=false;config.getChatRecordingService?.()?.recordSlashCommand({phase:"result",rawCommand:"/auth",outputHistoryItems:[feedbackItem]})}if(plan.modelSelection)logAuth(config,new AuthEvent(protocol,"manual","success"))}catch(error){handleAuthFailure(error,protocol)}},[settings,config,completeAuthentication,addItem,handleAuthFailure,onAuthError]);const openAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=true;setIsAuthDialogOpen(true)},[]);const closeAuthDialog=(0,import_react5.useCallback)(()=>{openedViaCommandRef.current=false;setIsAuthDialogOpen(false);setAuthError(null)},[]);const cancelAuthentication=(0,import_react5.useCallback)(()=>{if(isAuthenticating&&pendingAuthType==="qwen-oauth"){cancelQwenAuth()}if(isAuthenticating&&pendingAuthType){logAuth(config,new AuthEvent(pendingAuthType,"manual","cancelled"))}setIsAuthenticating(false);setExternalAuthState(null);setIsAuthDialogOpen(true);setAuthError(null)},[isAuthenticating,pendingAuthType,cancelQwenAuth,config]);(0,import_react5.useEffect)(()=>{const val=process.env["QWEN_DEFAULT_AUTH_TYPE"];const valid=["qwen-oauth","openai","openai-responses","anthropic","gemini","vertex-ai"];if(val&&!valid.includes(val)){onAuthError(t('Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}',{value:val,validValues:valid.join(", ")}))}},[onAuthError]);const state=(0,import_react5.useMemo)(()=>({authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState}),[authError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState]);const actions=(0,import_react5.useMemo)(()=>({setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication}),[setAuthState,onAuthError,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication]);return{authState,setAuthState,authError,onAuthError,isAuthDialogOpen,isAuthenticating,pendingAuthType,externalAuthState,qwenAuthState,closeAuthDialog,handleProviderSubmit,openAuthDialog,cancelAuthentication,state,actions}},"useAuthCommand");init_esbuild_shims();var import_react6=__toESM(require_react(),1);function useDeleteCommand(options){const[isDeleteDialogOpen,setIsDeleteDialogOpen]=(0,import_react6.useState)(false);const openDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(true)},[]);const closeDeleteDialog=(0,import_react6.useCallback)(()=>{setIsDeleteDialogOpen(false)},[]);const{config,addItem,logger}=options??{};const isDeletingManyRef=(0,import_react6.useRef)(false);const purgeSessionLogs=(0,import_react6.useCallback)(sessionIds=>{if(sessionIds.length===0)return;void logger?.removeSessionsMessages(sessionIds).catch(error=>{console.error("Failed to purge deleted sessions from log:",error)})},[logger]);const handleDelete=(0,import_react6.useCallback)(async sessionId=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}closeDeleteDialog();if(sessionId===config.getSessionId()){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}try{const sessionService=config.getSessionService();const success=await sessionService.removeSession(sessionId);if(success){purgeSessionLogs([sessionId]);fireSessionDeleteHook(config,sessionId);addItem?.({type:"info",text:t("Session deleted successfully.")},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete session. Session not found.")},Date.now())}}catch(error){console.error("handleDelete failed:",error);addItem?.({type:"error",text:t("Failed to delete session.")},Date.now())}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);const handleDeleteMany=(0,import_react6.useCallback)(async sessionIds=>{if(!config){return}if(isDeletingManyRef.current){addItem?.({type:"info",text:t("A batch delete is already in progress. Please wait.")},Date.now());return}try{closeDeleteDialog();isDeletingManyRef.current=true;const currentId=config.getSessionId();const filtered=sessionIds.filter(id=>id!==currentId);if(filtered.length===0){addItem?.({type:"info",text:t("Cannot delete the current active session.")},Date.now());return}if(filtered.length<sessionIds.length){addItem?.({type:"info",text:t("Current active session skipped.")},Date.now())}addItem?.({type:"info",text:t("Deleting {{count}} session(s)...",{count:String(filtered.length)})},Date.now());const sessionService=config.getSessionService();const result=await sessionService.removeSessions(filtered);purgeSessionLogs(result.removed);for(const sessionId of result.removed){fireSessionDeleteHook(config,sessionId)}const removedCount=result.removed.length;const failedIds=[...result.notFound,...result.errors.map(e=>e.sessionId)];const failedCount=failedIds.length;const sampleIds=failedIds.slice(0,3).map(id=>id.slice(0,8)).join(", ");const overflow=failedCount>3?`, +${failedCount-3} more`:"";const firstError=result.errors[0]?.error.message;const reason=firstError?` \u2014 ${firstError}`:"";if(removedCount>0&&failedCount===0){addItem?.({type:"info",text:t("Deleted {{count}} session(s).",{count:String(removedCount)})},Date.now())}else if(removedCount>0&&failedCount>0){addItem?.({type:"error",text:t("Deleted {{removed}} session(s); {{failed}} could not be deleted ({{ids}}{{overflow}}){{reason}}.",{removed:String(removedCount),failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}else{addItem?.({type:"error",text:t("Failed to delete {{failed}} session(s) ({{ids}}{{overflow}}){{reason}}.",{failed:String(failedCount),ids:sampleIds,overflow,reason})},Date.now())}}catch(error){console.error("handleDeleteMany failed:",error);const detail=error instanceof Error?error.message:String(error);addItem?.({type:"error",text:t("Failed to delete sessions: {{error}}",{error:detail})},Date.now())}finally{isDeletingManyRef.current=false}},[closeDeleteDialog,config,addItem,purgeSessionLogs]);return{isDeleteDialogOpen,openDeleteDialog,closeDeleteDialog,handleDelete,handleDeleteMany}}__name(useDeleteCommand,"useDeleteCommand");init_esbuild_shims();var import_react7=__toESM(require_react(),1);function sourceLabel(scope){switch(scope){case"workspace":return".qwen/settings.json";case"project":default:return".mcp.json"}}__name(sourceLabel,"sourceLabel");function summarize(config){let summary;if(config.httpUrl){summary=`${config.httpUrl} (http)`}else if(config.url){summary=`${config.url} (sse)`}else if(config.command){summary=`${config.command} ${config.args?.join(" ")??""} (stdio)`.replace(/\s+\(/," (")}else{summary="(unknown transport)"}const details=[];if(config.env&&Object.keys(config.env).length>0){details.push(`env: ${Object.keys(config.env).join(", ")}`)}if(config.headers&&Object.keys(config.headers).length>0){details.push(`headers: ${Object.keys(config.headers).join(", ")}`)}return details.length>0?`${summary} [${details.join("; ")}]`:summary}__name(summarize,"summarize");var useMcpApproval=__name(config=>{const[queue,setQueue]=(0,import_react7.useState)([]);const computePending=(0,import_react7.useCallback)(()=>{if(config.getApprovalMode()==="yolo")return[];const servers=config.getMcpServers()??{};const approvals=loadMcpApprovals();const root=config.getWorkingDir();return Object.entries(servers).filter(([,c])=>isGatedMcpScope(c.scope)).filter(([name,c])=>approvals.getState(root,name,c)==="pending").map(([name,c])=>({name,config:c,summary:summarize(c),source:sourceLabel(c.scope)}))},[config]);(0,import_react7.useEffect)(()=>{setQueue(computePending())},[computePending]);(0,import_react7.useEffect)(()=>{const onPendingChanged=__name(()=>{setQueue(computePending())},"onPendingChanged");appEvents.on("mcp-pending-approval-changed",onPendingChanged);return()=>{appEvents.off("mcp-pending-approval-changed",onPendingChanged)}},[computePending]);const reconnect=(0,import_react7.useCallback)(name=>{config.approveMcpServerForSession(name);const registry=config.getToolRegistry();void registry?.discoverToolsForServer?.(name)?.catch?.(error=>{if(process.env["DEBUG"]){console.error(`MCP reconnect failed for ${name}:`,error)}})},[config]);const handleMcpApprovalSelect=(0,import_react7.useCallback)(async choice=>{const approvals=loadMcpApprovals();const root=config.getWorkingDir();const current=queue[0];if(!current){return}if(choice==="approve_all"){for(const server of queue){await approvals.setState(root,server.name,server.config,"approved");reconnect(server.name)}setQueue([]);return}if(choice==="approve"){await approvals.setState(root,current.name,current.config,"approved");reconnect(current.name)}else{await approvals.setState(root,current.name,current.config,"rejected")}setQueue(q=>q.slice(1))},[config,queue,reconnect]);return{isMcpApprovalDialogOpen:queue.length>0,currentMcpApproval:queue[0],pendingMcpApprovals:queue,mcpApprovalRemaining:Math.max(0,queue.length-1),handleMcpApprovalSelect}},"useMcpApproval");init_esbuild_shims();var import_react8=__toESM(require_react(),1);import crypto from"node:crypto";import path from"node:path";import os from"node:os";import fs from"node:fs";var OUTPUT_UPDATE_INTERVAL_MS=1e3;var MAX_OUTPUT_LENGTH=1e4;var debugLogger3=createDebugLogger("SHELL_COMMAND_PROCESSOR");function copyString(value){return value.split("").join("")}__name(copyString,"copyString");function addShellCommandToLlmHistory(llmClient,rawQuery,resultText){const modelContent=resultText.length>MAX_OUTPUT_LENGTH?copyString(resultText.substring(0,MAX_OUTPUT_LENGTH))+"\n... (truncated)":resultText;llmClient.addHistory({role:"user",parts:[{text:`I ran the following shell command:
4
4
  \`\`\`sh
5
5
  ${rawQuery}
6
6
  \`\`\`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{msSinceLastInteraction}from"./chunk-UGLQO5K7.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{DEFAULT_OPENAI_LOG_RETENTION_DAYS}from"./chunk-MUEIZGTI.js";import{resolveOpenAILogDir}from"./chunk-5YK5GMWE.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-GG7RNHZW.js";import{createDebugLogger,sessionIdContext}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat as stat3}from"node:fs/promises";import{createHash}from"node:crypto";import{join as join2}from"node:path";init_esbuild_shims();import{opendir,readdir,stat,rm,rmdir,unlink}from"node:fs/promises";import{join}from"node:path";var DEBUG_LOG_FILE_SUFFIX=".txt";var debugLogger=createDebugLogger("HOUSEKEEPING");var MS_PER_DAY=24*60*60*1e3;var MS_PER_HOUR=60*60*1e3;var MIN_DATE_MS=-864e13;var SWEEP_CONCURRENCY=20;function getCutoffDate(cleanupPeriodDays){const periodMs=cleanupPeriodDays>0?cleanupPeriodDays*MS_PER_DAY:MS_PER_HOUR;return new Date(Math.max(Date.now()-periodMs,MIN_DATE_MS))}__name(getCutoffDate,"getCutoffDate");async function sweepOldSessionDirs(root,opts){const result={removed:0,errors:0};const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const sessionDirs=entries.filter(e=>e.isDirectory()&&!excludes.has(e.name)).map(e=>join(root,e.name));for(let i=0;i<sessionDirs.length;i+=SWEEP_CONCURRENCY){const batch=sessionDirs.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async dir=>{try{const s=await stat(dir);if(s.mtime<opts.cutoffDate){await rm(dir,{recursive:true,force:true});result.removed++}}catch(err){result.errors++;debugLogger.error(`failed to sweep ${dir}`,err)}}))}if(opts.removeEmptyRoot!==false){await rmdir(root).catch(()=>{})}return result}__name(sweepOldSessionDirs,"sweepOldSessionDirs");async function cleanupOldFileHistoryBackups(opts){return sweepOldSessionDirs(join(Storage.getGlobalQwenDir(),FILE_HISTORY_DIR),opts)}__name(cleanupOldFileHistoryBackups,"cleanupOldFileHistoryBackups");async function cleanupOldSubagentTranscripts(opts){return sweepOldSessionDirs(opts.subagentsRoot,{...opts,removeEmptyRoot:false})}__name(cleanupOldSubagentTranscripts,"cleanupOldSubagentTranscripts");var OPENAI_LOG_FILE_PATTERN=/^openai-(\d{4}-\d{2}-\d{2})T\d{2}-\d{2}-\d{2}\.\d{3}Z-[a-f0-9]{8}(?:-[a-zA-Z0-9._](?:[a-zA-Z0-9._-]*[a-zA-Z0-9._])?)?\.json$/;async function cleanupOldOpenAILogs(opts){const result={removed:0,errors:0,completed:true};if(opts.signal?.aborted){result.completed=false;return result}let dir;try{dir=await opendir(opts.logDir)}catch(e){if(isENOENT(e))return result;debugLogger.error("opendir failed",e);throw e}const cutoffDay=opts.cutoffDate.toISOString().slice(0,10);let batch=[];for await(const entry of dir){if(opts.signal?.aborted){result.completed=false;break}const filenameDate=entry.isFile()?OPENAI_LOG_FILE_PATTERN.exec(entry.name)?.[1]:void 0;if(!filenameDate)continue;const filePath=join(opts.logDir,entry.name);batch.push((async()=>{try{let shouldRemove;if(filenameDate!==cutoffDay){shouldRemove=filenameDate<cutoffDay}else{const s=await stat(filePath);shouldRemove=s.mtime<opts.cutoffDate}if(shouldRemove){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}})());if(batch.length===SWEEP_CONCURRENCY){await Promise.all(batch);batch=[]}}await Promise.all(batch);return result}__name(cleanupOldOpenAILogs,"cleanupOldOpenAILogs");function isENOENT(e){return e?.code==="ENOENT"}__name(isENOENT,"isENOENT");async function cleanupOldDebugLogs(opts){const result={removed:0,errors:0};const root=Storage.getGlobalDebugDir();const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const logFiles=entries.flatMap(entry=>{if(!entry.isFile()||!entry.name.endsWith(DEBUG_LOG_FILE_SUFFIX)){return[]}const sessionId=entry.name.slice(0,-DEBUG_LOG_FILE_SUFFIX.length);if(!opts.isValidSessionId(sessionId)||excludes.has(sessionId)){return[]}return[join(root,entry.name)]});for(let i=0;i<logFiles.length;i+=SWEEP_CONCURRENCY){const batch=logFiles.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async filePath=>{try{const s=await stat(filePath);if(s.mtime<opts.cutoffDate){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}}))}return result}__name(cleanupOldDebugLogs,"cleanupOldDebugLogs");init_esbuild_shims();import{mkdir,open,stat as stat2,unlink as unlink2,writeFile}from"node:fs/promises";import{dirname}from"node:path";var debugLogger2=createDebugLogger("HOUSEKEEPING");var ONE_DAY_MS=24*60*60*1e3;var STALE_LOCK_MS=60*60*1e3;async function runThrottledOnce(opts,task){const minIntervalMs=opts.minIntervalMs??ONE_DAY_MS;const staleLockMs=opts.staleLockMs??STALE_LOCK_MS;await mkdir(dirname(opts.lockPath),{mode:448}).catch(()=>{});const firstFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(firstFreshForMs!==void 0){return{status:"fresh",retryAfterMs:firstFreshForMs}}let acquired=await tryAcquire(opts.lockPath);if(!acquired){try{const s=await stat2(opts.lockPath);if(Date.now()-s.mtimeMs>staleLockMs){await unlink2(opts.lockPath).catch(()=>{});acquired=await tryAcquire(opts.lockPath)}}catch{acquired=await tryAcquire(opts.lockPath)}if(!acquired){debugLogger2.debug(`${opts.name}: skipping, lock held`);return{status:"locked"}}}try{const secondFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(secondFreshForMs!==void 0){return{status:"fresh",retryAfterMs:secondFreshForMs}}let taskCompleted=false;try{taskCompleted=await task()!==false}finally{if(taskCompleted){try{await writeFile(opts.markerPath,new Date().toISOString())}catch(err){debugLogger2.debug(`${opts.name}: marker write failed (cleanup succeeded)`,err)}}}return{status:taskCompleted?"completed":"incomplete"}}finally{await unlink2(opts.lockPath).catch(()=>{debugLogger2.debug(`${opts.name}: lock unlink failed (harmless)`)})}}__name(runThrottledOnce,"runThrottledOnce");async function markerFreshForMs(markerPath,minIntervalMs,name){try{const s=await stat2(markerPath);const age=Date.now()-s.mtimeMs;if(age<minIntervalMs){debugLogger2.debug(`${name}: skipping, ran ${age}ms ago`);return minIntervalMs-age}}catch{}return void 0}__name(markerFreshForMs,"markerFreshForMs");async function tryAcquire(lockPath){try{const fh=await open(lockPath,"wx");await fh.close();return true}catch(e){if(e?.code==="EEXIST"){return false}throw e}}__name(tryAcquire,"tryAcquire");var debugLogger3=createDebugLogger("HOUSEKEEPING");var STARTUP_DELAY_MS=10*60*1e3;var RECURRING_INTERVAL_MS=24*60*60*1e3;var RECENT_INTERACTION_MS=60*1e3;var CATCHUP_THRESHOLD_MS=7*24*60*60*1e3;var STARTUP_DELAY_CATCHUP_MS=60*1e3;var NON_INTERACTIVE_LOCK_RETRY_MS=60*1e3;var NON_INTERACTIVE_FAILURE_RETRY_MS=10*60*1e3;var NON_INTERACTIVE_STOP_GRACE_MS=250;var FILE_HISTORY_MARKER=".file-history-cleanup";var SUBAGENT_MARKER=".subagent-cleanup";var OPENAI_LOGS_MARKER=".openai-logs-cleanup";var DEBUG_LOGS_MARKER=".debug-logs-cleanup";var PSEUDO_DEBUG_SESSION_STEMS=new Set(["transcript-replay","workspace-mcp-discovery"]);var started=false;var nonInteractiveJobs=new Map;var nonInteractiveQueue=[];var activeNonInteractiveJob;var activeNonInteractiveAbortController;var nonInteractiveWorker;var nonInteractiveStopping=false;var nonInteractiveStopPromise;function startBackgroundHousekeeping(config,settings){if(started)return;started=true;void scheduleFirstPass(config,settings).catch(err=>{started=false;debugLogger3.error("scheduleFirstPass failed; chain will retry on next start",err)})}__name(startBackgroundHousekeeping,"startBackgroundHousekeeping");async function scheduleFirstPass(config,settings){const delay=await getFirstPassDelay(config,settings);debugLogger3.debug(`first pass in ${delay/1e3}s`);setTimeout(()=>scheduleNextPass(config,settings),delay).unref()}__name(scheduleFirstPass,"scheduleFirstPass");async function getFirstPassDelay(config,settings){const qwenDir=Storage.getGlobalQwenDir();const markerPaths=[join2(qwenDir,FILE_HISTORY_MARKER),getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir())];const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){markerPaths.push(getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}const catchUpStates=await Promise.all(markerPaths.map(needsCatchUp));return catchUpStates.some(Boolean)?STARTUP_DELAY_CATCHUP_MS:STARTUP_DELAY_MS}__name(getFirstPassDelay,"getFirstPassDelay");async function needsCatchUp(markerPath){try{const s=await stat3(markerPath);return Date.now()-s.mtimeMs>CATCHUP_THRESHOLD_MS}catch{return true}}__name(needsCatchUp,"needsCatchUp");function getSubagentMarkerPath(qwenDir,projectDir){const projectKey=createHash("sha256").update(projectDir).digest("hex").slice(0,16);return join2(qwenDir,`${SUBAGENT_MARKER}-${projectKey}`)}__name(getSubagentMarkerPath,"getSubagentMarkerPath");function getOpenAILogsMarkerPath(qwenDir,logDir){const logDirKey=createHash("sha256").update(logDir).digest("hex").slice(0,16);return join2(qwenDir,`${OPENAI_LOGS_MARKER}-${logDirKey}`)}__name(getOpenAILogsMarkerPath,"getOpenAILogsMarkerPath");function getDebugLogsMarkerPath(qwenDir,debugDir){const debugDirKey=createHash("sha256").update(debugDir).digest("hex").slice(0,16);return join2(qwenDir,`${DEBUG_LOGS_MARKER}-${debugDirKey}`)}__name(getDebugLogsMarkerPath,"getDebugLogsMarkerPath");function getOpenAILogCleanupTarget(config,settings){try{const customLogDir=config.getContentGeneratorConfig?.()?.openAILoggingDir??config.getModelsConfig?.()?.getGenerationConfig?.().openAILoggingDir??settings.merged.model?.openAILoggingDir;const systemRetention=settings.system?.settings.model?.openAILogRetentionDays;const workspaceRetention=settings.isTrusted?settings.workspace?.settings.model?.openAILogRetentionDays:void 0;if(customLogDir&&workspaceRetention!==void 0&&systemRetention===void 0){debugLogger3.error("workspace-scoped openAILogRetentionDays is unsafe with a custom openAILoggingDir; skipping cleanup");return void 0}const retentionDays=customLogDir?systemRetention??settings.user?.settings.model?.openAILogRetentionDays??settings.systemDefaults?.settings.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS:settings.merged.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS;return{logDir:resolveOpenAILogDir(customLogDir,config.getWorkingDir()),retentionDays}}catch(err){debugLogger3.error("failed to resolve OpenAI log cleanup target; skipping",err);return void 0}}__name(getOpenAILogCleanupTarget,"getOpenAILogCleanupTarget");function startNonInteractiveOpenAILogHousekeeping(config,settings){if(nonInteractiveStopping)return;sessionIdContext.exit(()=>{try{const target=getOpenAILogCleanupTarget(config,settings);if(!target||nonInteractiveJobs.has(target.logDir))return;const markerPath=getOpenAILogsMarkerPath(Storage.getGlobalQwenDir(),target.logDir);const job={target,markerPath,queued:false};nonInteractiveJobs.set(target.logDir,job);enqueueNonInteractiveJob(job)}catch(err){debugLogger3.error("failed to start non-interactive OpenAI log cleanup; skipping",err)}})}__name(startNonInteractiveOpenAILogHousekeeping,"startNonInteractiveOpenAILogHousekeeping");function stopNonInteractiveOpenAILogHousekeeping(){if(nonInteractiveStopPromise)return nonInteractiveStopPromise;nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer){clearTimeout(job.timer);job.timer=void 0}job.queued=false}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();nonInteractiveStopPromise=waitForNonInteractiveWorkerToStop();return nonInteractiveStopPromise}__name(stopNonInteractiveOpenAILogHousekeeping,"stopNonInteractiveOpenAILogHousekeeping");function enqueueNonInteractiveJob(job){if(nonInteractiveStopping||job.queued||activeNonInteractiveJob===job){return}job.queued=true;nonInteractiveQueue.push(job);startNonInteractiveWorker()}__name(enqueueNonInteractiveJob,"enqueueNonInteractiveJob");function startNonInteractiveWorker(){if(nonInteractiveWorker||nonInteractiveStopping)return;nonInteractiveWorker=drainNonInteractiveQueue().catch(err=>{debugLogger3.error("non-interactive OpenAI log worker failed",err)}).finally(()=>{nonInteractiveWorker=void 0;if(nonInteractiveQueue.length>0&&!nonInteractiveStopping){startNonInteractiveWorker()}})}__name(startNonInteractiveWorker,"startNonInteractiveWorker");async function drainNonInteractiveQueue(){while(!nonInteractiveStopping){const job=nonInteractiveQueue.shift();if(!job)return;job.queued=false;activeNonInteractiveJob=job;const abortController=new AbortController;activeNonInteractiveAbortController=abortController;try{const result=await runOpenAILogCleanup(job.target,job.markerPath,abortController.signal);if(nonInteractiveStopping)continue;switch(result.status){case"completed":scheduleNonInteractiveJob(job,RECURRING_INTERVAL_MS);break;case"fresh":scheduleNonInteractiveJob(job,Math.min(RECURRING_INTERVAL_MS,Math.max(NON_INTERACTIVE_LOCK_RETRY_MS,result.retryAfterMs)));break;case"locked":scheduleNonInteractiveJob(job,NON_INTERACTIVE_LOCK_RETRY_MS);break;case"incomplete":break;default:break}}catch(err){debugLogger3.error(`non-interactive OpenAI log cleanup failed for ${job.target.logDir}`,err);if(!nonInteractiveStopping){scheduleNonInteractiveJob(job,NON_INTERACTIVE_FAILURE_RETRY_MS)}}finally{activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0}}}__name(drainNonInteractiveQueue,"drainNonInteractiveQueue");async function runOpenAILogCleanup(target,markerPath,signal){return runThrottledOnce({name:"openai-logs-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldOpenAILogs({logDir:target.logDir,cutoffDate:getCutoffDate(target.retentionDays),signal});debugLogger3.debug(`openai-logs: removed=${r.removed} errors=${r.errors} completed=${r.completed}`);return r.completed?void 0:false})}__name(runOpenAILogCleanup,"runOpenAILogCleanup");function scheduleNonInteractiveJob(job,delayMs){if(nonInteractiveStopping)return;job.timer=setTimeout(()=>{job.timer=void 0;enqueueNonInteractiveJob(job)},delayMs);job.timer.unref()}__name(scheduleNonInteractiveJob,"scheduleNonInteractiveJob");async function waitForNonInteractiveWorkerToStop(){const worker=nonInteractiveWorker;if(!worker){nonInteractiveJobs.clear();return}let timeout;try{await Promise.race([worker,new Promise(resolve=>{timeout=setTimeout(resolve,NON_INTERACTIVE_STOP_GRACE_MS)})])}finally{if(timeout)clearTimeout(timeout);nonInteractiveJobs.clear()}}__name(waitForNonInteractiveWorkerToStop,"waitForNonInteractiveWorkerToStop");async function runPass(config,settings){if(msSinceLastInteraction()<RECENT_INTERACTION_MS){debugLogger3.debug("user active, deferring 10 min");setTimeout(()=>scheduleNextPass(config,settings),STARTUP_DELAY_MS).unref();return}try{await runHousekeeping(config,settings)}catch(err){debugLogger3.error("housekeeping pass failed; will retry next cycle",err)}setTimeout(()=>scheduleNextPass(config,settings),RECURRING_INTERVAL_MS).unref()}__name(runPass,"runPass");function scheduleNextPass(config,settings){void runPass(config,settings).catch(err=>{debugLogger3.error("runPass rejected unexpectedly",err)})}__name(scheduleNextPass,"scheduleNextPass");async function runHousekeeping(config,settings){const days=settings.merged.general?.cleanupPeriodDays??30;const cutoff=getCutoffDate(days);const currentSessionId=config.getSessionId();const qwenDir=Storage.getGlobalQwenDir();await runThrottledOnce({name:"file-history-cleanup",markerPath:join2(qwenDir,FILE_HISTORY_MARKER),lockPath:join2(qwenDir,FILE_HISTORY_MARKER+".lock")},async()=>{const r=await cleanupOldFileHistoryBackups({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId])});debugLogger3.debug(`file-history: removed=${r.removed} errors=${r.errors}`)});const debugLogsMarkerPath=getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir());await runThrottledOnce({name:"debug-logs-cleanup",markerPath:debugLogsMarkerPath,lockPath:debugLogsMarkerPath+".lock"},async()=>{const r=await cleanupOldDebugLogs({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),isValidSessionId:__name(v=>isValidSessionId(v)||PSEUDO_DEBUG_SESSION_STEMS.has(v),"isValidSessionId")});debugLogger3.debug(`debug-logs: removed=${r.removed} errors=${r.errors}`)});const projectDir=config.storage?.getProjectDir?.();if(projectDir){const markerPath=getSubagentMarkerPath(qwenDir,projectDir);await runThrottledOnce({name:"subagent-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldSubagentTranscripts({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),subagentsRoot:getSubagentsRootDir(projectDir)});debugLogger3.debug(`subagents: removed=${r.removed} errors=${r.errors}`)})}const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){await runOpenAILogCleanup(openaiTarget,getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}}__name(runHousekeeping,"runHousekeeping");function _resetForTesting(){started=false}__name(_resetForTesting,"_resetForTesting");async function _resetNonInteractiveForTesting(){nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer)clearTimeout(job.timer)}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();await nonInteractiveWorker;nonInteractiveJobs.clear();activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0;nonInteractiveWorker=void 0;nonInteractiveStopping=false;nonInteractiveStopPromise=void 0}__name(_resetNonInteractiveForTesting,"_resetNonInteractiveForTesting");var _needsCatchUpForTesting=needsCatchUp;var _getFirstPassDelayForTesting=getFirstPassDelay;var _runHousekeepingForTesting=runHousekeeping;var _runPassForTesting=runPass;var _FILE_HISTORY_MARKER_FOR_TESTING=FILE_HISTORY_MARKER;var _getDebugLogsMarkerPathForTesting=getDebugLogsMarkerPath;var _getSubagentMarkerPathForTesting=getSubagentMarkerPath;var _getOpenAILogsMarkerPathForTesting=getOpenAILogsMarkerPath;export{startBackgroundHousekeeping,startNonInteractiveOpenAILogHousekeeping,stopNonInteractiveOpenAILogHousekeeping,_resetForTesting,_resetNonInteractiveForTesting,_needsCatchUpForTesting,_getFirstPassDelayForTesting,_runHousekeepingForTesting,_runPassForTesting,_FILE_HISTORY_MARKER_FOR_TESTING,_getDebugLogsMarkerPathForTesting,_getSubagentMarkerPathForTesting,_getOpenAILogsMarkerPathForTesting};
3
+ import{msSinceLastInteraction}from"./chunk-UGLQO5K7.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{DEFAULT_OPENAI_LOG_RETENTION_DAYS}from"./chunk-YHPHQX6M.js";import{resolveOpenAILogDir}from"./chunk-5YK5GMWE.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-IFAUFERF.js";import{createDebugLogger,sessionIdContext}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat as stat3}from"node:fs/promises";import{createHash}from"node:crypto";import{join as join2}from"node:path";init_esbuild_shims();import{opendir,readdir,stat,rm,rmdir,unlink}from"node:fs/promises";import{join}from"node:path";var DEBUG_LOG_FILE_SUFFIX=".txt";var debugLogger=createDebugLogger("HOUSEKEEPING");var MS_PER_DAY=24*60*60*1e3;var MS_PER_HOUR=60*60*1e3;var MIN_DATE_MS=-864e13;var SWEEP_CONCURRENCY=20;function getCutoffDate(cleanupPeriodDays){const periodMs=cleanupPeriodDays>0?cleanupPeriodDays*MS_PER_DAY:MS_PER_HOUR;return new Date(Math.max(Date.now()-periodMs,MIN_DATE_MS))}__name(getCutoffDate,"getCutoffDate");async function sweepOldSessionDirs(root,opts){const result={removed:0,errors:0};const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const sessionDirs=entries.filter(e=>e.isDirectory()&&!excludes.has(e.name)).map(e=>join(root,e.name));for(let i=0;i<sessionDirs.length;i+=SWEEP_CONCURRENCY){const batch=sessionDirs.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async dir=>{try{const s=await stat(dir);if(s.mtime<opts.cutoffDate){await rm(dir,{recursive:true,force:true});result.removed++}}catch(err){result.errors++;debugLogger.error(`failed to sweep ${dir}`,err)}}))}if(opts.removeEmptyRoot!==false){await rmdir(root).catch(()=>{})}return result}__name(sweepOldSessionDirs,"sweepOldSessionDirs");async function cleanupOldFileHistoryBackups(opts){return sweepOldSessionDirs(join(Storage.getGlobalQwenDir(),FILE_HISTORY_DIR),opts)}__name(cleanupOldFileHistoryBackups,"cleanupOldFileHistoryBackups");async function cleanupOldSubagentTranscripts(opts){return sweepOldSessionDirs(opts.subagentsRoot,{...opts,removeEmptyRoot:false})}__name(cleanupOldSubagentTranscripts,"cleanupOldSubagentTranscripts");var OPENAI_LOG_FILE_PATTERN=/^openai-(\d{4}-\d{2}-\d{2})T\d{2}-\d{2}-\d{2}\.\d{3}Z-[a-f0-9]{8}(?:-[a-zA-Z0-9._](?:[a-zA-Z0-9._-]*[a-zA-Z0-9._])?)?\.json$/;async function cleanupOldOpenAILogs(opts){const result={removed:0,errors:0,completed:true};if(opts.signal?.aborted){result.completed=false;return result}let dir;try{dir=await opendir(opts.logDir)}catch(e){if(isENOENT(e))return result;debugLogger.error("opendir failed",e);throw e}const cutoffDay=opts.cutoffDate.toISOString().slice(0,10);let batch=[];for await(const entry of dir){if(opts.signal?.aborted){result.completed=false;break}const filenameDate=entry.isFile()?OPENAI_LOG_FILE_PATTERN.exec(entry.name)?.[1]:void 0;if(!filenameDate)continue;const filePath=join(opts.logDir,entry.name);batch.push((async()=>{try{let shouldRemove;if(filenameDate!==cutoffDay){shouldRemove=filenameDate<cutoffDay}else{const s=await stat(filePath);shouldRemove=s.mtime<opts.cutoffDate}if(shouldRemove){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}})());if(batch.length===SWEEP_CONCURRENCY){await Promise.all(batch);batch=[]}}await Promise.all(batch);return result}__name(cleanupOldOpenAILogs,"cleanupOldOpenAILogs");function isENOENT(e){return e?.code==="ENOENT"}__name(isENOENT,"isENOENT");async function cleanupOldDebugLogs(opts){const result={removed:0,errors:0};const root=Storage.getGlobalDebugDir();const excludes=opts.excludeSessionIds??new Set;let entries;try{entries=await readdir(root,{withFileTypes:true})}catch(e){if(isENOENT(e))return result;debugLogger.error("readdir failed",e);return result}const logFiles=entries.flatMap(entry=>{if(!entry.isFile()||!entry.name.endsWith(DEBUG_LOG_FILE_SUFFIX)){return[]}const sessionId=entry.name.slice(0,-DEBUG_LOG_FILE_SUFFIX.length);if(!opts.isValidSessionId(sessionId)||excludes.has(sessionId)){return[]}return[join(root,entry.name)]});for(let i=0;i<logFiles.length;i+=SWEEP_CONCURRENCY){const batch=logFiles.slice(i,i+SWEEP_CONCURRENCY);await Promise.all(batch.map(async filePath=>{try{const s=await stat(filePath);if(s.mtime<opts.cutoffDate){await unlink(filePath);result.removed++}}catch(err){if(isENOENT(err))return;result.errors++;debugLogger.error(`failed to sweep ${filePath}`,err)}}))}return result}__name(cleanupOldDebugLogs,"cleanupOldDebugLogs");init_esbuild_shims();import{mkdir,open,stat as stat2,unlink as unlink2,writeFile}from"node:fs/promises";import{dirname}from"node:path";var debugLogger2=createDebugLogger("HOUSEKEEPING");var ONE_DAY_MS=24*60*60*1e3;var STALE_LOCK_MS=60*60*1e3;async function runThrottledOnce(opts,task){const minIntervalMs=opts.minIntervalMs??ONE_DAY_MS;const staleLockMs=opts.staleLockMs??STALE_LOCK_MS;await mkdir(dirname(opts.lockPath),{mode:448}).catch(()=>{});const firstFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(firstFreshForMs!==void 0){return{status:"fresh",retryAfterMs:firstFreshForMs}}let acquired=await tryAcquire(opts.lockPath);if(!acquired){try{const s=await stat2(opts.lockPath);if(Date.now()-s.mtimeMs>staleLockMs){await unlink2(opts.lockPath).catch(()=>{});acquired=await tryAcquire(opts.lockPath)}}catch{acquired=await tryAcquire(opts.lockPath)}if(!acquired){debugLogger2.debug(`${opts.name}: skipping, lock held`);return{status:"locked"}}}try{const secondFreshForMs=await markerFreshForMs(opts.markerPath,minIntervalMs,opts.name);if(secondFreshForMs!==void 0){return{status:"fresh",retryAfterMs:secondFreshForMs}}let taskCompleted=false;try{taskCompleted=await task()!==false}finally{if(taskCompleted){try{await writeFile(opts.markerPath,new Date().toISOString())}catch(err){debugLogger2.debug(`${opts.name}: marker write failed (cleanup succeeded)`,err)}}}return{status:taskCompleted?"completed":"incomplete"}}finally{await unlink2(opts.lockPath).catch(()=>{debugLogger2.debug(`${opts.name}: lock unlink failed (harmless)`)})}}__name(runThrottledOnce,"runThrottledOnce");async function markerFreshForMs(markerPath,minIntervalMs,name){try{const s=await stat2(markerPath);const age=Date.now()-s.mtimeMs;if(age<minIntervalMs){debugLogger2.debug(`${name}: skipping, ran ${age}ms ago`);return minIntervalMs-age}}catch{}return void 0}__name(markerFreshForMs,"markerFreshForMs");async function tryAcquire(lockPath){try{const fh=await open(lockPath,"wx");await fh.close();return true}catch(e){if(e?.code==="EEXIST"){return false}throw e}}__name(tryAcquire,"tryAcquire");var debugLogger3=createDebugLogger("HOUSEKEEPING");var STARTUP_DELAY_MS=10*60*1e3;var RECURRING_INTERVAL_MS=24*60*60*1e3;var RECENT_INTERACTION_MS=60*1e3;var CATCHUP_THRESHOLD_MS=7*24*60*60*1e3;var STARTUP_DELAY_CATCHUP_MS=60*1e3;var NON_INTERACTIVE_LOCK_RETRY_MS=60*1e3;var NON_INTERACTIVE_FAILURE_RETRY_MS=10*60*1e3;var NON_INTERACTIVE_STOP_GRACE_MS=250;var FILE_HISTORY_MARKER=".file-history-cleanup";var SUBAGENT_MARKER=".subagent-cleanup";var OPENAI_LOGS_MARKER=".openai-logs-cleanup";var DEBUG_LOGS_MARKER=".debug-logs-cleanup";var PSEUDO_DEBUG_SESSION_STEMS=new Set(["transcript-replay","workspace-mcp-discovery"]);var started=false;var nonInteractiveJobs=new Map;var nonInteractiveQueue=[];var activeNonInteractiveJob;var activeNonInteractiveAbortController;var nonInteractiveWorker;var nonInteractiveStopping=false;var nonInteractiveStopPromise;function startBackgroundHousekeeping(config,settings){if(started)return;started=true;void scheduleFirstPass(config,settings).catch(err=>{started=false;debugLogger3.error("scheduleFirstPass failed; chain will retry on next start",err)})}__name(startBackgroundHousekeeping,"startBackgroundHousekeeping");async function scheduleFirstPass(config,settings){const delay=await getFirstPassDelay(config,settings);debugLogger3.debug(`first pass in ${delay/1e3}s`);setTimeout(()=>scheduleNextPass(config,settings),delay).unref()}__name(scheduleFirstPass,"scheduleFirstPass");async function getFirstPassDelay(config,settings){const qwenDir=Storage.getGlobalQwenDir();const markerPaths=[join2(qwenDir,FILE_HISTORY_MARKER),getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir())];const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){markerPaths.push(getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}const catchUpStates=await Promise.all(markerPaths.map(needsCatchUp));return catchUpStates.some(Boolean)?STARTUP_DELAY_CATCHUP_MS:STARTUP_DELAY_MS}__name(getFirstPassDelay,"getFirstPassDelay");async function needsCatchUp(markerPath){try{const s=await stat3(markerPath);return Date.now()-s.mtimeMs>CATCHUP_THRESHOLD_MS}catch{return true}}__name(needsCatchUp,"needsCatchUp");function getSubagentMarkerPath(qwenDir,projectDir){const projectKey=createHash("sha256").update(projectDir).digest("hex").slice(0,16);return join2(qwenDir,`${SUBAGENT_MARKER}-${projectKey}`)}__name(getSubagentMarkerPath,"getSubagentMarkerPath");function getOpenAILogsMarkerPath(qwenDir,logDir){const logDirKey=createHash("sha256").update(logDir).digest("hex").slice(0,16);return join2(qwenDir,`${OPENAI_LOGS_MARKER}-${logDirKey}`)}__name(getOpenAILogsMarkerPath,"getOpenAILogsMarkerPath");function getDebugLogsMarkerPath(qwenDir,debugDir){const debugDirKey=createHash("sha256").update(debugDir).digest("hex").slice(0,16);return join2(qwenDir,`${DEBUG_LOGS_MARKER}-${debugDirKey}`)}__name(getDebugLogsMarkerPath,"getDebugLogsMarkerPath");function getOpenAILogCleanupTarget(config,settings){try{const customLogDir=config.getContentGeneratorConfig?.()?.openAILoggingDir??config.getModelsConfig?.()?.getGenerationConfig?.().openAILoggingDir??settings.merged.model?.openAILoggingDir;const systemRetention=settings.system?.settings.model?.openAILogRetentionDays;const workspaceRetention=settings.isTrusted?settings.workspace?.settings.model?.openAILogRetentionDays:void 0;if(customLogDir&&workspaceRetention!==void 0&&systemRetention===void 0){debugLogger3.error("workspace-scoped openAILogRetentionDays is unsafe with a custom openAILoggingDir; skipping cleanup");return void 0}const retentionDays=customLogDir?systemRetention??settings.user?.settings.model?.openAILogRetentionDays??settings.systemDefaults?.settings.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS:settings.merged.model?.openAILogRetentionDays??DEFAULT_OPENAI_LOG_RETENTION_DAYS;return{logDir:resolveOpenAILogDir(customLogDir,config.getWorkingDir()),retentionDays}}catch(err){debugLogger3.error("failed to resolve OpenAI log cleanup target; skipping",err);return void 0}}__name(getOpenAILogCleanupTarget,"getOpenAILogCleanupTarget");function startNonInteractiveOpenAILogHousekeeping(config,settings){if(nonInteractiveStopping)return;sessionIdContext.exit(()=>{try{const target=getOpenAILogCleanupTarget(config,settings);if(!target||nonInteractiveJobs.has(target.logDir))return;const markerPath=getOpenAILogsMarkerPath(Storage.getGlobalQwenDir(),target.logDir);const job={target,markerPath,queued:false};nonInteractiveJobs.set(target.logDir,job);enqueueNonInteractiveJob(job)}catch(err){debugLogger3.error("failed to start non-interactive OpenAI log cleanup; skipping",err)}})}__name(startNonInteractiveOpenAILogHousekeeping,"startNonInteractiveOpenAILogHousekeeping");function stopNonInteractiveOpenAILogHousekeeping(){if(nonInteractiveStopPromise)return nonInteractiveStopPromise;nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer){clearTimeout(job.timer);job.timer=void 0}job.queued=false}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();nonInteractiveStopPromise=waitForNonInteractiveWorkerToStop();return nonInteractiveStopPromise}__name(stopNonInteractiveOpenAILogHousekeeping,"stopNonInteractiveOpenAILogHousekeeping");function enqueueNonInteractiveJob(job){if(nonInteractiveStopping||job.queued||activeNonInteractiveJob===job){return}job.queued=true;nonInteractiveQueue.push(job);startNonInteractiveWorker()}__name(enqueueNonInteractiveJob,"enqueueNonInteractiveJob");function startNonInteractiveWorker(){if(nonInteractiveWorker||nonInteractiveStopping)return;nonInteractiveWorker=drainNonInteractiveQueue().catch(err=>{debugLogger3.error("non-interactive OpenAI log worker failed",err)}).finally(()=>{nonInteractiveWorker=void 0;if(nonInteractiveQueue.length>0&&!nonInteractiveStopping){startNonInteractiveWorker()}})}__name(startNonInteractiveWorker,"startNonInteractiveWorker");async function drainNonInteractiveQueue(){while(!nonInteractiveStopping){const job=nonInteractiveQueue.shift();if(!job)return;job.queued=false;activeNonInteractiveJob=job;const abortController=new AbortController;activeNonInteractiveAbortController=abortController;try{const result=await runOpenAILogCleanup(job.target,job.markerPath,abortController.signal);if(nonInteractiveStopping)continue;switch(result.status){case"completed":scheduleNonInteractiveJob(job,RECURRING_INTERVAL_MS);break;case"fresh":scheduleNonInteractiveJob(job,Math.min(RECURRING_INTERVAL_MS,Math.max(NON_INTERACTIVE_LOCK_RETRY_MS,result.retryAfterMs)));break;case"locked":scheduleNonInteractiveJob(job,NON_INTERACTIVE_LOCK_RETRY_MS);break;case"incomplete":break;default:break}}catch(err){debugLogger3.error(`non-interactive OpenAI log cleanup failed for ${job.target.logDir}`,err);if(!nonInteractiveStopping){scheduleNonInteractiveJob(job,NON_INTERACTIVE_FAILURE_RETRY_MS)}}finally{activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0}}}__name(drainNonInteractiveQueue,"drainNonInteractiveQueue");async function runOpenAILogCleanup(target,markerPath,signal){return runThrottledOnce({name:"openai-logs-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldOpenAILogs({logDir:target.logDir,cutoffDate:getCutoffDate(target.retentionDays),signal});debugLogger3.debug(`openai-logs: removed=${r.removed} errors=${r.errors} completed=${r.completed}`);return r.completed?void 0:false})}__name(runOpenAILogCleanup,"runOpenAILogCleanup");function scheduleNonInteractiveJob(job,delayMs){if(nonInteractiveStopping)return;job.timer=setTimeout(()=>{job.timer=void 0;enqueueNonInteractiveJob(job)},delayMs);job.timer.unref()}__name(scheduleNonInteractiveJob,"scheduleNonInteractiveJob");async function waitForNonInteractiveWorkerToStop(){const worker=nonInteractiveWorker;if(!worker){nonInteractiveJobs.clear();return}let timeout;try{await Promise.race([worker,new Promise(resolve=>{timeout=setTimeout(resolve,NON_INTERACTIVE_STOP_GRACE_MS)})])}finally{if(timeout)clearTimeout(timeout);nonInteractiveJobs.clear()}}__name(waitForNonInteractiveWorkerToStop,"waitForNonInteractiveWorkerToStop");async function runPass(config,settings){if(msSinceLastInteraction()<RECENT_INTERACTION_MS){debugLogger3.debug("user active, deferring 10 min");setTimeout(()=>scheduleNextPass(config,settings),STARTUP_DELAY_MS).unref();return}try{await runHousekeeping(config,settings)}catch(err){debugLogger3.error("housekeeping pass failed; will retry next cycle",err)}setTimeout(()=>scheduleNextPass(config,settings),RECURRING_INTERVAL_MS).unref()}__name(runPass,"runPass");function scheduleNextPass(config,settings){void runPass(config,settings).catch(err=>{debugLogger3.error("runPass rejected unexpectedly",err)})}__name(scheduleNextPass,"scheduleNextPass");async function runHousekeeping(config,settings){const days=settings.merged.general?.cleanupPeriodDays??30;const cutoff=getCutoffDate(days);const currentSessionId=config.getSessionId();const qwenDir=Storage.getGlobalQwenDir();await runThrottledOnce({name:"file-history-cleanup",markerPath:join2(qwenDir,FILE_HISTORY_MARKER),lockPath:join2(qwenDir,FILE_HISTORY_MARKER+".lock")},async()=>{const r=await cleanupOldFileHistoryBackups({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId])});debugLogger3.debug(`file-history: removed=${r.removed} errors=${r.errors}`)});const debugLogsMarkerPath=getDebugLogsMarkerPath(qwenDir,Storage.getGlobalDebugDir());await runThrottledOnce({name:"debug-logs-cleanup",markerPath:debugLogsMarkerPath,lockPath:debugLogsMarkerPath+".lock"},async()=>{const r=await cleanupOldDebugLogs({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),isValidSessionId:__name(v=>isValidSessionId(v)||PSEUDO_DEBUG_SESSION_STEMS.has(v),"isValidSessionId")});debugLogger3.debug(`debug-logs: removed=${r.removed} errors=${r.errors}`)});const projectDir=config.storage?.getProjectDir?.();if(projectDir){const markerPath=getSubagentMarkerPath(qwenDir,projectDir);await runThrottledOnce({name:"subagent-cleanup",markerPath,lockPath:markerPath+".lock"},async()=>{const r=await cleanupOldSubagentTranscripts({cutoffDate:cutoff,excludeSessionIds:new Set([currentSessionId]),subagentsRoot:getSubagentsRootDir(projectDir)});debugLogger3.debug(`subagents: removed=${r.removed} errors=${r.errors}`)})}const openaiTarget=getOpenAILogCleanupTarget(config,settings);if(openaiTarget){await runOpenAILogCleanup(openaiTarget,getOpenAILogsMarkerPath(qwenDir,openaiTarget.logDir))}}__name(runHousekeeping,"runHousekeeping");function _resetForTesting(){started=false}__name(_resetForTesting,"_resetForTesting");async function _resetNonInteractiveForTesting(){nonInteractiveStopping=true;for(const job of nonInteractiveJobs.values()){if(job.timer)clearTimeout(job.timer)}nonInteractiveQueue.length=0;activeNonInteractiveAbortController?.abort();await nonInteractiveWorker;nonInteractiveJobs.clear();activeNonInteractiveJob=void 0;activeNonInteractiveAbortController=void 0;nonInteractiveWorker=void 0;nonInteractiveStopping=false;nonInteractiveStopPromise=void 0}__name(_resetNonInteractiveForTesting,"_resetNonInteractiveForTesting");var _needsCatchUpForTesting=needsCatchUp;var _getFirstPassDelayForTesting=getFirstPassDelay;var _runHousekeepingForTesting=runHousekeeping;var _runPassForTesting=runPass;var _FILE_HISTORY_MARKER_FOR_TESTING=FILE_HISTORY_MARKER;var _getDebugLogsMarkerPathForTesting=getDebugLogsMarkerPath;var _getSubagentMarkerPathForTesting=getSubagentMarkerPath;var _getOpenAILogsMarkerPathForTesting=getOpenAILogsMarkerPath;export{startBackgroundHousekeeping,startNonInteractiveOpenAILogHousekeeping,stopNonInteractiveOpenAILogHousekeeping,_resetForTesting,_resetNonInteractiveForTesting,_needsCatchUpForTesting,_getFirstPassDelayForTesting,_runHousekeepingForTesting,_runPassForTesting,_FILE_HISTORY_MARKER_FOR_TESTING,_getDebugLogsMarkerPathForTesting,_getSubagentMarkerPathForTesting,_getOpenAILogsMarkerPathForTesting};
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{getGitVersion,getNpmVersion}from"./chunk-CWU5NJOB.js";import{buildEnvStatusFromEnv,snapshotProcessEnv}from"./chunk-F7VMXOM5.js";import{mapDomainErrorToErrorKind}from"./chunk-KGXOCC6J.js";import{canUseRipgrep}from"./chunk-K6EQXZMK.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";var REQUIRED_NODE_MAJOR=22;function createDaemonStatusProvider(options={}){const readEnv=__name(()=>options.env??snapshotProcessEnv(),"readEnv");return{async getEnvStatus(boundWorkspace,acpChannelLive){return buildEnvStatusFromEnv(boundWorkspace,acpChannelLive,readEnv())},async getDaemonPreflightCells(boundWorkspace){return buildDaemonPreflightCells(boundWorkspace,readEnv())}}}__name(createDaemonStatusProvider,"createDaemonStatusProvider");async function buildDaemonPreflightCells(boundWorkspace,env){const nodeVersionCell=__name(()=>{try{const nodeVersion=process.versions.node;const major=Number.parseInt(nodeVersion.split(".")[0]??"0",10);if(Number.isFinite(major)&&major>=REQUIRED_NODE_MAJOR){return{kind:"node_version",status:"ok",locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}return{kind:"node_version",status:"error",errorKind:"missing_binary",error:`Node ${nodeVersion} is below the required >=${REQUIRED_NODE_MAJOR}.`,hint:`Upgrade Node to v${REQUIRED_NODE_MAJOR} or newer.`,locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}catch(err){return{kind:"node_version",status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon"}}},"nodeVersionCell");const cliEntryCell=__name(()=>{const cliEntry=env["QWEN_CLI_ENTRY"]||process.argv[1]||"";if(cliEntry){return{kind:"cli_entry",status:"ok",locality:"daemon",detail:{path:cliEntry,source:env["QWEN_CLI_ENTRY"]?"QWEN_CLI_ENTRY":"process.argv[1]"}}}return{kind:"cli_entry",status:"error",errorKind:"missing_binary",error:"Cannot determine CLI entry path for spawning the ACP child.",hint:"Set QWEN_CLI_ENTRY to the absolute path of the qwen entry script.",locality:"daemon"}},"cliEntryCell");const workspaceDirCell=__name(async()=>{try{const stat=await fs.stat(boundWorkspace);if(stat.isDirectory()){return{kind:"workspace_dir",status:"ok",locality:"daemon",detail:{path:boundWorkspace}}}return{kind:"workspace_dir",status:"error",errorKind:"missing_file",error:`Bound workspace path is not a directory: ${boundWorkspace}`,locality:"daemon",detail:{path:boundWorkspace}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind:"workspace_dir",status:"error",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{},locality:"daemon",detail:{path:boundWorkspace}}}},"workspaceDirCell");const slots=[{kind:"node_version",run:nodeVersionCell},{kind:"cli_entry",run:cliEntryCell},{kind:"workspace_dir",run:workspaceDirCell},{kind:"ripgrep",run:__name(()=>safeCheck("ripgrep",async()=>{const ok=await canUseRipgrep(true);return ok?{status:"ok"}:{status:"warning",hint:"Install ripgrep for faster grep tool execution."}}),"run")},{kind:"git",run:__name(()=>safeCheck("git",async()=>{const v=await getGitVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"git not found on PATH."}}),"run")},{kind:"npm",run:__name(()=>safeCheck("npm",async()=>{const v=await getNpmVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"npm not found on PATH."}}),"run")}];const settled=await Promise.allSettled(slots.map(s=>Promise.resolve().then(s.run)));return settled.map((result,i)=>{if(result.status==="fulfilled")return result.value;const err=result.reason;const errorKind=mapDomainErrorToErrorKind(err);return{kind:slots[i].kind,status:"error",locality:"daemon",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{}}})}__name(buildDaemonPreflightCells,"buildDaemonPreflightCells");async function safeCheck(kind,body){try{const r=await body();return{kind,status:r.status,locality:"daemon",...r.detail?{detail:r.detail}:{},...r.hint?{hint:r.hint}:{}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind,status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon",...errorKind?{errorKind}:{}}}}__name(safeCheck,"safeCheck");export{createDaemonStatusProvider};
3
+ import{getGitVersion,getNpmVersion}from"./chunk-NHXKNS7F.js";import{buildEnvStatusFromEnv,snapshotProcessEnv}from"./chunk-F7VMXOM5.js";import{mapDomainErrorToErrorKind}from"./chunk-KGXOCC6J.js";import{canUseRipgrep}from"./chunk-K6EQXZMK.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";var REQUIRED_NODE_MAJOR=22;function createDaemonStatusProvider(options={}){const readEnv=__name(()=>options.env??snapshotProcessEnv(),"readEnv");return{async getEnvStatus(boundWorkspace,acpChannelLive){return buildEnvStatusFromEnv(boundWorkspace,acpChannelLive,readEnv())},async getDaemonPreflightCells(boundWorkspace){return buildDaemonPreflightCells(boundWorkspace,readEnv())}}}__name(createDaemonStatusProvider,"createDaemonStatusProvider");async function buildDaemonPreflightCells(boundWorkspace,env){const nodeVersionCell=__name(()=>{try{const nodeVersion=process.versions.node;const major=Number.parseInt(nodeVersion.split(".")[0]??"0",10);if(Number.isFinite(major)&&major>=REQUIRED_NODE_MAJOR){return{kind:"node_version",status:"ok",locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}return{kind:"node_version",status:"error",errorKind:"missing_binary",error:`Node ${nodeVersion} is below the required >=${REQUIRED_NODE_MAJOR}.`,hint:`Upgrade Node to v${REQUIRED_NODE_MAJOR} or newer.`,locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}catch(err){return{kind:"node_version",status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon"}}},"nodeVersionCell");const cliEntryCell=__name(()=>{const cliEntry=env["QWEN_CLI_ENTRY"]||process.argv[1]||"";if(cliEntry){return{kind:"cli_entry",status:"ok",locality:"daemon",detail:{path:cliEntry,source:env["QWEN_CLI_ENTRY"]?"QWEN_CLI_ENTRY":"process.argv[1]"}}}return{kind:"cli_entry",status:"error",errorKind:"missing_binary",error:"Cannot determine CLI entry path for spawning the ACP child.",hint:"Set QWEN_CLI_ENTRY to the absolute path of the qwen entry script.",locality:"daemon"}},"cliEntryCell");const workspaceDirCell=__name(async()=>{try{const stat=await fs.stat(boundWorkspace);if(stat.isDirectory()){return{kind:"workspace_dir",status:"ok",locality:"daemon",detail:{path:boundWorkspace}}}return{kind:"workspace_dir",status:"error",errorKind:"missing_file",error:`Bound workspace path is not a directory: ${boundWorkspace}`,locality:"daemon",detail:{path:boundWorkspace}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind:"workspace_dir",status:"error",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{},locality:"daemon",detail:{path:boundWorkspace}}}},"workspaceDirCell");const slots=[{kind:"node_version",run:nodeVersionCell},{kind:"cli_entry",run:cliEntryCell},{kind:"workspace_dir",run:workspaceDirCell},{kind:"ripgrep",run:__name(()=>safeCheck("ripgrep",async()=>{const ok=await canUseRipgrep(true);return ok?{status:"ok"}:{status:"warning",hint:"Install ripgrep for faster grep tool execution."}}),"run")},{kind:"git",run:__name(()=>safeCheck("git",async()=>{const v=await getGitVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"git not found on PATH."}}),"run")},{kind:"npm",run:__name(()=>safeCheck("npm",async()=>{const v=await getNpmVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"npm not found on PATH."}}),"run")}];const settled=await Promise.allSettled(slots.map(s=>Promise.resolve().then(s.run)));return settled.map((result,i)=>{if(result.status==="fulfilled")return result.value;const err=result.reason;const errorKind=mapDomainErrorToErrorKind(err);return{kind:slots[i].kind,status:"error",locality:"daemon",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{}}})}__name(buildDaemonPreflightCells,"buildDaemonPreflightCells");async function safeCheck(kind,body){try{const r=await body();return{kind,status:r.status,locality:"daemon",...r.detail?{detail:r.detail}:{},...r.hint?{hint:r.hint}:{}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind,status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon",...errorKind?{errorKind}:{}}}}__name(safeCheck,"safeCheck");export{createDaemonStatusProvider};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -2,7 +2,7 @@
2
2
  "use strict";
3
3
  import{resolvePolicyToolSettings}from"./chunk-IV3HAIUN.js";import{MEDIA_MEMORY_FILE_NAME}from"./chunk-UYYQB2TU.js";import{DEFAULT_OMNI_PROCESSING_LIMITS,conditionUsesNamespace,evaluateFixedPolicyCondition}from"./chunk-GBFZYVZ4.js";import{OBJECT_EXTENSION_RE}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile}from"./chunk-ZBHL2CXR.js";import{OmniJsonCacheFile}from"./chunk-AMGUAA4G.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var AUDIO_TOKENS_PER_SECOND=7;var VISUAL_PIXELS_PER_TOKEN=32*32*2;function usable(value){return value!==void 0&&Number.isFinite(value)&&value>0}__name(usable,"usable");function estimateRawResourceTokens(media){const unavailable={estimatedTokenCount:0,method:"raw-resource-v1",status:"unavailable"};switch(media.modality){case"audio":{const durationMs=media.metadata.durationMs;if(!usable(durationMs))return unavailable;return{estimatedTokenCount:Math.ceil(durationMs/1e3*AUDIO_TOKENS_PER_SECOND),method:"raw-resource-v1",status:"ok"}}case"image":{const{width,height,frameCount}=media.metadata;if(!usable(width)||!usable(height))return unavailable;const frames=usable(frameCount)?frameCount:1;return{estimatedTokenCount:Math.ceil(width*height*frames/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}case"video":{const{width,height,durationMs,frameRate}=media.metadata;if(!usable(width)||!usable(height)||!usable(durationMs)||!usable(frameRate)){return unavailable}const frameCount=Math.ceil(durationMs/1e3*frameRate);return{estimatedTokenCount:Math.ceil(width*height*frameCount/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}default:return unavailable}}__name(estimateRawResourceTokens,"estimateRawResourceTokens");init_esbuild_shims();import{createHash}from"node:crypto";import path from"node:path";var MAX_CACHED_DISCLOSURE_LENGTH=2048;var FINGERPRINT_EXCLUDED_KEYS=new Set(["inputPath","outputDir","resourceId"]);function stableStringify(value){if(Array.isArray(value)){return`[${value.map(stableStringify).join(",")}]`}if(typeof value==="object"&&value!==null){const record=value;const body=Object.keys(record).sort().map(k=>`${JSON.stringify(k)}:${stableStringify(record[k])}`).join(",");return`{${body}}`}return JSON.stringify(value)??"null"}__name(stableStringify,"stableStringify");function computePolicyFingerprint(toolName,args,toolVersion="1"){const tunables={};for(const[k,v]of Object.entries(args)){if(!FINGERPRINT_EXCLUDED_KEYS.has(k)&&v!==void 0){tunables[k]=v}}return createHash("sha256").update(`${toolName}
4
4
  ${stableStringify(tunables)}
5
- ${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-T7AKBX25.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
5
+ ${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-3MSROJV5.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
6
6
  /**
7
7
  * @license
8
8
  * Copyright 2025 Google LLC