gerege-cli 0.26.6 → 0.26.7

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 (226) hide show
  1. package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LSNOJEKM.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
  3. package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
  4. package/chunks/{acpAgent-67UN66PB.js → acpAgent-3DTOHTDM.js} +3 -3
  5. package/chunks/{advisor-SAXMI4QZ.js → advisor-7JGQPS7X.js} +1 -1
  6. package/chunks/{agent-KV7BXY6C.js → agent-PNKQJGDO.js} +1 -1
  7. package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-7D33X7QQ.js} +1 -1
  8. package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-3R2MAUVE.js} +1 -1
  9. package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-2D7DECAE.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
  11. package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-OIHHZSPQ.js} +1 -1
  12. package/chunks/{batch-XFVQ4BLM.js → batch-6UDAMPAA.js} +1 -1
  13. package/chunks/{bridge-AE7AFEXB.js → bridge-QXVXPNJ6.js} +1 -1
  14. package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-P4W4R5SJ.js} +1 -1
  15. package/chunks/{chunk-RXN7DUMP.js → chunk-2J2BQ3PL.js} +2 -2
  16. package/chunks/{chunk-7453BHJO.js → chunk-2LMSDH6P.js} +1 -1
  17. package/chunks/{chunk-32XHDDIA.js → chunk-3EZ5GCUT.js} +1 -1
  18. package/chunks/{chunk-AYVCT5FF.js → chunk-3ICJI5KW.js} +1 -1
  19. package/chunks/{chunk-VRKYBH5G.js → chunk-4A663FE6.js} +5 -5
  20. package/chunks/{chunk-DA6LOBSB.js → chunk-4AKTP4MM.js} +1 -1
  21. package/chunks/{chunk-T53VMDXH.js → chunk-4LC4INFI.js} +1 -1
  22. package/chunks/{chunk-65ME4BOH.js → chunk-4QOVM2LL.js} +1 -1
  23. package/chunks/{chunk-MYV7GY3H.js → chunk-4VR4DUUD.js} +1 -1
  24. package/chunks/{chunk-GRAECADD.js → chunk-4W27Z3OL.js} +1 -1
  25. package/chunks/{chunk-B37YY4XU.js → chunk-53IB4U4E.js} +1 -1
  26. package/chunks/{chunk-OK7LBM5G.js → chunk-5R2JIZID.js} +1 -1
  27. package/chunks/{chunk-I6PUY2T3.js → chunk-5TWAP4OG.js} +1 -1
  28. package/chunks/{chunk-CBE6ZIHU.js → chunk-6JAXAFX7.js} +1 -1
  29. package/chunks/{chunk-OOJ2AQT3.js → chunk-6WV5RKYB.js} +1 -1
  30. package/chunks/{chunk-ELDZ4MNL.js → chunk-6YFNUVJR.js} +1 -1
  31. package/chunks/{chunk-3W32X2DH.js → chunk-7HFFTOAD.js} +1 -1
  32. package/chunks/{chunk-YH2XRWRF.js → chunk-ATTJQLQV.js} +1 -1
  33. package/chunks/{chunk-T5DKF33F.js → chunk-BIPPD7W6.js} +1 -1
  34. package/chunks/{chunk-CF6SZJNP.js → chunk-BVV7UXES.js} +1 -1
  35. package/chunks/{chunk-CGDFZEER.js → chunk-BY46PCWY.js} +1 -1
  36. package/chunks/{chunk-AEZYXPFS.js → chunk-CDKBM72V.js} +1 -1
  37. package/chunks/{chunk-OU7CEG7Q.js → chunk-CK3OKTTL.js} +1 -1
  38. package/chunks/{chunk-FKL3V5BO.js → chunk-DEJ47KJE.js} +1 -1
  39. package/chunks/{chunk-FEP6W4NJ.js → chunk-DQQN2HOP.js} +1 -1
  40. package/chunks/{chunk-SKGJ26HQ.js → chunk-DTX2OVQW.js} +1 -1
  41. package/chunks/{chunk-EXIFPXMB.js → chunk-DVUKYOCJ.js} +1 -1
  42. package/chunks/{chunk-FKZ46GKL.js → chunk-E3KWSRJN.js} +1 -1
  43. package/chunks/{chunk-BAUMVH4Q.js → chunk-EEPNACXJ.js} +1 -1
  44. package/chunks/{chunk-76FSYQTG.js → chunk-F5SLLEJY.js} +1 -1
  45. package/chunks/{chunk-IZ5MWA6E.js → chunk-F7622ZRQ.js} +1 -1
  46. package/chunks/{chunk-TB4AUC2L.js → chunk-FKUDVIME.js} +1 -1
  47. package/chunks/{chunk-SP6CQ3MO.js → chunk-FRVXSKL4.js} +1 -1
  48. package/chunks/{chunk-XISR37DQ.js → chunk-FTF2NFLB.js} +1 -1
  49. package/chunks/{chunk-NONBHCXP.js → chunk-G4MWPXNY.js} +1 -1
  50. package/chunks/{chunk-JRTOPEM3.js → chunk-GA35LMSX.js} +1 -1
  51. package/chunks/{chunk-GHIFIXNX.js → chunk-H34KVVI4.js} +1 -1
  52. package/chunks/{chunk-AFO5ER23.js → chunk-H5EXNXGW.js} +1 -1
  53. package/chunks/{chunk-ZENMAISJ.js → chunk-HJLRKM3W.js} +1 -1
  54. package/chunks/{chunk-BCI62WSL.js → chunk-HVP4UF2Q.js} +1 -1
  55. package/chunks/{chunk-AEKEZRIU.js → chunk-HXTYFGSQ.js} +1 -1
  56. package/chunks/{chunk-KJGRCIVY.js → chunk-IIHUDJX7.js} +1 -1
  57. package/chunks/{chunk-RSLTOIG5.js → chunk-IQMKQKKD.js} +2 -2
  58. package/chunks/{chunk-JWNKPINR.js → chunk-ISQMHOCC.js} +1 -1
  59. package/chunks/{chunk-OJ4K62S2.js → chunk-IY7M5HKF.js} +1 -1
  60. package/chunks/{chunk-LBLLWAKK.js → chunk-IZXHCHJD.js} +1 -1
  61. package/chunks/{chunk-NVOI6UDQ.js → chunk-JHC22BZH.js} +1 -1
  62. package/chunks/{chunk-BPFFRPWE.js → chunk-K7GN4CMV.js} +6 -6
  63. package/chunks/{chunk-N7PWZBXV.js → chunk-L7LO3YRT.js} +1 -1
  64. package/chunks/{chunk-MGATL4OA.js → chunk-LY4XTBL4.js} +1 -1
  65. package/chunks/{chunk-JEDL4IKF.js → chunk-LYFRGP42.js} +1 -1
  66. package/chunks/{chunk-G6DALGGS.js → chunk-MDCA4I63.js} +1 -1
  67. package/chunks/{chunk-W5Z4BWWA.js → chunk-MS2XCBPP.js} +1 -1
  68. package/chunks/{chunk-GBSRWT7J.js → chunk-MXZXQUVP.js} +1 -1
  69. package/chunks/{chunk-VD2GSW64.js → chunk-N4ZQC5HB.js} +1 -1
  70. package/chunks/{chunk-2LWJGXTW.js → chunk-N6EFYQ7M.js} +1 -1
  71. package/chunks/{chunk-P62S5JGM.js → chunk-NHPKD7LY.js} +1 -1
  72. package/chunks/{chunk-W66WWTOP.js → chunk-NPAENNRO.js} +1 -1
  73. package/chunks/{chunk-EYPLBTMI.js → chunk-NYBYDW6R.js} +1 -1
  74. package/chunks/{chunk-7RNOS7R4.js → chunk-O3TUZQP4.js} +1 -1
  75. package/chunks/{chunk-JH3V5SPA.js → chunk-OZFZBGZG.js} +1 -1
  76. package/chunks/{chunk-QDCUR3JB.js → chunk-P2MZZMCS.js} +1 -1
  77. package/chunks/{chunk-KZNYALFU.js → chunk-PMBI46K4.js} +1 -1
  78. package/chunks/{chunk-2TAJ5STJ.js → chunk-Q5RRVBTY.js} +1 -1
  79. package/chunks/{chunk-H3IR3GIE.js → chunk-QHYSRPQR.js} +1 -1
  80. package/chunks/{chunk-NA4ZF2FE.js → chunk-QONPET6Y.js} +2 -2
  81. package/chunks/{chunk-W2RQIZ6B.js → chunk-QSPXKBUX.js} +1 -1
  82. package/chunks/{chunk-WGFX3EL3.js → chunk-QTKPC24L.js} +1 -1
  83. package/chunks/{chunk-BHIDG6VZ.js → chunk-QTVSPQZQ.js} +1 -1
  84. package/chunks/{chunk-HOG66S6K.js → chunk-QVHDM6N7.js} +1 -1
  85. package/chunks/{chunk-4NDJKNN6.js → chunk-RT6J7PV4.js} +1 -1
  86. package/chunks/{chunk-NEKPQLFY.js → chunk-RULGA7WE.js} +2 -2
  87. package/chunks/{chunk-LTE4N6L3.js → chunk-SAVYMUU3.js} +1 -1
  88. package/chunks/{chunk-2JGTWRZJ.js → chunk-T3CQ72HC.js} +6 -6
  89. package/chunks/{chunk-FYBJGRX7.js → chunk-U5YOAOU3.js} +1 -1
  90. package/chunks/{chunk-EFIRES46.js → chunk-ULLW2AYD.js} +1 -1
  91. package/chunks/{chunk-MPVQDYPH.js → chunk-UM5KBBYP.js} +1 -1
  92. package/chunks/{chunk-M6KB5RVD.js → chunk-UVMLWDRU.js} +1 -1
  93. package/chunks/{chunk-5EXL4TKQ.js → chunk-VK7LOUOJ.js} +1 -1
  94. package/chunks/{chunk-T2YTHAJW.js → chunk-VUNHJ74J.js} +1 -1
  95. package/chunks/{chunk-HTAUIJB4.js → chunk-W2CV36HT.js} +1 -1
  96. package/chunks/{chunk-ET5M5WFN.js → chunk-WCI33URB.js} +1 -1
  97. package/chunks/{chunk-P3JEEDQZ.js → chunk-WEPC42YR.js} +1 -1
  98. package/chunks/{chunk-BQZF3UKI.js → chunk-WF7Q3ZSQ.js} +1 -1
  99. package/chunks/{chunk-GSPGIGO5.js → chunk-WK666FGZ.js} +3 -3
  100. package/chunks/{chunk-CUP2TNJK.js → chunk-WMLYHZZX.js} +1 -1
  101. package/chunks/{chunk-2N3NBTYJ.js → chunk-WSI4G7XC.js} +1 -1
  102. package/chunks/{chunk-U3Q72OGV.js → chunk-WXK7Z45R.js} +1 -1
  103. package/chunks/{chunk-MTDBCIDA.js → chunk-YWK3E4WJ.js} +1 -1
  104. package/chunks/{chunk-34HC2AXI.js → chunk-YY4GWNTU.js} +2 -2
  105. package/chunks/{chunk-UKLXKJKL.js → chunk-ZFOEVHWG.js} +1 -1
  106. package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
  107. package/chunks/{config-utils-OWY5G5Y2.js → config-utils-6B5FHBSF.js} +1 -1
  108. package/chunks/{contextCommand-IXFUZH65.js → contextCommand-FGRDE3GA.js} +1 -1
  109. package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-OFEHSKDB.js} +1 -1
  110. package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-D2KEWVHQ.js} +1 -1
  111. package/chunks/{cron-create-2422NBSJ.js → cron-create-RFGGKTL7.js} +1 -1
  112. package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
  113. package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-GHQBRDMC.js} +1 -1
  114. package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
  115. package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
  116. package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
  117. package/chunks/{edit-E5LEI2LL.js → edit-XCECLEH3.js} +1 -1
  118. package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-SEN2PMRM.js} +1 -1
  119. package/chunks/{environment-XBBIB3VA.js → environment-CCPQJYKS.js} +1 -1
  120. package/chunks/{errors-LNMQ7TUK.js → errors-Y6HHUTGK.js} +1 -1
  121. package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-HADWGMIG.js} +1 -1
  122. package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-GZS7WOQL.js} +1 -1
  123. package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-76B5HDLT.js} +1 -1
  124. package/chunks/{fast-path-M6K2RACY.js → fast-path-OEV7LQYV.js} +1 -1
  125. package/chunks/{glob-N2QT4U7U.js → glob-NLWCQRMS.js} +1 -1
  126. package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-43XV33BT.js} +1 -1
  127. package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
  128. package/chunks/{i18n-AGOA6MUI.js → i18n-JW6BVEGF.js} +1 -1
  129. package/chunks/{initializer-FRKYDUSX.js → initializer-UT6JLZ3O.js} +1 -1
  130. package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-LKWDV3S2.js} +1 -1
  131. package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-2KWKYVPC.js} +1 -1
  132. package/chunks/{list-DE7VUIR2.js → list-BKINK3S2.js} +1 -1
  133. package/chunks/{llm-N3JGJHYC.js → llm-3RWXAVM2.js} +4 -4
  134. package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-MDRBSH73.js} +1 -1
  135. package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
  136. package/chunks/{local-BE624O3A.js → local-TT4FLCTR.js} +1 -1
  137. package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-OBA6VWYL.js} +1 -1
  138. package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
  139. package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-4MSRX3DY.js} +1 -1
  140. package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-PX5PZJKZ.js} +1 -1
  141. package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
  142. package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-X7REHGB4.js} +1 -1
  143. package/chunks/{managed-npm-update-CTL6LH5Z.js → managed-npm-update-6HUVAJH7.js} +1 -1
  144. package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
  145. package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
  146. package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
  147. package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
  148. package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-MYOYTUM2.js} +1 -1
  149. package/chunks/{mcp-VC4CJPE5.js → mcp-5OTEMZ7P.js} +1 -1
  150. package/chunks/{memory-S6OJA3ZD.js → memory-TNW7RSAV.js} +1 -1
  151. package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-KNTWFZQS.js} +1 -1
  152. package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-U5C5P5UQ.js} +1 -1
  153. package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-R4KFI2WK.js} +1 -1
  154. package/chunks/{monitor-M3PNLCYP.js → monitor-RD2PFK42.js} +1 -1
  155. package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
  156. package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
  157. package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-YLRN3UZT.js} +1 -1
  158. package/chunks/{omni-6YBX4R6K.js → omni-CUJ52EW5.js} +1 -1
  159. package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-6B5MAU54.js} +1 -1
  160. package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
  161. package/chunks/{pidfile-XR4JF2Z6.js → pidfile-P2HIGAUA.js} +1 -1
  162. package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JSKN5UGS.js} +1 -1
  163. package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
  164. package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-IEDZONWG.js} +1 -1
  165. package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-FYZBJCF6.js} +1 -1
  166. package/chunks/{read-file-VD7OFO2E.js → read-file-VNZNSD6X.js} +1 -1
  167. package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
  168. package/chunks/{review-C365WGCW.js → review-TBJRZWTD.js} +1 -1
  169. package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-4W5B5FOE.js} +1 -1
  170. package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-44X262G5.js} +1 -1
  171. package/chunks/{runtime-J6SPBSCS.js → runtime-6H6LKD73.js} +1 -1
  172. package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-SQXDRGVN.js} +1 -1
  173. package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-62IZKHJG.js} +1 -1
  174. package/chunks/{scheduler-KCMSPHON.js → scheduler-QUCXJYRL.js} +1 -1
  175. package/chunks/{search-memory-EUBJ7IAV.js → search-memory-TC2Z34QN.js} +1 -1
  176. package/chunks/{send-message-CWWZUPSK.js → send-message-TFZX7KI7.js} +1 -1
  177. package/chunks/{serve-4CB4BWJ5.js → serve-WSICDFGG.js} +1 -1
  178. package/chunks/{server-JNANUIGC.js → server-GYYVTNGY.js} +3 -3
  179. package/chunks/{session-3LQLXPUA.js → session-KF3O23ZJ.js} +1 -1
  180. package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-7HFUSONH.js} +1 -1
  181. package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
  182. package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-3KDFTDEV.js} +1 -1
  183. package/chunks/{sessionService-U7ACD2HP.js → sessionService-XRTFLPDW.js} +1 -1
  184. package/chunks/{settings-FTGWYTUH.js → settings-QPPK6WXE.js} +1 -1
  185. package/chunks/{shell-E4RENYQC.js → shell-WYQDZWL7.js} +1 -1
  186. package/chunks/{skill-OLNPHRWB.js → skill-FYPT6AU7.js} +1 -1
  187. package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-OGFI5KZF.js} +1 -1
  188. package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-ANOOVPG7.js} +1 -1
  189. package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-45WTDY4E.js} +1 -1
  190. package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-TL5WK33V.js} +1 -1
  191. package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-N2IREVBM.js} +1 -1
  192. package/chunks/{team-create-HAVKHNU5.js → team-create-R77PRZ5U.js} +1 -1
  193. package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-6DCRKB5I.js} +1 -1
  194. package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
  195. package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-RQDXJGVR.js} +1 -1
  196. package/chunks/{tool-call-LZHZ5RVH.js → tool-call-LVB4NCDT.js} +1 -1
  197. package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-LRBB2KS6.js} +1 -1
  198. package/chunks/{tool-search-K6S3ON7M.js → tool-search-OG73QAQZ.js} +1 -1
  199. package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-A4CUF6AD.js} +1 -1
  200. package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-LSGOYTU2.js} +1 -1
  201. package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-OGC6BZO7.js} +1 -1
  202. package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-7J3GXTER.js} +1 -1
  203. package/chunks/{upload-config-TCCFCNCD.js → upload-config-ML5XEJIF.js} +1 -1
  204. package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
  205. package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
  206. package/chunks/{version-JYWKKMNP.js → version-7JN2YXL2.js} +1 -1
  207. package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-42ZR4FEZ.js} +1 -1
  208. package/chunks/{web-search-HAI5LW3G.js → web-search-74NLPMZJ.js} +1 -1
  209. package/chunks/{workflow-BZ2YFGF6.js → workflow-WNPHX42I.js} +1 -1
  210. package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
  211. package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-3YFBFAK3.js} +1 -1
  212. package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-EPJI6KRV.js} +1 -1
  213. package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
  214. package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-VEXYBDMA.js} +1 -1
  215. package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-NRZYTP2X.js} +1 -1
  216. package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
  217. package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-USATWO56.js} +1 -1
  218. package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-M5JTSFDL.js} +1 -1
  219. package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
  220. package/chunks/{write-file-HD5LHXGL.js → write-file-UMJVKE4S.js} +1 -1
  221. package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-76XYHQ3Z.js} +1 -1
  222. package/cli.js +2 -2
  223. package/execution-worker.js +1 -1
  224. package/export-transcript-document.js +1 -1
  225. package/gerege.mjs +11 -0
  226. package/package.json +1 -1
