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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/chunks/{MaxSizedBox-XGJBXFET.js → MaxSizedBox-QRQEXRXW.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-BNFJWFLQ.js → StandaloneSessionPicker-X274Q6BX.js} +1 -1
  3. package/chunks/{acp-subagent-executor-P5FBYPD5.js → acp-subagent-executor-YIFQD4LJ.js} +1 -1
  4. package/chunks/{acpAgent-J6G57ZCE.js → acpAgent-NW4XNW7P.js} +3 -3
  5. package/chunks/{advisor-3O63GFOM.js → advisor-W7KCVPBR.js} +1 -1
  6. package/chunks/{agent-ALZEISY2.js → agent-FGDWPNXW.js} +1 -1
  7. package/chunks/{agent-headless-XAKKB6OT.js → agent-headless-7KA3VVAB.js} +1 -1
  8. package/chunks/{agent-host-client-DIV2XAL5.js → agent-host-client-YZJLSOLB.js} +1 -1
  9. package/chunks/{agent-host-connections-ZQUMCO2F.js → agent-host-connections-5JGDPG3L.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-ZE7TAQPO.js → anthropicContentGenerator-QUXJVJ3I.js} +1 -1
  11. package/chunks/{autofix-pr-RZ4PWQ46.js → autofix-pr-UDRPJC7L.js} +1 -1
  12. package/chunks/{batch-AIMBHUMX.js → batch-GCEHGR5P.js} +1 -1
  13. package/chunks/{bridge-A3RRGPEI.js → bridge-JY2JXNVV.js} +1 -1
  14. package/chunks/{channel-settings-store-P3KM5GTN.js → channel-settings-store-EX6ZU6R3.js} +1 -1
  15. package/chunks/{chunk-P22U5UQR.js → chunk-27MJJU2I.js} +1 -1
  16. package/chunks/{chunk-RYRMDOIX.js → chunk-2LDABIAY.js} +3 -3
  17. package/chunks/{chunk-MYPEVUKI.js → chunk-2QZDPMIH.js} +1 -1
  18. package/chunks/{chunk-TW2REHPX.js → chunk-2SGTJMSU.js} +1 -1
  19. package/chunks/{chunk-NCW3NPS5.js → chunk-3BHXPXCC.js} +1 -1
  20. package/chunks/{chunk-XUB4JKSR.js → chunk-3NR3JBMA.js} +6 -6
  21. package/chunks/{chunk-NRJOUWP4.js → chunk-3QCFMVI6.js} +1 -1
  22. package/chunks/{chunk-EGMV4S6D.js → chunk-3YOERSU5.js} +1 -1
  23. package/chunks/{chunk-WXKD4L4A.js → chunk-4NIUXYUF.js} +1 -1
  24. package/chunks/{chunk-YHC27L5W.js → chunk-5FS5OQHO.js} +1 -1
  25. package/chunks/{chunk-L76RFQKW.js → chunk-5MGG2BGT.js} +1 -1
  26. package/chunks/{chunk-HHDQ5JAA.js → chunk-66LFVQJP.js} +1 -1
  27. package/chunks/{chunk-RJPELYUW.js → chunk-6KU7LHBT.js} +1 -1
  28. package/chunks/{chunk-SKU5J7Q7.js → chunk-6O7CARPF.js} +1 -1
  29. package/chunks/{chunk-CPOFE42B.js → chunk-6Z3TBTUS.js} +1 -1
  30. package/chunks/{chunk-HRRQHZQE.js → chunk-73TSS7KS.js} +1 -1
  31. package/chunks/{chunk-BSGONILH.js → chunk-776L3HAN.js} +1 -1
  32. package/chunks/{chunk-MZNZYCAC.js → chunk-7BL2OTHX.js} +1 -1
  33. package/chunks/{chunk-5DPLJQUC.js → chunk-7GYFDPEP.js} +1 -1
  34. package/chunks/{chunk-OD44AOSX.js → chunk-7KGCNYE4.js} +1 -1
  35. package/chunks/{chunk-4JLLFT6S.js → chunk-7SX547WS.js} +1 -1
  36. package/chunks/{chunk-5Q6POUDM.js → chunk-7VIES3RW.js} +1 -1
  37. package/chunks/{chunk-NMK72ZA4.js → chunk-ABEBQNYK.js} +1 -1
  38. package/chunks/{chunk-QZ5JBF3E.js → chunk-AD7JBW6R.js} +2 -2
  39. package/chunks/{chunk-E6XRNALG.js → chunk-AEX3XSTE.js} +1 -1
  40. package/chunks/{chunk-B7CYUTAO.js → chunk-AKDODQCI.js} +1 -1
  41. package/chunks/{chunk-EEARSY3D.js → chunk-B3I5LFFK.js} +1 -1
  42. package/chunks/{chunk-YSGVX6LT.js → chunk-B5Y56PDI.js} +1 -1
  43. package/chunks/{chunk-MEFN5DY3.js → chunk-BEBKKJP3.js} +1 -1
  44. package/chunks/{chunk-GYCGVZ32.js → chunk-BFPP7X4E.js} +1 -1
  45. package/chunks/{chunk-GNWPYWGQ.js → chunk-BY5GX6DQ.js} +1 -1
  46. package/chunks/{chunk-6W5ZZSQF.js → chunk-CUX3C6QV.js} +1 -1
  47. package/chunks/{chunk-HXYHIEMH.js → chunk-CXPRHT3E.js} +1 -1
  48. package/chunks/{chunk-53CWA7N2.js → chunk-D5H5GARR.js} +1 -1
  49. package/chunks/{chunk-DV67DRNT.js → chunk-DLY7QJ5Y.js} +1 -1
  50. package/chunks/{chunk-SFDOJ2FF.js → chunk-DN4QKOFL.js} +1 -1
  51. package/chunks/{chunk-VOAIDOUV.js → chunk-DP4YE24V.js} +1 -1
  52. package/chunks/{chunk-D2X6A5FH.js → chunk-DQLI7HH7.js} +1 -1
  53. package/chunks/{chunk-ET7ADS4X.js → chunk-DS2FKATN.js} +1 -1
  54. package/chunks/{chunk-FRSSRLIO.js → chunk-E6EW43WZ.js} +1 -1
  55. package/chunks/{chunk-F4AWT5LV.js → chunk-EEBFFC76.js} +1 -1
  56. package/chunks/{chunk-B7PJ5TNK.js → chunk-EGKUF5NS.js} +2 -2
  57. package/chunks/{chunk-B2YLVSQE.js → chunk-ERMAKXS3.js} +2 -2
  58. package/chunks/{chunk-PEZZTKPM.js → chunk-FB73O3E5.js} +1 -1
  59. package/chunks/{chunk-36DBNBTF.js → chunk-FEIUMWFA.js} +1 -1
  60. package/chunks/{chunk-YE3LA3U4.js → chunk-FWJKQA2H.js} +1 -1
  61. package/chunks/{chunk-VDNPMX5W.js → chunk-FZQJOSHD.js} +1 -1
  62. package/chunks/{chunk-YYSMMFK7.js → chunk-GNI5J2ON.js} +1 -1
  63. package/chunks/{chunk-6OCKLRQC.js → chunk-H3VGRICV.js} +1 -1
  64. package/chunks/{chunk-OSLFWRV2.js → chunk-HRTWLOGK.js} +1 -1
  65. package/chunks/{chunk-XZYQKCTU.js → chunk-IGIZ6AZE.js} +1 -1
  66. package/chunks/{chunk-RIBVEHUG.js → chunk-IHB7CDQ2.js} +1 -1
  67. package/chunks/{chunk-LO6OFMFC.js → chunk-IHEGGZBE.js} +1 -1
  68. package/chunks/{chunk-N5S6SIRO.js → chunk-IMTHBYJP.js} +1 -1
  69. package/chunks/{chunk-I5F24CVP.js → chunk-IP3K5SRR.js} +1 -1
  70. package/chunks/{chunk-2FYWJVGW.js → chunk-ISA4MFNT.js} +1 -1
  71. package/chunks/{chunk-GV3E2RHX.js → chunk-JGF3ND5D.js} +1 -1
  72. package/chunks/{chunk-ASQ7BSJ4.js → chunk-JJ4UPR4A.js} +1 -1
  73. package/chunks/{chunk-HOCNE2LO.js → chunk-JTUWFGEB.js} +1 -1
  74. package/chunks/{chunk-FDQFJFO5.js → chunk-KAN5KUJD.js} +1 -1
  75. package/chunks/{chunk-K7GCWWTI.js → chunk-KU4F6SSJ.js} +2 -2
  76. package/chunks/{chunk-QDQQFQB4.js → chunk-LBAINHIN.js} +1 -1
  77. package/chunks/{chunk-BAPIZCC7.js → chunk-LTJLPYFS.js} +1 -1
  78. package/chunks/{chunk-ZOUMCSDW.js → chunk-MSNPEQ2I.js} +1 -1
  79. package/chunks/{chunk-MPDGSR2S.js → chunk-N3YWQWSR.js} +5 -5
  80. package/chunks/{chunk-VEVQB4CI.js → chunk-NDTPBVER.js} +1 -1
  81. package/chunks/{chunk-L4WG2XDS.js → chunk-NJ77L3GS.js} +1 -1
  82. package/chunks/{chunk-U2DX235N.js → chunk-NL62UQDW.js} +1 -1
  83. package/chunks/{chunk-QASJXL5B.js → chunk-NYXR2655.js} +1 -1
  84. package/chunks/{chunk-5SPQ5V35.js → chunk-OEPXWKZL.js} +1 -1
  85. package/chunks/{chunk-EOR7AP7Z.js → chunk-OIKWJN7E.js} +1 -1
  86. package/chunks/{chunk-BT7V3O75.js → chunk-OIQKVWR7.js} +1 -1
  87. package/chunks/{chunk-ESXBBANA.js → chunk-OPBSEVFC.js} +1 -1
  88. package/chunks/{chunk-NW3H676V.js → chunk-P5RBFVMP.js} +1 -1
  89. package/chunks/{chunk-F7KVMGGZ.js → chunk-QD4KNY2J.js} +1 -1
  90. package/chunks/{chunk-2ZE6CAZV.js → chunk-RSLBGXPB.js} +1 -1
  91. package/chunks/{chunk-3R7NEEW7.js → chunk-S542WTV7.js} +1 -1
  92. package/chunks/{chunk-KXAZ2Z5M.js → chunk-SEK234IM.js} +1 -1
  93. package/chunks/{chunk-5DPXLL3H.js → chunk-TM6IVXAM.js} +1 -1
  94. package/chunks/{chunk-KMJLEAS3.js → chunk-TPTV6HPU.js} +1 -1
  95. package/chunks/{chunk-DCUBMMWG.js → chunk-TQ6FKWSC.js} +1 -1
  96. package/chunks/{chunk-JK2S74SA.js → chunk-TUBHG6EI.js} +1 -1
  97. package/chunks/{chunk-FMZ5U7J5.js → chunk-UBPC3F32.js} +1 -1
  98. package/chunks/{chunk-XB7DJWOJ.js → chunk-UG5B4UOQ.js} +6 -6
  99. package/chunks/{chunk-36S57YYW.js → chunk-UGWTN5IK.js} +1 -1
  100. package/chunks/{chunk-SK2DTYBZ.js → chunk-URMRX2MG.js} +1 -1
  101. package/chunks/{chunk-VB4DB57C.js → chunk-UY6J5CHF.js} +1 -1
  102. package/chunks/{chunk-STQ3TEZW.js → chunk-VSTQT667.js} +2 -2
  103. package/chunks/{chunk-SGUUOXLH.js → chunk-WDO33SWR.js} +1 -1
  104. package/chunks/{chunk-IVXR5JO2.js → chunk-WFJHBU7B.js} +1 -1
  105. package/chunks/{chunk-BINJRUHZ.js → chunk-XSRHGC5R.js} +1 -1
  106. package/chunks/{chunk-HN7EGFIP.js → chunk-XVF3FMTM.js} +1 -1
  107. package/chunks/{chunk-C5X6K67T.js → chunk-XYRNYCRQ.js} +1 -1
  108. package/chunks/{chunk-HZOPWFFL.js → chunk-YAMLF3SM.js} +1 -1
  109. package/chunks/{chunk-CMW64XU2.js → chunk-ZEZCRRQC.js} +1 -1
  110. package/chunks/{chunk-J5W6P7QD.js → chunk-ZF56DRDP.js} +1 -1
  111. package/chunks/{chunk-LHIEE3A2.js → chunk-ZSPOFXP3.js} +1 -1
  112. package/chunks/{chunk-Q6CXEN4H.js → chunk-ZZXAOGUV.js} +1 -1
  113. package/chunks/{codex-subagent-executor-HB3MUCY4.js → codex-subagent-executor-7RAVQBYA.js} +1 -1
  114. package/chunks/{config-utils-F7OF5UR2.js → config-utils-JFD4RJK3.js} +1 -1
  115. package/chunks/{contextCommand-Y3KO2FY6.js → contextCommand-U6CD3CW7.js} +1 -1
  116. package/chunks/{core-runtime-D7DAA5NY.js → core-runtime-ORCZRJ4O.js} +1 -1
  117. package/chunks/{create-sub-session-2HTWYAP4.js → create-sub-session-57WMU2AE.js} +1 -1
  118. package/chunks/{cron-create-Y5I6E2X4.js → cron-create-V466MOUE.js} +1 -1
  119. package/chunks/{daemon-git-worktree-guard-UOBMXOUC.js → daemon-git-worktree-guard-ATD77XOF.js} +1 -1
  120. package/chunks/{daemon-status-provider-L2225KDS.js → daemon-status-provider-5FVRNMAZ.js} +1 -1
  121. package/chunks/{daemon-trust-policy-5D52N5GL.js → daemon-trust-policy-6YRQV4ZM.js} +1 -1
  122. package/chunks/{daemon-trust-policy-monitor-RUE25K7A.js → daemon-trust-policy-monitor-QRUOWZQP.js} +1 -1
  123. package/chunks/{deferred-core-runtime-6BO5DI5B.js → deferred-core-runtime-TXIXMDDH.js} +1 -1
  124. package/chunks/{edit-B6DKSK3O.js → edit-FNXBINJ3.js} +1 -1
  125. package/chunks/{enterPlanMode-WVJ3XC3P.js → enterPlanMode-YMLAOTTS.js} +1 -1
  126. package/chunks/{environment-7WMACN3E.js → environment-RFNJLRF7.js} +1 -1
  127. package/chunks/{errors-BN73QF2O.js → errors-NHGSZ2BV.js} +1 -1
  128. package/chunks/{execution-tool-IGDH3MQT.js → execution-tool-L2BF6ZKP.js} +1 -1
  129. package/chunks/{execution-worker-WWP3JZGV.js → execution-worker-F5B2BI2W.js} +1 -1
  130. package/chunks/{exitPlanMode-7WHKOTS7.js → exitPlanMode-ZZVBF5V4.js} +1 -1
  131. package/chunks/{fast-path-B37HGFQO.js → fast-path-TOJYOAD3.js} +1 -1
  132. package/chunks/{glob-ZRXU5G5X.js → glob-SYPMYU4V.js} +1 -1
  133. package/chunks/{goal-tools-DQ5IZXCM.js → goal-tools-NOXNXZFR.js} +1 -1
  134. package/chunks/{handleAutoUpdate-FD7QAG2R.js → handleAutoUpdate-RS6Y2IWS.js} +1 -1
  135. package/chunks/{i18n-TI3ZCEHR.js → i18n-WWZD25J5.js} +1 -1
  136. package/chunks/{initializer-SB7P3LRU.js → initializer-YGR4YXAM.js} +1 -1
  137. package/chunks/{installationInfo-B337C7R4.js → installationInfo-EPURVILN.js} +1 -1
  138. package/chunks/{interactive-mod-session-OWRMETPP.js → interactive-mod-session-2VSTTHPA.js} +1 -1
  139. package/chunks/{list-2QKQIEOB.js → list-6JAKVRMZ.js} +1 -1
  140. package/chunks/{llm-GQ76E4DL.js → llm-V272EOVL.js} +4 -4
  141. package/chunks/{llm-content-generator-2A23HFLD.js → llm-content-generator-EXMC3NYS.js} +1 -1
  142. package/chunks/{loadedSettingsAdapter-RGQOA5BG.js → loadedSettingsAdapter-T6W2CKFA.js} +1 -1
  143. package/chunks/{local-OEBLERSJ.js → local-NUBKA3T2.js} +1 -1
  144. package/chunks/{local-execution-environment-FT5J4SUH.js → local-execution-environment-WO62QDKJ.js} +1 -1
  145. package/chunks/{loggingContentGenerator-WC23RZYM.js → loggingContentGenerator-KHRN6S3S.js} +1 -1
  146. package/chunks/{loop-wakeup-GIIIDUNG.js → loop-wakeup-TTAZMOYH.js} +1 -1
  147. package/chunks/{manage-memory-E2OAR2RV.js → manage-memory-BKA7QM4N.js} +1 -1
  148. package/chunks/{managed-execution-engine-CYYNVVP5.js → managed-execution-engine-32BLALNC.js} +1 -1
  149. package/chunks/{managed-local-serve-TUVNNY7K.js → managed-local-serve-UTJFLZI6.js} +1 -1
  150. package/chunks/{managed-npm-update-IDRZ32UK.js → managed-npm-update-XPIRAQ47.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-HON7TGY2.js → managed-runtime-attestation-worker-DDU4HUGS.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-OMLX5CTV.js → managed-runtime-bootstrap-7TTCLDQJ.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-J3P7WMDW.js → managed-runtime-session-worker-WBYLRXU3.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-LPFPOBTL.js → managed-runtime-ssh-worker-X2U2OK2E.js} +1 -1
  155. package/chunks/{managed-session-authority-I5OHOM7N.js → managed-session-authority-U76OGS6U.js} +1 -1
  156. package/chunks/{mcp-CGDIDRDI.js → mcp-UROGTJ3U.js} +1 -1
  157. package/chunks/{memory-VKXOH5UM.js → memory-M4OF6FV7.js} +1 -1
  158. package/chunks/{model-call-collection-ZTYFDFBB.js → model-call-collection-TW6Q7SXP.js} +1 -1
  159. package/chunks/{model-configuration-EXLM4SD3.js → model-configuration-4PJUBAYR.js} +1 -1
  160. package/chunks/{modelConfigUtils-XDMB6XPY.js → modelConfigUtils-ARMBTDAK.js} +1 -1
  161. package/chunks/{monitor-LKKCC6MQ.js → monitor-URMSEGAJ.js} +1 -1
  162. package/chunks/{nonInteractiveCli-J3Z3IZIF.js → nonInteractiveCli-YHOC5KZF.js} +1 -1
  163. package/chunks/{nonInteractiveToolExecutor-UQTMGYN2.js → nonInteractiveToolExecutor-DM5IGBP7.js} +1 -1
  164. package/chunks/{notebook-edit-JFD2KDI6.js → notebook-edit-3YSG73BK.js} +1 -1
  165. package/chunks/{omni-CI5JTMPR.js → omni-J6YYWKII.js} +1 -1
  166. package/chunks/{openaiContentGenerator-YZOV2TQX.js → openaiContentGenerator-UIFSPMTE.js} +1 -1
  167. package/chunks/{openaiResponsesContentGenerator-AHL7V6TE.js → openaiResponsesContentGenerator-U6Q536RZ.js} +1 -1
  168. package/chunks/{pidfile-ULOUTG67.js → pidfile-WCZE5ONH.js} +1 -1
  169. package/chunks/{processUtils-XX62FVFO.js → processUtils-3CDEN2GV.js} +1 -1
  170. package/chunks/{prompt-terminal-ledger-L6CWXBAW.js → prompt-terminal-ledger-VAQC6TC3.js} +1 -1
  171. package/chunks/{qwenContentGenerator-ZDXJW7EM.js → qwenContentGenerator-RWBGMON6.js} +1 -1
  172. package/chunks/{reactive-degrade-4OJ7XKSJ.js → reactive-degrade-GOTSVZKO.js} +1 -1
  173. package/chunks/{read-file-H6I32UZS.js → read-file-WNNTTHL5.js} +1 -1
  174. package/chunks/{resumeHistoryUtils-CTRMXPKQ.js → resumeHistoryUtils-UAGV4TC3.js} +1 -1
  175. package/chunks/{review-7SV2M7EL.js → review-JETUJT7N.js} +1 -1
  176. package/chunks/{ripGrep-Y2TGCQH5.js → ripGrep-OJNMOYPD.js} +1 -1
  177. package/chunks/{run-qwen-serve-6SWKYY6I.js → run-qwen-serve-BVNSBOLL.js} +1 -1
  178. package/chunks/{runtime-ITZIIC6D.js → runtime-CERVMTEG.js} +1 -1
  179. package/chunks/{sandboxConfig-FF2YF3RY.js → sandboxConfig-ZHW3GTMH.js} +1 -1
  180. package/chunks/{scheduled-tasks-WWPWNM3Y.js → scheduled-tasks-AAB5OESY.js} +1 -1
  181. package/chunks/{scheduler-ELSUH4GZ.js → scheduler-4ZZA357S.js} +1 -1
  182. package/chunks/{search-memory-465ZSHKG.js → search-memory-USJ3D7WQ.js} +1 -1
  183. package/chunks/{send-message-M5JFT3VH.js → send-message-QE2YZZ6M.js} +1 -1
  184. package/chunks/{serve-VTR7PTK2.js → serve-SX2PK3OZ.js} +1 -1
  185. package/chunks/{server-5NHPPEPR.js → server-OGTIIX65.js} +3 -3
  186. package/chunks/{session-HZLRQKEB.js → session-DXORIQDK.js} +1 -1
  187. package/chunks/{session-attachments-root-LS5Q4OT3.js → session-attachments-root-VHH2OZF6.js} +1 -1
  188. package/chunks/{session-execution-engine-selector-GS4LJPUU.js → session-execution-engine-selector-5WKZ6WXX.js} +1 -1
  189. package/chunks/{session-pr-refresh-FKYCCTWD.js → session-pr-refresh-MHXNT44I.js} +1 -1
  190. package/chunks/{sessionService-XUBKN4CM.js → sessionService-QDDGXOB7.js} +1 -1
  191. package/chunks/{settings-BFTTGWJN.js → settings-W3ALYJZM.js} +1 -1
  192. package/chunks/{shell-YEUMIQVE.js → shell-YROF2KXZ.js} +1 -1
  193. package/chunks/{skill-2MJ7S5SK.js → skill-CBEQAUIQ.js} +1 -1
  194. package/chunks/{skill-settings-DP7A2GMB.js → skill-settings-YRN4SHJO.js} +1 -1
  195. package/chunks/{spawnChannel-3IZ7S6U7.js → spawnChannel-M7Q6URLT.js} +1 -1
  196. package/chunks/{standalone-update-NAI3OI3P.js → standalone-update-WIRHMWE6.js} +1 -1
  197. package/chunks/{start-opentui-ui-D6ETKJSG.js → start-opentui-ui-OLHWNKCY.js} +1 -1
  198. package/chunks/{startInteractiveUI-FR5ZT72L.js → startInteractiveUI-KCHCIQWO.js} +1 -1
  199. package/chunks/{subscription-content-generator-JHU5YG2L.js → subscription-content-generator-YQLQKG6S.js} +1 -1
  200. package/chunks/{team-create-ZW3NXJ2M.js → team-create-I432CHIX.js} +1 -1
  201. package/chunks/{team-plan-approval-GPFOKUEV.js → team-plan-approval-APMPMLXS.js} +1 -1
  202. package/chunks/{terminal-image-renderer-WTEEKRMJ.js → terminal-image-renderer-3BNICGAX.js} +1 -1
  203. package/chunks/{theme-manager-STF74SF2.js → theme-manager-6KY7Q4ZR.js} +1 -1
  204. package/chunks/{tool-call-TVX5UHRJ.js → tool-call-QGOVXOVJ.js} +1 -1
  205. package/chunks/{tool-result-media-QALAETZ4.js → tool-result-media-LRSYJOND.js} +1 -1
  206. package/chunks/{tool-search-ZGJEYTBI.js → tool-search-HXP25AWV.js} +1 -1
  207. package/chunks/{total-session-admission-BOYLCRYA.js → total-session-admission-ISTRHUQ7.js} +1 -1
  208. package/chunks/{trustedFolders-65OZWLQO.js → trustedFolders-5BXMWMYB.js} +1 -1
  209. package/chunks/{update-relaunch-4LJ3SY6L.js → update-relaunch-NYGYYLSC.js} +1 -1
  210. package/chunks/{updateCheck-2QOAKEIH.js → updateCheck-UBLS3LUD.js} +1 -1
  211. package/chunks/{upload-config-5N7UDWC6.js → upload-config-Y372LVXX.js} +1 -1
  212. package/chunks/{useAutoAcceptIndicator-V37CGGMF.js → useAutoAcceptIndicator-RXZJRU74.js} +1 -1
  213. package/chunks/{validateNonInterActiveAuth-6ZTVWZ6W.js → validateNonInterActiveAuth-2GJ4ICJ3.js} +1 -1
  214. package/chunks/{version-EO3VIRH6.js → version-XRSNVEB2.js} +1 -1
  215. package/chunks/{web-fetch-B6LNZ2YK.js → web-fetch-B4VFVGWW.js} +1 -1
  216. package/chunks/{web-search-VIPZWUJX.js → web-search-3DSQWMAV.js} +1 -1
  217. package/chunks/{workflow-W5QEAOGN.js → workflow-RCCH5FPV.js} +1 -1
  218. package/chunks/{workflow-ancestor-trust-VE7B4RD2.js → workflow-ancestor-trust-N3QYH3OL.js} +1 -1
  219. package/chunks/{workspace-agents-D32D3K5S.js → workspace-agents-KEV4VBZD.js} +1 -1
  220. package/chunks/{workspace-providers-status-BOH7RJPV.js → workspace-providers-status-HW4VI4T7.js} +1 -1
  221. package/chunks/{workspace-recovery-worker-53GJWYJ5.js → workspace-recovery-worker-C3SSJ64A.js} +1 -1
  222. package/chunks/{workspace-registration-store-BMX2NT45.js → workspace-registration-store-K7VEBHIU.js} +1 -1
  223. package/chunks/{workspace-registry-SS2NKLEL.js → workspace-registry-C5ZPYT4P.js} +1 -1
  224. package/chunks/{workspace-runtime-coordinator-7ZKVLJDC.js → workspace-runtime-coordinator-ALWOLW3N.js} +1 -1
  225. package/chunks/{workspace-service-GIUD3D25.js → workspace-service-TNZJAC7M.js} +1 -1
  226. package/chunks/{workspace-skills-status-36A76TDX.js → workspace-skills-status-TI763F5M.js} +1 -1
  227. package/chunks/{workspace-trust-reconciler-VKKSY2AR.js → workspace-trust-reconciler-6UQ7HSUG.js} +1 -1
  228. package/chunks/{write-file-43JOGU55.js → write-file-2XXEHBZR.js} +1 -1
  229. package/chunks/{zoom-image-USUXATDM.js → zoom-image-P3E3V6PQ.js} +1 -1
  230. package/cli.js +2 -2
  231. package/execution-worker.js +1 -1
  232. package/export-transcript-document.js +1 -1
  233. package/package.json +3 -3
  234. package/web-shell/assets/{PierreFilePreview-Dx075_VT.js → PierreFilePreview-DtTOu9VE.js} +1 -1
  235. package/web-shell/assets/{SpreadsheetPreview-l2R-Y1o6.js → SpreadsheetPreview-C21imJIX.js} +1 -1
  236. package/web-shell/assets/{WorkspaceFileBrowser-CGi_eR1a.js → WorkspaceFileBrowser-DIWHfhtl.js} +1 -1
  237. package/web-shell/assets/{abnfDiagram-VCTEODGH-DZPHyWbH.js → abnfDiagram-VCTEODGH-qffA9juk.js} +1 -1
  238. package/web-shell/assets/{agents-route-Bp0Yjhm4.js → agents-route-4f6fKJaY.js} +1 -1
  239. package/web-shell/assets/{arc-BAS_Ct0z.js → arc-BOZg4dn0.js} +1 -1
  240. package/web-shell/assets/{architectureDiagram-5GKGNRK7-C5a7ooE1.js → architectureDiagram-5GKGNRK7-BOYWC6dJ.js} +1 -1
  241. package/web-shell/assets/{blockDiagram-NRAW4CY4-D-Wzzi9Z.js → blockDiagram-NRAW4CY4-CiN_IMJ7.js} +1 -1
  242. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BiYnmYkI.js → c4Diagram-UCG6FXSJ-WYLA0JW0.js} +1 -1
  243. package/web-shell/assets/channel-DtcoR96T.js +1 -0
  244. package/web-shell/assets/{chunk-2Q5K7J3B-DHi3a_yf.js → chunk-2Q5K7J3B-BZUPB745.js} +1 -1
  245. package/web-shell/assets/{chunk-5VM5RSS4-DKgiHWPM.js → chunk-5VM5RSS4-BHfjsu8x.js} +1 -1
  246. package/web-shell/assets/{chunk-F27PBJKO-qvFMzdl_.js → chunk-F27PBJKO-DHtQsOyA.js} +1 -1
  247. package/web-shell/assets/{chunk-G27WJ6UU-C9Apl4Df.js → chunk-G27WJ6UU-DvEX_QHY.js} +1 -1
  248. package/web-shell/assets/{chunk-JWPE2WC7-ManrSgDL.js → chunk-JWPE2WC7-CwQJmw1a.js} +1 -1
  249. package/web-shell/assets/{chunk-LCL6LL3I-DNZqkjQu.js → chunk-LCL6LL3I-Cv7bRuRV.js} +1 -1
  250. package/web-shell/assets/{chunk-POPQ4Y6H-CxineRE8.js → chunk-POPQ4Y6H-zGw4PzDB.js} +1 -1
  251. package/web-shell/assets/{chunk-SVP7TREG-BzmCQ6Bh.js → chunk-SVP7TREG-DZMGVnJg.js} +1 -1
  252. package/web-shell/assets/{chunk-XXDRQBXY-Dm6Ascgd.js → chunk-XXDRQBXY-Dg5_qrTq.js} +1 -1
  253. package/web-shell/assets/classDiagram-DTDB5LWJ-CBq-DXYQ.js +1 -0
  254. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBq-DXYQ.js +1 -0
  255. package/web-shell/assets/{cose-bilkent-JH36ORCC-Cs-vIewG.js → cose-bilkent-JH36ORCC-D07aXZdD.js} +1 -1
  256. package/web-shell/assets/{cynefin-OW5HDTMX-CrxyzLrG.js → cynefin-OW5HDTMX-B4txjD0l.js} +1 -1
  257. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Bf7RdtX4.js → cynefinDiagram-5FMLGOSQ-zFtLauJ6.js} +1 -1
  258. package/web-shell/assets/{dagre-3AP2YEHR-jN7qDhRR.js → dagre-3AP2YEHR-CKZj9zbB.js} +1 -1
  259. package/web-shell/assets/{diagram-S7CK7UJ4-KcNQ38Ue.js → diagram-S7CK7UJ4-DIsLTku6.js} +1 -1
  260. package/web-shell/assets/{diagram-UQ7AKVKN-9VmCS0SV.js → diagram-UQ7AKVKN-60CC00CO.js} +1 -1
  261. package/web-shell/assets/{diagram-VSXAHHWV-D-MA8NCD.js → diagram-VSXAHHWV-BCfHqY7L.js} +1 -1
  262. package/web-shell/assets/{diagram-VX7I27RA-323tLIBS.js → diagram-VX7I27RA-BbTOx9qC.js} +1 -1
  263. package/web-shell/assets/{diagram-Z3DM3KII-C547h61H.js → diagram-Z3DM3KII-DLjgnodz.js} +1 -1
  264. package/web-shell/assets/{docx-preview-DHO0seXT.js → docx-preview-CfGqg6IJ.js} +1 -1
  265. package/web-shell/assets/{ebnfDiagram-PWID7BFC-DfB8wLF5.js → ebnfDiagram-PWID7BFC-Cf1IQbGo.js} +1 -1
  266. package/web-shell/assets/{erDiagram-SSCWMZ5O-tzqYkCjp.js → erDiagram-SSCWMZ5O-BTVNpu1y.js} +1 -1
  267. package/web-shell/assets/{flowDiagram-A5DVABFB-Dsw6uHjD.js → flowDiagram-A5DVABFB-BC404IkJ.js} +1 -1
  268. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-D1SaF3O0.js → ganttDiagram-EL5Y4UJY-BHP58V1Y.js} +1 -1
  269. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D0EzECMT.js → gitGraphDiagram-WWUBYQGX-s1PkjMd4.js} +1 -1
  270. package/web-shell/assets/{index-ob2Iut7D.js → index-DZnv4pXI.js} +6 -6
  271. package/web-shell/assets/{index-C-YHF5xI.js → index-YpdTDWts.js} +1 -1
  272. package/web-shell/assets/{infoDiagram-RXCK75RN-6NnYMmcC.js → infoDiagram-RXCK75RN-DDaQbbGu.js} +1 -1
  273. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BnxsfuuS.js → ishikawaDiagram-5VMMS53U-FpQWCzWS.js} +1 -1
  274. package/web-shell/assets/{journeyDiagram-EYS64GPL-DduswigY.js → journeyDiagram-EYS64GPL-CC5YG1zk.js} +1 -1
  275. package/web-shell/assets/{kanban-definition-3QL26DDD-D0trNRAQ.js → kanban-definition-3QL26DDD-CsitCmSH.js} +1 -1
  276. package/web-shell/assets/{layout-nP-pCdd_.js → layout-DR8LNzXS.js} +1 -1
  277. package/web-shell/assets/{linear-DCw4lqG9.js → linear-Dt61H2xY.js} +1 -1
  278. package/web-shell/assets/{mermaid.core-DYjTp4Sk.js → mermaid.core-C3SdL30W.js} +6 -6
  279. package/web-shell/assets/{mindmap-definition-FBJOCRG2-BK9iSa2V.js → mindmap-definition-FBJOCRG2-BjxTLs9R.js} +1 -1
  280. package/web-shell/assets/{pegDiagram-XKGWAZYB-Dg0TQ1Ty.js → pegDiagram-XKGWAZYB-eBurSwq6.js} +1 -1
  281. package/web-shell/assets/{pieDiagram-E7YTZNPT-DKeqeVkg.js → pieDiagram-E7YTZNPT-BFWkbtZz.js} +1 -1
  282. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-C4zBeQXd.js → quadrantDiagram-AXDQQJYC-SThzXP6T.js} +1 -1
  283. package/web-shell/assets/{railroadDiagram-O6MQD6OU-jDnAGU3z.js → railroadDiagram-O6MQD6OU-D73YId-T.js} +1 -1
  284. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-D0sIdHq4.js → requirementDiagram-EFPCY7ZU-YecInWjM.js} +1 -1
  285. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BFz_QzXx.js → sankeyDiagram-P5KCCOFB-D4Gl35cC.js} +1 -1
  286. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DhDmjiCT.js → sequenceDiagram-WJ2MYXX4-C1JdJSRH.js} +1 -1
  287. package/web-shell/assets/{sizeCapture-X5ZJPWSS-D8Ov3K_0.js → sizeCapture-X5ZJPWSS-D3mHX34v.js} +1 -1
  288. package/web-shell/assets/{stateDiagram-HBIQ2CUA-Bb4f1ILo.js → stateDiagram-HBIQ2CUA-BR05d7ll.js} +1 -1
  289. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BBhqVmOU.js +1 -0
  290. package/web-shell/assets/{swimlanes-XN3QIQJK-CQyilPoS.js → swimlanes-XN3QIQJK-CENq9EQ7.js} +1 -1
  291. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DI8ON7to.js +8 -0
  292. package/web-shell/assets/{timeline-definition-24CTP7MA-B_CntdLT.js → timeline-definition-24CTP7MA-DFhKdLgc.js} +1 -1
  293. package/web-shell/assets/{vennDiagram-4TSXK5OY-BbuHkADM.js → vennDiagram-4TSXK5OY-C-p5h-ue.js} +1 -1
  294. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-0mNKcB-T.js → wardleyDiagram-VM6X3IG4-BCWSjHZH.js} +1 -1
  295. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BL-rMOQs.js → xychartDiagram-S5SC5T6Z-DBvE_Y0y.js} +1 -1
  296. package/web-shell/index.html +1 -1
  297. package/web-shell/sw.js +1 -1
  298. package/web-shell/assets/channel-B31dxYCL.js +0 -1
  299. package/web-shell/assets/classDiagram-DTDB5LWJ-CxU_Ty2M.js +0 -1
  300. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CxU_Ty2M.js +0 -1
  301. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-xbht8Czs.js +0 -1
  302. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dz34bASJ.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{msSinceLastInteraction}from"./chunk-UGLQO5K7.js";import{isValidSessionId}from"./chunk-LGFF5PJA.js";import{DEFAULT_OPENAI_LOG_RETENTION_DAYS}from"./chunk-F7KVMGGZ.js";import{resolveOpenAILogDir}from"./chunk-LWVY42EK.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-XUB4JKSR.js";import{createDebugLogger,sessionIdContext}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.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-QD4KNY2J.js";import{resolveOpenAILogDir}from"./chunk-LWVY42EK.js";import{FILE_HISTORY_DIR,getSubagentsRootDir}from"./chunk-3NR3JBMA.js";import{createDebugLogger,sessionIdContext}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.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{buildScheduledTaskRunPrompt,parseChannelDelivery,scheduledTaskRunSessionName,scheduledTaskRunSourceId}from"./chunk-LO6OFMFC.js";import{createSessionOrganizationService}from"./chunk-NW3H676V.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,sendConversationRuntimeUnavailable,sendGenerationClosedError}from"./chunk-J5W6P7QD.js";import{parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{SCHEDULED_TASK_RUN_SOURCE_TYPE}from"./chunk-BAPIZCC7.js";import{SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{isChannelDeliveryError}from"./chunk-O6ZQAVRG.js";import{MAX_JOBS,SessionService,gateCommandError,nextDurableFireMs,nextFireTime,parseCron}from"./chunk-XUB4JKSR.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,annotateCronRunSession,appendCronRun,cronTaskSessionDeletionId,generateCronTaskId,getCronFilePath,isValidCronTaskRoutingId,readCronTasks,taskHasLegacyCondition,updateCronTasks,withTaskGate}from"./chunk-DXUYBMFK.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{isDeepStrictEqual}from"node:util";import{access}from"node:fs/promises";var MAX_SCHEDULED_TASKS=MAX_JOBS;var MAX_PROMPT_LENGTH=1e5;var MAX_NAME_LENGTH=200;var MAX_CRON_LENGTH=200;var MAX_ROUTING_ID_LENGTH=MAX_CRON_TASK_ROUTING_ID_LENGTH;var MAX_SESSION_NAME_LENGTH=60;function scheduledTaskSessionName(label){const cleaned=stripTerminalControlSequences(label).replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"").trim().replace(/\s+/g," ");let short=cleaned;if(cleaned.length>MAX_SESSION_NAME_LENGTH){let cut=MAX_SESSION_NAME_LENGTH-1;const boundary=cleaned.charCodeAt(cut-1);if(boundary>=55296&&boundary<=56319)cut-=1;short=`${cleaned.slice(0,cut)}\u2026`}return short}__name(scheduledTaskSessionName,"scheduledTaskSessionName");var ExistingSessionScheduledTaskCreateError=class extends Error{constructor(status,code,message){super(message);this.status=status;this.code=code;this.name="ExistingSessionScheduledTaskCreateError"}static{__name(this,"ExistingSessionScheduledTaskCreateError")}};function assertReusableScheduledTaskSession(target,sessionId,allowActivePrompt,assertCallerPromptActive){const{bridge,workspaceCwd}=target;if(!bridge){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session management is not available for this workspace")}assertCallerPromptActive?.();let owner;try{owner=target.resolveLiveSessionOwner?.(sessionId)}catch(error){writeStderrLine(`qwen serve: failed to resolve scheduled-task session owner '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(owner?.kind==="unavailable"){throw new ExistingSessionScheduledTaskCreateError(503,"workspace_runtime_unavailable","The workspace runtime is unavailable")}if(owner?.kind==="ambiguous"){throw new ExistingSessionScheduledTaskCreateError(500,"ambiguous_session_owner",`Session owner is ambiguous for "${sessionId}"`)}if(owner?.kind==="found"&&owner.runtime.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}let summary;try{summary=bridge.getSessionSummary(sessionId)}catch(error){if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to look up scheduled-task session '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(summary.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}if(!allowActivePrompt&&summary.hasActivePrompt||(summary.pendingInteractionCount??0)>0){throw new ExistingSessionScheduledTaskCreateError(409,"session_busy",allowActivePrompt?"The caller session has a pending interaction; resolve it before binding the session to a task":"The requested session is busy; wait for its active prompt or pending interaction to finish before binding it to a task")}if(summary.sourceType==="scheduled_task"){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already reserved for a scheduled task")}if(summary.parentSessionId!==void 0||summary.sourceId!==void 0||summary.sourceType!==void 0&&summary.sourceType!=="default"){throw new ExistingSessionScheduledTaskCreateError(409,"session_source_ineligible","The requested session source cannot own a scheduled task")}}__name(assertReusableScheduledTaskSession,"assertReusableScheduledTaskSession");async function createScheduledTaskWithExistingSession(target,input,options){if(input.cron.length===0||input.cron.length>MAX_CRON_LENGTH||validateCron(input.cron)!==null){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_cron","The scheduled-task cron expression is invalid")}const prompt=input.prompt.trim();if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_prompt","The scheduled-task prompt is invalid")}const gate=input.gate?.trim();if(gate!==void 0){const gateError=gateCommandError(gate);if(gateError){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_gate",`The scheduled-task gate ${gateError}`)}if(!input.recurring){throw new ExistingSessionScheduledTaskCreateError(400,"gate_requires_recurring",GATE_REQUIRES_RECURRING_MESSAGE)}}const allowActivePrompt=options.source==="cron-tool";const assertCallerPromptActive=options.source==="cron-tool"?options.assertCallerPromptActive:void 0;assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);target.assertGenerationOpen?.();if(options.source==="rest"){const ensurePersisted=target.bridge?.ensureDefaultSessionPersisted;if(!ensurePersisted){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session persistence is not available for this workspace")}try{await ensurePersisted.call(target.bridge,input.sessionId)}catch(error){target.assertGenerationOpen?.();if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${input.sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to persist scheduled-task session '${input.sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"session_persistence_failed","Failed to persist the requested session")}target.assertGenerationOpen?.()}const now=Date.now();const task=withTaskGate({id:generateCronTaskId(),cron:input.cron,prompt,recurring:input.recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled:input.enabled!==false,sessionId:input.sessionId,sessionOwnedByTask:false,sessionMode:input.sessionMode==="per_run"?"per_run":"persistent",...input.sessionMode==="per_run"&&input.modelServiceId!==void 0?{modelServiceId:input.modelServiceId}:{},...input.sessionMode==="per_run"&&input.groupId!==void 0?{groupId:input.groupId}:{},...input.delivery!==void 0?{delivery:input.delivery}:{},...input.name!==void 0?{name:input.name}:{}},gate);let before;let after;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);if(tasks.some(candidate=>candidate.sessionId===input.sessionId)){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already bound to another scheduled task")}if(tasks.length>=MAX_SCHEDULED_TASKS){throw new ExistingSessionScheduledTaskCreateError(409,"max_tasks_reached",`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`)}before=tasks;after=[...tasks,task];return after},{assertCanCommit:target.assertGenerationOpen}));try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,before,after,"scheduled-task create");throw error}return task}__name(createScheduledTaskWithExistingSession,"createScheduledTaskWithExistingSession");function requireOpenGeneration(target,res){try{target.assertGenerationOpen?.();return true}catch(error){if(sendGenerationClosedError(res,error))return false;throw error}}__name(requireOpenGeneration,"requireOpenGeneration");async function rollbackCronMutation(target,before,after,route){if(!before||!after)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>isDeepStrictEqual(tasks,after)?before:tasks)).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to roll back a stale task mutation: ${error instanceof Error?error.message:String(error)}`)})}__name(rollbackCronMutation,"rollbackCronMutation");async function restoreConsumedOneShot(target,before,failedTask,removalGenerations,route){const id=failedTask.id;const index=before?.findIndex(t=>t.id===id)??-1;const original=index===-1?void 0:before[index];if(!original||!removalGenerations)return;let restoreGenerations;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{if([...removalGenerations].some(([key,generation])=>restoreGenerations?.get(key)!==generation))return tasks;if(tasks.some(t=>t.id===id))return tasks;const restored=[...tasks];restored.splice(Math.min(index,restored.length),0,{...failedTask,enabled:false});return restored},{observeDeletionIds:[...removalGenerations.keys()],onDeletionGenerations:__name(generations=>{restoreGenerations=generations},"onDeletionGenerations")})).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to restore the consumed one-shot task: ${error instanceof Error?error.message:String(error)}`)})}__name(restoreConsumedOneShot,"restoreConsumedOneShot");async function teardownBoundSession(target,sessionId){if(target.cleanupSession){await target.cleanupSession(sessionId).catch(()=>{})}else if(target.bridge){await target.bridge.closeSession(sessionId).catch(()=>{});const removed=await new SessionService(target.workspaceCwd,{runtimeBaseDir:target.runtimeBaseDir}).removeSession(sessionId).catch(()=>false);if(removed)target.bridge.markSessionCatalogChanged?.()}}__name(teardownBoundSession,"teardownBoundSession");async function dispatchTaskToFreshSession(target,task){const{bridge}=target;const sendPrompt=bridge?.sendPrompt?.bind(bridge);if(!bridge||!sendPrompt||!task.sessionId){throw new Error("Fresh-session dispatch is unavailable for this task")}const triggeredAt=task.lastFiredAt??Date.now();const child=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd:target.workspaceCwd,...task.modelServiceId?{modelServiceId:task.modelServiceId}:{},sessionScope:"thread",parentSessionId:task.sessionId,sourceType:SCHEDULED_TASK_RUN_SOURCE_TYPE,sourceId:scheduledTaskRunSourceId(task.id)}));try{if(task.modelServiceId&&child.modelApplied===false){throw new Error(`Scheduled task model selection failed: ${task.modelServiceId}`)}try{bridge.updateSessionMetadata(child.sessionId,{displayName:scheduledTaskRunSessionName(task.name??task.prompt,triggeredAt),titleSource:"auto"})}catch{}let markPromptAdmitted;const promptAdmitted=new Promise(resolve=>{markPromptAdmitted=resolve});const turn=sendPrompt(child.sessionId,{sessionId:child.sessionId,prompt:[{type:"text",text:buildScheduledTaskRunPrompt({id:task.id,name:task.name,cron:task.cron,prompt:task.prompt,triggeredAt,trigger:"manual",...task.gate?{gate:task.gate}:{}})}]},void 0,{onPromptAdmitted:markPromptAdmitted});void turn.catch(error=>{writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} prompt failed: ${error instanceof Error?error.message:String(error)}`)});await Promise.race([promptAdmitted,turn.then(()=>void 0,error=>Promise.reject(error))]);if(task.groupId){try{await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(target.workspaceCwd).updateSessionOrganization(child.sessionId,{groupId:task.groupId,color:null}));bridge.markSessionCatalogChanged?.()}catch(error){writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} could not be assigned to group ${task.groupId}: ${error instanceof Error?error.message:String(error)}`)}}}catch(error){await teardownBoundSession(target,child.sessionId);throw error}return child.sessionId}__name(dispatchTaskToFreshSession,"dispatchTaskToFreshSession");async function runWithScheduledTaskTarget(target,fn){const result=target.runtimeBaseDir===void 0?fn():Storage.runWithResolvedRuntimeBaseDir(target.runtimeBaseDir,fn);return await result}__name(runWithScheduledTaskTarget,"runWithScheduledTaskTarget");function sendActivityGateError(res,error){if(!error||typeof error!=="object"||error.code!=="daemon_draining"){return false}res.status(503).json({error:"The daemon is draining and no longer accepts work.",code:"daemon_draining"});return true}__name(sendActivityGateError,"sendActivityGateError");var GATE_REQUIRES_RECURRING_MESSAGE="A gate needs a recurring task: a one-shot whose gate prints nothing would be consumed with nothing delivered";function computeNextRunAt(task){if(task.enabled===false)return null;return nextDurableFireMs(task)}__name(computeNextRunAt,"computeNextRunAt");function toView(task){return{id:task.id,name:typeof task.name==="string"&&task.name.length>0?task.name:null,cron:task.cron,prompt:task.prompt,recurring:task.recurring,enabled:task.enabled!==false&&!taskHasLegacyCondition(task),createdAt:task.createdAt,lastFiredAt:task.lastFiredAt,nextRunAt:taskHasLegacyCondition(task)?null:computeNextRunAt(task),sessionId:typeof task.sessionId==="string"&&task.sessionId.length>0?task.sessionId:null,sessionMode:task.sessionMode==="per_run"?"per_run":"persistent",modelServiceId:task.modelServiceId??null,groupId:task.groupId??null,runs:Array.isArray(task.runs)?task.runs:[],...task.delivery!==void 0?{delivery:task.delivery}:{},gate:typeof task.gate==="string"&&task.gate.length>0?task.gate:null,gateStatus:task.gateStatus??null}}__name(toView,"toView");function validateCron(cron){try{parseCron(cron);nextFireTime(cron,new Date);return null}catch(err){return err instanceof Error?err.message:String(err)}}__name(validateCron,"validateCron");function canonicalCron(cron){try{const f=parseCron(cron);const s=__name(set=>[...set].sort((a,b)=>a-b).join(","),"s");return[s(f.minute),s(f.hour),s(f.dayOfMonth),s(f.month),s(f.dayOfWeek),f.domIsWild?"W":"",f.dowIsWild?"W":""].join("|")}catch{return null}}__name(canonicalCron,"canonicalCron");function registerScheduledTaskCrudRoutes(app,deps){const{prefix,resolveTarget,mutate,safeBody,channelDeliveryAuthorizations}=deps;const base=`${prefix}/scheduled-tasks`;const withTarget=__name(handler=>async(req,res)=>{const target=resolveTarget(req,res);if(!target)return;const operation=__name(async()=>{if(!requireOpenGeneration(target,res))return;await handler(req,res,target)},"operation");try{if(target.activity){await target.activity.run(operation)}else{await operation()}}catch(error){if(sendActivityGateError(res,error))return;throw error}},"withTarget");app.get(base,withTarget(async(_req,res,target)=>{try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(target.workspaceCwd));if(!requireOpenGeneration(target,res))return;res.status(200).json({v:1,tasks:tasks.map(toView)})}catch(err){if(sendActivityGateError(res,err))return;writeStderrLine(`qwen serve: GET ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to read scheduled tasks (the tasks file may be corrupt)",code:"scheduled_tasks_read_failed"})}}));app.post(base,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const body=safeBody(req);const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0){res.status(400).json({error:"`cron` is required and must be a non-empty string",code:"invalid_cron"});return}if(cron.length>MAX_CRON_LENGTH){res.status(400).json({error:`\`cron\` exceeds ${MAX_CRON_LENGTH}-character limit`,code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0){res.status(400).json({error:"`prompt` is required and must be a non-empty string",code:"invalid_prompt"});return}if(prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:`\`prompt\` exceeds ${MAX_PROMPT_LENGTH}-character limit`,code:"invalid_prompt"});return}const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(body["recurring"]!==void 0&&typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}if(body["enabled"]!==void 0&&typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}const sessionMode=body["sessionMode"]===void 0?"persistent":body["sessionMode"];if(sessionMode!=="persistent"&&sessionMode!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}const modelServiceId=body["modelServiceId"];if(modelServiceId!==void 0&&!isValidCronTaskRoutingId(modelServiceId)){res.status(400).json({error:`\`modelServiceId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}const groupId=body["groupId"];if(groupId!==void 0&&!isValidCronTaskRoutingId(groupId)){res.status(400).json({error:`\`groupId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}if(sessionMode!=="per_run"&&(modelServiceId!==void 0||groupId!==void 0)){res.status(400).json({error:'`modelServiceId` and `groupId` are only supported when `sessionMode` is "per_run"',code:"session_routing_requires_per_run"});return}if(typeof groupId==="string"){const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===groupId)){res.status(400).json({error:`Group not found: ${groupId}`,code:"group_not_found"});return}}const parsedSessionId=parseCallerSuppliedSessionId(body["sessionId"]);if(parsedSessionId.kind==="invalid"){res.status(400).json({error:'`sessionId` must be an RFC UUID v1-v5 (e.g. "550e8400-e29b-41d4-a716-446655440000")',code:"invalid_session_id"});return}const providedSessionId=parsedSessionId.kind==="valid"?parsedSessionId.sessionId:void 0;let delivery;if(body["delivery"]!==void 0){try{delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}if(sessionMode==="per_run"&&delivery!==void 0){res.status(400).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}const removedField=findRemovedTaskField(body);if(removedField){res.status(400).json(removedFieldError(removedField));return}const recurring=body["recurring"]!==false;const enabled=body["enabled"]!==false;let gate;if(body["gate"]!==void 0&&body["gate"]!==null){const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` ${gateError}`,code:"invalid_gate"});return}gate=body["gate"].trim();if(!recurring){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}}const taskId=generateCronTaskId();if(sessionMode==="per_run"&&(!bridge||!bridge.sendPrompt)){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(providedSessionId!==void 0){try{const task2=await createScheduledTaskWithExistingSession(target,{sessionId:providedSessionId,cron,prompt,recurring,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...nameResult.value!==void 0?{name:nameResult.value}:{},...gate!==void 0?{gate}:{}},{source:"rest"});if(task2.delivery&&task2.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task2.sessionId,taskId:task2.id,target:task2.delivery.target,recurring:task2.recurring,lastFiredAt:task2.lastFiredAt??void 0})}res.status(201).json(toView(task2))}catch(error){if(error instanceof ExistingSessionScheduledTaskCreateError){if(error.code==="workspace_runtime_unavailable"){res.set("Retry-After","1")}res.status(error.status).json({error:error.message,code:error.code});return}if(sendActivityGateError(res,error))return;if(sendGenerationClosedError(res,error))return;writeStderrLine(`qwen serve: POST ${base} failed to create a task for session '${providedSessionId}': ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"})}return}let boundSessionId;let sessionMintedHere=false;if(bridge){try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(workspaceCwd));if(tasks.length>=MAX_SCHEDULED_TASKS){res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}}catch{}if(!requireOpenGeneration(target,res))return;try{const session=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd,sessionScope:"thread",sourceType:"scheduled_task",sourceId:taskId}));boundSessionId=session.sessionId;sessionMintedHere=true;if(!requireOpenGeneration(target,res)){await teardownBoundSession(target,boundSessionId);return}try{await runWithScheduledTaskTarget(target,async()=>bridge.updateSessionMetadata(boundSessionId,{displayName:scheduledTaskSessionName(nameResult.value??prompt),titleSource:"auto"}))}catch{}}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed to create the task's session: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create the task's session",code:"scheduled_tasks_session_failed"});return}}const now=Date.now();const task=withTaskGate({id:taskId,cron,prompt,recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...boundSessionId!==void 0?{sessionId:boundSessionId}:{},...nameResult.value!==void 0?{name:nameResult.value}:{}},gate);const rollbackSession=__name(async()=>{if(boundSessionId!==void 0&&sessionMintedHere){await teardownBoundSession(target,boundSessionId)}},"rollbackSession");let overCap=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{if(tasks.length>=MAX_SCHEDULED_TASKS){overCap=true;return tasks}rollbackBefore=tasks;rollbackAfter=[...tasks,task];return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){await rollbackSession();if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}`);await rollbackSession();if(sendGenerationClosedError(res,error))return;throw error}}if(overCap){await rollbackSession();res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}if(task.delivery&&task.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task.sessionId,taskId:task.id,target:task.delivery.target,recurring:task.recurring,lastFiredAt:task.lastFiredAt??void 0})}res.status(201).json(toView(task))}));app.patch(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const body=safeBody(req);const patch={};let clearName=false;let clearDelivery=false;let clearModelServiceId=false;let clearGroupId=false;let clearGate=false;let missingGroupId;const removedPatchField=findRemovedTaskField(body);if(removedPatchField){res.status(400).json(removedFieldError(removedPatchField));return}if("cron"in body){const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0||cron.length>MAX_CRON_LENGTH){res.status(400).json({error:"`cron` must be a non-empty string within the length limit",code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}patch.cron=cron}if("prompt"in body){const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:"`prompt` must be a non-empty string within the length limit",code:"invalid_prompt"});return}patch.prompt=prompt}if("name"in body){const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(nameResult.value===void 0){clearName=true}else{patch.name=nameResult.value}}if("recurring"in body){if(typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}patch.recurring=body["recurring"]}if("enabled"in body){if(typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}patch.enabled=body["enabled"]}if("sessionMode"in body){if(body["sessionMode"]!=="persistent"&&body["sessionMode"]!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}patch.sessionMode=body["sessionMode"]}if("modelServiceId"in body){const value=body["modelServiceId"];if(value===null||value===""){clearModelServiceId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`modelServiceId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}else{patch.modelServiceId=value}}if("groupId"in body){const value=body["groupId"];if(value===null||value===""){clearGroupId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`groupId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}else{const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===value)){missingGroupId=value}patch.groupId=value}}if("delivery"in body){if(body["delivery"]===null){clearDelivery=true}else{try{patch.delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}}if("gate"in body){if(body["gate"]===null||body["gate"]===""){clearGate=true}else{const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` must be null or a shell command; it ${gateError}`,code:"invalid_gate"});return}patch.gate=body["gate"].trim()}}if(Object.keys(patch).length===0&&!clearName&&!clearDelivery&&!clearModelServiceId&&!clearGroupId&&!clearGate){res.status(400).json({error:"No updatable fields provided",code:"empty_patch"});return}let found=false;let updated;let blockedByArchive=false;let blockedLegacy=false;let blockedGateOneShot=false;let blockedSessionModeDelivery=false;let blockedSessionModeUnavailable=false;let blockedSessionModeUnbound=false;let blockedGroupNotFound=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(missingGroupId!==void 0&&current.groupId!==missingGroupId){blockedGroupNotFound=true;return tasks}const convertingToPerRun=patch.sessionMode==="per_run"&&current.sessionMode!=="per_run";if(convertingToPerRun&&(!bridge||!bridge.sendPrompt)){blockedSessionModeUnavailable=true;return tasks}if(convertingToPerRun&&!current.sessionId){blockedSessionModeUnbound=true;return tasks}if(patch.enabled===true&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if((patch.gate!==void 0||clearGate)&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(patch.enabled===true&&current.disabledByArchive===true){blockedByArchive=true;return tasks}let next={...current,...patch};if(clearName)delete next.name;if(clearDelivery)delete next.delivery;if(clearModelServiceId)delete next.modelServiceId;if(clearGroupId)delete next.groupId;if(next.sessionMode!=="per_run"){delete next.modelServiceId;delete next.groupId}if(next.sessionMode==="per_run"&&next.delivery){blockedSessionModeDelivery=true;return tasks}if(clearGate||patch.gate!==void 0){next=withTaskGate(next,clearGate?void 0:patch.gate);if(clearGate||patch.gate!==current.gate){delete next.gateStatus}}if(next.gate!==void 0&&!next.recurring&&(patch.gate!==void 0&&patch.gate!==current.gate||patch.recurring===false&&current.recurring!==false)){blockedGateOneShot=true;return tasks}const justReEnabled=current.enabled===false&&patch.enabled===true;const cronChanged=patch.cron!==void 0&&canonicalCron(patch.cron)!==canonicalCron(current.cron);const becameRecurring=patch.recurring===true&&current.recurring!==true;const becameOneShot=patch.recurring===false&&current.recurring!==false;const retryFailedOneShot=!next.recurring&&justReEnabled&&!cronChanged&&!becameOneShot&&current.runs?.at(-1)?.sessionDispatchFailed===true;{const now=Date.now();const minute=now-now%6e4;if(next.recurring&&(justReEnabled||cronChanged||becameRecurring)){next.lastFiredAt=minute}else if(!next.recurring&&!retryFailedOneShot&&(justReEnabled||cronChanged||becameOneShot)){next.createdAt=now;next.lastFiredAt=minute}}updated=next;rollbackBefore=tasks;rollbackAfter=tasks.map((t,i)=>i===idx?next:t);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: PATCH ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to update scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`PATCH ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!found){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(missingGroupId!==void 0&&blockedGroupNotFound){res.status(400).json({error:`Group not found: ${missingGroupId}`,code:"group_not_found"});return}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer be enabled or run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedByArchive){res.status(409).json({error:"This task was disabled by archiving its session; unarchive the session to re-enable it.",code:"task_session_archived"});return}if(blockedSessionModeUnavailable){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(blockedSessionModeUnbound){res.status(409).json({error:"This task is not bound to a session yet, so it cannot run in a new session every run. Try again once it has run or been opened at least once.",code:"session_mode_requires_bound_session"});return}if(blockedSessionModeDelivery){res.status(409).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}if(blockedGateOneShot){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}if(!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}const effectiveLabelChanged=patch.name!==void 0||clearName||patch.prompt!==void 0&&updated.name===void 0;if(bridge&&updated.sessionId&&updated.sessionOwnedByTask!==false&&effectiveLabelChanged){try{bridge.updateSessionMetadata(updated.sessionId,{displayName:scheduledTaskSessionName(updated.name??updated.prompt),titleSource:"auto"})}catch{}}if(updated.delivery&&updated.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:updated.sessionId,taskId:updated.id,target:updated.delivery.target,recurring:updated.recurring,lastFiredAt:updated.lastFiredAt??void 0})}if(clearDelivery&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}res.status(200).json(toView(updated))}));app.delete(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}let boundSessionId;let sessionOwnedByTask=true;let removed=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,async()=>{try{await access(getCronFilePath(workspaceCwd))}catch(error){if(error.code==="ENOENT")return;throw error}await updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;const match=tasks[idx].sessionId;if(typeof match==="string"&&match.length>0){boundSessionId=match;sessionOwnedByTask=tasks[idx].sessionOwnedByTask!==false}removed=true;rollbackBefore=tasks;rollbackAfter=tasks.filter((_,i)=>i!==idx);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen,deletionIds:[id]})})}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: DELETE ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to delete scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`DELETE ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!removed){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(boundSessionId&&sessionOwnedByTask&&bridge){try{await runWithScheduledTaskTarget(target,()=>bridge.closeSession(boundSessionId,void 0,{closeIfUnheld:true,reason:"scheduled_task_deleted"}))}catch(error){if(sendActivityGateError(res,error))return}}if(boundSessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,boundSessionId,id)}res.status(200).json({deleted:true,id})}));app.post(`${base}/:id/run`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const now=Date.now();let found=false;let blockedDisabled=false;let blockedLegacy=false;let updated;let rollbackBefore;let rollbackAfter;let removalGenerations;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(current.enabled===false){blockedDisabled=true;return tasks}const next={...current,lastFiredAt:now,runs:appendCronRun(current.runs,{at:now,kind:"manual",...current.sessionMode!=="per_run"&&current.sessionId?{sessionId:current.sessionId}:{}})};updated=next;rollbackBefore=tasks;const nextTasks=!current.recurring?tasks.filter((_,i)=>i!==idx):tasks.map((t,i)=>i===idx?next:t);rollbackAfter=nextTasks;return nextTasks},{assertCanCommit:target.assertGenerationOpen,observeDeletionIds:__name(tasks=>{const task=tasks.find(task2=>task2.id===id);return task?.sessionId?[id,cronTaskSessionDeletionId(task.sessionId)]:[id]},"observeDeletionIds"),onDeletionGenerations:__name(generations=>{removalGenerations=generations},"onDeletionGenerations")}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base}/${id}/run failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to record scheduled task run",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}/${id}/run`);if(sendGenerationClosedError(res,error))return;throw error}}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedDisabled){res.status(409).json({error:"Cannot run a disabled task; enable it first (unarchive its session if it was archived).",code:"task_disabled"});return}if(!found||!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(updated.sessionMode==="per_run"){const persistOutcome=__name(async outcome=>{if(!updated.recurring)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>tasks.map(task=>task.id===id?annotateCronRunSession(task,now,outcome):task),{assertCanCommit:target.assertGenerationOpen}))},"persistOutcome");let childSessionId;try{childSessionId=await dispatchTaskToFreshSession(target,updated)}catch(error){updated=annotateCronRunSession(updated,now,{dispatchFailed:true});if(updated.recurring){await persistOutcome({dispatchFailed:true}).catch(persistError=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not record the failed dispatch: ${persistError instanceof Error?persistError.message:String(persistError)}`)})}else{await restoreConsumedOneShot(target,rollbackBefore,updated,removalGenerations,`POST ${base}/${id}/run fresh-session dispatch`)}writeStderrLine(`qwen serve: POST ${base}/${id}/run could not create a fresh session: ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create a fresh session for the scheduled task",code:"scheduled_task_session_dispatch_failed"});return}updated=annotateCronRunSession(updated,now,{sessionId:childSessionId});await persistOutcome({sessionId:childSessionId}).catch(error=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not attribute fresh session ${childSessionId}: ${error instanceof Error?error.message:String(error)}`)})}if(!updated.recurring&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}const view=toView(updated);if(!updated.recurring)view.nextRunAt=null;res.status(200).json(view)}))}__name(registerScheduledTaskCrudRoutes,"registerScheduledTaskCrudRoutes");function registerScheduledTasksRoutes(app,deps){const{boundWorkspace,mutate,safeBody,bridge,channelDeliveryAuthorizations}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"",resolveTarget:__name((_req,res)=>{const runtime=deps.getRuntime?.();if(deps.getRuntime&&!runtime){res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active",code:"workspace_runtime_unavailable"});return null}if(runtime&&!requireTrustedWorkspaceRuntime(runtime,res))return null;return{workspaceCwd:boundWorkspace,...runtime?{runtimeBaseDir:runtime.sessionRuntimeBaseDir,...deps.cleanupSession?{cleanupSession:__name(sessionId=>deps.cleanupSession(runtime,sessionId),"cleanupSession")}:{}}:{},bridge:bridge===void 0?void 0:runtime?.bridge??bridge,...runtime?.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},...deps.workspaceRegistry?{resolveLiveSessionOwner:__name(sessionId=>deps.workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}:{}}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerScheduledTasksRoutes,"registerScheduledTasksRoutes");function registerWorkspaceQualifiedScheduledTasksRoutes(app,deps){const{workspaceRegistry,mutate,safeBody,manageScheduledTaskSessions,channelDeliveryAuthorizations,cleanupSession}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"/workspaces/:workspace",resolveTarget:__name((req,res)=>{const runtime=resolveWorkspaceRuntimeWithLiveCompatibilityFromParam(workspaceRegistry,req,res);if(!runtime)return null;if(!requireTrustedWorkspaceRuntime(runtime,res))return null;if(runtime.provenance==="live-conversation"&&!deps.conversationRuntimeActivity){sendConversationRuntimeUnavailable(res);return null}if(runtime.provenance==="live-conversation"&&req.method==="POST"&&req.params["id"]===void 0&&parseCallerSuppliedSessionId(safeBody(req)["sessionId"]).kind==="absent"){res.status(400).json({error:"Generic scheduled tasks cannot create sessions in the Conversations workspace.",code:"live_session_creation_reserved"});return null}return{workspaceCwd:runtime.workspaceCwd,runtimeBaseDir:runtime.sessionRuntimeBaseDir,...runtime.provenance==="live-conversation"&&deps.conversationRuntimeActivity?{activity:deps.conversationRuntimeActivity}:{},...cleanupSession?{cleanupSession:__name(sessionId=>cleanupSession(runtime,sessionId),"cleanupSession")}:{},bridge:manageScheduledTaskSessions?runtime.bridge:void 0,...runtime.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},resolveLiveSessionOwner:__name(sessionId=>workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerWorkspaceQualifiedScheduledTasksRoutes,"registerWorkspaceQualifiedScheduledTasksRoutes");var REMOVED_TASK_FIELDS=["runMode","condition"];function findRemovedTaskField(body){return REMOVED_TASK_FIELDS.find(field=>field in body)}__name(findRemovedTaskField,"findRemovedTaskField");function removedFieldError(field){return{error:`\`${field}\` is no longer supported: the isolated scheduled-task run mode was removed. Every task now runs in its bound session; call the \`create_sub_session\` tool from the task prompt for per-run isolation.`,code:"unsupported_field"}}__name(removedFieldError,"removedFieldError");function parseNameField(raw){if(raw===void 0||raw===null)return{value:void 0};if(typeof raw!=="string"){return{error:"`name` must be a string"}}const trimmed=raw.trim();if(trimmed.length===0)return{value:void 0};if(trimmed.length>MAX_NAME_LENGTH){return{error:`\`name\` exceeds ${MAX_NAME_LENGTH}-character limit`}}return{value:trimmed}}__name(parseNameField,"parseNameField");export{scheduledTaskSessionName,ExistingSessionScheduledTaskCreateError,createScheduledTaskWithExistingSession,registerScheduledTasksRoutes,registerWorkspaceQualifiedScheduledTasksRoutes};
3
+ import{buildScheduledTaskRunPrompt,parseChannelDelivery,scheduledTaskRunSessionName,scheduledTaskRunSourceId}from"./chunk-IHEGGZBE.js";import{createSessionOrganizationService}from"./chunk-P5RBFVMP.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeWithLiveCompatibilityFromParam,sendConversationRuntimeUnavailable,sendGenerationClosedError}from"./chunk-ZF56DRDP.js";import{parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{SCHEDULED_TASK_RUN_SOURCE_TYPE}from"./chunk-LTJLPYFS.js";import{SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{isChannelDeliveryError}from"./chunk-O6ZQAVRG.js";import{MAX_JOBS,SessionService,gateCommandError,nextDurableFireMs,nextFireTime,parseCron}from"./chunk-3NR3JBMA.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{MAX_CRON_TASK_ROUTING_ID_LENGTH,annotateCronRunSession,appendCronRun,cronTaskSessionDeletionId,generateCronTaskId,getCronFilePath,isValidCronTaskRoutingId,readCronTasks,taskHasLegacyCondition,updateCronTasks,withTaskGate}from"./chunk-DXUYBMFK.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{isDeepStrictEqual}from"node:util";import{access}from"node:fs/promises";var MAX_SCHEDULED_TASKS=MAX_JOBS;var MAX_PROMPT_LENGTH=1e5;var MAX_NAME_LENGTH=200;var MAX_CRON_LENGTH=200;var MAX_ROUTING_ID_LENGTH=MAX_CRON_TASK_ROUTING_ID_LENGTH;var MAX_SESSION_NAME_LENGTH=60;function scheduledTaskSessionName(label){const cleaned=stripTerminalControlSequences(label).replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"").trim().replace(/\s+/g," ");let short=cleaned;if(cleaned.length>MAX_SESSION_NAME_LENGTH){let cut=MAX_SESSION_NAME_LENGTH-1;const boundary=cleaned.charCodeAt(cut-1);if(boundary>=55296&&boundary<=56319)cut-=1;short=`${cleaned.slice(0,cut)}\u2026`}return short}__name(scheduledTaskSessionName,"scheduledTaskSessionName");var ExistingSessionScheduledTaskCreateError=class extends Error{constructor(status,code,message){super(message);this.status=status;this.code=code;this.name="ExistingSessionScheduledTaskCreateError"}static{__name(this,"ExistingSessionScheduledTaskCreateError")}};function assertReusableScheduledTaskSession(target,sessionId,allowActivePrompt,assertCallerPromptActive){const{bridge,workspaceCwd}=target;if(!bridge){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session management is not available for this workspace")}assertCallerPromptActive?.();let owner;try{owner=target.resolveLiveSessionOwner?.(sessionId)}catch(error){writeStderrLine(`qwen serve: failed to resolve scheduled-task session owner '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(owner?.kind==="unavailable"){throw new ExistingSessionScheduledTaskCreateError(503,"workspace_runtime_unavailable","The workspace runtime is unavailable")}if(owner?.kind==="ambiguous"){throw new ExistingSessionScheduledTaskCreateError(500,"ambiguous_session_owner",`Session owner is ambiguous for "${sessionId}"`)}if(owner?.kind==="found"&&owner.runtime.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}let summary;try{summary=bridge.getSessionSummary(sessionId)}catch(error){if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to look up scheduled-task session '${sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"scheduled_tasks_session_failed","Failed to look up the requested session")}if(summary.workspaceCwd!==workspaceCwd){throw new ExistingSessionScheduledTaskCreateError(400,"session_workspace_mismatch","The requested session belongs to a different workspace; use that workspace's scheduled-task endpoint")}if(!allowActivePrompt&&summary.hasActivePrompt||(summary.pendingInteractionCount??0)>0){throw new ExistingSessionScheduledTaskCreateError(409,"session_busy",allowActivePrompt?"The caller session has a pending interaction; resolve it before binding the session to a task":"The requested session is busy; wait for its active prompt or pending interaction to finish before binding it to a task")}if(summary.sourceType==="scheduled_task"){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already reserved for a scheduled task")}if(summary.parentSessionId!==void 0||summary.sourceId!==void 0||summary.sourceType!==void 0&&summary.sourceType!=="default"){throw new ExistingSessionScheduledTaskCreateError(409,"session_source_ineligible","The requested session source cannot own a scheduled task")}}__name(assertReusableScheduledTaskSession,"assertReusableScheduledTaskSession");async function createScheduledTaskWithExistingSession(target,input,options){if(input.cron.length===0||input.cron.length>MAX_CRON_LENGTH||validateCron(input.cron)!==null){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_cron","The scheduled-task cron expression is invalid")}const prompt=input.prompt.trim();if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_prompt","The scheduled-task prompt is invalid")}const gate=input.gate?.trim();if(gate!==void 0){const gateError=gateCommandError(gate);if(gateError){throw new ExistingSessionScheduledTaskCreateError(400,"invalid_gate",`The scheduled-task gate ${gateError}`)}if(!input.recurring){throw new ExistingSessionScheduledTaskCreateError(400,"gate_requires_recurring",GATE_REQUIRES_RECURRING_MESSAGE)}}const allowActivePrompt=options.source==="cron-tool";const assertCallerPromptActive=options.source==="cron-tool"?options.assertCallerPromptActive:void 0;assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);target.assertGenerationOpen?.();if(options.source==="rest"){const ensurePersisted=target.bridge?.ensureDefaultSessionPersisted;if(!ensurePersisted){throw new ExistingSessionScheduledTaskCreateError(409,"session_binding_unavailable","Session persistence is not available for this workspace")}try{await ensurePersisted.call(target.bridge,input.sessionId)}catch(error){target.assertGenerationOpen?.();if(error instanceof SessionNotFoundError){throw new ExistingSessionScheduledTaskCreateError(404,"session_not_found",`Session '${input.sessionId}' was not found`)}writeStderrLine(`qwen serve: failed to persist scheduled-task session '${input.sessionId}': ${error instanceof Error?error.message:String(error)}`);throw new ExistingSessionScheduledTaskCreateError(500,"session_persistence_failed","Failed to persist the requested session")}target.assertGenerationOpen?.()}const now=Date.now();const task=withTaskGate({id:generateCronTaskId(),cron:input.cron,prompt,recurring:input.recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled:input.enabled!==false,sessionId:input.sessionId,sessionOwnedByTask:false,sessionMode:input.sessionMode==="per_run"?"per_run":"persistent",...input.sessionMode==="per_run"&&input.modelServiceId!==void 0?{modelServiceId:input.modelServiceId}:{},...input.sessionMode==="per_run"&&input.groupId!==void 0?{groupId:input.groupId}:{},...input.delivery!==void 0?{delivery:input.delivery}:{},...input.name!==void 0?{name:input.name}:{}},gate);let before;let after;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{assertReusableScheduledTaskSession(target,input.sessionId,allowActivePrompt,assertCallerPromptActive);if(tasks.some(candidate=>candidate.sessionId===input.sessionId)){throw new ExistingSessionScheduledTaskCreateError(409,"session_already_bound","The requested session is already bound to another scheduled task")}if(tasks.length>=MAX_SCHEDULED_TASKS){throw new ExistingSessionScheduledTaskCreateError(409,"max_tasks_reached",`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`)}before=tasks;after=[...tasks,task];return after},{assertCanCommit:target.assertGenerationOpen}));try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,before,after,"scheduled-task create");throw error}return task}__name(createScheduledTaskWithExistingSession,"createScheduledTaskWithExistingSession");function requireOpenGeneration(target,res){try{target.assertGenerationOpen?.();return true}catch(error){if(sendGenerationClosedError(res,error))return false;throw error}}__name(requireOpenGeneration,"requireOpenGeneration");async function rollbackCronMutation(target,before,after,route){if(!before||!after)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>isDeepStrictEqual(tasks,after)?before:tasks)).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to roll back a stale task mutation: ${error instanceof Error?error.message:String(error)}`)})}__name(rollbackCronMutation,"rollbackCronMutation");async function restoreConsumedOneShot(target,before,failedTask,removalGenerations,route){const id=failedTask.id;const index=before?.findIndex(t=>t.id===id)??-1;const original=index===-1?void 0:before[index];if(!original||!removalGenerations)return;let restoreGenerations;await runWithScheduledTaskTarget(target,()=>updateCronTasks(target.workspaceCwd,tasks=>{if([...removalGenerations].some(([key,generation])=>restoreGenerations?.get(key)!==generation))return tasks;if(tasks.some(t=>t.id===id))return tasks;const restored=[...tasks];restored.splice(Math.min(index,restored.length),0,{...failedTask,enabled:false});return restored},{observeDeletionIds:[...removalGenerations.keys()],onDeletionGenerations:__name(generations=>{restoreGenerations=generations},"onDeletionGenerations")})).catch(error=>{writeStderrLine(`qwen serve: ${route} failed to restore the consumed one-shot task: ${error instanceof Error?error.message:String(error)}`)})}__name(restoreConsumedOneShot,"restoreConsumedOneShot");async function teardownBoundSession(target,sessionId){if(target.cleanupSession){await target.cleanupSession(sessionId).catch(()=>{})}else if(target.bridge){await target.bridge.closeSession(sessionId).catch(()=>{});const removed=await new SessionService(target.workspaceCwd,{runtimeBaseDir:target.runtimeBaseDir}).removeSession(sessionId).catch(()=>false);if(removed)target.bridge.markSessionCatalogChanged?.()}}__name(teardownBoundSession,"teardownBoundSession");async function dispatchTaskToFreshSession(target,task){const{bridge}=target;const sendPrompt=bridge?.sendPrompt?.bind(bridge);if(!bridge||!sendPrompt||!task.sessionId){throw new Error("Fresh-session dispatch is unavailable for this task")}const triggeredAt=task.lastFiredAt??Date.now();const child=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd:target.workspaceCwd,...task.modelServiceId?{modelServiceId:task.modelServiceId}:{},sessionScope:"thread",parentSessionId:task.sessionId,sourceType:SCHEDULED_TASK_RUN_SOURCE_TYPE,sourceId:scheduledTaskRunSourceId(task.id)}));try{if(task.modelServiceId&&child.modelApplied===false){throw new Error(`Scheduled task model selection failed: ${task.modelServiceId}`)}try{bridge.updateSessionMetadata(child.sessionId,{displayName:scheduledTaskRunSessionName(task.name??task.prompt,triggeredAt),titleSource:"auto"})}catch{}let markPromptAdmitted;const promptAdmitted=new Promise(resolve=>{markPromptAdmitted=resolve});const turn=sendPrompt(child.sessionId,{sessionId:child.sessionId,prompt:[{type:"text",text:buildScheduledTaskRunPrompt({id:task.id,name:task.name,cron:task.cron,prompt:task.prompt,triggeredAt,trigger:"manual",...task.gate?{gate:task.gate}:{}})}]},void 0,{onPromptAdmitted:markPromptAdmitted});void turn.catch(error=>{writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} prompt failed: ${error instanceof Error?error.message:String(error)}`)});await Promise.race([promptAdmitted,turn.then(()=>void 0,error=>Promise.reject(error))]);if(task.groupId){try{await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(target.workspaceCwd).updateSessionOrganization(child.sessionId,{groupId:task.groupId,color:null}));bridge.markSessionCatalogChanged?.()}catch(error){writeStderrLine(`qwen serve: scheduled-task session ${child.sessionId} could not be assigned to group ${task.groupId}: ${error instanceof Error?error.message:String(error)}`)}}}catch(error){await teardownBoundSession(target,child.sessionId);throw error}return child.sessionId}__name(dispatchTaskToFreshSession,"dispatchTaskToFreshSession");async function runWithScheduledTaskTarget(target,fn){const result=target.runtimeBaseDir===void 0?fn():Storage.runWithResolvedRuntimeBaseDir(target.runtimeBaseDir,fn);return await result}__name(runWithScheduledTaskTarget,"runWithScheduledTaskTarget");function sendActivityGateError(res,error){if(!error||typeof error!=="object"||error.code!=="daemon_draining"){return false}res.status(503).json({error:"The daemon is draining and no longer accepts work.",code:"daemon_draining"});return true}__name(sendActivityGateError,"sendActivityGateError");var GATE_REQUIRES_RECURRING_MESSAGE="A gate needs a recurring task: a one-shot whose gate prints nothing would be consumed with nothing delivered";function computeNextRunAt(task){if(task.enabled===false)return null;return nextDurableFireMs(task)}__name(computeNextRunAt,"computeNextRunAt");function toView(task){return{id:task.id,name:typeof task.name==="string"&&task.name.length>0?task.name:null,cron:task.cron,prompt:task.prompt,recurring:task.recurring,enabled:task.enabled!==false&&!taskHasLegacyCondition(task),createdAt:task.createdAt,lastFiredAt:task.lastFiredAt,nextRunAt:taskHasLegacyCondition(task)?null:computeNextRunAt(task),sessionId:typeof task.sessionId==="string"&&task.sessionId.length>0?task.sessionId:null,sessionMode:task.sessionMode==="per_run"?"per_run":"persistent",modelServiceId:task.modelServiceId??null,groupId:task.groupId??null,runs:Array.isArray(task.runs)?task.runs:[],...task.delivery!==void 0?{delivery:task.delivery}:{},gate:typeof task.gate==="string"&&task.gate.length>0?task.gate:null,gateStatus:task.gateStatus??null}}__name(toView,"toView");function validateCron(cron){try{parseCron(cron);nextFireTime(cron,new Date);return null}catch(err){return err instanceof Error?err.message:String(err)}}__name(validateCron,"validateCron");function canonicalCron(cron){try{const f=parseCron(cron);const s=__name(set=>[...set].sort((a,b)=>a-b).join(","),"s");return[s(f.minute),s(f.hour),s(f.dayOfMonth),s(f.month),s(f.dayOfWeek),f.domIsWild?"W":"",f.dowIsWild?"W":""].join("|")}catch{return null}}__name(canonicalCron,"canonicalCron");function registerScheduledTaskCrudRoutes(app,deps){const{prefix,resolveTarget,mutate,safeBody,channelDeliveryAuthorizations}=deps;const base=`${prefix}/scheduled-tasks`;const withTarget=__name(handler=>async(req,res)=>{const target=resolveTarget(req,res);if(!target)return;const operation=__name(async()=>{if(!requireOpenGeneration(target,res))return;await handler(req,res,target)},"operation");try{if(target.activity){await target.activity.run(operation)}else{await operation()}}catch(error){if(sendActivityGateError(res,error))return;throw error}},"withTarget");app.get(base,withTarget(async(_req,res,target)=>{try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(target.workspaceCwd));if(!requireOpenGeneration(target,res))return;res.status(200).json({v:1,tasks:tasks.map(toView)})}catch(err){if(sendActivityGateError(res,err))return;writeStderrLine(`qwen serve: GET ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to read scheduled tasks (the tasks file may be corrupt)",code:"scheduled_tasks_read_failed"})}}));app.post(base,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const body=safeBody(req);const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0){res.status(400).json({error:"`cron` is required and must be a non-empty string",code:"invalid_cron"});return}if(cron.length>MAX_CRON_LENGTH){res.status(400).json({error:`\`cron\` exceeds ${MAX_CRON_LENGTH}-character limit`,code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0){res.status(400).json({error:"`prompt` is required and must be a non-empty string",code:"invalid_prompt"});return}if(prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:`\`prompt\` exceeds ${MAX_PROMPT_LENGTH}-character limit`,code:"invalid_prompt"});return}const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(body["recurring"]!==void 0&&typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}if(body["enabled"]!==void 0&&typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}const sessionMode=body["sessionMode"]===void 0?"persistent":body["sessionMode"];if(sessionMode!=="persistent"&&sessionMode!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}const modelServiceId=body["modelServiceId"];if(modelServiceId!==void 0&&!isValidCronTaskRoutingId(modelServiceId)){res.status(400).json({error:`\`modelServiceId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}const groupId=body["groupId"];if(groupId!==void 0&&!isValidCronTaskRoutingId(groupId)){res.status(400).json({error:`\`groupId\` must be a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}if(sessionMode!=="per_run"&&(modelServiceId!==void 0||groupId!==void 0)){res.status(400).json({error:'`modelServiceId` and `groupId` are only supported when `sessionMode` is "per_run"',code:"session_routing_requires_per_run"});return}if(typeof groupId==="string"){const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===groupId)){res.status(400).json({error:`Group not found: ${groupId}`,code:"group_not_found"});return}}const parsedSessionId=parseCallerSuppliedSessionId(body["sessionId"]);if(parsedSessionId.kind==="invalid"){res.status(400).json({error:'`sessionId` must be an RFC UUID v1-v5 (e.g. "550e8400-e29b-41d4-a716-446655440000")',code:"invalid_session_id"});return}const providedSessionId=parsedSessionId.kind==="valid"?parsedSessionId.sessionId:void 0;let delivery;if(body["delivery"]!==void 0){try{delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}if(sessionMode==="per_run"&&delivery!==void 0){res.status(400).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}const removedField=findRemovedTaskField(body);if(removedField){res.status(400).json(removedFieldError(removedField));return}const recurring=body["recurring"]!==false;const enabled=body["enabled"]!==false;let gate;if(body["gate"]!==void 0&&body["gate"]!==null){const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` ${gateError}`,code:"invalid_gate"});return}gate=body["gate"].trim();if(!recurring){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}}const taskId=generateCronTaskId();if(sessionMode==="per_run"&&(!bridge||!bridge.sendPrompt)){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(providedSessionId!==void 0){try{const task2=await createScheduledTaskWithExistingSession(target,{sessionId:providedSessionId,cron,prompt,recurring,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...nameResult.value!==void 0?{name:nameResult.value}:{},...gate!==void 0?{gate}:{}},{source:"rest"});if(task2.delivery&&task2.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task2.sessionId,taskId:task2.id,target:task2.delivery.target,recurring:task2.recurring,lastFiredAt:task2.lastFiredAt??void 0})}res.status(201).json(toView(task2))}catch(error){if(error instanceof ExistingSessionScheduledTaskCreateError){if(error.code==="workspace_runtime_unavailable"){res.set("Retry-After","1")}res.status(error.status).json({error:error.message,code:error.code});return}if(sendActivityGateError(res,error))return;if(sendGenerationClosedError(res,error))return;writeStderrLine(`qwen serve: POST ${base} failed to create a task for session '${providedSessionId}': ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"})}return}let boundSessionId;let sessionMintedHere=false;if(bridge){try{const tasks=await runWithScheduledTaskTarget(target,()=>readCronTasks(workspaceCwd));if(tasks.length>=MAX_SCHEDULED_TASKS){res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}}catch{}if(!requireOpenGeneration(target,res))return;try{const session=await runWithScheduledTaskTarget(target,()=>bridge.spawnOrAttach({workspaceCwd,sessionScope:"thread",sourceType:"scheduled_task",sourceId:taskId}));boundSessionId=session.sessionId;sessionMintedHere=true;if(!requireOpenGeneration(target,res)){await teardownBoundSession(target,boundSessionId);return}try{await runWithScheduledTaskTarget(target,async()=>bridge.updateSessionMetadata(boundSessionId,{displayName:scheduledTaskSessionName(nameResult.value??prompt),titleSource:"auto"}))}catch{}}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed to create the task's session: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create the task's session",code:"scheduled_tasks_session_failed"});return}}const now=Date.now();const task=withTaskGate({id:taskId,cron,prompt,recurring,createdAt:now,lastFiredAt:now-now%6e4,enabled,sessionMode,...typeof modelServiceId==="string"?{modelServiceId}:{},...typeof groupId==="string"?{groupId}:{},...delivery!==void 0?{delivery}:{},...boundSessionId!==void 0?{sessionId:boundSessionId}:{},...nameResult.value!==void 0?{name:nameResult.value}:{}},gate);const rollbackSession=__name(async()=>{if(boundSessionId!==void 0&&sessionMintedHere){await teardownBoundSession(target,boundSessionId)}},"rollbackSession");let overCap=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{if(tasks.length>=MAX_SCHEDULED_TASKS){overCap=true;return tasks}rollbackBefore=tasks;rollbackAfter=[...tasks,task];return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){await rollbackSession();if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to create scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}`);await rollbackSession();if(sendGenerationClosedError(res,error))return;throw error}}if(overCap){await rollbackSession();res.status(409).json({error:`Maximum number of scheduled tasks (${MAX_SCHEDULED_TASKS}) reached`,code:"max_tasks_reached"});return}if(task.delivery&&task.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:task.sessionId,taskId:task.id,target:task.delivery.target,recurring:task.recurring,lastFiredAt:task.lastFiredAt??void 0})}res.status(201).json(toView(task))}));app.patch(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const body=safeBody(req);const patch={};let clearName=false;let clearDelivery=false;let clearModelServiceId=false;let clearGroupId=false;let clearGate=false;let missingGroupId;const removedPatchField=findRemovedTaskField(body);if(removedPatchField){res.status(400).json(removedFieldError(removedPatchField));return}if("cron"in body){const cron=typeof body["cron"]==="string"?body["cron"].trim():"";if(cron.length===0||cron.length>MAX_CRON_LENGTH){res.status(400).json({error:"`cron` must be a non-empty string within the length limit",code:"invalid_cron"});return}const cronError=validateCron(cron);if(cronError){res.status(400).json({error:cronError,code:"invalid_cron"});return}patch.cron=cron}if("prompt"in body){const prompt=typeof body["prompt"]==="string"?body["prompt"].trim():"";if(prompt.length===0||prompt.length>MAX_PROMPT_LENGTH){res.status(400).json({error:"`prompt` must be a non-empty string within the length limit",code:"invalid_prompt"});return}patch.prompt=prompt}if("name"in body){const nameResult=parseNameField(body["name"]);if(nameResult.error){res.status(400).json({error:nameResult.error,code:"invalid_name"});return}if(nameResult.value===void 0){clearName=true}else{patch.name=nameResult.value}}if("recurring"in body){if(typeof body["recurring"]!=="boolean"){res.status(400).json({error:"`recurring` must be a boolean",code:"invalid_recurring"});return}patch.recurring=body["recurring"]}if("enabled"in body){if(typeof body["enabled"]!=="boolean"){res.status(400).json({error:"`enabled` must be a boolean",code:"invalid_enabled"});return}patch.enabled=body["enabled"]}if("sessionMode"in body){if(body["sessionMode"]!=="persistent"&&body["sessionMode"]!=="per_run"){res.status(400).json({error:'`sessionMode` must be "persistent" or "per_run"',code:"invalid_session_mode"});return}patch.sessionMode=body["sessionMode"]}if("modelServiceId"in body){const value=body["modelServiceId"];if(value===null||value===""){clearModelServiceId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`modelServiceId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_model_service_id"});return}else{patch.modelServiceId=value}}if("groupId"in body){const value=body["groupId"];if(value===null||value===""){clearGroupId=true}else if(!isValidCronTaskRoutingId(value)){res.status(400).json({error:`\`groupId\` must be null or a non-empty string of at most ${MAX_ROUTING_ID_LENGTH} characters without control characters`,code:"invalid_group_id"});return}else{const groups=await runWithScheduledTaskTarget(target,()=>createSessionOrganizationService(workspaceCwd).listGroups());if(!groups.groups.some(group=>group.id===value)){missingGroupId=value}patch.groupId=value}}if("delivery"in body){if(body["delivery"]===null){clearDelivery=true}else{try{patch.delivery=parseChannelDelivery(body["delivery"])}catch(err){if(!isChannelDeliveryError(err))throw err;res.status(400).json({error:err.message,code:err.code});return}}}if("gate"in body){if(body["gate"]===null||body["gate"]===""){clearGate=true}else{const gateError=gateCommandError(body["gate"]);if(gateError){res.status(400).json({error:`\`gate\` must be null or a shell command; it ${gateError}`,code:"invalid_gate"});return}patch.gate=body["gate"].trim()}}if(Object.keys(patch).length===0&&!clearName&&!clearDelivery&&!clearModelServiceId&&!clearGroupId&&!clearGate){res.status(400).json({error:"No updatable fields provided",code:"empty_patch"});return}let found=false;let updated;let blockedByArchive=false;let blockedLegacy=false;let blockedGateOneShot=false;let blockedSessionModeDelivery=false;let blockedSessionModeUnavailable=false;let blockedSessionModeUnbound=false;let blockedGroupNotFound=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(missingGroupId!==void 0&&current.groupId!==missingGroupId){blockedGroupNotFound=true;return tasks}const convertingToPerRun=patch.sessionMode==="per_run"&&current.sessionMode!=="per_run";if(convertingToPerRun&&(!bridge||!bridge.sendPrompt)){blockedSessionModeUnavailable=true;return tasks}if(convertingToPerRun&&!current.sessionId){blockedSessionModeUnbound=true;return tasks}if(patch.enabled===true&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if((patch.gate!==void 0||clearGate)&&taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(patch.enabled===true&&current.disabledByArchive===true){blockedByArchive=true;return tasks}let next={...current,...patch};if(clearName)delete next.name;if(clearDelivery)delete next.delivery;if(clearModelServiceId)delete next.modelServiceId;if(clearGroupId)delete next.groupId;if(next.sessionMode!=="per_run"){delete next.modelServiceId;delete next.groupId}if(next.sessionMode==="per_run"&&next.delivery){blockedSessionModeDelivery=true;return tasks}if(clearGate||patch.gate!==void 0){next=withTaskGate(next,clearGate?void 0:patch.gate);if(clearGate||patch.gate!==current.gate){delete next.gateStatus}}if(next.gate!==void 0&&!next.recurring&&(patch.gate!==void 0&&patch.gate!==current.gate||patch.recurring===false&&current.recurring!==false)){blockedGateOneShot=true;return tasks}const justReEnabled=current.enabled===false&&patch.enabled===true;const cronChanged=patch.cron!==void 0&&canonicalCron(patch.cron)!==canonicalCron(current.cron);const becameRecurring=patch.recurring===true&&current.recurring!==true;const becameOneShot=patch.recurring===false&&current.recurring!==false;const retryFailedOneShot=!next.recurring&&justReEnabled&&!cronChanged&&!becameOneShot&&current.runs?.at(-1)?.sessionDispatchFailed===true;{const now=Date.now();const minute=now-now%6e4;if(next.recurring&&(justReEnabled||cronChanged||becameRecurring)){next.lastFiredAt=minute}else if(!next.recurring&&!retryFailedOneShot&&(justReEnabled||cronChanged||becameOneShot)){next.createdAt=now;next.lastFiredAt=minute}}updated=next;rollbackBefore=tasks;rollbackAfter=tasks.map((t,i)=>i===idx?next:t);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: PATCH ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to update scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`PATCH ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!found){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(missingGroupId!==void 0&&blockedGroupNotFound){res.status(400).json({error:`Group not found: ${missingGroupId}`,code:"group_not_found"});return}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer be enabled or run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedByArchive){res.status(409).json({error:"This task was disabled by archiving its session; unarchive the session to re-enable it.",code:"task_session_archived"});return}if(blockedSessionModeUnavailable){res.status(409).json({error:"Fresh-session dispatch is not available for this workspace",code:"session_mode_unavailable"});return}if(blockedSessionModeUnbound){res.status(409).json({error:"This task is not bound to a session yet, so it cannot run in a new session every run. Try again once it has run or been opened at least once.",code:"session_mode_requires_bound_session"});return}if(blockedSessionModeDelivery){res.status(409).json({error:"Per-run sessions do not support channel delivery",code:"session_mode_delivery_unsupported"});return}if(blockedGateOneShot){res.status(400).json({error:GATE_REQUIRES_RECURRING_MESSAGE,code:"gate_requires_recurring"});return}if(!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}const effectiveLabelChanged=patch.name!==void 0||clearName||patch.prompt!==void 0&&updated.name===void 0;if(bridge&&updated.sessionId&&updated.sessionOwnedByTask!==false&&effectiveLabelChanged){try{bridge.updateSessionMetadata(updated.sessionId,{displayName:scheduledTaskSessionName(updated.name??updated.prompt),titleSource:"auto"})}catch{}}if(updated.delivery&&updated.sessionId){channelDeliveryAuthorizations?.registerScheduledTask(workspaceCwd,{sessionId:updated.sessionId,taskId:updated.id,target:updated.delivery.target,recurring:updated.recurring,lastFiredAt:updated.lastFiredAt??void 0})}if(clearDelivery&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}res.status(200).json(toView(updated))}));app.delete(`${base}/:id`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd,bridge}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}let boundSessionId;let sessionOwnedByTask=true;let removed=false;let rollbackBefore;let rollbackAfter;try{await runWithScheduledTaskTarget(target,async()=>{try{await access(getCronFilePath(workspaceCwd))}catch(error){if(error.code==="ENOENT")return;throw error}await updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;const match=tasks[idx].sessionId;if(typeof match==="string"&&match.length>0){boundSessionId=match;sessionOwnedByTask=tasks[idx].sessionOwnedByTask!==false}removed=true;rollbackBefore=tasks;rollbackAfter=tasks.filter((_,i)=>i!==idx);return rollbackAfter},{assertCanCommit:target.assertGenerationOpen,deletionIds:[id]})})}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: DELETE ${base}/${id} failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to delete scheduled task",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`DELETE ${base}/${id}`);if(sendGenerationClosedError(res,error))return;throw error}}if(!removed){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(boundSessionId&&sessionOwnedByTask&&bridge){try{await runWithScheduledTaskTarget(target,()=>bridge.closeSession(boundSessionId,void 0,{closeIfUnheld:true,reason:"scheduled_task_deleted"}))}catch(error){if(sendActivityGateError(res,error))return}}if(boundSessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,boundSessionId,id)}res.status(200).json({deleted:true,id})}));app.post(`${base}/:id/run`,mutate(),withTarget(async(req,res,target)=>{const{workspaceCwd}=target;const id=typeof req.params["id"]==="string"?req.params["id"]:"";if(id.length===0){res.status(400).json({error:"Task id is required",code:"invalid_id"});return}const now=Date.now();let found=false;let blockedDisabled=false;let blockedLegacy=false;let updated;let rollbackBefore;let rollbackAfter;let removalGenerations;try{await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>{const idx=tasks.findIndex(t=>t.id===id);if(idx===-1)return tasks;found=true;const current=tasks[idx];if(taskHasLegacyCondition(current)){blockedLegacy=true;return tasks}if(current.enabled===false){blockedDisabled=true;return tasks}const next={...current,lastFiredAt:now,runs:appendCronRun(current.runs,{at:now,kind:"manual",...current.sessionMode!=="per_run"&&current.sessionId?{sessionId:current.sessionId}:{}})};updated=next;rollbackBefore=tasks;const nextTasks=!current.recurring?tasks.filter((_,i)=>i!==idx):tasks.map((t,i)=>i===idx?next:t);rollbackAfter=nextTasks;return nextTasks},{assertCanCommit:target.assertGenerationOpen,observeDeletionIds:__name(tasks=>{const task=tasks.find(task2=>task2.id===id);return task?.sessionId?[id,cronTaskSessionDeletionId(task.sessionId)]:[id]},"observeDeletionIds"),onDeletionGenerations:__name(generations=>{removalGenerations=generations},"onDeletionGenerations")}))}catch(err){if(sendActivityGateError(res,err))return;if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST ${base}/${id}/run failed: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Failed to record scheduled task run",code:"scheduled_tasks_write_failed"});return}if(rollbackBefore&&rollbackAfter){try{target.assertGenerationOpen?.()}catch(error){await rollbackCronMutation(target,rollbackBefore,rollbackAfter,`POST ${base}/${id}/run`);if(sendGenerationClosedError(res,error))return;throw error}}if(blockedLegacy){res.status(409).json({error:"This task uses the removed isolated run mode with a precondition and can no longer run. Recreate it (and call the `create_sub_session` tool from the prompt if you need per-run isolation).",code:"task_legacy_unsupported"});return}if(blockedDisabled){res.status(409).json({error:"Cannot run a disabled task; enable it first (unarchive its session if it was archived).",code:"task_disabled"});return}if(!found||!updated){res.status(404).json({error:"Task not found",code:"task_not_found"});return}if(updated.sessionMode==="per_run"){const persistOutcome=__name(async outcome=>{if(!updated.recurring)return;await runWithScheduledTaskTarget(target,()=>updateCronTasks(workspaceCwd,tasks=>tasks.map(task=>task.id===id?annotateCronRunSession(task,now,outcome):task),{assertCanCommit:target.assertGenerationOpen}))},"persistOutcome");let childSessionId;try{childSessionId=await dispatchTaskToFreshSession(target,updated)}catch(error){updated=annotateCronRunSession(updated,now,{dispatchFailed:true});if(updated.recurring){await persistOutcome({dispatchFailed:true}).catch(persistError=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not record the failed dispatch: ${persistError instanceof Error?persistError.message:String(persistError)}`)})}else{await restoreConsumedOneShot(target,rollbackBefore,updated,removalGenerations,`POST ${base}/${id}/run fresh-session dispatch`)}writeStderrLine(`qwen serve: POST ${base}/${id}/run could not create a fresh session: ${error instanceof Error?error.message:String(error)}`);res.status(500).json({error:"Failed to create a fresh session for the scheduled task",code:"scheduled_task_session_dispatch_failed"});return}updated=annotateCronRunSession(updated,now,{sessionId:childSessionId});await persistOutcome({sessionId:childSessionId}).catch(error=>{writeStderrLine(`qwen serve: POST ${base}/${id}/run could not attribute fresh session ${childSessionId}: ${error instanceof Error?error.message:String(error)}`)})}if(!updated.recurring&&updated.sessionId){channelDeliveryAuthorizations?.revokeScheduledTask(workspaceCwd,updated.sessionId,updated.id)}const view=toView(updated);if(!updated.recurring)view.nextRunAt=null;res.status(200).json(view)}))}__name(registerScheduledTaskCrudRoutes,"registerScheduledTaskCrudRoutes");function registerScheduledTasksRoutes(app,deps){const{boundWorkspace,mutate,safeBody,bridge,channelDeliveryAuthorizations}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"",resolveTarget:__name((_req,res)=>{const runtime=deps.getRuntime?.();if(deps.getRuntime&&!runtime){res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active",code:"workspace_runtime_unavailable"});return null}if(runtime&&!requireTrustedWorkspaceRuntime(runtime,res))return null;return{workspaceCwd:boundWorkspace,...runtime?{runtimeBaseDir:runtime.sessionRuntimeBaseDir,...deps.cleanupSession?{cleanupSession:__name(sessionId=>deps.cleanupSession(runtime,sessionId),"cleanupSession")}:{}}:{},bridge:bridge===void 0?void 0:runtime?.bridge??bridge,...runtime?.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},...deps.workspaceRegistry?{resolveLiveSessionOwner:__name(sessionId=>deps.workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}:{}}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerScheduledTasksRoutes,"registerScheduledTasksRoutes");function registerWorkspaceQualifiedScheduledTasksRoutes(app,deps){const{workspaceRegistry,mutate,safeBody,manageScheduledTaskSessions,channelDeliveryAuthorizations,cleanupSession}=deps;registerScheduledTaskCrudRoutes(app,{prefix:"/workspaces/:workspace",resolveTarget:__name((req,res)=>{const runtime=resolveWorkspaceRuntimeWithLiveCompatibilityFromParam(workspaceRegistry,req,res);if(!runtime)return null;if(!requireTrustedWorkspaceRuntime(runtime,res))return null;if(runtime.provenance==="live-conversation"&&!deps.conversationRuntimeActivity){sendConversationRuntimeUnavailable(res);return null}if(runtime.provenance==="live-conversation"&&req.method==="POST"&&req.params["id"]===void 0&&parseCallerSuppliedSessionId(safeBody(req)["sessionId"]).kind==="absent"){res.status(400).json({error:"Generic scheduled tasks cannot create sessions in the Conversations workspace.",code:"live_session_creation_reserved"});return null}return{workspaceCwd:runtime.workspaceCwd,runtimeBaseDir:runtime.sessionRuntimeBaseDir,...runtime.provenance==="live-conversation"&&deps.conversationRuntimeActivity?{activity:deps.conversationRuntimeActivity}:{},...cleanupSession?{cleanupSession:__name(sessionId=>cleanupSession(runtime,sessionId),"cleanupSession")}:{},bridge:manageScheduledTaskSessions?runtime.bridge:void 0,...runtime.generationGuard?{assertGenerationOpen:__name(()=>runtime.generationGuard?.assertOpen(),"assertGenerationOpen")}:{},resolveLiveSessionOwner:__name(sessionId=>workspaceRegistry.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")}},"resolveTarget"),mutate,safeBody,channelDeliveryAuthorizations})}__name(registerWorkspaceQualifiedScheduledTasksRoutes,"registerWorkspaceQualifiedScheduledTasksRoutes");var REMOVED_TASK_FIELDS=["runMode","condition"];function findRemovedTaskField(body){return REMOVED_TASK_FIELDS.find(field=>field in body)}__name(findRemovedTaskField,"findRemovedTaskField");function removedFieldError(field){return{error:`\`${field}\` is no longer supported: the isolated scheduled-task run mode was removed. Every task now runs in its bound session; call the \`create_sub_session\` tool from the task prompt for per-run isolation.`,code:"unsupported_field"}}__name(removedFieldError,"removedFieldError");function parseNameField(raw){if(raw===void 0||raw===null)return{value:void 0};if(typeof raw!=="string"){return{error:"`name` must be a string"}}const trimmed=raw.trim();if(trimmed.length===0)return{value:void 0};if(trimmed.length>MAX_NAME_LENGTH){return{error:`\`name\` exceeds ${MAX_NAME_LENGTH}-character limit`}}return{value:trimmed}}__name(parseNameField,"parseNameField");export{scheduledTaskSessionName,ExistingSessionScheduledTaskCreateError,createScheduledTaskWithExistingSession,registerScheduledTasksRoutes,registerWorkspaceQualifiedScheduledTasksRoutes};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{SessionService,TURN_INTERRUPTION_HISTORY_TAIL_COUNT,buildSessionHistoryFromConversation,detectTurnInterruption,effectiveHistoryEnd}from"./chunk-XUB4JKSR.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{closeSync as closeSync2,openSync as openSync2,readSync as readSync2,statSync as statSync2}from"node:fs";init_esbuild_shims();import{appendFileSync,closeSync,mkdirSync,openSync,readFileSync,readSync,statSync}from"node:fs";import*as path from"node:path";function isPromptLedgerTerminalRecord(record){return"terminal"in record}__name(isPromptLedgerTerminalRecord,"isPromptLedgerTerminalRecord");function appendPromptLedgerRecord(filePath,record){mkdirSync(path.dirname(filePath),{recursive:true});sealTornTailSync(filePath);appendFileSync(filePath,`${JSON.stringify(record)}
3
+ import{SessionService,TURN_INTERRUPTION_HISTORY_TAIL_COUNT,buildSessionHistoryFromConversation,detectTurnInterruption,effectiveHistoryEnd}from"./chunk-3NR3JBMA.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{closeSync as closeSync2,openSync as openSync2,readSync as readSync2,statSync as statSync2}from"node:fs";init_esbuild_shims();import{appendFileSync,closeSync,mkdirSync,openSync,readFileSync,readSync,statSync}from"node:fs";import*as path from"node:path";function isPromptLedgerTerminalRecord(record){return"terminal"in record}__name(isPromptLedgerTerminalRecord,"isPromptLedgerTerminalRecord");function appendPromptLedgerRecord(filePath,record){mkdirSync(path.dirname(filePath),{recursive:true});sealTornTailSync(filePath);appendFileSync(filePath,`${JSON.stringify(record)}
4
4
  `,{encoding:"utf8",mode:384})}__name(appendPromptLedgerRecord,"appendPromptLedgerRecord");function sealTornTailSync(filePath){let stats;try{stats=statSync(filePath)}catch(error){if(error.code==="ENOENT")return;throw error}if(stats.size===0)return;const fd=openSync(filePath,"r");try{const lastByte=Buffer.alloc(1);const bytesRead=readSync(fd,lastByte,0,1,stats.size-1);if(bytesRead===1&&lastByte[0]!==10){appendFileSync(filePath,"\n","utf8")}}finally{closeSync(fd)}}__name(sealTornTailSync,"sealTornTailSync");function coercePromptLedgerRecord(value){if(typeof value!=="object"||value===null)return void 0;const record=value;const promptId=record["promptId"];const at=record["at"];if(record["v"]!==1||typeof promptId!=="string")return void 0;if(typeof at!=="number"||!Number.isFinite(at))return void 0;if(record["state"]==="in_flight"){const tailUuid=record["tailUuid"];return{v:1,promptId,state:"in_flight",...typeof tailUuid==="string"&&tailUuid.length>0?{tailUuid}:{},at}}const terminal=record["terminal"];if(terminal!=="completed"&&terminal!=="cancelled"&&terminal!=="error"&&terminal!=="interrupted"){return void 0}const code=record["code"];const stopReason=record["stopReason"];return{v:1,promptId,terminal,...typeof code==="string"?{code}:{},...typeof stopReason==="string"?{stopReason}:{},at}}__name(coercePromptLedgerRecord,"coercePromptLedgerRecord");function readPromptLedgerRecords(filePath,options){let contents;let dropFirstLine=false;try{const tailBytes=options?.tailBytes;if(tailBytes===void 0){contents=readFileSync(filePath,"utf8")}else{const size=statSync(filePath).size;if(size<=tailBytes){contents=readFileSync(filePath,"utf8")}else{const fd=openSync(filePath,"r");try{const buffer=Buffer.alloc(tailBytes);const bytesRead=readSync(fd,buffer,0,tailBytes,size-tailBytes);contents=buffer.subarray(0,bytesRead).toString("utf8");dropFirstLine=true}finally{closeSync(fd)}}}}catch(error){if(error.code==="ENOENT")return[];throw error}const records=[];const lines=contents.split("\n");for(let i=dropFirstLine?1:0;i<lines.length;i++){const line=lines[i];if(line===void 0||line.length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}const record=coercePromptLedgerRecord(parsed);if(record!==void 0)records.push(record)}return records}__name(readPromptLedgerRecords,"readPromptLedgerRecords");function danglingInFlightPromptIds(records){const latest=new Map;for(const record of records){latest.set(record.promptId,record)}const dangling=[];for(const[promptId,record]of latest){if(!isPromptLedgerTerminalRecord(record))dangling.push(promptId)}return dangling}__name(danglingInFlightPromptIds,"danglingInFlightPromptIds");var PROMPT_TERMINALS_RESPONSE_LIMIT=64;function recentPromptTerminalRecords(records){const terminals=records.filter(isPromptLedgerTerminalRecord);return terminals.length<=PROMPT_TERMINALS_RESPONSE_LIMIT?terminals:terminals.slice(-PROMPT_TERMINALS_RESPONSE_LIMIT)}__name(recentPromptTerminalRecords,"recentPromptTerminalRecords");function createPromptLedgerSink(workspaceCwd,sessionRuntimeBaseDir){const sessionService=new SessionService(workspaceCwd,{runtimeBaseDir:sessionRuntimeBaseDir});return{appendSync(sessionId,record){appendPromptLedgerRecord(sessionService.getPromptLedgerPath(sessionId),record)},transcriptTailUuid(sessionId){return readTranscriptTailUuid(sessionService.getSessionTranscriptPath(sessionId))}}}__name(createPromptLedgerSink,"createPromptLedgerSink");var TRANSCRIPT_TAIL_BYTES=64*1024;function readTranscriptTailUuid(transcriptPath){let contents;try{const size=statSync2(transcriptPath).size;if(size===0)return void 0;const windowBytes=Math.min(size,TRANSCRIPT_TAIL_BYTES);const buffer=Buffer.alloc(windowBytes);const fd=openSync2(transcriptPath,"r");try{readSync2(fd,buffer,0,windowBytes,size-windowBytes)}finally{closeSync2(fd)}contents=buffer.toString("utf8")}catch{return void 0}const lines=contents.split("\n");for(let i=lines.length-1;i>=0;i--){const line=lines[i];if(line===void 0||line.length===0)continue;try{const uuid=JSON.parse(line).uuid;return typeof uuid==="string"&&uuid.length>0?uuid:void 0}catch{return void 0}}return void 0}__name(readTranscriptTailUuid,"readTranscriptTailUuid");async function reconcileDanglingPromptTerminals(sessionService,sessionId){const ledgerPath=sessionService.getPromptLedgerPath(sessionId);let records;try{records=readPromptLedgerRecords(ledgerPath)}catch{return}const snapshotLength=records.length;const dangling=danglingInFlightPromptIds(records);if(dangling.length===0)return;if(dangling.length>1)return;const target=dangling[0];if(target===void 0)return;const settledPromptIds=new Set(records.filter(isPromptLedgerTerminalRecord).map(r=>r.promptId));let targetAdmission;for(const record2 of records){if(!isPromptLedgerTerminalRecord(record2)&&!settledPromptIds.has(record2.promptId)){targetAdmission=record2}}if(targetAdmission===void 0||targetAdmission.promptId!==target){return}let resumed;try{resumed=await sessionService.loadSession(sessionId)}catch{return}if(resumed===void 0)return;const messages=resumed.conversation.messages;const admissionMarker=targetAdmission.tailUuid;let markerIndex=-1;if(admissionMarker!==void 0){markerIndex=messages.findIndex(record2=>record2.uuid===admissionMarker);let wroteAfterMarker=false;for(let i=markerIndex+1;i<messages.length;i++){const record2=messages[i];if(record2===void 0||record2.type==="system")continue;if(!record2.message||record2.subtype==="realtime_message")continue;wroteAfterMarker=true;break}if(markerIndex<0||!wroteAfterMarker)return}let lastVisibleWriteMs=NaN;let lastVisibleNonSystem;let compressedAfterAdmission=false;let localCommandCompleted=false;const admissionAt=targetAdmission.at;const isAfterAdmission=__name((idx,writeMs)=>admissionMarker!==void 0?idx>markerIndex:Number.isFinite(writeMs)&&writeMs>=admissionAt,"isAfterAdmission");for(let idx=0;idx<messages.length;idx++){const record2=messages[idx];const writeMs=Date.parse(record2.timestamp);if(record2.type==="system"){if(isCompressionResetRecord(record2)){if(isAfterAdmission(idx,writeMs))compressedAfterAdmission=true}else if(!localCommandCompleted&&isAfterAdmission(idx,writeMs)&&isLocalSlashCommandResult(record2,lastVisibleNonSystem)){localCommandCompleted=true}continue}if(!record2.message||record2.subtype==="realtime_message")continue;if(record2.provenance==="system")continue;if(record2.subtype==="agent_mention"||record2.subtype==="agent_message"){continue}if(Number.isFinite(writeMs))lastVisibleWriteMs=writeMs;lastVisibleNonSystem=record2}let lastOtherTerminalAt=0;for(const record2 of records){if(isPromptLedgerTerminalRecord(record2)&&record2.promptId!==target){if(record2.code==="prompt_deadline_exceeded")return;lastOtherTerminalAt=Math.max(lastOtherTerminalAt,record2.at)}}if(compressedAfterAdmission||!Number.isFinite(lastVisibleWriteMs)||lastVisibleWriteMs<=targetAdmission.at||lastVisibleWriteMs<=lastOtherTerminalAt){return}const{apiHistory,completedToolCallIds}=buildSessionHistoryFromConversation(resumed.conversation);const classifiableEnd=effectiveHistoryEnd(apiHistory);const historyTail=apiHistory.slice(Math.max(0,classifiableEnd-TURN_INTERRUPTION_HISTORY_TAIL_COUNT),classifiableEnd);const verdict=detectTurnInterruption(historyTail,completedToolCallIds);const interrupted=verdict.kind!=="none"||tailHoldsAnyFunctionCall(historyTail);const lastVisibleNonSystemType=lastVisibleNonSystem?.type;if(!interrupted&&lastVisibleNonSystemType!=="assistant"&&lastVisibleNonSystemType!=="tool_result"&&!localCommandCompleted){return}let refetch;try{refetch=readPromptLedgerRecords(ledgerPath)}catch{return}if(refetch.length!==snapshotLength)return;const record=interrupted?{v:1,promptId:target,terminal:"interrupted",code:"daemon_lost",at:Date.now()}:{v:1,promptId:target,terminal:"completed",stopReason:"reconstructed_from_transcript",at:Date.now()};try{appendPromptLedgerRecord(ledgerPath,record)}catch{}}__name(reconcileDanglingPromptTerminals,"reconcileDanglingPromptTerminals");function isCompressionResetRecord(record){if(record.type!=="system"||record.subtype!=="chat_compression"){return false}return Boolean(record.systemPayload?.compressedHistory)}__name(isCompressionResetRecord,"isCompressionResetRecord");function isLocalSlashCommandResult(record,previous){if(record.subtype!=="slash_command")return false;const payload=record.systemPayload;const items=payload?.outputHistoryItems;const parts=previous?.message?.parts;const first=parts?.[0];return payload?.phase==="result"&&payload.sentToModel!==true&&Array.isArray(items)&&items.length>0&&items.every(item=>item["type"]==="assistant")&&previous?.type==="user"&&previous.subtype===void 0&&previous.message?.role==="user"&&parts?.length===1&&first!==void 0&&typeof first.text==="string"&&Object.keys(first).length===1&&first.text===payload.rawCommand}__name(isLocalSlashCommandResult,"isLocalSlashCommandResult");function tailHoldsAnyFunctionCall(history){const last=history[history.length-1];if(last?.role!=="model")return false;return(last.parts??[]).some(part=>part.functionCall!==void 0)}__name(tailHoldsAnyFunctionCall,"tailHoldsAnyFunctionCall");var RECENT_TERMINALS_TAIL_BYTES=256*1024;function readRecentPromptTerminals(sessionService,sessionId){try{const terminals=recentPromptTerminalRecords(readPromptLedgerRecords(sessionService.getPromptLedgerPath(sessionId),{tailBytes:RECENT_TERMINALS_TAIL_BYTES}));return terminals.length>0?terminals:void 0}catch{return void 0}}__name(readRecentPromptTerminals,"readRecentPromptTerminals");function withPromptTerminals(session,terminals){if(terminals===void 0||terminals.length===0)return session;return{...session,promptTerminals:[...terminals]}}__name(withPromptTerminals,"withPromptTerminals");export{createPromptLedgerSink,readTranscriptTailUuid,reconcileDanglingPromptTerminals,readRecentPromptTerminals,withPromptTerminals};
5
5
  /**
6
6
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-B7CYUTAO.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-4RGPHRL7.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-A4CHYJUQ.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-XUB4JKSR.js";import{backgroundFixHolding}from"./chunk-BPDVCOZ5.js";import{getCurrentAgentId}from"./chunk-WXQQVXYN.js";import{FileOperationEvent,ReadFileTool,getLanguageFromFilePath,logFileOperation}from"./chunk-R5AA46IX.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-TQGZS3WN.js";import{safeLiteralReplace}from"./chunk-DBRQGEEI.js";import{BaseDeclarativeTool,StructuredToolError}from"./chunk-5KGH76NL.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";init_esbuild_shims();var UNICODE_EQUIVALENT_MAP={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function normalizeBasicCharacters(text){if(text===""){return text}let normalized="";for(const char of text){normalized+=UNICODE_EQUIVALENT_MAP[char]??char}return normalized}__name(normalizeBasicCharacters,"normalizeBasicCharacters");var LINE_COMPARISON_PASSES=[value=>value,value=>value.trimEnd()];function normalizeLineForComparison(value){return normalizeBasicCharacters(value).trimEnd()}__name(normalizeLineForComparison,"normalizeLineForComparison");function seekSequenceWithTransform(lines,pattern,transform){if(pattern.length===0){return 0}if(pattern.length>lines.length){return null}outer:for(let i=0;i<=lines.length-pattern.length;i++){for(let p=0;p<pattern.length;p++){if(transform(lines[i+p])!==transform(pattern[p])){continue outer}}return i}return null}__name(seekSequenceWithTransform,"seekSequenceWithTransform");function buildLineIndex(text){const lines=text.split("\n");const offsets=new Array(lines.length+1);let cursor=0;for(let i=0;i<lines.length;i++){offsets[i]=cursor;cursor+=lines[i].length;if(i<lines.length-1){cursor+=1}}offsets[lines.length]=text.length;return{lines,offsets}}__name(buildLineIndex,"buildLineIndex");function sliceFromLines(text,offsets,lines,startLine,lineCount,includeTrailingNewline){if(lineCount===0){return includeTrailingNewline?"\n":""}const startIndex=offsets[startLine]??0;const lastLineIndex=startLine+lineCount-1;const lastLineStart=offsets[lastLineIndex]??0;let endIndex=lastLineStart+(lines[lastLineIndex]?.length??0);if(includeTrailingNewline){const nextLineStart=offsets[startLine+lineCount];if(nextLineStart!==void 0){endIndex=nextLineStart}else if(text.endsWith("\n")){endIndex=text.length}}return text.slice(startIndex,endIndex)}__name(sliceFromLines,"sliceFromLines");function findLineBasedMatch(haystack,needle){const{lines,offsets}=buildLineIndex(haystack);const patternLines=needle.split("\n");const endsWithNewline=needle.endsWith("\n");if(patternLines.length===0){return null}const attemptMatch=__name(candidate=>{for(const pass of LINE_COMPARISON_PASSES){const idx=seekSequenceWithTransform(lines,candidate,pass);if(idx!==null){return idx}}return seekSequenceWithTransform(lines,candidate,normalizeLineForComparison)},"attemptMatch");let matchIndex=attemptMatch(patternLines);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,patternLines.length-(endsWithNewline?1:0),endsWithNewline),removedTrailingFinalEmptyLine:false,lineBasedMatch:true}}if(patternLines.at(-1)===""){const trimmedPattern=patternLines.slice(0,-1);if(trimmedPattern.length===0){return null}matchIndex=attemptMatch(trimmedPattern);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,trimmedPattern.length,false),removedTrailingFinalEmptyLine:true,lineBasedMatch:true}}}return null}__name(findLineBasedMatch,"findLineBasedMatch");function findMatchedSlice(haystack,needle){if(needle===""){return null}const literalIndex=haystack.indexOf(needle);if(literalIndex!==-1){return{slice:haystack.slice(literalIndex,literalIndex+needle.length),removedTrailingFinalEmptyLine:false}}const normalizedHaystack=normalizeBasicCharacters(haystack);const normalizedNeedleChars=normalizeBasicCharacters(needle);const normalizedIndex=normalizedHaystack.indexOf(normalizedNeedleChars);if(normalizedIndex!==-1){return{slice:haystack.slice(normalizedIndex,normalizedIndex+needle.length),removedTrailingFinalEmptyLine:false}}return findLineBasedMatch(haystack,needle)}__name(findMatchedSlice,"findMatchedSlice");function removeTrailingNewline(text){if(text.endsWith("\r\n")){return text.slice(0,-2)}if(text.endsWith("\n")||text.endsWith("\r")){return text.slice(0,-1)}return text}__name(removeTrailingNewline,"removeTrailingNewline");function adjustNewStringForTrailingLine(newString,removedTrailingLine){return removedTrailingLine?removeTrailingNewline(newString):newString}__name(adjustNewStringForTrailingLine,"adjustNewStringForTrailingLine");function normalizeEditStrings(fileContent,oldString,newString){if(fileContent===null||oldString===""){return{oldString,newString}}const canonicalOriginal=findMatchedSlice(fileContent,oldString);if(canonicalOriginal!==null){return{oldString:canonicalOriginal.slice,newString:adjustNewStringForTrailingLine(newString,canonicalOriginal.removedTrailingFinalEmptyLine),...canonicalOriginal.lineBasedMatch?{lineBasedMatch:true}:{}}}return{oldString,newString}}__name(normalizeEditStrings,"normalizeEditStrings");function maybeAugmentOldStringForDeletion(fileContent,oldString,newString,lineBasedMatch=false){if(fileContent===null||oldString===""||newString!==""||oldString.endsWith("\n")){return oldString}const candidate=`${oldString}
3
+ import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-AKDODQCI.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-4RGPHRL7.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-A4CHYJUQ.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-3NR3JBMA.js";import{backgroundFixHolding}from"./chunk-BPDVCOZ5.js";import{getCurrentAgentId}from"./chunk-WXQQVXYN.js";import{FileOperationEvent,ReadFileTool,getLanguageFromFilePath,logFileOperation}from"./chunk-R5AA46IX.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-CQGP2BAW.js";import{fileExists,getSpecificMimeType}from"./chunk-TQGZS3WN.js";import{safeLiteralReplace}from"./chunk-DBRQGEEI.js";import{BaseDeclarativeTool,StructuredToolError}from"./chunk-5KGH76NL.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";init_esbuild_shims();var UNICODE_EQUIVALENT_MAP={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function normalizeBasicCharacters(text){if(text===""){return text}let normalized="";for(const char of text){normalized+=UNICODE_EQUIVALENT_MAP[char]??char}return normalized}__name(normalizeBasicCharacters,"normalizeBasicCharacters");var LINE_COMPARISON_PASSES=[value=>value,value=>value.trimEnd()];function normalizeLineForComparison(value){return normalizeBasicCharacters(value).trimEnd()}__name(normalizeLineForComparison,"normalizeLineForComparison");function seekSequenceWithTransform(lines,pattern,transform){if(pattern.length===0){return 0}if(pattern.length>lines.length){return null}outer:for(let i=0;i<=lines.length-pattern.length;i++){for(let p=0;p<pattern.length;p++){if(transform(lines[i+p])!==transform(pattern[p])){continue outer}}return i}return null}__name(seekSequenceWithTransform,"seekSequenceWithTransform");function buildLineIndex(text){const lines=text.split("\n");const offsets=new Array(lines.length+1);let cursor=0;for(let i=0;i<lines.length;i++){offsets[i]=cursor;cursor+=lines[i].length;if(i<lines.length-1){cursor+=1}}offsets[lines.length]=text.length;return{lines,offsets}}__name(buildLineIndex,"buildLineIndex");function sliceFromLines(text,offsets,lines,startLine,lineCount,includeTrailingNewline){if(lineCount===0){return includeTrailingNewline?"\n":""}const startIndex=offsets[startLine]??0;const lastLineIndex=startLine+lineCount-1;const lastLineStart=offsets[lastLineIndex]??0;let endIndex=lastLineStart+(lines[lastLineIndex]?.length??0);if(includeTrailingNewline){const nextLineStart=offsets[startLine+lineCount];if(nextLineStart!==void 0){endIndex=nextLineStart}else if(text.endsWith("\n")){endIndex=text.length}}return text.slice(startIndex,endIndex)}__name(sliceFromLines,"sliceFromLines");function findLineBasedMatch(haystack,needle){const{lines,offsets}=buildLineIndex(haystack);const patternLines=needle.split("\n");const endsWithNewline=needle.endsWith("\n");if(patternLines.length===0){return null}const attemptMatch=__name(candidate=>{for(const pass of LINE_COMPARISON_PASSES){const idx=seekSequenceWithTransform(lines,candidate,pass);if(idx!==null){return idx}}return seekSequenceWithTransform(lines,candidate,normalizeLineForComparison)},"attemptMatch");let matchIndex=attemptMatch(patternLines);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,patternLines.length-(endsWithNewline?1:0),endsWithNewline),removedTrailingFinalEmptyLine:false,lineBasedMatch:true}}if(patternLines.at(-1)===""){const trimmedPattern=patternLines.slice(0,-1);if(trimmedPattern.length===0){return null}matchIndex=attemptMatch(trimmedPattern);if(matchIndex!==null){return{slice:sliceFromLines(haystack,offsets,lines,matchIndex,trimmedPattern.length,false),removedTrailingFinalEmptyLine:true,lineBasedMatch:true}}}return null}__name(findLineBasedMatch,"findLineBasedMatch");function findMatchedSlice(haystack,needle){if(needle===""){return null}const literalIndex=haystack.indexOf(needle);if(literalIndex!==-1){return{slice:haystack.slice(literalIndex,literalIndex+needle.length),removedTrailingFinalEmptyLine:false}}const normalizedHaystack=normalizeBasicCharacters(haystack);const normalizedNeedleChars=normalizeBasicCharacters(needle);const normalizedIndex=normalizedHaystack.indexOf(normalizedNeedleChars);if(normalizedIndex!==-1){return{slice:haystack.slice(normalizedIndex,normalizedIndex+needle.length),removedTrailingFinalEmptyLine:false}}return findLineBasedMatch(haystack,needle)}__name(findMatchedSlice,"findMatchedSlice");function removeTrailingNewline(text){if(text.endsWith("\r\n")){return text.slice(0,-2)}if(text.endsWith("\n")||text.endsWith("\r")){return text.slice(0,-1)}return text}__name(removeTrailingNewline,"removeTrailingNewline");function adjustNewStringForTrailingLine(newString,removedTrailingLine){return removedTrailingLine?removeTrailingNewline(newString):newString}__name(adjustNewStringForTrailingLine,"adjustNewStringForTrailingLine");function normalizeEditStrings(fileContent,oldString,newString){if(fileContent===null||oldString===""){return{oldString,newString}}const canonicalOriginal=findMatchedSlice(fileContent,oldString);if(canonicalOriginal!==null){return{oldString:canonicalOriginal.slice,newString:adjustNewStringForTrailingLine(newString,canonicalOriginal.removedTrailingFinalEmptyLine),...canonicalOriginal.lineBasedMatch?{lineBasedMatch:true}:{}}}return{oldString,newString}}__name(normalizeEditStrings,"normalizeEditStrings");function maybeAugmentOldStringForDeletion(fileContent,oldString,newString,lineBasedMatch=false){if(fileContent===null||oldString===""||newString!==""||oldString.endsWith("\n")){return oldString}const candidate=`${oldString}
4
4
  `;const hasCandidate=lineBasedMatch?findLineBasedMatchOffsets(fileContent,candidate).length>0:fileContent.includes(candidate);return hasCandidate?candidate:oldString}__name(maybeAugmentOldStringForDeletion,"maybeAugmentOldStringForDeletion");function countOccurrences(source,substr){if(substr===""){return 0}let count=0;let index=source.indexOf(substr);while(index!==-1){count++;index=source.indexOf(substr,index+substr.length)}return count}__name(countOccurrences,"countOccurrences");function findLineBasedMatchOffsets(source,substr){const offsets=[];if(substr===""){return offsets}let index=source.indexOf(substr);while(index!==-1){const end=index+substr.length;const startsLine=index===0||source[index-1]==="\n";const endsLine=substr.endsWith("\n")||end===source.length||source[end]==="\n";if(startsLine&&endsLine){offsets.push(index);index=source.indexOf(substr,end)}else{index=source.indexOf(substr,index+1)}}return offsets}__name(findLineBasedMatchOffsets,"findLineBasedMatchOffsets");var SNIPPET_CONTEXT_LINES=4;var SNIPPET_MAX_LINES=1e3;function extractEditSnippet(oldContent,newContent){const newLines=newContent.split("\n");const totalLines=newLines.length;if(oldContent===null){return{startLine:1,endLine:totalLines,totalLines,content:newContent}}if(oldContent===newContent||!newContent){return null}const oldLines=oldContent.split("\n");let firstDiffLine=0;const minLength=Math.min(oldLines.length,newLines.length);while(firstDiffLine<minLength){if(oldLines[firstDiffLine]!==newLines[firstDiffLine]){break}firstDiffLine++}let oldEndIndex=oldLines.length-1;let newEndIndex=newLines.length-1;while(oldEndIndex>=firstDiffLine&&newEndIndex>=firstDiffLine){if(oldLines[oldEndIndex]!==newLines[newEndIndex]){break}oldEndIndex--;newEndIndex--}const changeStart=firstDiffLine+1;const changeEnd=newEndIndex+1;if(changeEnd-changeStart>SNIPPET_MAX_LINES){return null}const snippetStart=Math.max(1,changeStart-SNIPPET_CONTEXT_LINES);const snippetEnd=Math.min(totalLines,changeEnd+SNIPPET_CONTEXT_LINES);const snippetLines=newLines.slice(snippetStart-1,snippetEnd);return{startLine:snippetStart,endLine:snippetEnd,totalLines,content:snippetLines.join("\n")}}__name(extractEditSnippet,"extractEditSnippet");var debugLogger=createDebugLogger("EDIT_PRIOR_READ");function applyReplacement(currentContent,oldString,newString,isNewFile,matchOffsets){if(isNewFile){return newString}if(currentContent===null){return oldString===""?newString:""}if(oldString===""&&!isNewFile){return currentContent}if(matchOffsets!==void 0){const pieces=[];let cursor=0;for(const offset of matchOffsets){pieces.push(currentContent.slice(cursor,offset),newString);cursor=offset+oldString.length}pieces.push(currentContent.slice(cursor));return pieces.join("")}return safeLiteralReplace(currentContent,oldString,newString)}__name(applyReplacement,"applyReplacement");var EditToolInvocation=class{constructor(config,params){this.config=config;this.params=params}static{__name(this,"EditToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}async calculateEdit(params,original,signal){const observation=original??await this.config.getFileSystemService().textFileIo?.inspect(params.file_path,signal);const sandboxFileVersion=captureRuntimeFileVersion(this.config,params.file_path);const replaceAll=params.replace_all??false;let currentContent=null;let fileExists2=observation?observation.kind==="file":await fileExists(params.file_path);let isNewFile=false;let finalNewString=params.new_string;let finalOldString=params.old_string;let occurrences=0;let error=void 0;let useBOM=false;let detectedEncoding="utf-8";let detectedLineEnding="lf";if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),params.file_path,"editing");if(!decision.ok){return{currentContent:null,newContent:"",occurrences:0,error:{display:decision.displayMessage,raw:decision.rawMessage,type:decision.type},isNewFile:false,encoding:"utf-8",bom:false,lineEnding:"lf"}}}if(fileExists2){try{const fileInfo=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:params.file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);currentContent=fileInfo.content.replace(/\r\n/g,"\n");fileExists2=true}catch(err){if(!isNodeError(err)||err.code!=="ENOENT"){throw err}fileExists2=false}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),params.file_path,"editing",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection",{path:params.file_path,reason:postDecision.type});return{currentContent:null,newContent:"",occurrences:0,error:{display:postDecision.displayMessage,raw:postDecision.rawMessage,type:postDecision.type},isNewFile:false,encoding:"utf-8",bom:false,lineEnding:"lf"}}}const normalizedStrings=normalizeEditStrings(currentContent,finalOldString,finalNewString);finalOldString=normalizedStrings.oldString;finalNewString=normalizedStrings.newString;let matchOffsets;if(finalOldString===""&&!fileExists2){isNewFile=true}else if(!fileExists2){error={display:`File not found. Cannot apply edit. Use an empty old_string to create a new file.`,raw:`File not found: ${params.file_path}`,type:"file_not_found"}}else if(currentContent!==null){finalOldString=maybeAugmentOldStringForDeletion(currentContent,finalOldString,finalNewString,normalizedStrings.lineBasedMatch);if(normalizedStrings.lineBasedMatch){matchOffsets=findLineBasedMatchOffsets(currentContent,finalOldString)}occurrences=matchOffsets?.length??countOccurrences(currentContent,finalOldString);if(params.old_string===""){error={display:`Failed to edit. Attempted to create a file that already exists.`,raw:`File already exists, cannot create: ${params.file_path}`,type:"attempt_to_create_existing_file"}}else if(occurrences===0){error={display:`Failed to edit, could not find the string to replace.`,raw:`Failed to edit, 0 occurrences found for old_string in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${ReadFileTool.Name} tool to verify.`,type:"edit_no_occurrence_found"}}else if(!replaceAll&&occurrences>1){error={display:`Failed to edit because the text matches multiple locations. Provide more context or set replace_all to true.`,raw:`Failed to edit. Found ${occurrences} occurrences for old_string in ${params.file_path} but replace_all was not enabled.`,type:"edit_expected_occurrence_mismatch"}}else if(finalOldString===finalNewString){error={display:`No changes to apply. The old_string and new_string are identical.`,raw:`No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,type:"edit_no_change"}}}else{error={display:`Failed to read content of file.`,raw:`Failed to read content of existing file: ${params.file_path}`,type:"read_content_failure"}}const newContent=!error?applyReplacement(currentContent,finalOldString,finalNewString,isNewFile,matchOffsets):currentContent??"";if(!error&&fileExists2&&currentContent===newContent){error={display:"No changes to apply. The new content is identical to the current content.",raw:`No changes to apply. The new content is identical to the current content in file: ${params.file_path}`,type:"edit_no_change"}}if(!error){const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(params.file_path,newContent,this.config.getProjectRoot());if(teamMemoryError){const preExisting=currentContent!==null&&(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(params.file_path,currentContent,this.config.getProjectRoot())!==null;const message=preExisting?`${teamMemoryError} Note: the secret already exists in the current file content, so removing it from your edit alone is not enough \u2014 delete the committed secret from the file.`:teamMemoryError;error={display:message,raw:message,type:"invalid_tool_params"}}}return{currentContent,newContent,sandboxFileVersion,occurrences,error,isNewFile,bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(abortSignal){let editData;try{editData=await this.calculateEdit(this.params,void 0,abortSignal)}catch(error){if(abortSignal.aborted){throw error}const errorMsg=isNodeError(error)&&error.code==="EISDIR"?`Target is a directory, not a file: ${this.params.file_path} (${error.code})`:getErrorMessage(error);throw new Error(`Error preparing edit: ${errorMsg}`)}if(editData.error){throw new StructuredToolError(editData.error.raw,editData.error.type)}const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,editData.currentContent??"",editData.newContent,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Edit: ${shortenPath(makeRelative(this.params.file_path,this.config.getTargetDir()))}`,fileName,filePath:this.params.file_path,fileDiff,originalContent:editData.currentContent,newContent:editData.newContent,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());if(this.params.old_string===""){return`Create ${shortenPath(relativePath)}`}if(this.params.old_string===this.params.new_string){return`No file changes to ${shortenPath(relativePath)}`}return shortenPath(relativePath)}async execute(signal){try{const io=this.config.getFileSystemService().textFileIo;return io?await io.withMutation(this.params.file_path,signal,mutation=>this.executeObserved(signal,mutation)):await this.executeObserved(signal)}catch(error){if(signal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(signal,mutation){let editData;try{editData=await this.calculateEdit(this.params,mutation?.original,signal)}catch(error){if(signal.aborted){throw error}const errorMsg=getErrorMessage(error);return{llmContent:`Error preparing edit: ${errorMsg}`,returnDisplay:`Error preparing edit: ${errorMsg}`,error:{message:errorMsg,type:"edit_preparation_failure"}}}if(editData.error){return{llmContent:editData.error.raw,returnDisplay:`Error: ${editData.error.display}`,error:{message:editData.error.raw,type:editData.error.type}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"editing",{expectExisting:!editData.isNewFile});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:this.params.file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!this.config.getShellExecutionSandbox?.()){this.ensureParentDirectoriesExist(this.params.file_path)}let committedStats;const write=__name(async params=>{if(mutation)committedStats=await mutation.write(params);else await writeRuntimeFile(this.config,params,editData.sandboxFileVersion,signal)},"write");if(editData.isNewFile){const userEncoding=this.config.getDefaultFileEncoding();let useBOM=false;if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(this.params.file_path)}await write({path:this.params.file_path,content:editData.newContent,toolWriteOrigin:"edit",_meta:{bom:useBOM}})}else{await write({path:this.params.file_path,content:editData.newContent,toolWriteOrigin:"edit",_meta:{bom:editData.bom,encoding:editData.encoding,lineEnding:editData.lineEnding}})}if(!mutation&&!this.params.modified_by_user){CommitAttributionService.getInstance().recordEdit(this.params.file_path,editData.currentContent,editData.newContent)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(this.params.file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(this.params.file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(this.params.file_path);const originallyProposedContent=this.params.ai_proposed_content||editData.newContent;const diffStat=getDiffStat(fileName,editData.currentContent??"",originallyProposedContent,editData.newContent);const fileDiff=createPatchSmart(fileName,editData.currentContent??"",editData.newContent,"Current","Proposed");const displayResult={fileDiff,fileName,filePath:this.params.file_path,originalContent:editData.currentContent,newContent:editData.newContent,diffStat};const mimetype=getSpecificMimeType(this.params.file_path);const programmingLanguage=getLanguageFromFilePath(this.params.file_path);const extension=path.extname(this.params.file_path);const operation=editData.isNewFile?"create":"update";logFileOperation(this.config,new FileOperationEvent(EditTool.Name,operation,editData.newContent.split("\n").length,mimetype,extension,programmingLanguage));const llmSuccessMessageParts=[editData.isNewFile?`Created new file: ${this.params.file_path} with provided content.`:`The file: ${this.params.file_path} has been updated.`];const artifact=buildWorkspaceArtifactCandidate(this.config,this.params.file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const snippetResult=extractEditSnippet(editData.currentContent,editData.newContent);if(snippetResult){const snippetText=`Showing lines ${snippetResult.startLine}-${snippetResult.endLine} of ${snippetResult.totalLines} from the edited file:
5
5
 
6
6
  ---
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import{remarkParse,unified}from"./chunk-AZ3CKMCT.js";import{estimateTextTokens}from"./chunk-RP57XAJ2.js";import{ignoreBrokenPipe}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{homedir}from"node:os";import path2 from"node:path";import*as fs2 from"node:fs/promises";init_esbuild_shims();init_esbuild_shims();var MEMORY_IMPORT_BUDGET={maxCalls:32,maxReservedTokens:512e3,batchSections:8,sourceBytes:65536,contextBytes:32768,outputTokens:8192,promptBytes:32768};function packMemoryImportSections(sections){const groups=new Map;for(const section of[...sections].sort((a,b)=>a.id.localeCompare(b.id))){const key=`${section.scope??""}:${section.groupId}`;const group=groups.get(key)??[];group.push(section);groups.set(key,group)}const batches=[];for(const group of groups.values()){let batch=[];let bytes=0;for(const section of group){const size=Buffer.byteLength(section.content);if(batch.length&&(batch.length===MEMORY_IMPORT_BUDGET.batchSections||bytes+size>MEMORY_IMPORT_BUDGET.sourceBytes)){batches.push(batch);batch=[];bytes=0}batch.push(section);bytes+=size}if(batch.length)batches.push(batch)}return batches}__name(packMemoryImportSections,"packMemoryImportSections");function estimateMemoryImport(sections){const batches=packMemoryImportSections(sections);const modelCalls=batches.length*2;const sourceTokens=sections.reduce((n,section)=>n+estimateTextTokens(section.content),0);const sourceBytes=Buffer.byteLength(JSON.stringify(sections.map(({id,content})=>({id,content}))));const reservedTokens=modelCalls*(MEMORY_IMPORT_BUDGET.contextBytes+MEMORY_IMPORT_BUDGET.promptBytes+MEMORY_IMPORT_BUDGET.outputTokens+1024)+sourceBytes+modelCalls;return{basis:"source-only-with-context-reserve",modelCalls,sourceTokens,maxOutputTokens:modelCalls*MEMORY_IMPORT_BUDGET.outputTokens,reservedTokens,exceedsBudget:modelCalls>MEMORY_IMPORT_BUDGET.maxCalls||reservedTokens>MEMORY_IMPORT_BUDGET.maxReservedTokens,limits:MEMORY_IMPORT_BUDGET}}__name(estimateMemoryImport,"estimateMemoryImport");import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import path from"node:path";import{constants}from"node:fs";var MemoryImportRequestError=class extends Error{static{__name(this,"MemoryImportRequestError")}};var IMPORT_LIMITS={files:256,fileBytes:512*1024,totalBytes:8*1024*1024,sectionBytes:64*1024,headings:4096,markdownLines:16384,inlineMarkers:4096};function digest(value){return createHash("sha256").update(value).digest("hex")}__name(digest,"digest");function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(record,"record");function validSourcePath(value){return value.length<=512&&!/[\\\p{Cc}]/u.test(value)&&!value.startsWith("/")&&!/^[a-z]:/i.test(value)&&value.split("/").every(part=>part!==""&&part!=="."&&part!=="..")&&(/^(?:MEMORY|memory_summary)\.md$/.test(value)||/^rollout_summaries\/[\w.-]+\.md$/.test(value))}__name(validSourcePath,"validSourcePath");function validateSource(value){if(!record(value)||value["version"]!==1||value["source"]!=="codex"||!Array.isArray(value["files"])||value["files"].length===0||value["files"].length>IMPORT_LIMITS.files)throw new MemoryImportRequestError("Invalid version 1 Codex source set.");let bytes=0;const seen=new Set;const files=value["files"].map(file=>{if(!record(file)||typeof file["path"]!=="string"||!validSourcePath(file["path"])||typeof file["content"]!=="string"||file["content"].includes("\0"))throw new MemoryImportRequestError("Invalid Codex Markdown resource. Only memory Markdown and rollout_summaries/*.md are accepted.");const size=Buffer.byteLength(file["content"]);bytes+=size;if(size>IMPORT_LIMITS.fileBytes||bytes>IMPORT_LIMITS.totalBytes||seen.has(file["path"].toLowerCase()))throw new MemoryImportRequestError("Source exceeds limits or contains duplicate paths.");seen.add(file["path"].toLowerCase());return{path:file["path"],content:file["content"]}});if(!files.some(file=>file.path==="MEMORY.md"||file.path==="memory_summary.md"))throw new MemoryImportRequestError("Select the Codex memories folder containing MEMORY.md or memory_summary.md.");return{version:1,source:"codex",files:files.sort((a,b)=>a.path.localeCompare(b.path))}}__name(validateSource,"validateSource");var parser=unified().use(remarkParse);function headingTitle(raw){const atx=raw.match(/^ {0,3}#{1,6}(?:[\t ]+|$)/);if(atx)return raw.slice(atx[0].length).replace(/[\t ]+#+[\t ]*$/,"").trim();return raw.split(/\r\n|[\r\n]/).slice(0,-1).join(" ").trim()}__name(headingTitle,"headingTitle");function scopeFor(content,title,summary){const scopes=[];for(const match of content.matchAll(/(?:^|[\s;(])cwd\s*[=:]\s*(?:`([^`\n]+)`|([^\r\n,;()\s]+))/gim)){if(match[1]!==void 0){scopes.push({value:match[1].trim(),quoted:true,prose:false});continue}const trailing=content.slice(match.index+match[0].length).split(/\r\n|[\r\n]/,1)[0].trim();scopes.push({value:match[2].trim(),quoted:false,prose:/[^\s,;()]/.test(trailing)})}const heading=title.trim();if(/^(?:\/|[A-Za-z]:[\\/])/.test(heading))scopes.push({value:heading.replace(/^`|`$/g,""),quoted:false,prose:false});const strip=__name(value=>value.replace(/[\\/]+$/,"").replace(/[.:!?'"]+$/,""),"strip");const unique=[...new Set(scopes.map(scope=>strip(scope.value)))];if(unique.length===1&&/^(?:\/|[A-Za-z]:[\\/])/.test(unique[0])&&scopes.every(scope=>!scope.prose&&!/[*?{}[\]\p{Cc}]|\bcwd\s*[=:]/u.test(scope.value)&&(scope.quoted||!/\s/.test(scope.value))))return{suggestedScope:"project",sourceProject:unique[0],reason:"Source project hint; explicit target mapping is required."};if(scopes.length)return{suggestedScope:"unassigned",reason:"Ambiguous or unsupported project scope; assign explicitly."};if(summary&&/^(?:user profile|user preferences)$/i.test(title))return{suggestedScope:"user",reason:"Explicit user-level summary section."};return{suggestedScope:"unassigned",reason:"No reliable project scope; assign explicitly."}}__name(scopeFor,"scopeFor");function previewSource(input){const source=validateSource(input);const sections=[];const warnings=[];let headingCount=0;let lineCount=0;let markerCount=0;let expandedBytes=0;const paths=new Set(source.files.map(file=>file.path));const referenced=new Set;for(const file of source.files.filter(f=>!f.path.startsWith("rollout_summaries/"))){for(const match of file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g))referenced.add(match[0])}for(const ref of referenced)if(!paths.has(ref))warnings.push(`Missing referenced Markdown: ${ref}`);for(const file of source.files){if(file.path.startsWith("rollout_summaries/")&&!referenced.has(file.path)){warnings.push(`Unreferenced supporting resource excluded: ${file.path}`);continue}const atxCandidates=file.content.match(/^ {0,3}#{1,6}(?:[\t ]|$)/gm)?.length??0;if(headingCount+atxCandidates>4*IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");for(let i=0;i<file.content.length;i++){const char=file.content[i];if(char==="\n"||char==="\r"&&file.content[i+1]!=="\n")lineCount++;if("*_~[]<>!`&\\".includes(char))markerCount++;if(lineCount>IMPORT_LIMITS.markdownLines||markerCount>IMPORT_LIMITS.inlineMarkers)throw new MemoryImportRequestError("Source exceeds the Markdown complexity limit; split it into smaller source sets before importing.")}const tree=parser.parse(file.content);const headings=tree.children.filter(node=>node.type==="heading").map((node,index,nodes)=>({offset:node.position.start.offset,line:node.position.start.line,depth:node.depth,title:headingTitle(file.content.slice(node.position.start.offset,node.position.end.offset)),preface:file.content.slice(node.position.start.offset,nodes[index+1]?.position.start.offset).trim()}));headingCount+=headings.length;if(headingCount>IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");const scopedDepths=headings.filter(heading=>/^(?:`?\/|`?[A-Za-z]:[\\/])/.test(heading.title)||/\bcwd\s*[=:]/i.test(heading.preface)).map(heading=>heading.depth);const minDepth=headings.length?Math.min(...headings.map(h=>h.depth)):1;const depth=Math.max(file.path==="memory_summary.md"?2:minDepth,...scopedDepths);const boundaries=headings.filter(heading=>heading.depth<=depth);if(!boundaries.length||boundaries[0].offset>0)boundaries.unshift({offset:0,line:1,title:file.path,depth:0,preface:""});for(let i=0;i<boundaries.length;i++){const boundary=boundaries[i];const own=file.content.slice(boundary.offset,boundaries[i+1]?.offset).trim();if(!own||/^v\d+$/.test(own)||own.split(/\r\n|[\r\n]/).every(line=>!line.trim()||/^#{1,6}\s/.test(line)))continue;const ancestors=[];for(const heading of headings){if(heading.offset>=boundary.offset)break;while(ancestors.length&&ancestors.at(-1).depth>=heading.depth)ancestors.pop();ancestors.push(heading)}while(ancestors.length&&ancestors.at(-1).depth>=boundary.depth)ancestors.pop();const parts=[...ancestors.map(heading=>heading.preface),own];expandedBytes+=parts.reduce((bytes,part)=>bytes+Buffer.byteLength(part),0)+2*(parts.length-1);if(expandedBytes>IMPORT_LIMITS.totalBytes)throw new MemoryImportRequestError("Source expanded context exceeds 8 MiB; split shared context and project groups before importing.");const content=parts.join("\n\n");let scope=scopeFor(content,boundary.title,file.path==="memory_summary.md");if(scope.suggestedScope==="unassigned"&&!/\bcwd\s*[=:]/i.test(content)){const parent=ancestors.at(-1);if(parent)scope=scopeFor(content,parent.title,file.path==="memory_summary.md")}const references=[...new Set(Array.from(content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0]))];const selectable=Buffer.byteLength(content)<=IMPORT_LIMITS.sectionBytes;if(!selectable)warnings.push(`${file.path}:${boundary.line}: section exceeds ${IMPORT_LIMITS.sectionBytes} bytes; split it before import.`);const id=digest(`${file.path}\0${content}`);if(sections.some(section=>section.id===id))continue;sections.push({id,groupId:digest(`${scope.suggestedScope}\0${scope.sourceProject??""}`),title:boundary.title,path:file.path,line:boundary.line,content,references,...scope,selectable})}}const groups=new Map;for(const section of sections){const group=groups.get(section.groupId)??{id:section.groupId,scope:section.suggestedScope,sourceProject:section.sourceProject,sectionIds:[]};group.sectionIds.push(section.id);groups.set(group.id,group)}return{version:1,kind:"preview",digest:digest(JSON.stringify(source)),groups:[...groups.values()].map(group=>({...group,estimate:estimateMemoryImport(sections.filter(section=>section.selectable&&section.groupId===group.id))})),sections,warnings,estimate:estimateMemoryImport(sections.filter(section=>section.selectable))}}__name(previewSource,"previewSource");async function readLocalSource(directory){const root=await fs.realpath(directory);const files=[];const read=__name(async relative=>{const file=path.join(root,relative);const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>IMPORT_LIMITS.fileBytes)throw new Error("Source must contain regular bounded Markdown files.");const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const opened=await handle.stat();if(!opened.isFile()||opened.size>IMPORT_LIMITS.fileBytes)throw new Error("Source changed while opening.");const buffer=Buffer.alloc(IMPORT_LIMITS.fileBytes+1);let length=0;while(length<buffer.length){const read2=await handle.read(buffer,length,buffer.length-length,null);if(!read2.bytesRead)break;length+=read2.bytesRead}if(length>IMPORT_LIMITS.fileBytes||files.reduce((sum,entry)=>sum+Buffer.byteLength(entry.content),length)>IMPORT_LIMITS.totalBytes)throw new Error("Source exceeds byte limits.");files.push({path:relative,content:buffer.subarray(0,length).toString("utf8")})}finally{await handle.close()}},"read");for(const name of["MEMORY.md","memory_summary.md"]){try{await read(name)}catch(error){if(error.code!=="ENOENT")throw error}}const refs=new Set(files.flatMap(file=>Array.from(file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0])));if(refs.size+files.length>IMPORT_LIMITS.files)throw new Error("Too many referenced source files.");if(refs.size){const dir=await fs.lstat(path.join(root,"rollout_summaries")).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(dir&&(!dir.isDirectory()||dir.isSymbolicLink()))throw new Error("Supporting resource directory must not be a symlink.");if(dir)for(const ref of refs){try{await read(ref)}catch(error){if(error.code!=="ENOENT")throw error}}}return validateSource({version:1,source:"codex",files})}__name(readLocalSource,"readLocalSource");var writeStdoutLineFlushed=__name(message=>new Promise((resolve,reject)=>process.stdout.write(message.endsWith("\n")?message:`${message}
4
- `,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-OEBLERSJ.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
4
+ `,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-NUBKA3T2.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{readConfigFile}from"./chunk-E6XRNALG.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{normalizeClaudeMcpServer}from"./chunk-XUB4JKSR.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");export{loadProjectMcpServers};
3
+ import{readConfigFile}from"./chunk-AEX3XSTE.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{normalizeClaudeMcpServer}from"./chunk-3NR3JBMA.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");export{loadProjectMcpServers};
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{loadSettings}from"./chunk-E6XRNALG.js";import{t}from"./chunk-HRRQHZQE.js";import{loadEnvironment}from"./chunk-OSLFWRV2.js";import{collectProviderModelsForProtocol}from"./chunk-53CWA7N2.js";import{resolveModelSelectionAuthType}from"./chunk-N3AKLLXG.js";import{VERTEX_ADC_HINT,hasVertexProjectConfigured}from"./chunk-SFDOJ2FF.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var DEFAULT_ENV_KEYS={["openai"]:"OPENAI_API_KEY",["openai-responses"]:"OPENAI_API_KEY",["anthropic"]:"ANTHROPIC_API_KEY",["gemini"]:"GEMINI_API_KEY",["vertex-ai"]:"GOOGLE_API_KEY"};function findModelConfig(modelProviders,providerProtocol,authType,modelId,baseUrl){if(!modelProviders||!modelId){return void 0}const models=collectProviderModelsForProtocol(modelProviders,providerProtocol,authType);if(models.length===0){return void 0}if(baseUrl){return models.find(m=>m.id===modelId&&m.baseUrl===baseUrl)??models.find(m=>m.id===modelId)}return models.find(m=>m.id===modelId)}__name(findModelConfig,"findModelConfig");function resolveSelectedModel(settings,config){const modelsConfig=config?.getModelsConfig();if(modelsConfig){return{modelId:modelsConfig.getModel(),baseUrl:modelsConfig.getGenerationConfig()?.baseUrl}}return{modelId:settings.model?.name,baseUrl:settings.model?.baseUrl}}__name(resolveSelectedModel,"resolveSelectedModel");function hasEnvValue(settings,envKey){if(!envKey){return false}if(process.env[envKey]){return true}const settingsEnv=settings.env;const settingsEnvValue=settingsEnv?.[envKey];return typeof settingsEnvValue==="string"&&settingsEnvValue.trim().length>0}__name(hasEnvValue,"hasEnvValue");function hasApiKeyForAuth(authType,settings,config){const modelProviders=settings.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelAuthType=!config&&(authType==="openai"||authType==="openai-responses")?resolveModelSelectionAuthType(authType,modelId,modelProviders,settings.providerProtocol,baseUrl):authType;const modelConfig=findModelConfig(modelProviders,settings.providerProtocol,modelAuthType,modelId,baseUrl);const resolvedApiKey=config?.getModelsConfig().getGenerationConfig()?.apiKey;if(resolvedApiKey){return{hasKey:true,checkedEnvKey:modelConfig?.envKey??DEFAULT_ENV_KEYS[authType],isExplicitEnvKey:!!modelConfig?.envKey}}if(modelConfig?.envKey){const hasKey=hasEnvValue(settings,modelConfig.envKey);return{hasKey,checkedEnvKey:modelConfig.envKey,isExplicitEnvKey:true}}const defaultEnvKey=DEFAULT_ENV_KEYS[authType];if(defaultEnvKey){const hasKey=hasEnvValue(settings,defaultEnvKey);if(hasKey){return{hasKey,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}}if(settings.security?.auth?.apiKey){return{hasKey:true,checkedEnvKey:defaultEnvKey||void 0,isExplicitEnvKey:false}}return{hasKey:false,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}__name(hasApiKeyForAuth,"hasApiKeyForAuth");function isVertexAdcEligible(settings,config){const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelConfig=findModelConfig(settings.modelProviders,settings.providerProtocol,"vertex-ai",modelId,baseUrl);return!modelConfig?.envKey}__name(isVertexAdcEligible,"isVertexAdcEligible");function hasVertexProject(settings){const settingsEnv=settings.env;return hasVertexProjectConfigured(key=>{const fromProcess=process.env[key];if(fromProcess!==void 0){return fromProcess}const fromSettings=settingsEnv?.[key];return typeof fromSettings==="string"?fromSettings:void 0})}__name(hasVertexProject,"hasVertexProject");function getApiKeyError(authMethod,settings,config){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings,config);if(hasKey){return null}const envKeyHint=checkedEnvKey||DEFAULT_ENV_KEYS[authMethod];if(isExplicitEnvKey){return t("{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.",{envKeyHint})}return t("{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.",{envKeyHint})}__name(getApiKeyError,"getApiKeyError");function validateAuthMethod(authMethod,config){const settings=loadSettings(process.cwd(),false);loadEnvironment(settings.merged);if(authMethod==="qwen-subscription"){return null}if(authMethod==="openai"||authMethod==="openai-responses"){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings.merged,config);if(!hasKey){const envKeyHint=checkedEnvKey?`'${checkedEnvKey}'`:"'OPENAI_API_KEY'";if(isExplicitEnvKey){return t("Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.",{envKeyHint})}return t("Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.",{envKeyHint})}return null}if(authMethod==="qwen-oauth"){return t("Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.")}if(authMethod==="anthropic"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}const modelProviders=settings.merged.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings.merged,config);const modelConfig=findModelConfig(modelProviders,settings.merged.providerProtocol,authMethod,modelId,baseUrl);if(modelConfig&&!modelConfig.baseUrl){return t("Anthropic provider missing required baseUrl in modelProviders[].baseUrl.")}if(!modelConfig&&!process.env["ANTHROPIC_BASE_URL"]){return t("ANTHROPIC_BASE_URL environment variable not found.")}return null}if(authMethod==="gemini"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}return null}if(authMethod==="vertex-ai"){const adcEligible=isVertexAdcEligible(settings.merged,config);if(!adcEligible||!hasVertexProject(settings.merged)){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return adcEligible?apiKeyError+VERTEX_ADC_HINT:apiKeyError}}process.env["GOOGLE_GENAI_USE_VERTEXAI"]="true";return null}return t("Invalid auth method selected.")}__name(validateAuthMethod,"validateAuthMethod");export{validateAuthMethod};
3
+ import{loadSettings}from"./chunk-AEX3XSTE.js";import{t}from"./chunk-73TSS7KS.js";import{loadEnvironment}from"./chunk-HRTWLOGK.js";import{collectProviderModelsForProtocol}from"./chunk-D5H5GARR.js";import{resolveModelSelectionAuthType}from"./chunk-N3AKLLXG.js";import{VERTEX_ADC_HINT,hasVertexProjectConfigured}from"./chunk-DN4QKOFL.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var DEFAULT_ENV_KEYS={["openai"]:"OPENAI_API_KEY",["openai-responses"]:"OPENAI_API_KEY",["anthropic"]:"ANTHROPIC_API_KEY",["gemini"]:"GEMINI_API_KEY",["vertex-ai"]:"GOOGLE_API_KEY"};function findModelConfig(modelProviders,providerProtocol,authType,modelId,baseUrl){if(!modelProviders||!modelId){return void 0}const models=collectProviderModelsForProtocol(modelProviders,providerProtocol,authType);if(models.length===0){return void 0}if(baseUrl){return models.find(m=>m.id===modelId&&m.baseUrl===baseUrl)??models.find(m=>m.id===modelId)}return models.find(m=>m.id===modelId)}__name(findModelConfig,"findModelConfig");function resolveSelectedModel(settings,config){const modelsConfig=config?.getModelsConfig();if(modelsConfig){return{modelId:modelsConfig.getModel(),baseUrl:modelsConfig.getGenerationConfig()?.baseUrl}}return{modelId:settings.model?.name,baseUrl:settings.model?.baseUrl}}__name(resolveSelectedModel,"resolveSelectedModel");function hasEnvValue(settings,envKey){if(!envKey){return false}if(process.env[envKey]){return true}const settingsEnv=settings.env;const settingsEnvValue=settingsEnv?.[envKey];return typeof settingsEnvValue==="string"&&settingsEnvValue.trim().length>0}__name(hasEnvValue,"hasEnvValue");function hasApiKeyForAuth(authType,settings,config){const modelProviders=settings.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelAuthType=!config&&(authType==="openai"||authType==="openai-responses")?resolveModelSelectionAuthType(authType,modelId,modelProviders,settings.providerProtocol,baseUrl):authType;const modelConfig=findModelConfig(modelProviders,settings.providerProtocol,modelAuthType,modelId,baseUrl);const resolvedApiKey=config?.getModelsConfig().getGenerationConfig()?.apiKey;if(resolvedApiKey){return{hasKey:true,checkedEnvKey:modelConfig?.envKey??DEFAULT_ENV_KEYS[authType],isExplicitEnvKey:!!modelConfig?.envKey}}if(modelConfig?.envKey){const hasKey=hasEnvValue(settings,modelConfig.envKey);return{hasKey,checkedEnvKey:modelConfig.envKey,isExplicitEnvKey:true}}const defaultEnvKey=DEFAULT_ENV_KEYS[authType];if(defaultEnvKey){const hasKey=hasEnvValue(settings,defaultEnvKey);if(hasKey){return{hasKey,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}}if(settings.security?.auth?.apiKey){return{hasKey:true,checkedEnvKey:defaultEnvKey||void 0,isExplicitEnvKey:false}}return{hasKey:false,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}__name(hasApiKeyForAuth,"hasApiKeyForAuth");function isVertexAdcEligible(settings,config){const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelConfig=findModelConfig(settings.modelProviders,settings.providerProtocol,"vertex-ai",modelId,baseUrl);return!modelConfig?.envKey}__name(isVertexAdcEligible,"isVertexAdcEligible");function hasVertexProject(settings){const settingsEnv=settings.env;return hasVertexProjectConfigured(key=>{const fromProcess=process.env[key];if(fromProcess!==void 0){return fromProcess}const fromSettings=settingsEnv?.[key];return typeof fromSettings==="string"?fromSettings:void 0})}__name(hasVertexProject,"hasVertexProject");function getApiKeyError(authMethod,settings,config){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings,config);if(hasKey){return null}const envKeyHint=checkedEnvKey||DEFAULT_ENV_KEYS[authMethod];if(isExplicitEnvKey){return t("{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.",{envKeyHint})}return t("{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.",{envKeyHint})}__name(getApiKeyError,"getApiKeyError");function validateAuthMethod(authMethod,config){const settings=loadSettings(process.cwd(),false);loadEnvironment(settings.merged);if(authMethod==="qwen-subscription"){return null}if(authMethod==="openai"||authMethod==="openai-responses"){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings.merged,config);if(!hasKey){const envKeyHint=checkedEnvKey?`'${checkedEnvKey}'`:"'OPENAI_API_KEY'";if(isExplicitEnvKey){return t("Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.",{envKeyHint})}return t("Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.",{envKeyHint})}return null}if(authMethod==="qwen-oauth"){return t("Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.")}if(authMethod==="anthropic"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}const modelProviders=settings.merged.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings.merged,config);const modelConfig=findModelConfig(modelProviders,settings.merged.providerProtocol,authMethod,modelId,baseUrl);if(modelConfig&&!modelConfig.baseUrl){return t("Anthropic provider missing required baseUrl in modelProviders[].baseUrl.")}if(!modelConfig&&!process.env["ANTHROPIC_BASE_URL"]){return t("ANTHROPIC_BASE_URL environment variable not found.")}return null}if(authMethod==="gemini"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}return null}if(authMethod==="vertex-ai"){const adcEligible=isVertexAdcEligible(settings.merged,config);if(!adcEligible||!hasVertexProject(settings.merged)){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return adcEligible?apiKeyError+VERTEX_ADC_HINT:apiKeyError}}process.env["GOOGLE_GENAI_USE_VERTEXAI"]="true";return null}return t("Invalid auth method selected.")}__name(validateAuthMethod,"validateAuthMethod");export{validateAuthMethod};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{registerCleanup}from"./chunk-LHIEE3A2.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
3
+ import{registerCleanup}from"./chunk-ZSPOFXP3.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
4
4
  `)}}});const enabled=process.env["QWEN_CODE_CPU_PROFILE"]==="1";if(!enabled)return;void startCpuProfile().then(result=>{if(!result.ok){process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
5
5
  `)}})}__name(initCpuProfiler,"initCpuProfiler");async function startCpuProfile(opts){if(state!=="idle"){return{ok:false,error:state==="recording"?"CPU profiling is already in progress.":"CPU profiler is currently stopping. Please wait a moment and try again."}}state="recording";try{const inspectorSession=await getOrCreateSession();await inspectorSession.post("Profiler.enable");await inspectorSession.post("Profiler.setSamplingInterval",{interval:opts?.samplingInterval??DEFAULT_SAMPLING_INTERVAL_US});await inspectorSession.post("Profiler.start");return{ok:true}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(startCpuProfile,"startCpuProfile");async function stopCpuProfile(options){if(state!=="recording"){return{ok:false,error:state==="idle"?"CPU profiler is not recording.":"CPU profiler is already stopping."}}const outputDir=options?.outputDir??defaultOutputDir();const now=options?.now??new Date;const rateLimitMs=options?.rateLimitMs??RATE_LIMIT_MS;const maxProfiles=options?.maxProfiles??MAX_PROFILES;try{enforceRateLimit(outputDir,now,rateLimitMs)}catch(error){state="idle";if(session){session.post("Profiler.stop").catch(()=>{});session.post("Profiler.disable").catch(()=>{})}disconnectSession();return{ok:false,error:formatError(error)}}state="stopping";try{if(!session){throw new Error("Inspector session lost unexpectedly during Profiler.stop; the profile data could not be retrieved.")}const result=await session.post("Profiler.stop");if(!result.profile){throw new Error("V8 Profiler.stop returned an empty profile; recording may have been interrupted.")}await session.post("Profiler.disable");fs.mkdirSync(outputDir,{recursive:true,mode:448});try{fs.chmodSync(outputDir,448)}catch{}checkDiskSpace(outputDir);const filePath=path.join(outputDir,`qwen-code-cpu-${process.pid}-${formatTimestamp(now)}.cpuprofile`);try{fs.writeFileSync(filePath,JSON.stringify(result.profile),{mode:384})}catch(writeError){try{fs.rmSync(filePath,{force:true})}catch{}throw writeError}recordWrite(outputDir,now);cleanupOldProfiles(outputDir,maxProfiles);state="idle";return{ok:true,filePath}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(stopCpuProfile,"stopCpuProfile");function isCpuProfileRecording(){return state==="recording"}__name(isCpuProfileRecording,"isCpuProfileRecording");function registerSignalHandler(){if(signalHandlerRegistered)return;if(process.platform==="win32")return;signalHandlerRegistered=true;process.on("SIGUSR1",handleSigusr1)}__name(registerSignalHandler,"registerSignalHandler");function defaultOutputDir(){return path.join(os.homedir(),".qwen","cpu-profiles")}__name(defaultOutputDir,"defaultOutputDir");function formatTimestamp(now){return now.toISOString().replace(/[:.]/g,"-")}__name(formatTimestamp,"formatTimestamp");function formatError(error){return error instanceof Error?error.message:String(error)}__name(formatError,"formatError");var sessionFactory=null;async function getOrCreateSession(){if(session)return session;if(sessionFactory){session=await sessionFactory();return session}const inspectorModule=await import("node:inspector/promises");const newSession=new inspectorModule.Session;newSession.connect();session=newSession;return session}__name(getOrCreateSession,"getOrCreateSession");function disconnectSession(){if(session){try{session.disconnect()}catch{}session=null}}__name(disconnectSession,"disconnectSession");function handleSigusr1(){if(state==="idle"){void startCpuProfile().then(result=>{if(result.ok){process.stderr.write(`[cpu-profiler] Recording started (PID ${process.pid}). Send SIGUSR1 again to stop.
6
6
  `)}else{process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}