@@ -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-NONBHCXP.js";import{resolveOpenAILogDir}from"./chunk-QX7W2HY7.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-2JGTWRZJ.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-G4MWPXNY.js";import{resolveOpenAILogDir}from"./chunk-QX7W2HY7.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-T3CQ72HC.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{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-2JGTWRZJ.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-OMSVOFTC.js";import{getMemoryBaseDir}from"./chunk-KVA6DHHF.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-5DTFN37U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
3
+ import{normalizeWorkspaceRelativePath}from"./chunk-YJ6APXNB.js";import{MAX_SNAPSHOTS,ManagedToolProtocolError,managedToolDigest}from"./chunk-T3CQ72HC.js";import{MANAGED_SESSION_LIMITS,assertManagedSessionDurableRef,assertManagedSessionKey,assertManagedSessionSequence,assertManagedSessionStableId}from"./chunk-OMSVOFTC.js";import{getMemoryBaseDir}from"./chunk-KVA6DHHF.js";import{normalizeQwenCustomIgnoreFileNames}from"./chunk-5DTFN37U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";var MANAGED_TOOL_FILE_HISTORY_MAX_BYTES=8*1024*1024;function captureManagedToolExecutionContext(config){const filtering=config.getFileFilteringOptions();return{workspaceDirectories:[...config.getWorkspaceContext().getDirectories()],memoryBaseDir:getMemoryBaseDir(),lsToolEnabled:config.isLsToolEnabled(),grepOptions:{useRipgrep:config.getUseRipgrep(),useBuiltinRipgrep:config.getUseBuiltinRipgrep()},outputLimits:{chars:encodeOutputLimit(config.getTruncateToolOutputThreshold()),lines:encodeOutputLimit(config.getTruncateToolOutputLines()),charsExplicit:config.isTruncateToolOutputThresholdExplicit()},fileFilteringOptions:{respectGitIgnore:filtering.respectGitIgnore,respectQwenIgnore:filtering.respectQwenIgnore,customIgnoreFiles:normalizeQwenCustomIgnoreFileNames(filtering.customIgnoreFiles)}}}__name(captureManagedToolExecutionContext,"captureManagedToolExecutionContext");function record(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))throw new ManagedToolProtocolError;const result=value;if(keys&&Object.keys(result).some(key=>!keys.includes(key)))throw new ManagedToolProtocolError;return result}__name(record,"record");function text(value,limit){if(typeof value!=="string"||!value.length||value.length>limit||value.includes("\0"))throw new ManagedToolProtocolError;return value}__name(text,"text");function uuid(value){const result=text(value,256);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result))throw new ManagedToolProtocolError;return result}__name(uuid,"uuid");function integer(value){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0)throw new ManagedToolProtocolError;return value}__name(integer,"integer");function timestamp(value){const result=text(value,32);const date=new Date(result);if(!Number.isFinite(date.getTime())||date.toISOString()!==result)throw new ManagedToolProtocolError;return result}__name(timestamp,"timestamp");function parseManagedToolFileHistoryPromptId(value){return text(value,128)}__name(parseManagedToolFileHistoryPromptId,"parseManagedToolFileHistoryPromptId");function snapshots(value){if(!Array.isArray(value)||value.length>MAX_SNAPSHOTS)throw new ManagedToolProtocolError;const prompts=new Set;return value.map(item=>{const snapshot=record(item,["promptId","timestamp","trackedFileBackups"]);const promptId=parseManagedToolFileHistoryPromptId(snapshot["promptId"]);if(prompts.has(promptId))throw new ManagedToolProtocolError;prompts.add(promptId);return{promptId,timestamp:timestamp(snapshot["timestamp"]),trackedFileBackups:Object.fromEntries(Object.entries(record(snapshot["trackedFileBackups"])).map(([filePath,value2])=>{text(filePath,4096);if(filePath.split(/[/\\]/).includes(".."))throw new ManagedToolProtocolError;const backup=record(value2,["backupFileName","version","backupTime","failed"]);const backupFileName=backup["backupFileName"]===null?null:text(backup["backupFileName"],256);if(backupFileName!==null&&(backupFileName==="."||backupFileName===".."||/[/\\]/.test(backupFileName)))throw new ManagedToolProtocolError;if("failed"in backup&&typeof backup["failed"]!=="boolean")throw new ManagedToolProtocolError;return[filePath,{backupFileName,version:integer(backup["version"]),backupTime:timestamp(backup["backupTime"]),..."failed"in backup?{failed:backup["failed"]}:{}}]}))}})}__name(snapshots,"snapshots");function absolutePath(value){const result=text(value,4096);if(!path.isAbsolute(result)||path.normalize(result)!==result)throw new ManagedToolProtocolError;return result}__name(absolutePath,"absolutePath");function encodeOutputLimit(value){return value===Number.POSITIVE_INFINITY?null:value}__name(encodeOutputLimit,"encodeOutputLimit");function outputLimit(value){if(value===null)return null;if(typeof value!=="number"||!Number.isFinite(value)||value<=0)throw new ManagedToolProtocolError;return value}__name(outputLimit,"outputLimit");function grepOptions(value){const input=record(value,["useRipgrep","useBuiltinRipgrep"]);if(typeof input["useRipgrep"]!=="boolean"||typeof input["useBuiltinRipgrep"]!=="boolean")throw new ManagedToolProtocolError;return{useRipgrep:input["useRipgrep"],useBuiltinRipgrep:input["useBuiltinRipgrep"]}}__name(grepOptions,"grepOptions");function outputLimits(value){const input=record(value,["chars","lines","charsExplicit"]);if(typeof input["charsExplicit"]!=="boolean")throw new ManagedToolProtocolError;return{chars:outputLimit(input["chars"]),lines:outputLimit(input["lines"]),charsExplicit:input["charsExplicit"]}}__name(outputLimits,"outputLimits");function executionContext(value){const input=record(value,["workspaceDirectories","memoryBaseDir","fileFilteringOptions","lsToolEnabled","grepOptions","outputLimits"]);const filtering=record(input["fileFilteringOptions"],["respectGitIgnore","respectQwenIgnore","customIgnoreFiles"]);if(!Array.isArray(input["workspaceDirectories"])||!Array.isArray(filtering["customIgnoreFiles"])||typeof filtering["respectGitIgnore"]!=="boolean"||typeof filtering["respectQwenIgnore"]!=="boolean"||typeof input["lsToolEnabled"]!=="boolean")throw new ManagedToolProtocolError;const directories=input["workspaceDirectories"].map(absolutePath);if(new Set(directories).size!==directories.length)throw new ManagedToolProtocolError;const customIgnoreFiles=filtering["customIgnoreFiles"].map(value2=>text(value2,4096));if(JSON.stringify(normalizeQwenCustomIgnoreFileNames(customIgnoreFiles))!==JSON.stringify(customIgnoreFiles))throw new ManagedToolProtocolError;return{workspaceDirectories:directories,memoryBaseDir:absolutePath(input["memoryBaseDir"]),lsToolEnabled:input["lsToolEnabled"],..."grepOptions"in input?{grepOptions:grepOptions(input["grepOptions"])}:{},..."outputLimits"in input?{outputLimits:outputLimits(input["outputLimits"])}:{},fileFilteringOptions:{respectGitIgnore:filtering["respectGitIgnore"],respectQwenIgnore:filtering["respectQwenIgnore"],customIgnoreFiles}}}__name(executionContext,"executionContext");function parseManagedToolFileHistoryBinding(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","ownerRuntimeSessionId","executionCwd","executionContext","snapshots"]);const executionCwd=text(input["executionCwd"],4096);if(!path.isAbsolute(executionCwd)||path.normalize(executionCwd)!==executionCwd)throw new ManagedToolProtocolError;return{ownerSessionId:uuid(input["ownerSessionId"]),ownerRuntimeSessionId:uuid(input["ownerRuntimeSessionId"]),executionCwd,..."executionContext"in input?{executionContext:executionContext(input["executionContext"])}:{},snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryBinding,"parseManagedToolFileHistoryBinding");function parseManagedToolFileHistoryState(value){managedToolDigest(value,MANAGED_TOOL_FILE_HISTORY_MAX_BYTES);const input=record(value,["ownerSessionId","revision","snapshots"]);return{ownerSessionId:uuid(input["ownerSessionId"]),revision:integer(input["revision"]),snapshots:snapshots(input["snapshots"])}}__name(parseManagedToolFileHistoryState,"parseManagedToolFileHistoryState");init_esbuild_shims();function historyPath(value){if(typeof value!=="string"||value==="."||normalizeWorkspaceRelativePath(value)!==value)throw new Error("Invalid Hosted file history path.");return value}__name(historyPath,"historyPath");function parseHostedFileHistoryState(value,owner){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid Hosted file history state.");const state=value;if(Object.keys(state).sort().join(",")!=="files,ownerSessionId,snapshots"||state["ownerSessionId"]!==owner)throw new Error("Hosted file history owner conflicts.");const{snapshots:snapshots2}=parseManagedToolFileHistoryState({ownerSessionId:owner,revision:0,snapshots:state["snapshots"]});const paths=new Set(snapshots2.flatMap(s=>Object.keys(s.trackedFileBackups).map(historyPath)));const files=state["files"];if(!files||typeof files!=="object"||Array.isArray(files)||Object.keys(files).length!==paths.size)throw new Error("Hosted file history files conflict.");for(const[file,expected]of Object.entries(files)){if(!paths.has(historyPath(file)))throw new Error("Hosted file history file is untracked.");if(expected!==null&&(typeof expected!=="object"||Array.isArray(expected)||Object.keys(expected).sort().join(",")!=="digest,mode"||!/^sha256:[a-f0-9]{64}$/.test(expected.digest)||!Number.isSafeInteger(expected.mode)||expected.mode<0||expected.mode>4095))throw new Error("Invalid Hosted file history file state.")}return structuredClone({ownerSessionId:owner,snapshots:snapshots2,files})}__name(parseHostedFileHistoryState,"parseHostedFileHistoryState");var HOSTED_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function parseHostedFileHistoryRecord(value,owner){const record2=value;if(!record2||typeof record2!=="object"||Array.isArray(record2)||record2.schemaVersion!==1||!(record2.pendingTurn===null||typeof record2.pendingTurn==="string")||record2.pendingMessageId!==void 0&&(typeof record2.pendingMessageId!=="string"||!record2.pendingTurn)||!(record2.pendingUndo===null||typeof record2.pendingUndo?.requestId==="string"&&typeof record2.pendingUndo.promptId==="string"))throw new Error("Invalid Hosted file history record.");const state=parseHostedFileHistoryState(record2.state,owner);const undoReceipts=record2.undoReceipts===void 0?[]:record2.undoReceipts;if(!Array.isArray(undoReceipts))throw new Error("Invalid Hosted file history undo receipts: expected an array.");const requests=new Set;const prompts=new Set(state.snapshots.map(snapshot=>snapshot.promptId));for(const[index,receipt]of undoReceipts.entries()){const invalid=__name(reason=>{throw new Error(`Invalid Hosted file history undo receipt ${index}: ${reason}.`)},"invalid");if(!receipt||typeof receipt!=="object"||Array.isArray(receipt)||Object.keys(receipt).sort().join(",")!=="conflict,filesChanged,promptId,requestId")invalid("expected exactly requestId, promptId, filesChanged and conflict");if(typeof receipt.requestId!=="string"||!HOSTED_UUID.test(receipt.requestId))invalid("requestId must be a lowercase UUID v1-v5");if(typeof receipt.promptId!=="string"||!HOSTED_UUID.test(receipt.promptId))invalid("promptId must be a lowercase UUID v1-v5");if(!prompts.has(receipt.promptId))invalid("promptId is not a retained snapshot");if(requests.has(receipt.requestId))invalid("requestId is duplicated");if(typeof receipt.conflict!=="boolean")invalid("conflict must be a boolean");if(!Array.isArray(receipt.filesChanged))invalid("filesChanged must be an array");if(receipt.filesChanged.some(file=>typeof file!=="string"||!Object.hasOwn(state.files,file)))invalid("filesChanged must contain only tracked paths");if(new Set(receipt.filesChanged).size!==receipt.filesChanged.length)invalid("filesChanged contains duplicate paths");if(receipt.conflict&&receipt.filesChanged.length!==0)invalid("conflict must have no changed paths");if(record2.pendingUndo?.requestId===receipt.requestId&&record2.pendingUndo.promptId!==receipt.promptId)invalid("promptId does not match pendingUndo");requests.add(receipt.requestId)}return{schemaVersion:1,state,pendingTurn:record2.pendingTurn,...record2.pendingMessageId!==void 0?{pendingMessageId:record2.pendingMessageId}:{},pendingUndo:record2.pendingUndo,undoReceipts}}__name(parseHostedFileHistoryRecord,"parseHostedFileHistoryRecord");init_esbuild_shims();import{createHash,randomBytes}from"node:crypto";var TOOL_PUBLICATION_PROTOCOL="managed-tool-publication/1";var TOOL_PUBLICATION_LIMITS=Object.freeze({maxBodyBytes:64*1024,maxCaptureBytes:2**41,producerBytes:2*1024*1024+64*1024+2*256*1024,admissionBytes:2*1024*1024});var BINDING_KEYS=["publication","publicationId","sessionKey","turnId","executionCallId","modelCallId","runtimeBindingId","reference","bindingGeneration","captureId","revision","captureScope","capturePolicy","argsRef","requestDigest","writerId","writerGeneration","activationId","activationEpoch","intentSequence","checkpointRef"];function requireValue(condition){if(!condition)throw new Error("Invalid managed tool publication.")}__name(requireValue,"requireValue");function closed(value,keys){requireValue(value!==null&&typeof value==="object");requireValue(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);const present=Object.keys(value);requireValue(present.length===keys.length&&present.every(key=>keys.includes(key)));return Object.fromEntries(present.map(key=>[key,value[key]]))}__name(closed,"closed");function id(value){return assertManagedSessionStableId(value,"publication id")}__name(id,"id");function token(value){const text2=id(value);requireValue(/^[a-z0-9_-]{1,128}$/.test(text2));return text2}__name(token,"token");function count(value,max=Number.MAX_SAFE_INTEGER-1){const result=assertManagedSessionSequence(value,"publication count");requireValue(result>0&&result<=max);return result}__name(count,"count");function wireDigest(value){requireValue(typeof value==="string"&&/^sha256:[0-9a-f]{64}$/.test(value));return value}__name(wireDigest,"wireDigest");function ref(value,kind){const result=assertManagedSessionDurableRef(value,"publication ref");requireValue(result.kind===kind&&result.schemaVersion===1&&result.byteLength>0&&result.byteLength<=(kind==="managed-checkpoint"?MANAGED_SESSION_LIMITS.maxEventBytes:TOOL_PUBLICATION_LIMITS.maxBodyBytes));return Object.freeze(result)}__name(ref,"ref");function bounded(value){requireValue(Buffer.byteLength(JSON.stringify(value))<=TOOL_PUBLICATION_LIMITS.maxBodyBytes);return Object.freeze(value)}__name(bounded,"bounded");function parseToolPublicationBinding(value){const r=closed(value,BINDING_KEYS);requireValue(r["publication"]===TOOL_PUBLICATION_PROTOCOL&&r["revision"]===1&&r["captureScope"]==="process_pipes"&&r["capturePolicy"]==="complete_required");const generation=id(r["bindingGeneration"]);requireValue(/^[1-9][0-9]{0,18}$/.test(generation)&&BigInt(generation)<=9223372036854775807n);const reference=closed(r["reference"],["sessionId","promptId","callId","argsDigest"]);return bounded({publication:TOOL_PUBLICATION_PROTOCOL,publicationId:token(r["publicationId"]),sessionKey:Object.freeze(assertManagedSessionKey(r["sessionKey"])),turnId:id(r["turnId"]),executionCallId:id(r["executionCallId"]),modelCallId:id(r["modelCallId"]),runtimeBindingId:id(r["runtimeBindingId"]),reference:Object.freeze({sessionId:id(reference["sessionId"]),promptId:id(reference["promptId"]),callId:id(reference["callId"]),argsDigest:wireDigest(reference["argsDigest"])}),bindingGeneration:generation,captureId:token(r["captureId"]),revision:1,captureScope:"process_pipes",capturePolicy:"complete_required",argsRef:ref(r["argsRef"],"managed-tool-input"),requestDigest:wireDigest(r["requestDigest"]),writerId:id(r["writerId"]),writerGeneration:count(r["writerGeneration"]),activationId:id(r["activationId"]),activationEpoch:count(r["activationEpoch"]),intentSequence:count(r["intentSequence"]),checkpointRef:ref(r["checkpointRef"],"managed-checkpoint")})}__name(parseToolPublicationBinding,"parseToolPublicationBinding");function toolPublicationManifestIdentity(binding){const b=parseToolPublicationBinding(binding);return{tenantId:b.sessionKey.tenantId,sessionId:b.sessionKey.sessionId,turnId:b.turnId,executionCallId:b.executionCallId,callId:b.reference.callId,invocationDigest:b.reference.argsDigest,bindingGeneration:b.bindingGeneration,captureId:b.captureId,revision:b.revision}}__name(toolPublicationManifestIdentity,"toolPublicationManifestIdentity");function createToolPublicationToken(){return randomBytes(32).toString("base64url")}__name(createToolPublicationToken,"createToolPublicationToken");export{MANAGED_TOOL_FILE_HISTORY_MAX_BYTES,captureManagedToolExecutionContext,parseManagedToolFileHistoryPromptId,parseManagedToolFileHistoryBinding,parseManagedToolFileHistoryState,historyPath,parseHostedFileHistoryState,HOSTED_UUID,parseHostedFileHistoryRecord,parseToolPublicationBinding,toolPublicationManifestIdentity,createToolPublicationToken};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import{PROVIDER_SOURCED_FIELDS}from"./chunk-GOR7FFVE.js";import{preloadRuntimeFetchModule}from"./chunk-ZZZAYAJW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function getDefaultApiKeyEnvVar(authType){switch(authType){case"openai":case"openai-responses":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}__name(getDefaultApiKeyEnvVar,"getDefaultApiKeyEnvVar");function getDefaultModelEnvVar(authType){switch(authType){case"openai":case"openai-responses":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}__name(getDefaultModelEnvVar,"getDefaultModelEnvVar");var VERTEX_ADC_HINT=" Alternatively, set GOOGLE_CLOUD_PROJECT to authenticate with Application Default Credentials instead of an API key.";function adcHint(authType,explicitEnvKey){return authType==="vertex-ai"&&!explicitEnvKey?VERTEX_ADC_HINT:""}__name(adcHint,"adcHint");var ModelConfigError=class extends Error{static{__name(this,"ModelConfigError")}constructor(message){super(message);this.name=new.target.name;Object.setPrototypeOf(this,new.target.prototype)}};var StrictMissingCredentialsError=class extends ModelConfigError{static{__name(this,"StrictMissingCredentialsError")}code="STRICT_MISSING_CREDENTIALS";constructor(authType,model,envKey){const providerKey=authType||"(unknown)";const modelName=model||"(unknown)";super(`Missing credentials for modelProviders model '${modelName}'. `+(envKey?`Current configured envKey: '${envKey}'. Set that environment variable, or update modelProviders.${providerKey}[].envKey.`:`Configure modelProviders.${providerKey}[].envKey and set that environment variable.`)+adcHint(authType,envKey))}};var StrictMissingModelIdError=class extends ModelConfigError{static{__name(this,"StrictMissingModelIdError")}code="STRICT_MISSING_MODEL_ID";constructor(authType){super(`Missing model id for strict modelProviders resolution (authType: ${authType}).`)}};var MissingApiKeyError=class extends ModelConfigError{static{__name(this,"MissingApiKeyError")}code="MISSING_API_KEY";constructor(params){super(`Missing API key for ${params.authType} auth. Current model: '${params.model||"(unknown)"}', baseUrl: '${params.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${params.envKey}'.`+adcHint(params.authType,params.explicitEnvKey))}};var MissingModelError=class extends ModelConfigError{static{__name(this,"MissingModelError")}code="MISSING_MODEL";constructor(params){super(`Missing model for ${params.authType} auth. Set the environment variable '${params.envKey}'.`)}};var MissingBaseUrlError=class extends ModelConfigError{static{__name(this,"MissingBaseUrlError")}code="MISSING_BASE_URL";constructor(params){super(`Missing baseUrl for modelProviders model '${params.model||"(unknown)"}'. Configure modelProviders.${params.authType||"(unknown)"}[].baseUrl.`)}};var MissingAnthropicBaseUrlEnvError=class extends ModelConfigError{static{__name(this,"MissingAnthropicBaseUrlEnvError")}code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};init_esbuild_shims();function setSource(sources,path,source){sources[path]=source}__name(setSource,"setSource");function getSeedSource(seed,path){return seed?.[path]}__name(getSeedSource,"getSeedSource");function resolveContentGeneratorConfigWithSources(config,authType,generationConfig,seedSources,options){const sources={...seedSources||{}};const strictModelProvider=options?.strictModelProvider===true;const newContentGeneratorConfig={...generationConfig||{},authType,reasoningSnapshot:generationConfig?.reasoningSnapshot??config?.getReasoningSnapshot?.(),reasoningRouteBaseUrl:generationConfig&&"reasoningRouteBaseUrl"in generationConfig?generationConfig.reasoningRouteBaseUrl:config?.getCurrentModelRegistryBaseUrl?.(),proxy:config?.getProxy()};setSource(sources,"authType",{kind:"computed",detail:"provided by caller"});if(config?.getProxy()){setSource(sources,"proxy",{kind:"computed",detail:"Config.getProxy()"})}const seedOrUnknown=__name(path=>getSeedSource(seedSources,path)??{kind:"unknown"},"seedOrUnknown");for(const field of PROVIDER_SOURCED_FIELDS){if(generationConfig&&field in generationConfig&&!sources[field]){setSource(sources,field,seedOrUnknown(field))}}const validation=validateModelConfig(newContentGeneratorConfig,strictModelProvider);if(!validation.valid){throw new Error(validation.errors.map(e=>e.message).join("\n"))}return{config:newContentGeneratorConfig,sources}}__name(resolveContentGeneratorConfigWithSources,"resolveContentGeneratorConfigWithSources");var VERTEX_PROJECT_ENV_VAR="GOOGLE_CLOUD_PROJECT";function hasVertexProjectConfigured(lookup=key=>process.env[key]){return!!lookup(VERTEX_PROJECT_ENV_VAR)?.trim()}__name(hasVertexProjectConfigured,"hasVertexProjectConfigured");function usesVertexApplicationDefaultCredentials(config){return config.authType==="vertex-ai"&&!config.apiKeyEnvKey&&hasVertexProjectConfigured()}__name(usesVertexApplicationDefaultCredentials,"usesVertexApplicationDefaultCredentials");function validateModelConfig(config,isStrictModelProvider=false){const errors=[];if(config.authType==="qwen-oauth"){return{valid:true,errors:[]}}if(!config.apiKey&&!usesVertexApplicationDefaultCredentials(config)){if(isStrictModelProvider){errors.push(new StrictMissingCredentialsError(config.authType,config.model,config.apiKeyEnvKey))}else{const envKey=config.apiKeyEnvKey||getDefaultApiKeyEnvVar(config.authType);errors.push(new MissingApiKeyError({authType:config.authType,model:config.model,baseUrl:config.baseUrl,envKey,explicitEnvKey:config.apiKeyEnvKey}))}}if(!config.model){if(isStrictModelProvider){errors.push(new StrictMissingModelIdError(config.authType))}else{const envKey=getDefaultModelEnvVar(config.authType);errors.push(new MissingModelError({authType:config.authType,envKey}))}}if(config.authType==="anthropic"&&!config.baseUrl){if(isStrictModelProvider){errors.push(new MissingBaseUrlError({authType:config.authType,model:config.model}))}else if(config.authType==="anthropic"){errors.push(new MissingAnthropicBaseUrlEnvError)}}return{valid:errors.length===0,errors}}__name(validateModelConfig,"validateModelConfig");function getModuleNotFoundError(error){let current=error;while(current instanceof Error){if("code"in current&&current.code==="ERR_MODULE_NOT_FOUND"){return current}current=current.cause}return void 0}__name(getModuleNotFoundError,"getModuleNotFoundError");function wrapProviderLoadError(error,authType){const moduleNotFoundError=getModuleNotFoundError(error);if(!moduleNotFoundError){return error}return new Error(`Qwen Code was updated in the background and needs to be restarted.
4
- Please exit and restart Qwen Code to use the '${authType}' provider.`,{cause:moduleNotFoundError})}__name(wrapProviderLoadError,"wrapProviderLoadError");var LazyContentGenerator=class{constructor(loader){this.loader=loader}static{__name(this,"LazyContentGenerator")}generatorPromise;preloadedOnly=false;getGenerator(){this.generatorPromise??=this.loader();return this.generatorPromise}getGeneratorForUse(){this.preloadedOnly=false;return this.getGenerator()}preload(){if(!this.generatorPromise){this.preloadedOnly=true}return this.getGenerator()}resetPreload(){if(!this.preloadedOnly)return;this.preloadedOnly=false;this.generatorPromise=void 0}async generateContent(request,userPromptId){return(await this.getGeneratorForUse()).generateContent(request,userPromptId)}async generateContentStream(request,userPromptId){return(await this.getGeneratorForUse()).generateContentStream(request,userPromptId)}async embedContent(request){return(await this.getGeneratorForUse()).embedContent(request)}};async function preloadContentGenerator(generator){if(generator instanceof LazyContentGenerator){await generator.preload()}}__name(preloadContentGenerator,"preloadContentGenerator");function resetPreloadedContentGenerator(generator){if(generator instanceof LazyContentGenerator){generator.resetPreload()}}__name(resetPreloadedContentGenerator,"resetPreloadedContentGenerator");async function createContentGenerator(generatorConfig,config,isInitialAuth){const validation=validateModelConfig(generatorConfig,false);if(!validation.valid){throw new Error(validation.errors.map(e=>e.message).join("\n"))}const authType=generatorConfig.authType;if(!authType){throw new Error("ContentGeneratorConfig must have an authType")}await preloadRuntimeFetchModule();let loadBaseGenerator;try{if(authType==="openai"){loadBaseGenerator=__name(async()=>{const{createOpenAIContentGenerator}=await import("./openaiContentGenerator-XRXX33FY.js");return createOpenAIContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="openai-responses"){loadBaseGenerator=__name(async()=>{const{createOpenAIResponsesContentGenerator}=await import("./openaiResponsesContentGenerator-L6ONEHMR.js");return createOpenAIResponsesContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="qwen-oauth"){const{getQwenOAuthClient:getQwenOauthClient}=await import("./qwenOAuth2-B7D5JO3Y.js");try{const qwenClient=await getQwenOauthClient(config,isInitialAuth?{requireCachedCredentials:true}:void 0);loadBaseGenerator=__name(async()=>{const{QwenContentGenerator}=await import("./qwenContentGenerator-QSA32XEL.js");return new QwenContentGenerator(qwenClient,generatorConfig,config)},"loadBaseGenerator")}catch(error){if(getModuleNotFoundError(error)){throw error}throw new Error(error instanceof Error?error.message:String(error))}}else if(authType==="anthropic"){loadBaseGenerator=__name(async()=>{const{createAnthropicContentGenerator}=await import("./anthropicContentGenerator-V7TX2NXP.js");return createAnthropicContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="gemini"||authType==="vertex-ai"){loadBaseGenerator=__name(async()=>{const{createLlmContentGenerator}=await import("./llm-content-generator-VMUBA7OJ.js");return createLlmContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else{throw new Error(`Error creating contentGenerator: Unsupported authType: ${authType}`)}}catch(error){throw wrapProviderLoadError(error,authType)}return new LazyContentGenerator(async()=>{try{const[baseGenerator,{LoggingContentGenerator}]=await Promise.all([loadBaseGenerator(),import("./loggingContentGenerator-2MHAI6JR.js")]);return new LoggingContentGenerator(baseGenerator,config,generatorConfig)}catch(error){throw wrapProviderLoadError(error,authType)}})}__name(createContentGenerator,"createContentGenerator");export{getDefaultApiKeyEnvVar,VERTEX_ADC_HINT,resolveContentGeneratorConfigWithSources,hasVertexProjectConfigured,preloadContentGenerator,resetPreloadedContentGenerator,createContentGenerator};
4
+ Please exit and restart Qwen Code to use the '${authType}' provider.`,{cause:moduleNotFoundError})}__name(wrapProviderLoadError,"wrapProviderLoadError");var LazyContentGenerator=class{constructor(loader){this.loader=loader}static{__name(this,"LazyContentGenerator")}generatorPromise;preloadedOnly=false;getGenerator(){this.generatorPromise??=this.loader();return this.generatorPromise}getGeneratorForUse(){this.preloadedOnly=false;return this.getGenerator()}preload(){if(!this.generatorPromise){this.preloadedOnly=true}return this.getGenerator()}resetPreload(){if(!this.preloadedOnly)return;this.preloadedOnly=false;this.generatorPromise=void 0}async generateContent(request,userPromptId){return(await this.getGeneratorForUse()).generateContent(request,userPromptId)}async generateContentStream(request,userPromptId){return(await this.getGeneratorForUse()).generateContentStream(request,userPromptId)}async embedContent(request){return(await this.getGeneratorForUse()).embedContent(request)}};async function preloadContentGenerator(generator){if(generator instanceof LazyContentGenerator){await generator.preload()}}__name(preloadContentGenerator,"preloadContentGenerator");function resetPreloadedContentGenerator(generator){if(generator instanceof LazyContentGenerator){generator.resetPreload()}}__name(resetPreloadedContentGenerator,"resetPreloadedContentGenerator");async function createContentGenerator(generatorConfig,config,isInitialAuth){const validation=validateModelConfig(generatorConfig,false);if(!validation.valid){throw new Error(validation.errors.map(e=>e.message).join("\n"))}const authType=generatorConfig.authType;if(!authType){throw new Error("ContentGeneratorConfig must have an authType")}await preloadRuntimeFetchModule();let loadBaseGenerator;try{if(authType==="openai"){loadBaseGenerator=__name(async()=>{const{createOpenAIContentGenerator}=await import("./openaiContentGenerator-6B5MAU54.js");return createOpenAIContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="openai-responses"){loadBaseGenerator=__name(async()=>{const{createOpenAIResponsesContentGenerator}=await import("./openaiResponsesContentGenerator-I245I3R7.js");return createOpenAIResponsesContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="qwen-oauth"){const{getQwenOAuthClient:getQwenOauthClient}=await import("./qwenOAuth2-B7D5JO3Y.js");try{const qwenClient=await getQwenOauthClient(config,isInitialAuth?{requireCachedCredentials:true}:void 0);loadBaseGenerator=__name(async()=>{const{QwenContentGenerator}=await import("./qwenContentGenerator-IEDZONWG.js");return new QwenContentGenerator(qwenClient,generatorConfig,config)},"loadBaseGenerator")}catch(error){if(getModuleNotFoundError(error)){throw error}throw new Error(error instanceof Error?error.message:String(error))}}else if(authType==="anthropic"){loadBaseGenerator=__name(async()=>{const{createAnthropicContentGenerator}=await import("./anthropicContentGenerator-MGTJJGEQ.js");return createAnthropicContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="gemini"||authType==="vertex-ai"){loadBaseGenerator=__name(async()=>{const{createLlmContentGenerator}=await import("./llm-content-generator-MDRBSH73.js");return createLlmContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else{throw new Error(`Error creating contentGenerator: Unsupported authType: ${authType}`)}}catch(error){throw wrapProviderLoadError(error,authType)}return new LazyContentGenerator(async()=>{try{const[baseGenerator,{LoggingContentGenerator}]=await Promise.all([loadBaseGenerator(),import("./loggingContentGenerator-CK7IKYQH.js")]);return new LoggingContentGenerator(baseGenerator,config,generatorConfig)}catch(error){throw wrapProviderLoadError(error,authType)}})}__name(createContentGenerator,"createContentGenerator");export{getDefaultApiKeyEnvVar,VERTEX_ADC_HINT,resolveContentGeneratorConfigWithSources,hasVertexProjectConfigured,preloadContentGenerator,resetPreloadedContentGenerator,createContentGenerator};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{JsonFormatter}from"./chunk-OU7CEG7Q.js";import{parseAndFormatApiError}from"./chunk-2JGTWRZJ.js";import{runExitCleanup}from"./chunk-AYVCT5FF.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{FatalBudgetExceededError,FatalCancellationError,FatalTurnLimitedError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("CLI_ERRORS");var AlreadyReportedError=class extends Error{static{__name(this,"AlreadyReportedError")}exitCode;constructor(message,exitCode=1){super(message);this.name="AlreadyReportedError";this.exitCode=exitCode}};function getErrorMessage(error){if(error instanceof Error){return error.message}if(error!==null&&typeof error==="object"&&"message"in error&&typeof error.message==="string"){return error.message}if(error!==null&&typeof error==="object"){try{const stringified=JSON.stringify(error);return stringified??String(error)}catch{return String(error)}}return String(error)}__name(getErrorMessage,"getErrorMessage");function extractErrorCode(error){const errorWithCode=error;if(typeof errorWithCode.exitCode==="number"){return errorWithCode.exitCode}if(errorWithCode.code!==void 0){return errorWithCode.code}if(errorWithCode.status!==void 0){return errorWithCode.status}return 1}__name(extractErrorCode,"extractErrorCode");function getNumericExitCode(errorCode){return typeof errorCode==="number"?errorCode:1}__name(getNumericExitCode,"getNumericExitCode");var exiting=false;async function exitAfterCleanup(code){if(exiting)return new Promise(()=>{});exiting=true;await runExitCleanup();return process.exit(code)}__name(exitAfterCleanup,"exitAfterCleanup");function _resetExitLatchForTest(){exiting=false}__name(_resetExitLatchForTest,"_resetExitLatchForTest");async function handleError(error,config,customErrorCode){if(error instanceof AlreadyReportedError){if(config.getOutputFormat()==="json"){const formatter=new JsonFormatter;const errorCode=customErrorCode??error.exitCode;const formattedError=formatter.formatError(error,errorCode);writeStderrLine(formattedError);return exitAfterCleanup(getNumericExitCode(errorCode))}await runExitCleanup();throw error}const errorMessage=parseAndFormatApiError(error,config.getContentGeneratorConfig()?.authType);if(config.getOutputFormat()==="json"){const formatter=new JsonFormatter;const errorCode=customErrorCode??extractErrorCode(error);const formattedError=formatter.formatError(error instanceof Error?error:new Error(getErrorMessage(error)),errorCode);writeStderrLine(formattedError);return exitAfterCleanup(getNumericExitCode(errorCode))}else{writeStderrLine(errorMessage);await runExitCleanup();throw error}}__name(handleError,"handleError");var TOOL_NAME_ECHO_LIMIT=64;var DENIAL_REASON_ECHO_LIMIT=500;function sanitizeForStderr(text,limit){const clean=stripAnsiAndControl(text.replace(/\s+/g," ")).replace(new RegExp("\\p{Cf}","gu"),"").trim();return clean.length>limit?`${clean.slice(0,limit)}\u2026`:clean}__name(sanitizeForStderr,"sanitizeForStderr");function handleToolError(toolName,toolError,config,errorCode,resultDisplay,options={}){const isExecutionDenied=errorCode==="execution_denied";const isNonInteractive=!config.isInteractive();const isTextMode=config.getOutputFormat()==="text";if(isExecutionDenied&&isNonInteractive&&isTextMode){const displayName=sanitizeForStderr(toolName,TOOL_NAME_ECHO_LIMIT);if(options.approvalRequired){process.stderr.write(`Warning: Tool "${displayName}" requires user approval but cannot execute in non-interactive mode.
3
+ import{JsonFormatter}from"./chunk-CK3OKTTL.js";import{parseAndFormatApiError}from"./chunk-T3CQ72HC.js";import{runExitCleanup}from"./chunk-3ICJI5KW.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{FatalBudgetExceededError,FatalCancellationError,FatalTurnLimitedError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("CLI_ERRORS");var AlreadyReportedError=class extends Error{static{__name(this,"AlreadyReportedError")}exitCode;constructor(message,exitCode=1){super(message);this.name="AlreadyReportedError";this.exitCode=exitCode}};function getErrorMessage(error){if(error instanceof Error){return error.message}if(error!==null&&typeof error==="object"&&"message"in error&&typeof error.message==="string"){return error.message}if(error!==null&&typeof error==="object"){try{const stringified=JSON.stringify(error);return stringified??String(error)}catch{return String(error)}}return String(error)}__name(getErrorMessage,"getErrorMessage");function extractErrorCode(error){const errorWithCode=error;if(typeof errorWithCode.exitCode==="number"){return errorWithCode.exitCode}if(errorWithCode.code!==void 0){return errorWithCode.code}if(errorWithCode.status!==void 0){return errorWithCode.status}return 1}__name(extractErrorCode,"extractErrorCode");function getNumericExitCode(errorCode){return typeof errorCode==="number"?errorCode:1}__name(getNumericExitCode,"getNumericExitCode");var exiting=false;async function exitAfterCleanup(code){if(exiting)return new Promise(()=>{});exiting=true;await runExitCleanup();return process.exit(code)}__name(exitAfterCleanup,"exitAfterCleanup");function _resetExitLatchForTest(){exiting=false}__name(_resetExitLatchForTest,"_resetExitLatchForTest");async function handleError(error,config,customErrorCode){if(error instanceof AlreadyReportedError){if(config.getOutputFormat()==="json"){const formatter=new JsonFormatter;const errorCode=customErrorCode??error.exitCode;const formattedError=formatter.formatError(error,errorCode);writeStderrLine(formattedError);return exitAfterCleanup(getNumericExitCode(errorCode))}await runExitCleanup();throw error}const errorMessage=parseAndFormatApiError(error,config.getContentGeneratorConfig()?.authType);if(config.getOutputFormat()==="json"){const formatter=new JsonFormatter;const errorCode=customErrorCode??extractErrorCode(error);const formattedError=formatter.formatError(error instanceof Error?error:new Error(getErrorMessage(error)),errorCode);writeStderrLine(formattedError);return exitAfterCleanup(getNumericExitCode(errorCode))}else{writeStderrLine(errorMessage);await runExitCleanup();throw error}}__name(handleError,"handleError");var TOOL_NAME_ECHO_LIMIT=64;var DENIAL_REASON_ECHO_LIMIT=500;function sanitizeForStderr(text,limit){const clean=stripAnsiAndControl(text.replace(/\s+/g," ")).replace(new RegExp("\\p{Cf}","gu"),"").trim();return clean.length>limit?`${clean.slice(0,limit)}\u2026`:clean}__name(sanitizeForStderr,"sanitizeForStderr");function handleToolError(toolName,toolError,config,errorCode,resultDisplay,options={}){const isExecutionDenied=errorCode==="execution_denied";const isNonInteractive=!config.isInteractive();const isTextMode=config.getOutputFormat()==="text";if(isExecutionDenied&&isNonInteractive&&isTextMode){const displayName=sanitizeForStderr(toolName,TOOL_NAME_ECHO_LIMIT);if(options.approvalRequired){process.stderr.write(`Warning: Tool "${displayName}" requires user approval but cannot execute in non-interactive mode.
4
4
  To enable automatic tool execution, use the -y flag (YOLO mode):
5
5
  Example: qwen -p 'your prompt' -y
6
6