@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{classifyTopLevelConversationSource}from"./chunk-7M5JT3ID.js";import{A1_MIN_VERSION,a1VersionAtLeast,parseA1Version}from"./chunk-U3ZLJQMS.js";import{parseWorktreePaths,runStatus}from"./chunk-U2DX235N.js";import{isAoneCanonicalHost,parseRemoteUrl}from"./chunk-F2L3WXJO.js";import{sanitizedGitEnv}from"./chunk-5DPLJQUC.js";import{PathMutexRegistry}from"./chunk-TCKM7S2Z.js";import{createSessionOrganizationService}from"./chunk-NW3H676V.js";import{HIDDEN_CATALOG_SOURCE_TYPES,isHiddenCatalogSource}from"./chunk-DHYCGKLG.js";import{safeLogValue}from"./chunk-SVGTUGV2.js";import{createWorkspaceRuntimeSessionService,getWorkspaceRouteContext,requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeFromParam,sendGenerationClosedError,sendUntrustedWorkspaceResponse,setWorkspaceRouteContext}from"./chunk-J5W6P7QD.js";import{normalizeSessionIdForLookup,parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{EVENT_SCHEMA_VERSION}from"./chunk-OFWAMIMB.js";import{SessionArchivedError,SessionArchivingError,SessionConflictError,SessionNotArchivedError,SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{canonicalizeWorkspace,canonicalizeWorkspaces}from"./chunk-L5UULTGF.js";import{sanitizeLogText}from"./chunk-6WGM7K6B.js";import{loadIgnoreRules}from"./chunk-HXYHIEMH.js";import{readWorktreeSession,readWorktreeSessionStrict}from"./chunk-NGQDWVC6.js";import{GROUP_COLOR_OPTIONS,SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SessionIdCaseConflictError,SessionOrganizationError,SessionService,SessionTranscriptChangedError,SessionWriterUnavailableError,StandardFileSystemService,canonicalSessionPrUrl,detectLineEnding,encodeTextFileContentAsync,fetchRemoteWebUrl,readSessionPrsDetailed,repoKeyFromWebUrl,toSessionPrInfo}from"./chunk-XUB4JKSR.js";import{cronTaskSessionDeletionId,getCronFilePath,readCronTasks,updateCronTasks}from"./chunk-DXUYBMFK.js";import{GitWorktreeService,gitEnv,readWorktreeSessionMarker,readWorktreeSessionMarkerStrict,worktreeHasWork}from"./chunk-B4ZATWBT.js";import{glob}from"./chunk-OBOU4ZZM.js";import{findGitRoot}from"./chunk-744VRMDB.js";import{CursorNotAtLineBoundaryError,LargeNonUtf8TextError,TextScanBudgetExceededError,decodeBufferWithEncodingInfoAsync,isUtf8CompatibleEncoding,isWithinRoot}from"./chunk-TQGZS3WN.js";import{addDaemonRequestAttribute}from"./chunk-ZBWKMYJX.js";import{LOG_LINE_UNSAFE_RE,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*as path5 from"node:path";init_esbuild_shims();init_esbuild_shims();import{promises as fsp}from"node:fs";import*as path from"node:path";init_esbuild_shims();var DEFAULT_STATUS_BY_KIND={path_outside_workspace:400,symlink_escape:400,path_not_found:404,binary_file:422,file_too_large:413,hash_mismatch:409,file_already_exists:409,text_not_found:422,ambiguous_text_match:422,untrusted_workspace:403,permission_denied:403,io_error:503,internal_error:500,parse_error:400};var FsError=class extends Error{static{__name(this,"FsError")}kind;status;hint;constructor(kind,message,options){super(message,options?.cause===void 0?void 0:{cause:options.cause});this.name="FsError";this.kind=kind;this.status=options?.status??DEFAULT_STATUS_BY_KIND[kind];this.hint=options?.hint}};function isFsError(err){return err instanceof FsError}__name(isFsError,"isFsError");function wrapAsFsError(err,fallbackKind="internal_error"){if(err instanceof FsError)return err;const errno=err?.code;const message=err instanceof Error?err.message:"unknown filesystem error";switch(errno){case"ENOENT":return new FsError("path_not_found",message,{cause:err});case"EACCES":case"EPERM":return new FsError("permission_denied",message,{cause:err});case"ELOOP":return new FsError("symlink_escape",message,{cause:err,hint:"symlink chain forms a cycle or exceeds SYMLOOP_MAX"});case"EISDIR":return new FsError("parse_error",message,{cause:err,hint:"EISDIR \u2014 path is a directory but a regular file was expected"});case"ENOTDIR":return new FsError("parse_error",message,{cause:err,hint:"ENOTDIR \u2014 a path component is a regular file but a directory was expected"});case"ENOSPC":return new FsError("io_error",message,{cause:err,hint:"filesystem is full (df -h reporting 100%)"});case"EIO":return new FsError("io_error",message,{cause:err,hint:"underlying I/O error (failing disk or kernel-level fault)"});case"EBUSY":case"ETXTBSY":return new FsError("io_error",message,{cause:err,hint:"file is busy; another process holds an exclusive handle"});case"ENAMETOOLONG":return new FsError("io_error",message,{cause:err,hint:"path exceeds the OS PATH_MAX"});case"EMFILE":case"ENFILE":return new FsError("io_error",message,{cause:err,hint:"too many open files; daemon is at file-descriptor limit"});default:return new FsError(fallbackKind,message,{cause:err})}}__name(wrapAsFsError,"wrapAsFsError");var ENOENT_TOLERATING_INTENTS=new Set(["write","stat"]);function hasSuspiciousPathPattern(p){if(process.platform==="win32"){const colonIndex=p.indexOf(":",2);if(colonIndex!==-1)return true}if(process.platform==="win32"&&/~\d+/.test(p))return true;if(p.startsWith("\\\\?\\")||p.startsWith("\\\\.\\")||p.startsWith("//?/")||p.startsWith("//./")){return true}if(p.startsWith("\\\\")&&p.length>2&&p[2]!=="\\"||p.startsWith("//")&&p.length>2&&p[2]!=="/"){return true}if(/(^|\/|\\)\.{3,}(\/|\\|$)/.test(p))return true;for(const seg of p.split(/[\\/]/)){if(seg===""||seg==="."||seg==="..")continue;if(/[.\s]+$/.test(seg))return true;if(/(^|\.)(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i.test(seg)){return true}}return false}__name(hasSuspiciousPathPattern,"hasSuspiciousPathPattern");var MAX_ANCESTOR_HOPS=40;var CANONICAL_BOUND_CACHE=new Map;function canonicalizeBoundWorkspaceCached(boundWorkspace){const cached=CANONICAL_BOUND_CACHE.get(boundWorkspace);if(cached!==void 0)return cached;const canonical=canonicalizeWorkspace(boundWorkspace);CANONICAL_BOUND_CACHE.set(boundWorkspace,canonical);return canonical}__name(canonicalizeBoundWorkspaceCached,"canonicalizeBoundWorkspaceCached");function canonicalizeBoundWorkspacesCached(boundWorkspaces){const inputs=typeof boundWorkspaces==="string"?[boundWorkspaces]:boundWorkspaces;if(inputs.length===0){throw new FsError("parse_error","boundWorkspaces must include at least one workspace root")}const out=[];const seen=new Set;for(const workspace of inputs){const canonical=canonicalizeBoundWorkspaceCached(workspace);if(seen.has(canonical))continue;seen.add(canonical);out.push(canonical)}return out}__name(canonicalizeBoundWorkspacesCached,"canonicalizeBoundWorkspacesCached");function findContainingWorkspace(absolute,boundWorkspaces){let match;for(const workspace of boundWorkspaces){if(isWithinRoot(absolute,workspace)&&(match===void 0||workspace.length>match.length)){match=workspace}}return match}__name(findContainingWorkspace,"findContainingWorkspace");async function findExistingAncestor(absolute){let current=absolute;const tailParts=[];for(let i=0;i<MAX_ANCESTOR_HOPS;i++){let stat2=null;try{stat2=await fsp.stat(current)}catch(err){const code=err?.code;if(code==="ENOENT"||code==="ENOTDIR"){}else{throw err}}if(stat2){if(tailParts.length>0&&!stat2.isDirectory()){throw new FsError("parse_error",`path component is not a directory: ${absolute}`,{hint:"a non-directory file occupies a path segment"})}return{ancestor:current,tail:tailParts.join(path.sep)}}const parent=path.dirname(current);if(parent===current){throw new FsError("path_not_found",`no existing ancestor for ${absolute}`)}tailParts.unshift(path.basename(current));current=parent}throw new FsError("path_not_found",`path traversal exceeded ${MAX_ANCESTOR_HOPS} hops while finding ancestor`,{hint:"path is too deeply nested or filesystem is responding unexpectedly"})}__name(findExistingAncestor,"findExistingAncestor");async function resolveWithinWorkspace(input,boundWorkspaces,intent){if(typeof input!=="string"||input.length===0){throw new FsError("parse_error","path must be a non-empty string")}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace",`path contains suspicious pattern: ${input}`,{hint:"paths with NTFS ADS, 8.3 short names, UNC prefixes, or trailing dots are rejected outright"})}const boundCanonicals=canonicalizeBoundWorkspacesCached(boundWorkspaces);const primary=boundCanonicals[0];if(primary===void 0){throw new FsError("parse_error","boundWorkspaces must include at least one workspace root")}const absolute=path.resolve(primary,input);let boundCanonical=findContainingWorkspace(absolute,boundCanonicals);let preResolvedCanonical;if(boundCanonical===void 0&&path.isAbsolute(input)){try{preResolvedCanonical=await fsp.realpath(absolute);boundCanonical=findContainingWorkspace(preResolvedCanonical,boundCanonicals)}catch(err){const code=err?.code;if(code==="ENOENT"||code==="ENOTDIR"){try{const{ancestor,tail}=await findExistingAncestor(absolute);const ancestorReal=await fsp.realpath(ancestor);const canonicalCandidate=tail?path.join(ancestorReal,tail):ancestorReal;boundCanonical=findContainingWorkspace(canonicalCandidate,boundCanonicals);if(boundCanonical!==void 0){const finalPathIsSymlink=await fsp.lstat(absolute).then(stat2=>stat2.isSymbolicLink()).catch(lstatErr=>{if(lstatErr.code==="ENOENT"||lstatErr.code==="ENOTDIR"){return false}throw lstatErr});if(!finalPathIsSymlink&&ENOENT_TOLERATING_INTENTS.has(intent)){preResolvedCanonical=canonicalCandidate}}}catch(innerErr){const innerCode=innerErr?.code;if(innerCode!=="ENOENT"&&innerCode!=="ENOTDIR"){throw innerErr}}}else{throw err}}}if(boundCanonical===void 0){throw new FsError("path_outside_workspace",`path escapes workspace: ${input}`)}let canonical;try{canonical=preResolvedCanonical??await fsp.realpath(absolute)}catch(err){const code=err?.code;if(code==="ENOENT"&&ENOENT_TOLERATING_INTENTS.has(intent)){let symlinkResolvedCanonical=null;try{let cursor=absolute;const visitedInodes=new Set;let firstHopTarget=null;let resolvedFully=false;for(let hop=0;hop<MAX_ANCESTOR_HOPS;hop++){let linkStat;try{linkStat=await fsp.lstat(cursor)}catch(lstatErr){const lcode=lstatErr?.code;if(lcode==="ENOENT"||lcode==="ENOTDIR"){resolvedFully=true;break}throw lstatErr}if(!linkStat.isSymbolicLink()){resolvedFully=true;break}const ino=typeof linkStat.ino==="bigint"?linkStat.ino:BigInt(linkStat.ino);if(ino!==0n&&visitedInodes.has(ino)){throw new FsError("symlink_escape",`symlink cycle detected at ${cursor}`,{hint:"symlink loops back onto a previously visited inode"})}if(ino!==0n)visitedInodes.add(ino);const target=await fsp.readlink(cursor);const absTarget=path.isAbsolute(target)?target:path.resolve(path.dirname(cursor),target);if(firstHopTarget===null)firstHopTarget=target;cursor=absTarget}if(!resolvedFully){throw new FsError("symlink_escape",`symlink chain exceeded ${MAX_ANCESTOR_HOPS} hops for ${input}`,{hint:"symlink chain is too long or contains a cycle"})}if(firstHopTarget!==null){const{ancestor:targetAncestor,tail:targetTail}=await findExistingAncestor(cursor);const targetAncestorReal=await fsp.realpath(targetAncestor);const canonicalTarget=targetTail?path.join(targetAncestorReal,targetTail):targetAncestorReal;if(!boundCanonicals.some(root=>isWithinRoot(canonicalTarget,root))){throw new FsError("symlink_escape",`dangling symlink target escapes workspace: ${input}`,{hint:"symlink chain leaves the workspace; enable QWEN_AUDIT_RAW_PATHS for the resolved target"})}symlinkResolvedCanonical=canonicalTarget}}catch(err2){if(err2 instanceof FsError)throw err2;const code2=err2?.code;if(code2!=="ENOENT")throw err2}if(symlinkResolvedCanonical!==null){canonical=symlinkResolvedCanonical}else{const{ancestor,tail}=await findExistingAncestor(absolute);const ancestorReal=await fsp.realpath(ancestor);canonical=tail?path.join(ancestorReal,tail):ancestorReal}}else if(code==="ENOENT"){throw new FsError("path_not_found",`path does not exist: ${input}`,{cause:err})}else if(code==="ELOOP"){throw new FsError("symlink_escape",`symlink loop or chain too long for ${input}`,{cause:err,hint:"a symlink in the path forms a cycle or exceeds SYMLOOP_MAX"})}else if(code==="EACCES"){throw new FsError("permission_denied",`permission denied resolving ${input}`,{cause:err})}else{throw err}}if(!boundCanonicals.some(root=>isWithinRoot(canonical,root))){const kind=canonical!==absolute?"symlink_escape":"path_outside_workspace";throw new FsError(kind,kind==="symlink_escape"?`symlink resolves outside workspace: ${input}`:`path escapes workspace: ${input}`)}return canonical}__name(resolveWithinWorkspace,"resolveWithinWorkspace");init_esbuild_shims();import*as path2 from"node:path";var MAX_READ_BYTES=256*1024;var MAX_TEXT_SCAN_BYTES=8*1024*1024;var MAX_WRITE_BYTES=5*1024*1024;var MAX_UPLOAD_BYTES=50*1024*1024;var BINARY_PROBE_BYTES=4096;function shouldIgnore(absolute,boundWorkspace,ignore,kind="file"){const rel=path2.relative(boundWorkspace,absolute);if(rel===""||rel.startsWith(".."))return{ignored:false};const fileFilter=ignore.getFileFilter();const dirFilter=ignore.getDirectoryFilter();if(kind==="directory"){const withSlash=rel.endsWith("/")?rel:`${rel}/`;if(dirFilter(withSlash))return{ignored:true,category:"directory"};if(fileFilter(rel))return{ignored:true,category:"file"};return{ignored:false}}if(fileFilter(rel))return{ignored:true,category:"file"};if(dirFilter(rel))return{ignored:true,category:"directory"};return{ignored:false}}__name(shouldIgnore,"shouldIgnore");function assertTrustedForIntent(trusted,intent){if(trusted)return;switch(intent){case"read":case"list":case"glob":case"stat":return;case"write":case"edit":case"delete":throw new FsError("untrusted_workspace",`workspace is not trusted; ${intent} operations are forbidden`,{hint:"mark the folder as trusted in the daemon configuration to allow writes"});default:{const _exhaustive=intent;throw new FsError("untrusted_workspace",`workspace is not trusted; intent "${String(_exhaustive)}" is not classified`,{hint:"unknown intent reached the trust gate; classify it in policy.ts"})}}}__name(assertTrustedForIntent,"assertTrustedForIntent");function enforceReadSize(fileBytes,maxBytes=MAX_READ_BYTES){if(fileBytes<=maxBytes){return{bytesToRead:fileBytes,truncated:false}}return{bytesToRead:maxBytes,truncated:true}}__name(enforceReadSize,"enforceReadSize");function enforceWriteSize(bytes,maxBytes=MAX_WRITE_BYTES){if(bytes>maxBytes){throw new FsError("file_too_large",`payload of ${bytes} bytes exceeds write limit of ${maxBytes} bytes`,{hint:"split the write into smaller chunks or raise the daemon limit"})}}__name(enforceWriteSize,"enforceWriteSize");init_esbuild_shims();import{createHash}from"node:crypto";import*as path3 from"node:path";var FS_ACCESS_EVENT_TYPE="fs.access";var FS_DENIED_EVENT_TYPE="fs.denied";function hashPath(absolute){return createHash("sha256").update(absolute).digest("hex").slice(0,16)}__name(hashPath,"hashPath");var CROSS_DRIVE_RELPATH="<cross-drive>";function relForAudit(raw,boundWorkspace){const rel=path3.isAbsolute(raw)?path3.relative(boundWorkspace,raw):raw;return path3.isAbsolute(rel)?CROSS_DRIVE_RELPATH:rel}__name(relForAudit,"relForAudit");function rawPathsEnabled(){return process.env["QWEN_AUDIT_RAW_PATHS"]==="1"}__name(rawPathsEnabled,"rawPathsEnabled");function createAuditPublisher(deps){const includeRawPaths=deps.includeRawPaths??rawPathsEnabled();const{emit,boundWorkspace}=deps;return{recordAccess(ctx,record){const absolute=String(record.absolute);const payload={kind:FS_ACCESS_EVENT_TYPE,intent:record.intent,route:ctx.route,pathHash:hashPath(absolute),durationMs:record.durationMs};if(ctx.sessionId)payload.sessionId=ctx.sessionId;if(record.sizeBytes!==void 0)payload.sizeBytes=record.sizeBytes;if(record.truncated)payload.truncated=true;if(record.matchedIgnore)payload.matchedIgnore=record.matchedIgnore;if(record.operation!==void 0)payload.operation=record.operation;if(record.pattern!==void 0&&includeRawPaths){payload.pattern=record.pattern}if(includeRawPaths){payload.relPath=relForAudit(absolute,boundWorkspace)}emit({v:EVENT_SCHEMA_VERSION,type:FS_ACCESS_EVENT_TYPE,data:payload,originatorClientId:ctx.originatorClientId})},recordDenied(ctx,record){const probe=path3.isAbsolute(record.input)?record.input:path3.resolve(boundWorkspace,record.input);const payload={kind:FS_DENIED_EVENT_TYPE,intent:record.intent,route:ctx.route,pathHash:hashPath(probe),errorKind:record.errorKind};if(ctx.sessionId)payload.sessionId=ctx.sessionId;if(record.hint)payload.hint=record.hint;if(record.message&&includeRawPaths){payload.message=record.message}if(record.pattern!==void 0&&includeRawPaths){payload.pattern=record.pattern}if(includeRawPaths){payload.relPath=relForAudit(record.input,boundWorkspace)}emit({v:EVENT_SCHEMA_VERSION,type:FS_DENIED_EVENT_TYPE,data:payload,originatorClientId:ctx.originatorClientId})}}}__name(createAuditPublisher,"createAuditPublisher");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import{constants as fsConstants,promises as fsp2}from"node:fs";import*as path4 from"node:path";init_esbuild_shims();var CURSOR_VERSION=1;var MAX_TEXT_CURSOR_CHARS=1024;function encodeTextCursor(state){return Buffer.from(JSON.stringify({v:CURSOR_VERSION,...state}),"utf8").toString("base64url")}__name(encodeTextCursor,"encodeTextCursor");function decodeTextCursor(cursor){if(cursor.length===0||cursor.length>MAX_TEXT_CURSOR_CHARS){throw new FsError("parse_error",`cursor must be a non-empty string of at most ${MAX_TEXT_CURSOR_CHARS} characters`,{hint:"pass a cursor returned by a previous read"})}let parsed;try{parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"))}catch{throw new FsError("parse_error","cursor is not a valid read cursor",{hint:"pass a cursor returned by a previous read"})}if(typeof parsed!=="object"||parsed===null){throw new FsError("parse_error","cursor is not a valid read cursor",{hint:"pass a cursor returned by a previous read"})}const raw=parsed;const off=raw["off"];const size=raw["size"];const dev=raw["dev"];const ino=raw["ino"];if(raw["v"]!==CURSOR_VERSION||!Number.isSafeInteger(off)||off<0||!Number.isSafeInteger(size)||size<0||typeof dev!=="string"||typeof ino!=="string"){throw new FsError("parse_error","cursor is not a valid read cursor",{hint:"pass a cursor returned by a previous read"})}return{off,size,dev,ino}}__name(decodeTextCursor,"decodeTextCursor");function assertCursorMatchesFile(cursor,stats,path8){if(String(stats.dev)!==cursor.dev||String(stats.ino)!==cursor.ino||stats.size<cursor.size){throw new FsError("hash_mismatch",`cursor no longer matches the file it was issued for: ${path8}`,{hint:"re-read the file from the beginning to get a fresh cursor"})}}__name(assertCursorMatchesFile,"assertCursorMatchesFile");var OWNER_ONLY_NEW_FILE_MODE=384;function resolveNewFileModeBits(policy,umask){return policy==="system"?438&~(umask??process.umask()):OWNER_ONLY_NEW_FILE_MODE}__name(resolveNewFileModeBits,"resolveNewFileModeBits");function createWorkspaceFileSystemFactory(deps){const boundWorkspaces=canonicalizeWorkspaces(deps.boundWorkspaces);if(boundWorkspaces.length===0){throw new Error("WorkspaceFileSystem requires at least one workspace root")}assertNoNestedWorkspaces(boundWorkspaces);const primaryWorkspace=boundWorkspaces[0];const workspaces=boundWorkspaces.map(workspace=>{const ignore=deps.ignore??loadIgnoreRules({projectRoot:workspace,useGitignore:true,useQwenignore:true,...deps.customIgnoreFiles!==void 0?{customIgnoreFiles:deps.customIgnoreFiles}:{},ignoreDirs:[]});Object.freeze(ignore);return{path:workspace,ignore}});const audit=createAuditPublisher({emit:deps.emit,boundWorkspace:primaryWorkspace,includeRawPaths:deps.includeRawPaths});const lowFs=new StandardFileSystemService;const pathLocks=deps.pathLocks??new PathMutexRegistry;const newFileMode=deps.newFileMode??"owner";const forRequest=__name(ctx=>new WorkspaceFileSystemImpl({primaryWorkspace,workspaces,trusted:deps.trusted,audit,ctx,lowFs,pathLocks,generationGuard:deps.generationGuard,newFileMode}),"forRequest");return{assertCanWrite(){deps.generationGuard?.assertOpen();assertTrustedForIntent(deps.trusted,"write")},forRequest,async writeSameHostToolText(ctx,request){try{deps.generationGuard?.assertOpen()}catch(err){throw recordSameHostToolWriteDenied(audit,ctx,request.path,err)}let resolved;try{resolved=await resolveWithinWorkspace(request.path,workspaces.map(workspace=>workspace.path),"write");deps.generationGuard?.assertOpen()}catch(err){if(!(err instanceof FsError&&err.kind==="path_outside_workspace")){throw recordSameHostToolWriteDenied(audit,ctx,request.path,err)}try{await writeSameHostToolTextOutsideWorkspace({request,trusted:deps.trusted,audit,ctx,pathLocks,generationGuard:deps.generationGuard,newFileMode});return}catch(outsideErr){throw recordSameHostToolWriteDenied(audit,ctx,request.path,outsideErr)}}try{await forRequest(ctx).writeTextOverwrite(resolved,request.content)}catch(err){if(isWorkspaceGenerationClosedError(err)){recordSameHostToolWriteDenied(audit,ctx,request.path,err)}throw err}}}}__name(createWorkspaceFileSystemFactory,"createWorkspaceFileSystemFactory");async function writeSameHostToolTextOutsideWorkspace(deps){const start=performance.now();deps.generationGuard?.assertOpen();assertTrustedForIntent(deps.trusted,"write");enforceWriteSize(Buffer.byteLength(deps.request.content,"utf-8"));const target=await resolveSameHostToolWriteTarget(deps.request.path);await deps.pathLocks.runExclusive(target,async()=>{deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(void 0,deps.request.meta??{});const content=meta.bom&&deps.request.content.charCodeAt(0)===65279?deps.request.content.slice(1):deps.request.content;const result=await atomicWriteTextResolvedFile({target,content,mode:"overwrite",meta,newFileModeBits:resolveNewFileModeBits(deps.newFileMode),assertGenerationOpen:__name(()=>deps.generationGuard?.assertOpen(),"assertGenerationOpen")});deps.audit.recordAccess(deps.ctx,{intent:"write",absolute:target,durationMs:performance.now()-start,sizeBytes:result.sizeBytes})})}__name(writeSameHostToolTextOutsideWorkspace,"writeSameHostToolTextOutsideWorkspace");async function resolveSameHostToolWriteTarget(input){if(!path4.isAbsolute(input)){throw new FsError("path_outside_workspace",`same-host external tool write requires an absolute path: ${input}`)}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace",`path contains suspicious pattern: ${input}`)}let leaf;try{leaf=await fsp2.lstat(input,{bigint:true})}catch(err){if(err?.code!=="ENOENT"){throw err}const parent=await fsp2.realpath(path4.dirname(input));const parentStat=await fsp2.lstat(parent,{bigint:true});if(!parentStat.isDirectory()){throw new FsError("parse_error",`parent path is not a directory: ${parent}`)}return path4.join(parent,path4.basename(input))}if(leaf.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be overwritten: ${input}`,{hint:"resolve the target explicitly before writing"})}if(!leaf.isFile()){throw new FsError("parse_error",`path is not a regular file: ${input}`)}const canonical=await fsp2.realpath(input);const canonicalStat=await fsp2.lstat(canonical,{bigint:true});if(!canonicalStat.isFile()){throw new FsError("parse_error",`canonical path is not a regular file: ${canonical}`)}assertSameFile(leaf,canonicalStat,input,"write");return canonical}__name(resolveSameHostToolWriteTarget,"resolveSameHostToolWriteTarget");function isWorkspaceGenerationClosedError(error){return error instanceof Error&&"code"in error&&error.code==="workspace_generation_closed"}__name(isWorkspaceGenerationClosedError,"isWorkspaceGenerationClosedError");function recordSameHostToolWriteDenied(audit,ctx,input,error){const fsError=wrapAsFsError(error);audit.recordDenied(ctx,{intent:"write",input,errorKind:fsError.kind,hint:fsError.hint,message:fsError.message});return isWorkspaceGenerationClosedError(error)&&error instanceof Error?error:fsError}__name(recordSameHostToolWriteDenied,"recordSameHostToolWriteDenied");function assertNoNestedWorkspaces(workspaces){for(let i=0;i<workspaces.length;i++){const a=workspaces[i];if(a===void 0)continue;for(let j=i+1;j<workspaces.length;j++){const b=workspaces[j];if(b===void 0)continue;if(isWithinRoot(a,b)||isWithinRoot(b,a)){throw new Error(`Nested workspace roots are not supported: ${JSON.stringify(a)} and ${JSON.stringify(b)}`)}}}}__name(assertNoNestedWorkspaces,"assertNoNestedWorkspaces");var WorkspaceFileSystemImpl=class{constructor(deps){this.deps=deps}static{__name(this,"WorkspaceFileSystemImpl")}workspaceForPath(p){let match;for(const workspace of this.deps.workspaces){if(isWithinRoot(p,workspace.path)&&(match===void 0||workspace.path.length>match.path.length)){match=workspace}}return match}ignoreVerdict(p,kind="file"){const workspace=this.workspaceForPath(p);if(!workspace)return{ignored:false};return shouldIgnore(p,workspace.path,workspace.ignore,kind)}async resolve(input,intent){try{this.deps.generationGuard?.assertOpen();const resolved=await resolveWithinWorkspace(input,this.deps.workspaces.map(workspace=>workspace.path),intent);this.deps.generationGuard?.assertOpen();return resolved}catch(err){throw this.recordAndWrap(err,intent,input)}}async stat(p){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"stat");const st=await fsp2.lstat(p);this.deps.generationGuard?.assertOpen();const out={kind:kindFromStatLike(st),sizeBytes:st.size,modifiedMs:st.mtimeMs};this.deps.audit.recordAccess(this.deps.ctx,{intent:"stat",absolute:p,durationMs:performance.now()-start,sizeBytes:st.size});return out}catch(err){throw this.recordAndWrap(err,"stat",p)}}async readText(p,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"read");if(opts.line!==void 0&&(!Number.isSafeInteger(opts.line)||opts.line<1)){throw new FsError("parse_error",`line must be a positive integer, got ${opts.line}`)}if(opts.limit!==void 0&&(!Number.isSafeInteger(opts.limit)||opts.limit<1)){throw new FsError("parse_error",`limit must be a positive integer, got ${opts.limit}`)}if(opts.cursor!==void 0&&opts.line!==void 0){throw new FsError("parse_error","cursor and line are mutually exclusive; a cursor already encodes where to resume")}if(opts.maxBytes!==void 0&&(!Number.isSafeInteger(opts.maxBytes)||opts.maxBytes<1||opts.maxBytes>MAX_READ_BYTES)){throw new FsError("parse_error",`maxBytes must be a positive integer in [1, ${MAX_READ_BYTES}], got ${opts.maxBytes}`)}const snapshot=await readTextFromResolvedFile(p,opts,this.deps.lowFs);this.deps.generationGuard?.assertOpen();const ignoreVerdict=this.ignoreVerdict(p,"file");const meta=snapshot.meta;if(ignoreVerdict.ignored)meta.matchedIgnore=ignoreVerdict.category;this.deps.audit.recordAccess(this.deps.ctx,{intent:"read",absolute:p,durationMs:performance.now()-start,sizeBytes:meta.sizeBytes,truncated:meta.truncated,matchedIgnore:meta.matchedIgnore});return{content:snapshot.content,meta}}catch(err){throw this.recordAndWrap(err,"read",p)}}async readBytes(p,opts={}){const out=await this.readBytesWindow(p,opts);return out.buffer}async readBytesWindow(p,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"read");const offset=opts.offset??0;const maxBytes=opts.maxBytes??MAX_READ_BYTES;if(!Number.isSafeInteger(offset)||offset<0){throw new FsError("parse_error",`offset must be a non-negative integer, got ${offset}`)}if(!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>MAX_READ_BYTES){throw new FsError("parse_error",`maxBytes must be a positive integer in [1, ${MAX_READ_BYTES}], got ${maxBytes}`)}const pre=await fsp2.lstat(p);if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${p}`)}const fh=await fsp2.open(p,"r");let st;let buf;try{st=await fh.stat();assertSameFile(pre,st,p,"read");const available=Math.max(0,st.size-offset);const toRead=Math.min(maxBytes,available);buf=Buffer.allocUnsafe(toRead);if(toRead>0){const read=await fh.read(buf,0,toRead,offset);buf=read.bytesRead===toRead?buf:buf.subarray(0,read.bytesRead)}const afterRead=await fh.stat();assertSameFile(st,afterRead,p,"read");if(afterRead.size!==st.size||afterRead.mtimeMs!==st.mtimeMs){throw new FsError("hash_mismatch",`file changed during read: ${p}`,{hint:"retry after re-reading the latest file hash"})}}finally{await fh.close()}await assertInodeStableAfterRead(p,st.ino);this.deps.generationGuard?.assertOpen();const fullWindow=offset===0&&buf.length===st.size;const out={buffer:buf,sizeBytes:st.size,returnedBytes:buf.length,offset,truncated:!fullWindow,...fullWindow?{hash:hashBuffer(buf)}:{}};this.deps.audit.recordAccess(this.deps.ctx,{intent:"read",absolute:p,durationMs:performance.now()-start,sizeBytes:buf.length,truncated:out.truncated});return out}catch(err){throw this.recordAndWrap(err,"read",p)}}async list(p,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"list");if(opts.maxEntries!==void 0&&(!Number.isSafeInteger(opts.maxEntries)||opts.maxEntries<1)){throw new FsError("parse_error",`maxEntries must be a positive integer, got ${opts.maxEntries}`)}const entries=[];const dir=await fsp2.opendir(p);for await(const d of dir){this.deps.generationGuard?.assertOpen();const childAbs=path4.join(p,d.name);const kind=kindFromStatLike(d);const verdict=this.ignoreVerdict(childAbs,kind==="directory"?"directory":"file");if(verdict.ignored&&!opts.includeIgnored)continue;entries.push({name:d.name,kind,ignored:verdict.ignored});if(opts.maxEntries!==void 0&&entries.length>=opts.maxEntries){break}}this.deps.generationGuard?.assertOpen();this.deps.audit.recordAccess(this.deps.ctx,{intent:"list",absolute:p,durationMs:performance.now()-start,sizeBytes:entries.length,truncated:opts.maxEntries!==void 0&&entries.length>=opts.maxEntries});return entries}catch(err){throw this.recordAndWrap(err,"list",p)}}async glob(pattern,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"glob");if(pattern.split(/[\\/]/).some(seg=>seg==="..")){throw new FsError("parse_error",`glob pattern may not contain '..' segments: ${pattern}`)}if(path4.isAbsolute(pattern)||/^[A-Za-z]:[\\/]/.test(pattern)||pattern.startsWith("\\\\")||pattern.startsWith("//")){throw new FsError("parse_error",`glob pattern must be workspace-relative: ${pattern}`,{hint:'pass a relative pattern such as "src/**/*.ts"'})}const searchRoots=[];if(opts.cwd===void 0){for(const workspace of this.deps.workspaces){searchRoots.push({cwd:workspace.path,workspace})}}else{const cwd=opts.cwd;let cwdReal;const directWorkspace=this.workspaceForPath(cwd);if(directWorkspace&&cwd===directWorkspace.path){cwdReal=cwd}else{try{cwdReal=await fsp2.realpath(path4.resolve(cwd))}catch(err){const code=err?.code;if(code==="ENOENT"){throw new FsError("path_not_found",`glob cwd does not exist: ${cwd}`,{cause:err})}throw err}}const workspace=this.workspaceForPath(cwdReal);if(!workspace){throw new FsError("path_outside_workspace",`glob cwd is outside workspace: ${cwd}`,{hint:"opts.cwd must be a path obtained from fs.resolve()"})}searchRoots.push({cwd:cwdReal,workspace})}const out=[];const seenCanonicals=new Set;const max=opts.maxResults??Number.POSITIVE_INFINITY;let escapedCount=0;let permissionErrorCount=0;let transientErrorCount=0;const globErrors=[];let successfulGlobRoots=0;for(const searchRoot of searchRoots){this.deps.generationGuard?.assertOpen();if(out.length>=max)break;let matches;try{await fsp2.access(searchRoot.cwd,fsConstants.R_OK|fsConstants.X_OK);const rootStat=await fsp2.stat(searchRoot.cwd);if(!rootStat.isDirectory()){const err=new Error(`glob workspace root is not a directory: ${searchRoot.cwd}`);err.code="ENOTDIR";throw err}matches=await glob(pattern,{cwd:searchRoot.cwd,nodir:false,absolute:true,dot:true,ignore:["**/node_modules/**","**/.git/**"]})}catch(err){globErrors.push(err);this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:errorKindForRealpathFailure(err),hint:`glob failed for workspace root: ${errorCode(err)??"unknown error"}`,pattern});continue}successfulGlobRoots+=1;for(const hit of matches){this.deps.generationGuard?.assertOpen();if(out.length>=max)break;const absolute=path4.resolve(hit);let canonical;try{canonical=await fsp2.realpath(absolute)}catch(err){const code=errorCode(err);if(code==="ENOENT"||code==="ELOOP"){escapedCount+=1}else if(code==="EACCES"||code==="EPERM"){permissionErrorCount+=1}else{transientErrorCount+=1}continue}const inAnyWorkspace=this.deps.workspaces.some(workspace=>isWithinRoot(canonical,workspace.path));if(!inAnyWorkspace){escapedCount+=1;continue}if(seenCanonicals.has(canonical))continue;let dirent=null;try{dirent=await fsp2.lstat(canonical)}catch{dirent=null}const kind=dirent?.isDirectory()?"directory":"file";const verdict=this.ignoreVerdict(canonical,kind);if(verdict.ignored&&!opts.includeIgnored)continue;seenCanonicals.add(canonical);out.push(canonical)}}if(globErrors.length>0&&successfulGlobRoots===0){if(globErrors.length===1)throw globErrors[0];throw new AggregateError(globErrors,"glob failed for all workspace roots")}if(escapedCount>0){this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:"symlink_escape",hint:`glob filtered ${escapedCount} hit(s) that resolved outside workspace`,pattern})}if(permissionErrorCount>0){this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:"permission_denied",hint:`glob skipped ${permissionErrorCount} hit(s) due to EACCES/EPERM`,pattern})}if(transientErrorCount>0){this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:"io_error",hint:`glob skipped ${transientErrorCount} hit(s) due to transient I/O errors`,pattern})}this.deps.generationGuard?.assertOpen();this.deps.audit.recordAccess(this.deps.ctx,{intent:"glob",absolute:this.deps.primaryWorkspace,durationMs:performance.now()-start,sizeBytes:out.length,pattern});return out}catch(err){throw this.recordAndWrap(err,"glob",pattern)}}async writeTextAtomic(p,content,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");validateWriteTextAtomicOptions(opts);const decodedSizeBytes=Buffer.byteLength(content,"utf-8");enforceWriteSize(decodedSizeBytes);const out=await this.deps.pathLocks.runExclusive(p,async()=>{const existingMeta=opts.mode==="replace"?await readExistingTextMeta(p,opts.expectedHash):void 0;if(opts.mode==="create"){await assertCreateTargetAbsent(p)}this.deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(existingMeta,opts);const result=await atomicWriteTextResolvedFile({target:p,content,mode:opts.mode,expectedHash:opts.expectedHash,meta,newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");if(verdict.ignored)meta.matchedIgnore=verdict.category;meta.sizeBytes=result.sizeBytes;meta.hash=result.hash;this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:meta.matchedIgnore});return{created:opts.mode==="create",sizeBytes:result.sizeBytes,hash:result.hash,meta}});return out}catch(err){throw this.recordAndWrap(err,"write",p)}}async writeTextOverwrite(p,content,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const decodedSizeBytes=Buffer.byteLength(content,"utf-8");enforceWriteSize(decodedSizeBytes);const out=await this.deps.pathLocks.runExclusive(p,async()=>{let targetExisted=false;try{await fsp2.lstat(p);targetExisted=true}catch(err){if(err?.code!=="ENOENT"){throw err}}let existingMeta;try{existingMeta=await readExistingTextMeta(p)}catch(err){const code=err?.code;const kind=err?.kind;if(code!=="ENOENT"&&code!=="EACCES"&&code!=="EPERM"&&kind!=="file_too_large"&&kind!=="binary_file"){throw err}}this.deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(existingMeta,opts);const result=await atomicWriteTextResolvedFile({target:p,content,mode:"overwrite",meta,newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");if(verdict.ignored)meta.matchedIgnore=verdict.category;meta.sizeBytes=result.sizeBytes;meta.hash=result.hash;this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:meta.matchedIgnore});return{created:!targetExisted,sizeBytes:result.sizeBytes,hash:result.hash,meta}});return out}catch(err){throw this.recordAndWrap(err,"write",p)}}async writeText(p,content,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const sizeBytes=Buffer.byteLength(content,"utf-8");enforceWriteSize(sizeBytes);await assertNotSymlinkBeforeWrite(p);this.deps.generationGuard?.assertOpen();await this.deps.lowFs.writeTextFile({path:p,content,_meta:opts?buildWriteMeta(opts):void 0});const verdict=this.ignoreVerdict(p,"file");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes,matchedIgnore:verdict.ignored?verdict.category:void 0})}catch(err){throw this.recordAndWrap(err,"write",p)}}async editAtomic(p,oldText,newText,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"edit");if(!isContentHash(opts.expectedHash)){throw new FsError("parse_error","expectedHash must match sha256:<64 lowercase hex chars>")}if(typeof oldText!=="string"||oldText.length===0){throw new FsError("parse_error",`oldText must be a non-empty string for edit on ${p}`)}if(typeof newText!=="string"){throw new FsError("parse_error","newText must be a string")}const out=await this.deps.pathLocks.runExclusive(p,async()=>{const snapshot=await readTextSnapshotFromResolvedFile(p);if(snapshot.meta.hash!==opts.expectedHash){throw new FsError("hash_mismatch",`expected ${opts.expectedHash}, found ${snapshot.meta.hash}`,{hint:"re-read the file and retry with the latest hash"})}const current=snapshot.content;const occurrences=countOccurrences(current,oldText);if(occurrences===0){const snippet=oldText.length>80?oldText.slice(0,80)+"...":oldText;throw new FsError("text_not_found",`oldText not found in ${p}`,{hint:`searched for: ${JSON.stringify(snippet)}`})}if(occurrences>1){throw new FsError("ambiguous_text_match",`oldText appears ${occurrences} times in ${p}`,{hint:"pass a larger oldText span that occurs exactly once"})}const idx=current.indexOf(oldText);const next=current.slice(0,idx)+newText+current.slice(idx+oldText.length);enforceWriteSize(Buffer.byteLength(next,"utf-8"));this.deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(snapshot.meta,{});const result=await atomicWriteTextResolvedFile({target:p,content:next,mode:"replace",expectedHash:opts.expectedHash,meta,newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");if(verdict.ignored)meta.matchedIgnore=verdict.category;meta.sizeBytes=result.sizeBytes;meta.hash=result.hash;this.deps.audit.recordAccess(this.deps.ctx,{intent:"edit",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:meta.matchedIgnore});return{writtenBytes:result.sizeBytes,hash:result.hash,meta}});return out}catch(err){throw this.recordAndWrap(err,"edit",p)}}async edit(p,oldText,newText,opts){if(opts?.expectedHash!==void 0){return this.editAtomic(p,oldText,newText,{expectedHash:opts.expectedHash})}const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"edit");if(oldText.length===0){throw new FsError("parse_error",`oldText must be a non-empty string for edit on ${p}`,{hint:"empty oldText would match at position 0 and silently prepend newText"})}return await this.deps.pathLocks.runExclusive(p,async()=>{const snapshot=await readTextSnapshotFromResolvedFile(p);const current=snapshot.content;const idx=current.indexOf(oldText);if(idx===-1){const snippet=oldText.length>80?oldText.slice(0,80)+"\u2026":oldText;throw new FsError("parse_error",`oldText not found in ${p}`,{hint:`edit() expects oldText to appear verbatim; searched for: ${JSON.stringify(snippet)}`})}const next=current.slice(0,idx)+newText+current.slice(idx+oldText.length);const writtenBytes=Buffer.byteLength(next,"utf-8");enforceWriteSize(writtenBytes);this.deps.generationGuard?.assertOpen();const result=await atomicWriteTextResolvedFile({target:p,content:next,mode:"overwrite",meta:mergeWriteMeta(snapshot.meta,{}),newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");this.deps.audit.recordAccess(this.deps.ctx,{intent:"edit",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:verdict.ignored?verdict.category:void 0});return{writtenBytes:result.sizeBytes}})}catch(err){throw this.recordAndWrap(err,"edit",p)}}async writeBytesAtomic(p,data){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");enforceWriteSize(data.length,MAX_UPLOAD_BYTES);const out=await this.deps.pathLocks.runExclusive(p,async()=>{await assertCreateTargetAbsent(p);this.deps.generationGuard?.assertOpen();const result=await atomicPublishResolvedFile({target:p,buf:data,mode:"create",assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:verdict.ignored?verdict.category:void 0});return{sizeBytes:result.sizeBytes,hash:result.hash}});return out}catch(err){throw this.recordAndWrap(err,"write",p,{audit:!(isFsError(err)&&err.kind==="file_already_exists")})}}async deleteFile(input){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");const basename3=path4.basename(input);if(!input||input.includes("\0")||hasSuspiciousPathPattern(input)||input.endsWith("/")||input.endsWith(path4.sep)||basename3==="."||basename3===".."){throw new FsError("parse_error","Deletion requires a regular file path")}const parent=await resolveWithinWorkspace(path4.dirname(input),this.deps.workspaces.map(workspace=>workspace.path),"delete");const target=path4.join(parent,basename3);if(!this.workspaceForPath(target)||this.deps.workspaces.some(workspace=>workspace.path===target)){throw new FsError("path_outside_workspace","Cannot delete a workspace root")}return await this.deps.pathLocks.runExclusive(target,async()=>{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");if(await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","Deletion parent changed")}const stat2=await fsp2.lstat(target);if(!stat2.isFile()){throw new FsError(stat2.isSymbolicLink()?"symlink_escape":"parse_error","Only regular files can be deleted")}if(await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","Deletion parent changed")}this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");const verdict=this.ignoreVerdict(target,"file");await fsp2.unlink(target);this.deps.audit.recordAccess(this.deps.ctx,{intent:"delete",absolute:target,durationMs:performance.now()-start,sizeBytes:stat2.size,matchedIgnore:verdict.ignored?verdict.category:void 0});return target})}catch(err){throw this.recordAndWrap(err,"delete",input)}}async deleteDirectory(input){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");const basename3=path4.basename(input);if(!input||input.includes("\0")||input.endsWith("/")||input.endsWith(path4.sep)||basename3==="."||basename3===".."){throw new FsError("parse_error","Deletion requires a directory path")}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace","path contains a suspicious pattern")}const parent=await resolveWithinWorkspace(path4.dirname(input),this.deps.workspaces.map(workspace=>workspace.path),"delete");const target=path4.join(parent,basename3);if(!this.workspaceForPath(target)||this.deps.workspaces.some(workspace=>workspace.path===target)){throw new FsError("path_outside_workspace","Cannot delete a workspace root")}return await this.deps.pathLocks.runExclusive(target,async()=>{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");if(await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","Deletion parent changed")}const stat2=await fsp2.lstat(target);if(!stat2.isDirectory()){throw new FsError(stat2.isSymbolicLink()?"symlink_escape":"parse_error","Only directories can be deleted")}if(await fsp2.realpath(target)!==target){throw new FsError("symlink_escape","Deletion directory changed")}this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");try{await fsp2.rm(target,{recursive:true,force:false})}catch(error){if(error.code==="ENOTEMPTY"){throw new FsError("io_error","Directory contents changed during removal",{cause:error,hint:"Retry deleting the directory."})}throw error}const verdict=this.ignoreVerdict(target,"directory");this.deps.audit.recordAccess(this.deps.ctx,{intent:"delete",operation:"rm",absolute:target,durationMs:performance.now()-start,matchedIgnore:verdict.ignored?verdict.category:void 0});return target})}catch(error){throw this.recordAndWrap(error,"delete",input)}}async createDirectory(input){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const basename3=path4.basename(input);if(!input||input.includes("\0")||input.endsWith("/")||input.endsWith(path4.sep)||basename3==="."||basename3===".."){throw new FsError("parse_error","path must name a new directory")}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace","path contains a suspicious pattern")}const parent=await resolveWithinWorkspace(path4.dirname(input),this.deps.workspaces.map(workspace=>workspace.path),"list");const target=path4.join(parent,basename3);return await this.deps.pathLocks.runExclusive(target,async()=>{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");try{const existing=await fsp2.lstat(target);if(existing.isSymbolicLink()){throw new FsError("symlink_escape","directory path is a symlink")}throw new FsError("file_already_exists","path already exists")}catch(error){if(error.code!=="ENOENT")throw error}const parentStat=await fsp2.lstat(parent);if(!parentStat.isDirectory()||await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","directory parent changed")}this.deps.generationGuard?.assertOpen();try{await fsp2.mkdir(target,{mode:493})}catch(error){if(error.code==="EEXIST"){throw new FsError("file_already_exists","path already exists")}throw error}if(!(await fsp2.lstat(target)).isDirectory()){throw new FsError("symlink_escape","created directory changed")}const verdict=this.ignoreVerdict(target,"directory");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",operation:"mkdir",absolute:target,durationMs:performance.now()-start,sizeBytes:0,matchedIgnore:verdict.ignored?verdict.category:void 0});return target})}catch(error){throw this.recordAndWrap(error,"write",input)}}async mkdir(p,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const out=await this.deps.pathLocks.runExclusive(p,async()=>{await ensureResolvedDirectory(p,{recursive:opts?.recursive??false,assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});this.deps.generationGuard?.assertOpen();const verdict=this.ignoreVerdict(p,"directory");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:0,operation:"mkdir",matchedIgnore:verdict.ignored?verdict.category:void 0});return void 0});return out}catch(err){throw this.recordAndWrap(err,"write",p)}}recordAndWrap(err,intent,input,opts){if(err instanceof Error&&"code"in err&&err.code==="workspace_generation_closed"){return err}const fs3=wrapAsFsError(err);if(opts?.audit===false){return fs3}this.deps.audit.recordDenied(this.deps.ctx,{intent,input,errorKind:fs3.kind,hint:fs3.hint,message:fs3.message,pattern:intent==="glob"?input:void 0});return fs3}};var CONTENT_HASH_RE=/^sha256:[0-9a-f]{64}$/;function isContentHash(value){return typeof value==="string"&&CONTENT_HASH_RE.test(value)}__name(isContentHash,"isContentHash");function validateWriteTextAtomicOptions(opts){if(opts.mode!=="create"&&opts.mode!=="replace"){throw new FsError("parse_error",'mode must be either "create" or "replace" (use writeTextOverwrite() for unconditional overwrites)')}if(opts.expectedHash!==void 0&&!isContentHash(opts.expectedHash)){throw new FsError("parse_error","expectedHash must match sha256:<64 lowercase hex chars>")}if(opts.mode==="replace"&&opts.expectedHash===void 0){throw new FsError("parse_error",'expectedHash is required when mode is "replace"')}if(opts.lineEnding!==void 0&&opts.lineEnding!=="lf"&&opts.lineEnding!=="crlf"){throw new FsError("parse_error",'lineEnding must be "lf" or "crlf"')}}__name(validateWriteTextAtomicOptions,"validateWriteTextAtomicOptions");async function readTextFromResolvedFile(p,opts,lowFs){const pre=await fsp2.lstat(p);if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink: ${p}`,{hint:"re-resolve the target file instead of reading through a link"})}if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${p}`)}if(opts.cursor!==void 0){return readTextCursorWindowFromResolvedFile(p,pre,opts,lowFs)}const wantsWindow=opts.limit!==void 0||opts.maxBytes!==void 0||opts.line!==void 0;if(pre.size>MAX_READ_BYTES&&wantsWindow){return readLargeTextWindowFromResolvedFile(p,pre,opts,lowFs)}return readTextSnapshotFromResolvedFile(p,opts,pre)}__name(readTextFromResolvedFile,"readTextFromResolvedFile");async function readTextSnapshotFromResolvedFile(p,opts={},knownPre){const pre=knownPre??await fsp2.lstat(p);if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink: ${p}`,{hint:"re-resolve the target file instead of reading through a link"})}if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${p}`)}if(pre.size>MAX_READ_BYTES){throw new FsError("file_too_large",`file of ${pre.size} bytes exceeds read cap of ${MAX_READ_BYTES} bytes`,{hint:"use a finite line limit for large UTF-8 text, or readBytes for explicit byte-windowed access"})}const raw=await readStableRegularFileBuffer(p,pre);if(looksBinary(raw)){throw new FsError("binary_file",`binary file: ${p}`,{hint:"use readBytes for binary content"})}const decoded=await decodeBufferWithEncodingInfoAsync(raw);const startLineIndex=opts.line!==void 0?opts.line-1:0;const sliced=sliceDecodedText(decoded.content,startLineIndex,opts.limit??Number.POSITIVE_INFINITY);const maxOutputBytes=opts.maxBytes??MAX_READ_BYTES;const sizeOutcome=enforceReadSize(raw.length,maxOutputBytes);let content=sliced.content;let byteTruncated=false;const meta={encoding:decoded.encoding,bom:decoded.bom,lineEnding:detectLineEnding(decoded.content),sizeBytes:raw.length,originalLineCount:sliced.originalLineCount,hash:hashBuffer(raw)};const output=Buffer.from(content,"utf-8");if(output.length>maxOutputBytes){content=safeUtf8Truncate(output,maxOutputBytes).toString("utf-8");meta.truncated=true;byteTruncated=true}if(sizeOutcome.truncated){meta.truncated=true}if(opts.limit!==void 0&&Number.isFinite(opts.limit)&&sliced.originalLineCount>opts.limit+startLineIndex){meta.truncated=true}const pageableLineCount=sliced.originalLineCount-(decoded.content.endsWith("\n")?1:0);meta.hasMore=byteTruncated||sliced.endLine<pageableLineCount;const bomBytes=decoded.bom?3:0;const decodedBytesMatchSource=isUtf8CompatibleEncoding(decoded.encoding)&&Buffer.from(decoded.content,"utf-8").equals(raw.subarray(bomBytes));if(meta.hasMore&&!byteTruncated&&decodedBytesMatchSource){const startByte=bomBytes+sliced.startByteOffset;const contentBytes=Buffer.byteLength(content,"utf-8");const nextOffset=startByte+contentBytes+1;if(nextOffset<raw.length){meta.nextCursor=encodeTextCursor({off:nextOffset,size:raw.length,dev:String(pre.dev),ino:String(pre.ino)})}}return{content,meta}}__name(readTextSnapshotFromResolvedFile,"readTextSnapshotFromResolvedFile");function assertStreamWindowStable(before,after,p,reason){const beforeSize=toBigInt(before.size);const afterSize=toBigInt(after.size);if(afterSize<beforeSize||afterSize===beforeSize&&(after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs)){throw new FsError("hash_mismatch",`${reason}: ${p}`,{hint:"retry after re-reading the latest file"})}}__name(assertStreamWindowStable,"assertStreamWindowStable");async function readTextCursorWindowFromResolvedFile(p,pre,opts,lowFs){const cursor=decodeTextCursor(opts.cursor);const fh=await fsp2.open(p,"r");let opened;let afterRead;let window;let primaryError;let hasPrimaryError=false;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");assertStreamWindowStable(pre,opened,p,"file changed before read");assertCursorMatchesFile(cursor,opened,p);try{const probe=Buffer.alloc(Math.min(BINARY_PROBE_BYTES,opened.size));if(probe.length>0){const{bytesRead}=await fh.read(probe,0,probe.length,0);if(looksBinary(probe.subarray(0,bytesRead))){throw new FsError("binary_file",`binary file: ${p}`,{hint:"use readBytes for binary content"})}}window=await lowFs.readTextCursorFromHandle({fileHandle:fh,startOffset:cursor.off,fileSize:opened.size,maxOutputBytes:opts.maxBytes??MAX_READ_BYTES,maxSnapBytes:MAX_TEXT_SCAN_BYTES,...opts.limit!==void 0?{limit:opts.limit}:{}})}catch(err){hasPrimaryError=true;primaryError=err}afterRead=await fh.stat()}finally{await fh.close()}if(opened===void 0||afterRead===void 0){throw new FsError("internal_error",`failed to stat opened file: ${p}`)}const post=await fsp2.lstat(p);if(post.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink during read: ${p}`,{hint:"TOCTOU swap detected via post-read lstat"})}assertSameFile(opened,afterRead,p,"read");assertStreamWindowStable(opened,afterRead,p,"file changed during read");assertSameFile(opened,post,p,"read");assertStreamWindowStable(opened,post,p,"file changed during read");if(hasPrimaryError){if(primaryError instanceof LargeNonUtf8TextError){throw new FsError("binary_file",primaryError.message,{cause:primaryError,hint:"convert the file to UTF-8, or use readBytes for the raw bytes"})}if(primaryError instanceof CursorNotAtLineBoundaryError){throw new FsError("parse_error",primaryError.message,{cause:primaryError,hint:"pass a cursor returned by a previous read"})}throw primaryError}if(window===void 0){throw new FsError("internal_error",`cursor text read returned no result: ${p}`)}const meta={encoding:window.encoding,bom:window.bom,lineEnding:window.lineEnding,sizeBytes:opened.size,truncated:true,hasMore:window.nextOffset!==void 0||window.truncatedByBytes===true};if(window.nextOffset!==void 0){meta.nextCursor=encodeTextCursor({off:window.nextOffset,size:opened.size,dev:String(opened.dev),ino:String(opened.ino)})}return{content:window.content,meta}}__name(readTextCursorWindowFromResolvedFile,"readTextCursorWindowFromResolvedFile");async function readLargeTextWindowFromResolvedFile(p,pre,opts,lowFs){const fh=await fsp2.open(p,"r");let opened;let afterRead;let result;let primaryError;let hasPrimaryError=false;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");assertStreamWindowStable(pre,opened,p,"file changed before read");try{const probe=Buffer.alloc(Math.min(BINARY_PROBE_BYTES,opened.size));if(probe.length>0){const{bytesRead}=await fh.read(probe,0,probe.length,0);if(looksBinary(probe.subarray(0,bytesRead))){throw new FsError("binary_file",`binary file: ${p}`,{hint:"use readBytes for binary content"})}}result=await lowFs.readTextFileFromHandle({fileHandle:fh,fileSize:opened.size,limit:opts.limit??Number.POSITIVE_INFINITY,line:opts.line!==void 0?opts.line-1:0,maxOutputBytes:opts.maxBytes??MAX_READ_BYTES,maxScanBytes:MAX_TEXT_SCAN_BYTES})}catch(err){hasPrimaryError=true;primaryError=err}afterRead=await fh.stat()}finally{await fh.close()}if(opened===void 0||afterRead===void 0){throw new FsError("internal_error",`failed to stat opened file: ${p}`)}const post=await fsp2.lstat(p);if(post.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink during read: ${p}`,{hint:"TOCTOU swap detected via post-read lstat"})}assertSameFile(opened,afterRead,p,"read");assertStreamWindowStable(opened,afterRead,p,"file changed during read");assertSameFile(opened,post,p,"read");assertStreamWindowStable(opened,post,p,"file changed during read");if(hasPrimaryError){if(primaryError instanceof LargeNonUtf8TextError){throw new FsError("binary_file",primaryError.message,{cause:primaryError,hint:"convert the file to UTF-8, or use readBytes for the raw bytes"})}if(primaryError instanceof TextScanBudgetExceededError){throw new FsError("file_too_large",primaryError.message,{cause:primaryError,hint:`line offsets are resolved by scanning from byte 0 and stop after ${MAX_TEXT_SCAN_BYTES} bytes; page with the cursor from a shallower read to reach this offset in O(1), or use readBytes for raw bytes`})}throw primaryError}if(result===void 0){throw new FsError("internal_error",`large text range read returned no result: ${p}`)}const content=result.content;const readMeta=result._meta;const meta={encoding:readMeta?.encoding,bom:readMeta?.bom,lineEnding:readMeta?.lineEnding??detectLineEnding(content),sizeBytes:opened.size,truncated:true,hasMore:readMeta?.nextByteOffset!==void 0||readMeta?.truncatedByBytes===true};if(readMeta?.nextByteOffset!==void 0){meta.nextCursor=encodeTextCursor({off:readMeta.nextByteOffset,size:opened.size,dev:String(opened.dev),ino:String(opened.ino)})}if(readMeta?.originalLineCountExact===true&&readMeta?.originalLineCount!==void 0){meta.originalLineCount=readMeta.originalLineCount}return{content,meta}}__name(readLargeTextWindowFromResolvedFile,"readLargeTextWindowFromResolvedFile");async function readStableRegularFileBuffer(p,pre){const fh=await fsp2.open(p,"r");let opened;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");if(opened.size>MAX_READ_BYTES){throw new FsError("file_too_large",`file of ${opened.size} bytes exceeds read cap of ${MAX_READ_BYTES} bytes`,{hint:"use a finite line limit for large UTF-8 text, or readBytes for explicit byte-windowed access"})}const out=Buffer.alloc(opened.size);let offset=0;while(offset<opened.size){const read=await fh.read(out,offset,opened.size-offset,offset);if(read.bytesRead===0)break;offset+=read.bytesRead}const afterRead=await fh.stat();assertSameFile(opened,afterRead,p,"read");if(afterRead.size!==opened.size||afterRead.mtimeMs!==opened.mtimeMs){throw new FsError("hash_mismatch",`file changed during read: ${p}`,{hint:"retry after re-reading the latest file hash"})}const post=await fsp2.lstat(p);assertSameFile(pre,post,p,"read");if(post.size!==opened.size||post.mtimeMs!==opened.mtimeMs){throw new FsError("hash_mismatch",`file changed during read: ${p}`,{hint:"retry after re-reading the latest file hash"})}return offset===out.length?out:out.subarray(0,offset)}finally{await fh.close()}}__name(readStableRegularFileBuffer,"readStableRegularFileBuffer");function sliceDecodedText(content,startLine,limit){const lines=content.split("\n");const originalLineCount=lines.length;const endLine=Math.min(startLine+limit,originalLineCount);const actualStartLine=Math.min(startLine,originalLineCount);let startByteOffset=0;for(let i=0;i<actualStartLine;i++){startByteOffset+=Buffer.byteLength(lines[i],"utf-8")+1}return{content:lines.slice(actualStartLine,endLine).join("\n"),originalLineCount,startByteOffset,endLine}}__name(sliceDecodedText,"sliceDecodedText");function looksBinary(buf){if(buf.length===0)return false;const bomProbe=buf.subarray(0,Math.min(4,buf.length));const hasUnicodeBom=bomProbe.length>=4&&(bomProbe[0]===255&&bomProbe[1]===254&&bomProbe[2]===0&&bomProbe[3]===0||bomProbe[0]===0&&bomProbe[1]===0&&bomProbe[2]===254&&bomProbe[3]===255)||bomProbe.length>=3&&bomProbe[0]===239&&bomProbe[1]===187&&bomProbe[2]===191||bomProbe.length>=2&&(bomProbe[0]===255&&bomProbe[1]===254||bomProbe[0]===254&&bomProbe[1]===255);if(hasUnicodeBom)return false;const sampleLength=Math.min(4096,buf.length);let nonPrintableCount=0;for(let i=0;i<sampleLength;i++){if(buf[i]===0)return true;if(buf[i]<9||buf[i]>13&&buf[i]<32){nonPrintableCount++}}return nonPrintableCount/sampleLength>.3}__name(looksBinary,"looksBinary");async function readExistingTextMeta(p,expectedHash){const snapshot=await readTextSnapshotFromResolvedFile(p);if(expectedHash!==void 0&&snapshot.meta.hash!==expectedHash){throw new FsError("hash_mismatch",`expected ${expectedHash}, found ${snapshot.meta.hash}`,{hint:"re-read the file and retry with the latest hash"})}return snapshot.meta}__name(readExistingTextMeta,"readExistingTextMeta");function mergeWriteMeta(existing,opts){return{encoding:opts.encoding??existing?.encoding??"utf-8",bom:opts.bom??existing?.bom??false,lineEnding:opts.lineEnding??existing?.lineEnding??"lf"}}__name(mergeWriteMeta,"mergeWriteMeta");async function atomicWriteTextResolvedFile(input){const buf=await encodeTextFileContentAsync(input.target,input.content,buildWriteMeta(input.meta));enforceWriteSize(buf.length);return atomicPublishResolvedFile({target:input.target,buf,mode:input.mode,expectedHash:input.expectedHash,newFileModeBits:input.newFileModeBits,assertGenerationOpen:input.assertGenerationOpen})}__name(atomicWriteTextResolvedFile,"atomicWriteTextResolvedFile");async function ensureResolvedDirectory(target,opts){const assertRealDirectory=__name(async p=>{const st=await fsp2.lstat(p);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`directory path is a symlink: ${p}`,{hint:"re-resolve the target after detecting symlink swaps"})}if(!st.isDirectory()){throw new FsError("parse_error",`path exists and is not a directory: ${p}`)}},"assertRealDirectory");const assertParentNotSymlink=__name(async p=>{const parent=path4.dirname(p);const st=await fsp2.lstat(parent);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`directory parent is a symlink: ${parent}`,{hint:"re-resolve the target after detecting symlink swaps"})}},"assertParentNotSymlink");try{await assertRealDirectory(target);return}catch(err){if(isFsError(err))throw err;if(err.code!=="ENOENT")throw err}if(!opts.recursive){opts.assertGenerationOpen();await assertParentNotSymlink(target);try{await fsp2.mkdir(target,{mode:493})}catch(err){if(err.code!=="EEXIST")throw err}await assertRealDirectory(target);return}const missing=[];let current=target;while(true){try{await assertRealDirectory(current);break}catch(err){if(isFsError(err))throw err;if(err.code!=="ENOENT")throw err;missing.push(current);const parent=path4.dirname(current);if(parent===current)throw err;current=parent}}for(const entry of missing.reverse()){opts.assertGenerationOpen();await assertParentNotSymlink(entry);try{await fsp2.mkdir(entry,{mode:493})}catch(err){if(err.code!=="EEXIST")throw err}await assertRealDirectory(entry)}}__name(ensureResolvedDirectory,"ensureResolvedDirectory");async function atomicPublishResolvedFile(input){const target=input.target;const parent=path4.dirname(target);const parentStat=await fsp2.lstat(parent);if(parentStat.isSymbolicLink()){throw new FsError("symlink_escape",`parent path is a symlink: ${parent}`,{hint:"re-resolve the target after detecting parent-symlink swaps"})}if(!parentStat.isDirectory()){throw new FsError("parse_error",`parent path is not a directory: ${parent}`)}const tmpSuffix=`.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;const tmpNameMaxBytes=255;const tmpBaseMaxBytes=tmpNameMaxBytes-1-Buffer.byteLength(tmpSuffix,"utf-8");let tmpBase=path4.basename(target);if(Buffer.byteLength(tmpBase,"utf-8")>tmpBaseMaxBytes){tmpBase=safeUtf8Truncate(Buffer.from(tmpBase,"utf-8"),tmpBaseMaxBytes).toString("utf-8")}const tmpPath=path4.join(parent,`.${tmpBase}${tmpSuffix}`);let tempLive=false;let tempHandle;let tempStat;try{tempHandle=await reserveTempFile(tmpPath);tempLive=true;const written=await writeBufferToTemp({tmpPath,buf:input.buf,handle:tempHandle});tempStat=written.stat;const targetState=await assertAtomicTargetPrecondition({target,mode:input.mode,expectedHash:input.expectedHash});await chmodHandleBestEffort(tempHandle,targetState.mode??input.newFileModeBits??OWNER_ONLY_NEW_FILE_MODE);await assertTempPathMatchesStat(tmpPath,tempStat);await tempHandle.close();tempHandle=void 0;await assertTempPathMatchesStat(tmpPath,tempStat);input.assertGenerationOpen?.();if(input.mode==="create"){await publishCreateNoClobber(tmpPath,target)}else{await renameWithRetryLocal(tmpPath,target,3,50)}tempLive=false;await fsyncParentDirBestEffort(parent);return written}catch(err){await tempHandle?.close().catch(()=>void 0);if(tempLive){try{await fsp2.unlink(tmpPath)}catch{}}throw err}}__name(atomicPublishResolvedFile,"atomicPublishResolvedFile");async function reserveTempFile(tmpPath){return fsp2.open(tmpPath,"wx",384)}__name(reserveTempFile,"reserveTempFile");async function writeBufferToTemp(input){await input.handle.writeFile(input.buf);await syncHandleBestEffort(input.handle);const st=await fsp2.lstat(input.tmpPath);const opened=await input.handle.stat();assertSameFile(opened,st,input.tmpPath,"write");if(st.isSymbolicLink()){throw new FsError("symlink_escape",`temporary path became a symlink: ${input.tmpPath}`,{hint:"temp-file race detected before final rename"})}if(!st.isFile()){throw new FsError("parse_error",`temporary path is not a regular file: ${input.tmpPath}`)}return{sizeBytes:input.buf.length,hash:hashBuffer(input.buf),stat:st}}__name(writeBufferToTemp,"writeBufferToTemp");async function assertCreateTargetAbsent(target){try{const st=await fsp2.lstat(target);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be created over: ${target}`,{hint:"remove the symlink or resolve the target explicitly"})}throw new FsError("file_already_exists",`file already exists: ${target}`)}catch(err){const code=err?.code;if(code==="ENOENT")return;throw err}}__name(assertCreateTargetAbsent,"assertCreateTargetAbsent");async function assertAtomicTargetPrecondition(input){if(input.mode==="create"){await assertCreateTargetAbsent(input.target);return{}}if(input.mode==="overwrite"){let pre2;try{pre2=await fsp2.lstat(input.target)}catch(err){if(err?.code==="ENOENT"){return{}}throw err}if(pre2.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be overwritten atomically: ${input.target}`,{hint:"re-resolve the target file instead of writing through a link"})}if(!pre2.isFile()){throw new FsError("parse_error",`path is not a regular file: ${input.target}`)}return{mode:pre2.mode&4095}}if(!isContentHash(input.expectedHash)){throw new FsError("parse_error",'expectedHash is required when mode is "replace"')}const pre=await fsp2.lstat(input.target);if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be replaced atomically: ${input.target}`,{hint:"re-resolve the target file instead of writing through a link"})}if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${input.target}`)}const actual=await hashRegularFileAtPath(input.target,pre);if(actual!==input.expectedHash){throw new FsError("hash_mismatch",`expected ${input.expectedHash}, found ${actual}`,{hint:"re-read the file and retry with the latest hash"})}return{mode:pre.mode&4095}}__name(assertAtomicTargetPrecondition,"assertAtomicTargetPrecondition");async function hashRegularFileAtPath(p,pre){const fh=await fsp2.open(p,"r");const hash=createHash2("sha256");let opened;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");const buf=Buffer.allocUnsafe(64*1024);let offset=0;while(offset<opened.size){const read=await fh.read(buf,0,Math.min(buf.length,opened.size-offset),offset);if(read.bytesRead===0)break;hash.update(buf.subarray(0,read.bytesRead));offset+=read.bytesRead}}finally{await fh.close()}if(opened===void 0){throw new FsError("internal_error",`failed to stat opened file: ${p}`)}const post=await fsp2.lstat(p);assertSameFile(pre,post,p,"read");if(post.size!==opened.size||post.mtimeMs!==opened.mtimeMs){throw new FsError("hash_mismatch",`file changed during hash: ${p}`,{hint:"retry after re-reading the latest file hash"})}return`sha256:${hash.digest("hex")}`}__name(hashRegularFileAtPath,"hashRegularFileAtPath");function hashBuffer(buf){return`sha256:${createHash2("sha256").update(buf).digest("hex")}`}__name(hashBuffer,"hashBuffer");function assertSameFile(pre,post,p,intent){const preDev=toBigInt(pre.dev);const postDev=toBigInt(post.dev);const preIno=toBigInt(pre.ino);const postIno=toBigInt(post.ino);if(preDev!==0n&&postDev!==0n&&preIno!==0n&&postIno!==0n&&(preDev!==postDev||preIno!==postIno)){throw new FsError("symlink_escape",`path changed during ${intent}: ${p}`,{hint:"TOCTOU swap detected via device/inode comparison"})}}__name(assertSameFile,"assertSameFile");function toBigInt(value){return typeof value==="bigint"?value:BigInt(value)}__name(toBigInt,"toBigInt");async function syncHandleBestEffort(fh){try{await fh.sync()}catch{}}__name(syncHandleBestEffort,"syncHandleBestEffort");async function fsyncParentDirBestEffort(parent){let fh;try{fh=await fsp2.open(parent,"r");await fh.sync()}catch{}finally{await fh?.close().catch(()=>void 0)}}__name(fsyncParentDirBestEffort,"fsyncParentDirBestEffort");async function chmodHandleBestEffort(fh,mode){try{await fh.chmod(mode)}catch{}}__name(chmodHandleBestEffort,"chmodHandleBestEffort");async function assertTempPathMatchesStat(tmpPath,expected){const st=await fsp2.lstat(tmpPath);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`temporary path is a symlink: ${tmpPath}`,{hint:"temp-file race detected before final rename"})}if(!st.isFile()){throw new FsError("parse_error",`temporary path is not a regular file: ${tmpPath}`)}assertSameFile(expected,st,tmpPath,"write")}__name(assertTempPathMatchesStat,"assertTempPathMatchesStat");async function publishCreateNoClobber(tmpPath,target){try{await fsp2.link(tmpPath,target)}catch(err){const code=err?.code;if(code==="EEXIST"){throw new FsError("file_already_exists",`file already exists: ${target}`)}throw err}await fsp2.unlink(tmpPath).catch(()=>void 0)}__name(publishCreateNoClobber,"publishCreateNoClobber");async function renameWithRetryLocal(src,dest,retries,delayMs){for(let attempt=0;attempt<=retries;attempt++){try{await fsp2.rename(src,dest);return}catch(err){const code=err?.code;const retryable=code==="EPERM"||code==="EACCES";if(!retryable||attempt===retries)throw err;await new Promise(resolve4=>setTimeout(resolve4,delayMs*2**attempt))}}}__name(renameWithRetryLocal,"renameWithRetryLocal");function countOccurrences(haystack,needle){let count=0;let index=0;while(true){const found=haystack.indexOf(needle,index);if(found===-1)return count;count+=1;index=found+needle.length}}__name(countOccurrences,"countOccurrences");function safeUtf8Truncate(buf,maxBytes){if(buf.length<=maxBytes)return buf;let end=maxBytes;while(end>0&&(buf[end]&192)===128)end--;return buf.subarray(0,end)}__name(safeUtf8Truncate,"safeUtf8Truncate");async function assertInodeStableAfterRead(p,preIno){const post=await fsp2.lstat(p);if(post.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink during read: ${p}`,{hint:"TOCTOU swap detected via post-read lstat"})}const preNum=toBigInt(preIno);const postNum=toBigInt(post.ino);if(preNum!==0n&&postNum!==0n&&preNum!==postNum){throw new FsError("symlink_escape",`path inode changed during read: ${p}`,{hint:"TOCTOU swap detected via inode comparison"})}}__name(assertInodeStableAfterRead,"assertInodeStableAfterRead");async function assertNotSymlinkBeforeWrite(p){let pre;try{pre=await fsp2.lstat(p)}catch(err){const code=err?.code;if(code==="ENOENT")return;throw err}if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink before write: ${p}`,{hint:"TOCTOU swap detected via pre-write lstat \u2014 re-resolve before retrying"})}}__name(assertNotSymlinkBeforeWrite,"assertNotSymlinkBeforeWrite");function kindFromStatLike(s){if(s.isSymbolicLink())return"symlink";if(s.isDirectory())return"directory";if(s.isFile())return"file";return"other"}__name(kindFromStatLike,"kindFromStatLike");function errorCode(err){return err?.code}__name(errorCode,"errorCode");function errorKindForRealpathFailure(err){const code=errorCode(err);if(code==="EACCES"||code==="EPERM")return"permission_denied";if(code==="ENOENT"||code==="ELOOP")return"symlink_escape";return"io_error"}__name(errorKindForRealpathFailure,"errorKindForRealpathFailure");function buildWriteMeta(opts){const meta={};if(opts.bom!==void 0)meta["bom"]=opts.bom;if(opts.encoding)meta["encoding"]=opts.encoding;if(opts.lineEnding)meta["lineEnding"]=opts.lineEnding;return Object.keys(meta).length>0?meta:void 0}__name(buildWriteMeta,"buildWriteMeta");var MAX_LIST_ENTRIES=2e3;var MAX_FILE_LINE_LIMIT=2e3;var DEFAULT_FILE_BYTES_MAX_BYTES=64*1024;var DEFAULT_GLOB_MAX_RESULTS=5e3;var MAX_GLOB_MAX_RESULTS=5e4;function applyReadHeaders(res){res.set("Cache-Control","no-store");res.set("X-Content-Type-Options","nosniff")}__name(applyReadHeaders,"applyReadHeaders");function sendFsError(res,err,route){applyReadHeaders(res);if(sendGenerationClosedError(res,err))return;if(isFsError(err)){const fs3=err;res.status(fs3.status).json({errorKind:fs3.kind,error:fs3.message,hint:fs3.hint,status:fs3.status});return}writeStderrLine(`qwen serve: ${route} unexpected error: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({errorKind:"internal_error",error:err instanceof Error?err.message:String(err),status:500})}__name(sendFsError,"sendFsError");function parseIntInRange(raw,min,max){if(raw===void 0)return void 0;if(typeof raw!=="string"||!/^\d+$/.test(raw))return null;const n=Number.parseInt(raw,10);if(!Number.isSafeInteger(n)||n<min||n>max)return null;return n}__name(parseIntInRange,"parseIntInRange");function parseBoolFlag(raw){return raw==="1"||raw==="true"}__name(parseBoolFlag,"parseBoolFlag");function requireStringQuery(res,raw,name,route){if(typeof raw!=="string"||raw.length===0){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`${name} query parameter is required`,status:400});writeStderrLine(`qwen serve: ${route} rejected request missing required ?${name}`);return null}return raw}__name(requireStringQuery,"requireStringQuery");function routeName(req,legacyRoute){const context=getWorkspaceRouteContext(req);if(!context)return legacyRoute;return`${context.routePrefix}${legacyRoute.slice("GET ".length)}`}__name(routeName,"routeName");function getFsFactory(req,res){const context=getWorkspaceRouteContext(req);if(context)return context.runtime.routeFileSystemFactory;const factory=req.app.locals.fsFactory;if(!factory){applyReadHeaders(res);res.status(500).json({errorKind:"internal_error",error:"workspace filesystem factory is not configured",status:500});return null}return factory}__name(getFsFactory,"getFsFactory");async function handleGetFile(req,res,deps){const ROUTE=routeName(req,"GET /file");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const maxBytes=parseIntInRange(req.query["maxBytes"],1,256*1024);if(maxBytes===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:"`maxBytes` must be a positive integer in [1, 262144]",status:400});return}const line=parseIntInRange(req.query["line"],1,Number.MAX_SAFE_INTEGER);if(line===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:"`line` must be a positive integer",status:400});return}const limit=parseIntInRange(req.query["limit"],1,MAX_FILE_LINE_LIMIT);if(limit===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`limit\` must be a positive integer in [1, ${MAX_FILE_LINE_LIMIT}]`,status:400});return}const rawCursor=req.query["cursor"];if(rawCursor!==void 0&&(typeof rawCursor!=="string"||rawCursor.length===0||rawCursor.length>MAX_TEXT_CURSOR_CHARS)){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`cursor\` must be a non-empty string of at most ${MAX_TEXT_CURSOR_CHARS} characters`,status:400});return}const cursor=rawCursor;const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"read");const out=await fs3.readText(resolved,{maxBytes,line,limit,cursor});const returnedBytes=Buffer.byteLength(out.content,"utf-8");applyReadHeaders(res);res.status(200).json({kind:"file",path:workspaceRelative(req,resolved),content:out.content,encoding:out.meta.encoding??"utf-8",bom:out.meta.bom===true,lineEnding:out.meta.lineEnding,sizeBytes:out.meta.sizeBytes??returnedBytes,returnedBytes,truncated:out.meta.truncated===true,hash:out.meta.hash,matchedIgnore:out.meta.matchedIgnore??null,originalLineCount:out.meta.originalLineCount??null,nextCursor:out.meta.nextCursor??null,hasMore:out.meta.hasMore===true})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetFile,"handleGetFile");async function handleGetFileBytes(req,res,deps){const ROUTE=routeName(req,"GET /file/bytes");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const offset=parseIntInRange(req.query["offset"],0,Number.MAX_SAFE_INTEGER);if(offset===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:"`offset` must be a non-negative safe integer",status:400});return}const maxBytes=parseIntInRange(req.query["maxBytes"],1,MAX_READ_BYTES);if(maxBytes===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`maxBytes\` must be a positive integer in [1, ${MAX_READ_BYTES}]`,status:400});return}const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"read");const out=await fs3.readBytesWindow(resolved,{offset:offset??0,maxBytes:maxBytes??DEFAULT_FILE_BYTES_MAX_BYTES});applyReadHeaders(res);res.status(200).json({kind:"file_bytes",path:workspaceRelative(req,resolved),offset:out.offset,sizeBytes:out.sizeBytes,returnedBytes:out.returnedBytes,truncated:out.truncated,contentBase64:out.buffer.toString("base64"),...out.hash?{hash:out.hash}:{}})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetFileBytes,"handleGetFileBytes");async function handleGetStat(req,res,deps){const ROUTE=routeName(req,"GET /stat");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"stat");const st=await fs3.stat(resolved);applyReadHeaders(res);res.status(200).json({kind:"stat",path:workspaceRelative(req,resolved),type:st.kind,sizeBytes:st.sizeBytes,modifiedMs:st.modifiedMs})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetStat,"handleGetStat");async function handleGetList(req,res,deps){const ROUTE=routeName(req,"GET /list");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const includeIgnored=parseBoolFlag(req.query["includeIgnored"]);const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"list");const entries=await fs3.list(resolved,{includeIgnored,maxEntries:MAX_LIST_ENTRIES+1});let truncated=false;let returned=entries;if(returned.length>MAX_LIST_ENTRIES){returned=returned.slice(0,MAX_LIST_ENTRIES);truncated=true}applyReadHeaders(res);res.status(200).json({kind:"list",path:workspaceRelative(req,resolved),entries:returned,truncated,matchedIgnore:null})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetList,"handleGetList");async function handleGetGlob(req,res,deps){const ROUTE=routeName(req,"GET /glob");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const pattern=requireStringQuery(res,req.query["pattern"],"pattern",ROUTE);if(pattern===null)return;const includeIgnored=parseBoolFlag(req.query["includeIgnored"]);const maxResults=parseIntInRange(req.query["maxResults"],1,MAX_GLOB_MAX_RESULTS);if(maxResults===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`maxResults\` must be a positive integer in [1, ${MAX_GLOB_MAX_RESULTS}]`,status:400});return}const cwdRaw=req.query["cwd"];const cwdString=typeof cwdRaw==="string"&&cwdRaw.length>0?cwdRaw:void 0;const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});const start=performance.now();try{const cwdResolved=cwdString?await fs3.resolve(cwdString,"list"):void 0;const cap=maxResults??DEFAULT_GLOB_MAX_RESULTS;const probe=await fs3.glob(pattern,{cwd:cwdResolved,includeIgnored,maxResults:cap+1});const truncated=probe.truncated===true||probe.length>cap;const trimmed=truncated?probe.slice(0,cap):probe;const relMatches=trimmed.map(m=>workspaceRelative(req,m));applyReadHeaders(res);res.status(200).json({kind:"glob",pattern,cwd:cwdString??"",matches:relMatches,count:relMatches.length,truncated,durationMs:Math.round(performance.now()-start)})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetGlob,"handleGetGlob");function workspaceRelative(req,resolved){const boundWorkspace=getWorkspaceRouteContext(req)?.runtime.workspaceCwd??req.app.locals.boundWorkspace;if(!boundWorkspace){throw new Error("bound workspace is not configured")}let rel=path5.relative(boundWorkspace,resolved);if(isOutsideWorkspaceRelative(rel)){try{rel=path5.relative(canonicalizeWorkspace(boundWorkspace),resolved)}catch{throw new FsError("path_outside_workspace","path resolved outside workspace")}}if(isOutsideWorkspaceRelative(rel)){throw new FsError("path_outside_workspace","path resolved outside workspace")}if(rel==="")return".";return path5.sep==="/"?rel:rel.split(path5.sep).join("/")}__name(workspaceRelative,"workspaceRelative");function isOutsideWorkspaceRelative(rel){return rel===".."||rel.startsWith(`..${path5.sep}`)||path5.isAbsolute(rel)}__name(isOutsideWorkspaceRelative,"isOutsideWorkspaceRelative");function registerWorkspaceFileReadRoutes(app,deps){app.get("/file",(req,res)=>handleGetFile(req,res,deps));app.get("/file/bytes",(req,res)=>handleGetFileBytes(req,res,deps));app.get("/stat",(req,res)=>handleGetStat(req,res,deps));app.get("/list",(req,res)=>handleGetList(req,res,deps));app.get("/glob",(req,res)=>handleGetGlob(req,res,deps))}__name(registerWorkspaceFileReadRoutes,"registerWorkspaceFileReadRoutes");function registerWorkspaceQualifiedFileReadRoutes(app,deps){const resolve4=__name((req,res)=>{const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return false;setWorkspaceRouteContext(req,{runtime,routePrefix:"GET /workspaces/:workspace"});return true},"resolve");app.get("/workspaces/:workspace/file",(req,res)=>{if(!resolve4(req,res))return;void handleGetFile(req,res,deps)});app.get("/workspaces/:workspace/file/bytes",(req,res)=>{if(!resolve4(req,res))return;void handleGetFileBytes(req,res,deps)});app.get("/workspaces/:workspace/stat",(req,res)=>{if(!resolve4(req,res))return;void handleGetStat(req,res,deps)});app.get("/workspaces/:workspace/list",(req,res)=>{if(!resolve4(req,res))return;void handleGetList(req,res,deps)});app.get("/workspaces/:workspace/glob",(req,res)=>{if(!resolve4(req,res))return;void handleGetGlob(req,res,deps)})}__name(registerWorkspaceQualifiedFileReadRoutes,"registerWorkspaceQualifiedFileReadRoutes");init_esbuild_shims();init_esbuild_shims();import path6 from"node:path";var PersistedSessionListCache=class{constructor(ttlMs,maxRetainedSummaries){this.ttlMs=ttlMs;this.maxRetainedSummaries=maxRetainedSummaries}static{__name(this,"PersistedSessionListCache")}slots=new Map;retainedSummaries=0;lookup(scope,loader,options={}){options.signal?.throwIfAborted();const key=this.key(scope);let slot=this.slots.get(key);if(!slot){slot={generation:0};this.slots.set(key,slot)}const now=Date.now();if(slot.value){const cacheAgeMs=Math.max(0,now-slot.value.completedAt);if(cacheAgeMs<this.ttlMs){const snapshot=slot.value.snapshot;return{status:"cache_hit",promise:Promise.resolve().then(()=>{options.signal?.throwIfAborted();return snapshot}),cacheAgeMs}}this.removeValue(slot)}if(slot.inFlight!==void 0&&slot.inFlight.generation===slot.generation&&!slot.inFlight.controller.signal.aborted){return{status:"single_flight",promise:this.attachWaiter(key,slot,slot.inFlight,options.signal)}}const generation=slot.generation;const controller=new AbortController;const load={generation,controller,promise:void 0,waiterCount:0,settled:false};const managed=Promise.resolve().then(()=>{controller.signal.throwIfAborted();return loader(controller.signal)}).then(snapshot=>{load.settled=true;const current=this.slots.get(key);if(current===slot&&current.inFlight===load){current.inFlight=void 0;if(current.generation===generation&&!controller.signal.aborted&&snapshot.sessions.length<=this.maxRetainedSummaries){this.installValue(key,current,snapshot)}else if(current.value===void 0){this.slots.delete(key)}}return snapshot},error=>{load.settled=true;const current=this.slots.get(key);if(current===slot&&current.inFlight===load){current.inFlight=void 0;if(current.value===void 0)this.slots.delete(key)}throw error});load.promise=managed;slot.inFlight=load;return{status:"scan",promise:this.attachWaiter(key,slot,load,options.signal)}}invalidate(scope){const key=this.key(scope);const slot=this.slots.get(key);if(!slot)return;slot.generation+=1;this.removeValue(slot);if(slot.inFlight===void 0)this.slots.delete(key)}clear(){for(const slot of this.slots.values()){if(slot.value)clearTimeout(slot.value.expiryTimer)}this.slots.clear();this.retainedSummaries=0}installValue(key,slot,snapshot){const completedAt=Date.now();this.evictFor(snapshot.sessions.length);const remainingTtlMs=Math.max(0,this.ttlMs-(Date.now()-completedAt));const expiryTimer=setTimeout(()=>{const current=this.slots.get(key);if(current!==slot||current.value?.expiryTimer!==expiryTimer){return}this.removeValue(current);if(current.inFlight===void 0)this.slots.delete(key)},remainingTtlMs);if(typeof expiryTimer.unref==="function")expiryTimer.unref();const value={snapshot,completedAt,expiryTimer};slot.value=value;this.retainedSummaries+=snapshot.sessions.length}evictFor(incomingSummaries){while(this.retainedSummaries+incomingSummaries>this.maxRetainedSummaries){let oldest;for(const[key,slot]of this.slots){if(slot.value&&(oldest===void 0||slot.value.completedAt<oldest.completedAt)){oldest={key,slot,completedAt:slot.value.completedAt}}}if(!oldest)return;this.removeValue(oldest.slot);if(oldest.slot.inFlight===void 0)this.slots.delete(oldest.key)}}removeValue(slot){const value=slot.value;if(!value)return;clearTimeout(value.expiryTimer);this.retainedSummaries-=value.snapshot.sessions.length;slot.value=void 0}attachWaiter(key,slot,load,signal){load.waiterCount+=1;return new Promise((resolve4,reject)=>{let settled=false;const settle=__name(finish=>{if(settled)return;settled=true;signal?.removeEventListener("abort",onAbort);load.waiterCount-=1;if(load.waiterCount===0&&!load.settled){load.controller.abort(new DOMException("No active session list waiters","AbortError"));const current=this.slots.get(key);if(current===slot&&current.inFlight===load){current.inFlight=void 0;if(current.value===void 0)this.slots.delete(key)}}finish()},"settle");const onAbort=__name(()=>{if(load.settled)return;settle(()=>reject(signal?.reason))},"onAbort");signal?.addEventListener("abort",onAbort,{once:true});if(signal?.aborted)onAbort();void load.promise.then(snapshot=>settle(()=>resolve4(snapshot)),error=>settle(()=>reject(error)))})}key(scope){return JSON.stringify([path6.resolve(scope.runtimeBaseDir),scope.workspaceCwd,scope.archiveState])}};init_esbuild_shims();function laterActivityTimestamp(live,persisted){const liveTime=live===void 0?Number.NaN:Date.parse(live);const persistedTime=persisted===void 0?Number.NaN:Date.parse(persisted);const liveValid=Number.isFinite(liveTime);const persistedValid=Number.isFinite(persistedTime);if(liveValid&&persistedValid){return liveTime>=persistedTime?live:persisted}if(liveValid)return live;if(persistedValid)return persisted;return live??persisted}__name(laterActivityTimestamp,"laterActivityTimestamp");var DEFAULT_SESSION_PAGE_SIZE=20;var MAX_SESSION_PAGE_SIZE=100;var MAX_ORGANIZED_SESSIONS=5e4;var MAX_EMITTED_CURSOR_SESSION_IDS=64;var PERSISTED_SESSION_LIST_CACHE_TTL_MS=2e3;var persistedSessionListCache=new PersistedSessionListCache(PERSISTED_SESSION_LIST_CACHE_TTL_MS,MAX_ORGANIZED_SESSIONS);function invalidateWorkspaceSessionListCache(options){for(const archiveState of options.archiveStates){persistedSessionListCache.invalidate({runtimeBaseDir:options.runtimeBaseDir,workspaceCwd:options.workspaceCwd,archiveState})}}__name(invalidateWorkspaceSessionListCache,"invalidateWorkspaceSessionListCache");var InvalidCursorError=class extends Error{static{__name(this,"InvalidCursorError")}constructor(cursor,kind="numeric"){super(`Invalid cursor: "${cursor}" is not a valid ${kind} cursor`);this.name="InvalidCursorError"}};function isPersistedSessionCursor(cursor){if(cursor==="")return false;const trimmed=cursor.trim();if(trimmed==="")return false;const parts=trimmed.split("|");if(parts.length===2&&parts[0].trim()!==""&&parts[1].length>0){const mtime=Number(parts[0]);if(Number.isFinite(mtime)&&mtime>=0)return true}const parsed=Number(trimmed);return Number.isFinite(parsed)&&parsed>=0&&parsed<=Number.MAX_SAFE_INTEGER}__name(isPersistedSessionCursor,"isPersistedSessionCursor");function parseSessionCursor(cursor){if(cursor==="")return void 0;if(!isPersistedSessionCursor(cursor)){throw new InvalidCursorError(cursor,"persisted")}const trimmed=cursor.trim();const parsed=Number(trimmed);return Number.isFinite(parsed)?parsed:trimmed}__name(parseSessionCursor,"parseSessionCursor");function parseEmittedSessionIds(value){if(value===void 0)return[];if(!Array.isArray(value)||value.some(id=>typeof id!=="string"||id.length===0)){return void 0}return value}__name(parseEmittedSessionIds,"parseEmittedSessionIds");function parseOrganizedCursor(cursor,expected){if(cursor==="")return void 0;try{const decoded=Buffer.from(cursor,"base64url").toString("utf8");const parsed=JSON.parse(decoded);const last=parsed.last;if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)||typeof last!=="object"||last===null||Array.isArray(last)||typeof last.isPinned!=="boolean"||typeof last.activityTime!=="number"||!Number.isFinite(last.activityTime)||typeof last.sessionId!=="string"||last.sessionId.length===0||parsed.catalogKind!==void 0&&parsed.catalogKind!=="organized"||parsed.paginateMerged!==void 0&&parsed.paginateMerged!==expected.paginateMerged||(parsed.sortBy??"updatedAt")!==(expected.sortBy??"updatedAt")||parsed.group!==expected.group||parsed.archiveState!==expected.archiveState||parsed.sourceType!==expected.sourceType||parsed.sourceId!==expected.sourceId||parsed.conversationKind!==expected.conversationKind){throw new Error("invalid organized cursor")}const emitted=parseEmittedSessionIds(parsed.emitted);if(emitted===void 0){throw new Error("invalid organized cursor")}return{last,emitted}}catch{throw new InvalidCursorError(cursor,"organized")}}__name(parseOrganizedCursor,"parseOrganizedCursor");function encodeOrganizedCursor(last,group,archiveState,paginateMerged,sourceType,sourceId,conversationKind,emitted=[],sortBy){return Buffer.from(JSON.stringify({catalogKind:"organized",sortBy,paginateMerged,group,archiveState,sourceType,sourceId,conversationKind,last,...emitted.length>0?{emitted}:{}}),"utf8").toString("base64url")}__name(encodeOrganizedCursor,"encodeOrganizedCursor");function parseLiveSessionCursor(cursor){if(cursor==="")return void 0;try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)||typeof parsed.activityTime!=="number"||!Number.isFinite(parsed.activityTime)||typeof parsed.sessionId!=="string"||parsed.sessionId.length===0){throw new Error("invalid live cursor")}return parsed}catch{throw new InvalidCursorError(cursor,"live")}}__name(parseLiveSessionCursor,"parseLiveSessionCursor");function encodeLiveSessionCursor(last){return Buffer.from(JSON.stringify(last),"utf8").toString("base64url")}__name(encodeLiveSessionCursor,"encodeLiveSessionCursor");function matchesSessionMetadataSource(session,filter){if(filter.conversationKind==="standalone-top-level"&&classifyTopLevelConversationSource(session)?.kind!=="standalone"){return false}const sourceTypeMatches=filter.sourceType===void 0||session.sourceType===filter.sourceType||filter.sourceType==="default"&&(session.sourceType===void 0||session.sourceType==="qwen-live");return sourceTypeMatches&&(filter.sourceId===void 0||session.sourceId===filter.sourceId)}__name(matchesSessionMetadataSource,"matchesSessionMetadataSource");function parseMetadataSessionCursor(cursor,expected){if(cursor==="")return void 0;try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));const last=parsed.last;if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)||typeof last!=="object"||last===null||Array.isArray(last)||typeof last.activityTime!=="number"||!Number.isFinite(last.activityTime)||typeof last.sessionId!=="string"||last.sessionId.length===0||parsed.catalogKind!==void 0&&parsed.catalogKind!=="metadata"||parsed.paginateMerged!==void 0&&parsed.paginateMerged!==expected.paginateMerged||(parsed.sortBy??"updatedAt")!==(expected.sortBy??"updatedAt")||parsed.parentSessionId!==expected.parentSessionId||parsed.sourceType!==expected.sourceType||parsed.sourceId!==expected.sourceId||parsed.conversationKind!==expected.conversationKind||parsed.archiveState!==expected.archiveState){throw new Error("invalid metadata cursor")}const emitted=parseEmittedSessionIds(parsed.emitted);if(emitted===void 0){throw new Error("invalid metadata cursor")}return{last:{activityTime:last.activityTime,sessionId:last.sessionId},emitted}}catch{throw new InvalidCursorError(cursor,expected.parentSessionId!==void 0?"parent":"metadata")}}__name(parseMetadataSessionCursor,"parseMetadataSessionCursor");function encodeMetadataSessionCursor(last,filter,archiveState,paginateMerged,emitted=[]){return Buffer.from(JSON.stringify({catalogKind:"metadata",paginateMerged,...filter,archiveState,last,...emitted.length>0?{emitted}:{}}),"utf8").toString("base64url")}__name(encodeMetadataSessionCursor,"encodeMetadataSessionCursor");async function enrichWorktreeSidecars(bySessionId,sessionService,archiveState="active",signal){for(const[sessionId,summary]of bySessionId){signal?.throwIfAborted();if(summary.worktree)continue;let sidecar;try{const sidecarPath=sessionService.getWorktreeSessionPathForArchiveState(sessionId,archiveState);sidecar=signal?await readWorktreeSession(sidecarPath,{signal}):await readWorktreeSession(sidecarPath)}catch{signal?.throwIfAborted();sidecar=null}if(sidecar&&await readWorktreeSessionMarker(sidecar.worktreePath)===sessionId){bySessionId.set(sessionId,{...summary,worktree:{slug:sidecar.slug,path:sidecar.worktreePath,branch:sidecar.worktreeBranch}})}}}__name(enrichWorktreeSidecars,"enrichWorktreeSidecars");async function enrichPrSidecars(bySessionId,sessionService,archiveState,signal){for(const[sessionId,summary]of bySessionId){signal?.throwIfAborted();let result;try{const sidecarPath=sessionService.getPrSessionPathForArchiveState(sessionId,archiveState);result=signal?await readSessionPrsDetailed(sidecarPath,{signal}):await readSessionPrsDetailed(sidecarPath)}catch{signal?.throwIfAborted();result={status:"invalid"}}if(result.status==="ok"){bySessionId.set(sessionId,{...summary,prs:sidecarToPrInfos(result.prs)})}}}__name(enrichPrSidecars,"enrichPrSidecars");function toSummary(item){return{sessionId:item.sessionId,workspaceCwd:item.cwd,createdAt:item.startTime,updatedAt:new Date(item.mtime).toISOString(),displayName:item.customTitle||item.prompt,...item.customTitle&&item.titleSource?{titleSource:item.titleSource}:{},...item.parentSessionId?{parentSessionId:item.parentSessionId}:{},...item.sourceType?{sourceType:item.sourceType}:{},...item.sourceId!==void 0?{sourceId:item.sourceId}:{},clientCount:0,hasActivePrompt:false,isArchived:item.isArchived===true}}__name(toSummary,"toSummary");function mergeLiveSessionSummary(existing,live){const merged={...existing,...live,createdAt:existing.createdAt,displayName:live.displayName??existing.displayName,parentSessionId:existing.parentSessionId??live.parentSessionId,sourceType:existing.sourceType??live.sourceType,sourceId:existing.sourceType!==void 0?existing.sourceId:live.sourceId,updatedAt:laterActivityTimestamp(live.updatedAt,existing.updatedAt),clientCount:live.clientCount,hasActivePrompt:live.hasActivePrompt,backgroundTurn:live.backgroundTurn,hasRunningBackgroundTasks:live.hasRunningBackgroundTasks,isArchived:false};if(existing.prs||live.prs){merged.prs=mergeSummaryPrs(existing.prs,live.prs)}return merged}__name(mergeLiveSessionSummary,"mergeLiveSessionSummary");function sidecarToPrInfos(sidecar){return sidecar.map(toSessionPrInfo)}__name(sidecarToPrInfos,"sidecarToPrInfos");function mergeSummaryPrs(persistedPrs,livePrs){const live=livePrs??[];const persisted=persistedPrs??[];const liveByNumber=new Map(live.map(l=>[l.number,l]));const persistedNumbers=new Set(persisted.map(p=>p.number));const consumedLive=new Set;const ordered=[];for(const p of persisted){const liveEntry=liveByNumber.get(p.number);if(!liveEntry){ordered.push(p);continue}const samePr=canonicalSessionPrUrl(p.url)===canonicalSessionPrUrl(liveEntry.url);const matchedTwinExists=persisted.some(q=>q.number===p.number&&canonicalSessionPrUrl(q.url)===canonicalSessionPrUrl(liveEntry.url));if(!samePr&&matchedTwinExists)continue;if(consumedLive.has(p.number))continue;consumedLive.add(p.number);ordered.push(samePr?{...liveEntry,...p.state?{state:p.state}:{},...p.issues?{issues:p.issues}:{}}:p)}for(const liveEntry of live){if(!persistedNumbers.has(liveEntry.number)&&persisted.length<SESSION_PR_LIST_LIMIT){ordered.push(liveEntry)}}return ordered.slice(-SESSION_PR_LIST_LIMIT)}__name(mergeSummaryPrs,"mergeSummaryPrs");async function liveOnlySummary(live,sessionService,signal){const summary={...live,createdAt:live.createdAt,clientCount:live.clientCount,hasActivePrompt:live.hasActivePrompt,backgroundTurn:live.backgroundTurn,hasRunningBackgroundTasks:live.hasRunningBackgroundTasks,isArchived:false};let result;try{const sidecarPath=sessionService.getPrSessionPathForArchiveState(live.sessionId,"active");result=signal?await readSessionPrsDetailed(sidecarPath,{signal}):await readSessionPrsDetailed(sidecarPath)}catch{signal?.throwIfAborted();result={status:"invalid"}}if(result.status==="ok"){summary.prs=mergeSummaryPrs(sidecarToPrInfos(result.prs),live.prs)}return summary}__name(liveOnlySummary,"liveOnlySummary");function clonePersistedSummary(session){return{...session,...session.worktree?{worktree:{...session.worktree}}:{}}}__name(clonePersistedSummary,"clonePersistedSummary");async function loadAllPersistedSummaries(sessionService,archiveState,signal){const scanStartedAt=performance.now();signal.throwIfAborted();const sessions=[];let truncated=false;let scanPages=0;let cursor;do{scanPages+=1;const page=await sessionService.listSessions({cursor,size:1e4,archiveState,signal,excludeSourceTypes:[...HIDDEN_CATALOG_SOURCE_TYPES]});signal.throwIfAborted();const remaining=MAX_ORGANIZED_SESSIONS-sessions.length;sessions.push(...page.items.slice(0,remaining).map(toSummary));cursor=page.nextCursor;if(page.items.length===0){break}if(page.items.length>remaining||sessions.length>=MAX_ORGANIZED_SESSIONS&&cursor!==void 0){writeStderrLine(`qwen serve: organized session list truncated at ${MAX_ORGANIZED_SESSIONS} sessions`);truncated=true;break}}while(cursor!==void 0);const bySessionId=new Map(sessions.map(session=>[session.sessionId,session]));await enrichWorktreeSidecars(bySessionId,sessionService,archiveState,signal);await enrichPrSidecars(bySessionId,sessionService,archiveState,signal);signal.throwIfAborted();return{sessions:[...bySessionId.values()],truncated,scanPages,scanDurationMs:Math.max(0,performance.now()-scanStartedAt)}}__name(loadAllPersistedSummaries,"loadAllPersistedSummaries");async function listAllPersistedSummaries(sessionService,workspaceCwd,archiveState,runtimeBaseDir,queryKind,signal){const lookup=persistedSessionListCache.lookup({runtimeBaseDir,workspaceCwd,archiveState},loadSignal=>loadAllPersistedSummaries(sessionService,archiveState,loadSignal),{signal});addDaemonRequestAttribute("qwen-code.daemon.session_list.cache_status",lookup.status);addDaemonRequestAttribute("qwen-code.daemon.session_list.archive_state",archiveState);addDaemonRequestAttribute("qwen-code.daemon.session_list.query_kind",queryKind);if(lookup.cacheAgeMs!==void 0){addDaemonRequestAttribute("qwen-code.daemon.session_list.cache_age_ms",lookup.cacheAgeMs)}const snapshot=await lookup.promise;signal?.throwIfAborted();addDaemonRequestAttribute("qwen-code.daemon.session_list.persisted_sessions",snapshot.sessions.length);addDaemonRequestAttribute("qwen-code.daemon.session_list.scan_pages",snapshot.scanPages);addDaemonRequestAttribute("qwen-code.daemon.session_list.truncated",snapshot.truncated);if(lookup.status!=="cache_hit"){addDaemonRequestAttribute("qwen-code.daemon.session_list.scan_duration_ms",snapshot.scanDurationMs)}return snapshot}__name(listAllPersistedSummaries,"listAllPersistedSummaries");function getSummaryActivityTime(session,sortBy){if(sortBy==="lastUserPromptAt"){const time2=Date.parse(session.lastUserPromptAt??"");return Number.isFinite(time2)?time2:Number.MIN_SAFE_INTEGER}const time=Date.parse(session.updatedAt??session.createdAt);return Number.isFinite(time)?time:0}__name(getSummaryActivityTime,"getSummaryActivityTime");function getLiveSessionCursorKey(session,sortBy){return{activityTime:getSummaryActivityTime(session,sortBy),sessionId:session.sessionId}}__name(getLiveSessionCursorKey,"getLiveSessionCursorKey");function compareLiveSessionCursorKeys(a,b){const byTime=b.activityTime-a.activityTime;if(byTime!==0)return byTime;return a.sessionId.localeCompare(b.sessionId)}__name(compareLiveSessionCursorKeys,"compareLiveSessionCursorKeys");function compareOrganizedSessions(activityTimeById,a,b){return compareOrganizedCursorKeys(getOrganizedCursorKey(activityTimeById,a),getOrganizedCursorKey(activityTimeById,b))}__name(compareOrganizedSessions,"compareOrganizedSessions");function getOrganizedCursorKey(activityTimeById,session){return{isPinned:session.isPinned===true,activityTime:activityTimeById.get(session.sessionId)??0,sessionId:session.sessionId}}__name(getOrganizedCursorKey,"getOrganizedCursorKey");function compareOrganizedCursorKeys(a,b){const byPinned=Number(b.isPinned)-Number(a.isPinned);if(byPinned!==0)return byPinned;const byTime=b.activityTime-a.activityTime;if(byTime!==0)return byTime;return a.sessionId.localeCompare(b.sessionId)}__name(compareOrganizedCursorKeys,"compareOrganizedCursorKeys");function nextEmittedSessionIds(options){const candidates=new Set(options.carried);for(const row of options.page){if(options.liveSessionIds.has(row.sessionId)){candidates.add(row.sessionId)}}const kept=[];for(const sessionId of candidates){const row=options.listedById.get(sessionId);if(!row){kept.push({sessionId,persistedTime:Number.NEGATIVE_INFINITY});continue}const persistedTime=options.persistedTimeById.get(sessionId);if(persistedTime===void 0){kept.push({sessionId,persistedTime:Number.NEGATIVE_INFINITY});continue}if(options.reenters(row,persistedTime)){kept.push({sessionId,persistedTime})}}if(kept.length>MAX_EMITTED_CURSOR_SESSION_IDS){kept.sort((a,b)=>a.persistedTime-b.persistedTime);kept.length=MAX_EMITTED_CURSOR_SESSION_IDS}return kept.map(entry=>entry.sessionId)}__name(nextEmittedSessionIds,"nextEmittedSessionIds");function applyOrganization(session,organization){return{...session,groupId:organization?.groupId??null,color:organization?.color??null,isPinned:organization?.isPinned===true,...organization?.pinnedAt!==void 0?{pinnedAt:organization.pinnedAt}:{}}}__name(applyOrganization,"applyOrganization");async function listOrganizedWorkspaceSessionsForResponse(bridge,workspaceCwd,options,pageSize,readOptions){const archiveState=options.archiveState??"active";const sessionService=new SessionService(workspaceCwd);const organizationService=createSessionOrganizationService(workspaceCwd);readOptions.signal?.throwIfAborted();const snapshot=await organizationService.readSnapshot();readOptions.signal?.throwIfAborted();const knownGroupIds=new Set(snapshot.groups.map(group2=>group2.id));const group=options.group??"all";if(group!=="all"&&group!=="pinned"&&group!=="ungrouped"&&!knownGroupIds.has(group)){throw new SessionOrganizationError(`Group not found: ${group}`,"group_not_found","group")}const cursor=options.cursor!==void 0?parseOrganizedCursor(options.cursor,{paginateMerged:readOptions.paginateMerged===true,group,sortBy:options.sortBy,archiveState,sourceType:options.sourceType,sourceId:options.sourceId,conversationKind:options.conversationKind}):void 0;const cursorKey=cursor?.last;const emittedBeforePage=new Set(cursor?.emitted??[]);const isFirstPage=cursorKey===void 0;let liveMergeFailed=false;const bySessionId=new Map;const persisted=await listAllPersistedSummaries(sessionService,workspaceCwd,archiveState,readOptions.runtimeBaseDir,"organized",readOptions.signal);readOptions.signal?.throwIfAborted();for(const session of persisted.sessions){bySessionId.set(session.sessionId,applyOrganization(clonePersistedSummary(session),snapshot.sessions.get(session.sessionId)))}const persistedTimeById=new Map(persisted.sessions.map(session=>[session.sessionId,getSummaryActivityTime(session)]));const liveSessionIds=new Set;if(readOptions.mergeLive!==false&&archiveState!=="archived"){try{const liveSessions=bridge.listWorkspaceSessions(workspaceCwd);for(const live of liveSessions){liveSessionIds.add(live.sessionId);const existing=bySessionId.get(live.sessionId);const organization=snapshot.sessions.get(live.sessionId);if(existing){bySessionId.set(live.sessionId,applyOrganization(mergeLiveSessionSummary(existing,live),organization))}else if((isFirstPage||readOptions.paginateMerged||options.sortBy==="lastUserPromptAt")&&(!persisted.truncated||!await(readOptions.signal?sessionService.sessionExists(live.sessionId,{signal:readOptions.signal}):sessionService.sessionExists(live.sessionId)))){bySessionId.set(live.sessionId,applyOrganization(await liveOnlySummary(live,sessionService,readOptions.signal),organization))}}}catch(error){readOptions.signal?.throwIfAborted();liveMergeFailed=true;writeStderrLine(`qwen serve: organized session list live merge failed; using persisted sessions only: ${error instanceof Error?error.message:String(error)}`)}}const filtered=[...bySessionId.values()].filter(session=>{if(isHiddenCatalogSource(session.sourceType))return false;if(!matchesSessionMetadataSource(session,options))return false;if(group==="all")return true;if(group==="pinned")return session.isPinned===true;if(group==="ungrouped")return session.groupId==null&&session.color==null;return session.color==null&&session.groupId===group});readOptions.signal?.throwIfAborted();if(options.sortBy==="lastUserPromptAt"){await enrichPromptTimes(filtered,sessionService,archiveState,readOptions,true);for(const session of filtered)persistedTimeById.set(session.sessionId,getSummaryActivityTime(session,options.sortBy))}const activityTimeById=new Map(filtered.map(session=>[session.sessionId,getSummaryActivityTime(session,options.sortBy)]));filtered.sort((a,b)=>compareOrganizedSessions(activityTimeById,a,b));readOptions.signal?.throwIfAborted();const afterCursor=cursorKey===void 0?filtered:filtered.filter(session=>!emittedBeforePage.has(session.sessionId)&&compareOrganizedCursorKeys(cursorKey,getOrganizedCursorKey(activityTimeById,session))<0);const page=afterCursor.slice(0,pageSize);let nextCursor;if(page.length<afterCursor.length){const boundary=getOrganizedCursorKey(activityTimeById,page[page.length-1]);const emitted=nextEmittedSessionIds({carried:emittedBeforePage,page,liveSessionIds,listedById:new Map(filtered.map(session=>[session.sessionId,session])),persistedTimeById,reenters:__name((row,persistedTime)=>[true,false].some(isPinned=>compareOrganizedCursorKeys(boundary,{isPinned,activityTime:persistedTime,sessionId:row.sessionId})<0),"reenters")});nextCursor=encodeOrganizedCursor(boundary,group,archiveState,readOptions.paginateMerged===true,options.sourceType,options.sourceId,options.conversationKind,emitted,options.sortBy)}return{sessions:page,...readOptions.includeGroups?{groups:{groups:snapshot.groups,colorOptions:[...GROUP_COLOR_OPTIONS]}}:{},...nextCursor!==void 0?{nextCursor}:{},...liveMergeFailed?{liveMergeFailed:true}:{},...persisted.truncated?{truncated:true}:{}}}__name(listOrganizedWorkspaceSessionsForResponse,"listOrganizedWorkspaceSessionsForResponse");async function listWorkspaceSessionsByMetadataForResponse(bridge,workspaceCwd,options,pageSize,filter,readOptions){const archiveState=options.archiveState??"active";const sessionService=new SessionService(workspaceCwd);const bySessionId=new Map;const persisted=await listAllPersistedSummaries(sessionService,workspaceCwd,archiveState,readOptions.runtimeBaseDir,"metadata",readOptions.signal);readOptions.signal?.throwIfAborted();const canonicalizeStandaloneIds=filter.conversationKind==="standalone-top-level";const conflictedStandaloneIds=new Set;const persistedTimeById=new Map;for(const session of persisted.sessions){let sessionId=session.sessionId;if(canonicalizeStandaloneIds){const parsed=parseCallerSuppliedSessionId(sessionId);if(parsed.kind!=="valid")continue;sessionId=parsed.sessionId;if(conflictedStandaloneIds.has(sessionId))continue;if(bySessionId.has(sessionId)){bySessionId.delete(sessionId);persistedTimeById.delete(sessionId);conflictedStandaloneIds.add(sessionId);continue}}bySessionId.set(sessionId,{...clonePersistedSummary(session),sessionId});persistedTimeById.set(sessionId,getSummaryActivityTime(session))}const liveSessionIds=new Set;let liveMergeFailed=false;if(readOptions.mergeLive!==false&&archiveState!=="archived"){try{for(const live of bridge.listWorkspaceSessions(workspaceCwd)){let sessionId=live.sessionId;if(canonicalizeStandaloneIds){const parsed=parseCallerSuppliedSessionId(sessionId);if(parsed.kind!=="valid"||conflictedStandaloneIds.has(parsed.sessionId)){continue}sessionId=parsed.sessionId}const canonicalLive=sessionId===live.sessionId?live:{...live,sessionId};liveSessionIds.add(sessionId);const existing=bySessionId.get(sessionId);if(existing){bySessionId.set(sessionId,mergeLiveSessionSummary(existing,canonicalLive))}else if(!persisted.truncated||!await(readOptions.signal?sessionService.sessionExists(sessionId,{signal:readOptions.signal}):sessionService.sessionExists(sessionId))){bySessionId.set(sessionId,await liveOnlySummary(canonicalLive,sessionService,readOptions.signal))}}}catch(error){readOptions.signal?.throwIfAborted();liveMergeFailed=true;writeStderrLine(`qwen serve: session metadata filter live merge failed; using persisted sessions only: ${error instanceof Error?error.message:String(error)}`)}}const matches=[...bySessionId.values()].filter(session=>!isHiddenCatalogSource(session.sourceType)&&(filter.parentSessionId===void 0||session.parentSessionId===filter.parentSessionId)&&matchesSessionMetadataSource(session,filter));readOptions.signal?.throwIfAborted();const cursor=options.cursor!==void 0&&options.cursor!==""?parseMetadataSessionCursor(options.cursor,{paginateMerged:readOptions.paginateMerged===true,...filter,archiveState}):void 0;if(options.sortBy==="lastUserPromptAt"){await enrichPromptTimes(matches,sessionService,archiveState,readOptions,true);for(const session of matches)persistedTimeById.set(session.sessionId,getSummaryActivityTime(session,options.sortBy))}matches.sort((a,b)=>compareLiveSessionCursorKeys(getLiveSessionCursorKey(a,options.sortBy),getLiveSessionCursorKey(b,options.sortBy)));const cursorKey=cursor?.last;const emittedBeforePage=new Set(cursor?.emitted??[]);const afterCursor=cursorKey===void 0?matches:matches.filter(session=>!emittedBeforePage.has(session.sessionId)&&compareLiveSessionCursorKeys(cursorKey,getLiveSessionCursorKey(session,options.sortBy))<0);const page=afterCursor.slice(0,pageSize);let nextCursor;if(page.length<afterCursor.length){const boundary=getLiveSessionCursorKey(page[page.length-1],options.sortBy);const emitted=nextEmittedSessionIds({carried:emittedBeforePage,page,liveSessionIds,listedById:new Map(matches.map(session=>[session.sessionId,session])),persistedTimeById,reenters:__name((row,persistedTime)=>compareLiveSessionCursorKeys(boundary,{activityTime:persistedTime,sessionId:row.sessionId})<0,"reenters")});nextCursor=encodeMetadataSessionCursor(boundary,filter,archiveState,readOptions.paginateMerged===true,emitted)}return{sessions:page,...nextCursor!==void 0?{nextCursor}:{},...liveMergeFailed?{liveMergeFailed:true}:{},...persisted.truncated?{truncated:true}:{}}}__name(listWorkspaceSessionsByMetadataForResponse,"listWorkspaceSessionsByMetadataForResponse");function waitForQuestionTime(promise,signal){if(!signal)return promise;return new Promise((resolve4,reject)=>{const abort=__name(()=>{signal.removeEventListener("abort",abort);reject(signal.reason)},"abort");signal.addEventListener("abort",abort,{once:true});if(signal.aborted)abort();void promise.then(value=>{signal.removeEventListener("abort",abort);resolve4(value)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}__name(waitForQuestionTime,"waitForQuestionTime");async function listWorkspaceSessionsForResponse(bridge,workspaceCwd,options,readOptions={}){readOptions.signal?.throwIfAborted();const runtimeBaseDir=new Storage(workspaceCwd,readOptions.runtimeBaseDir).getRuntimeBaseDir();const result=await Storage.runWithResolvedRuntimeBaseDir(runtimeBaseDir,()=>listWorkspaceSessionsForResponseInRuntime(bridge,workspaceCwd,options,{...readOptions.mergeLive!==void 0?{mergeLive:readOptions.mergeLive}:{},...readOptions.paginateMerged!==void 0?{paginateMerged:readOptions.paginateMerged}:{},...readOptions.includeGroups!==void 0?{includeGroups:readOptions.includeGroups}:{},...readOptions.signal!==void 0?{signal:readOptions.signal}:{},runtimeBaseDir}));readOptions.signal?.throwIfAborted();if(options?.sortBy!=="lastUserPromptAt"){await enrichPromptTimes(result.sessions,new SessionService(workspaceCwd,{runtimeBaseDir}),options?.archiveState??"active",readOptions)}return result}__name(listWorkspaceSessionsForResponse,"listWorkspaceSessionsForResponse");async function enrichPromptTimes(sessions,service,archiveState,readOptions,preferCache=false){let nextIndex=0;await Promise.all(Array.from({length:Math.min(2,sessions.length)},async()=>{while(nextIndex<sessions.length){readOptions.signal?.throwIfAborted();const session=sessions[nextIndex++];try{session.lastUserPromptAt=await waitForQuestionTime(preferCache?service.getLastUserPromptAt(session.sessionId,archiveState,{preferCache:true}):service.getLastUserPromptAt(session.sessionId,archiveState),readOptions.signal)}catch{readOptions.signal?.throwIfAborted();session.lastUserPromptAt=void 0}}}));readOptions.signal?.throwIfAborted()}__name(enrichPromptTimes,"enrichPromptTimes");async function listWorkspaceSessionsForResponseInRuntime(bridge,workspaceCwd,options,readOptions){readOptions.signal?.throwIfAborted();const rawSize=options?.size;const requestedSize=typeof rawSize==="number"&&Number.isSafeInteger(rawSize)?rawSize:DEFAULT_SESSION_PAGE_SIZE;const pageSize=Math.min(Math.max(requestedSize,1),MAX_SESSION_PAGE_SIZE);if(options?.view==="organized"){return listOrganizedWorkspaceSessionsForResponse(bridge,workspaceCwd,options,pageSize,readOptions)}if(readOptions.paginateMerged||options?.sortBy==="lastUserPromptAt"||options?.parentSessionId!==void 0||options?.sourceType!==void 0||options?.conversationKind!==void 0){return listWorkspaceSessionsByMetadataForResponse(bridge,workspaceCwd,options??{},pageSize,{...options?.sortBy!==void 0?{sortBy:options.sortBy}:{},...options?.parentSessionId!==void 0?{parentSessionId:options.parentSessionId}:{},...options?.sourceType!==void 0?{sourceType:options.sourceType}:{},...options?.sourceId!==void 0?{sourceId:options.sourceId}:{},...options?.conversationKind!==void 0?{conversationKind:options.conversationKind}:{}},readOptions)}let persistedCursor;if(options?.cursor!=null){persistedCursor=parseSessionCursor(options.cursor)}const isFirstPage=persistedCursor===void 0;const sessionService=new SessionService(workspaceCwd);const archiveState=options?.archiveState??"active";const persisted=await sessionService.listSessions({cursor:persistedCursor,size:pageSize,archiveState,excludeSourceTypes:[...HIDDEN_CATALOG_SOURCE_TYPES],...readOptions.signal?{signal:readOptions.signal}:{}});readOptions.signal?.throwIfAborted();const bySessionId=new Map;for(const item of persisted.items){bySessionId.set(item.sessionId,toSummary(item))}await enrichWorktreeSidecars(bySessionId,sessionService,archiveState,readOptions.signal);await enrichPrSidecars(bySessionId,sessionService,archiveState,readOptions.signal);readOptions.signal?.throwIfAborted();if(archiveState==="archived"||readOptions.mergeLive===false){const sessions2=[...bySessionId.values()];const nextCursor2=persisted.nextCursor!=null?String(persisted.nextCursor):void 0;return{sessions:sessions2,nextCursor:nextCursor2}}const liveSessions=bridge.listWorkspaceSessions(workspaceCwd).filter(session=>!isHiddenCatalogSource(session.sourceType));for(const live of liveSessions){const existing=bySessionId.get(live.sessionId);if(existing){bySessionId.set(live.sessionId,mergeLiveSessionSummary(existing,live))}else if(isFirstPage&&(persisted.nextCursor==null||!await(readOptions.signal?sessionService.sessionExists(live.sessionId,{signal:readOptions.signal}):sessionService.sessionExists(live.sessionId)))){bySessionId.set(live.sessionId,await liveOnlySummary(live,sessionService,readOptions.signal))}}const sessions=[...bySessionId.values()].sort((a,b)=>{const aTime=Date.parse(a.updatedAt??a.createdAt);const bTime=Date.parse(b.updatedAt??b.createdAt);return bTime-aTime});readOptions.signal?.throwIfAborted();const nextCursor=persisted.nextCursor!=null?String(persisted.nextCursor):void 0;return{sessions,nextCursor}}__name(listWorkspaceSessionsForResponseInRuntime,"listWorkspaceSessionsForResponseInRuntime");async function listLiveWorkspaceSessionsForResponse(bridge,workspaceCwd,options,readOptions={}){const runtimeBaseDir=new Storage(workspaceCwd,readOptions.runtimeBaseDir).getRuntimeBaseDir();return Storage.runWithResolvedRuntimeBaseDir(runtimeBaseDir,async()=>{const rawSize=options?.size;const requestedSize=typeof rawSize==="number"&&Number.isSafeInteger(rawSize)?rawSize:DEFAULT_SESSION_PAGE_SIZE;const pageSize=Math.min(Math.max(requestedSize,1),MAX_SESSION_PAGE_SIZE);const cursorKey=options?.cursor!==void 0?parseLiveSessionCursor(options.cursor):void 0;const sessions=bridge.listWorkspaceSessions(workspaceCwd).filter(session=>!isHiddenCatalogSource(session.sourceType)).sort((a,b)=>compareLiveSessionCursorKeys(getLiveSessionCursorKey(a),getLiveSessionCursorKey(b)));const afterCursor=cursorKey===void 0?sessions:sessions.filter(session=>compareLiveSessionCursorKeys(cursorKey,getLiveSessionCursorKey(session))<0);const page=afterCursor.slice(0,pageSize);const sessionService=new SessionService(workspaceCwd);const enriched=await Promise.all(page.map(summary=>liveOnlySummary(summary,sessionService,readOptions.signal)));const nextCursor=page.length<afterCursor.length?encodeLiveSessionCursor(getLiveSessionCursorKey(page[page.length-1])):void 0;return{sessions:enriched,...nextCursor!==void 0?{nextCursor}:{}}})}__name(listLiveWorkspaceSessionsForResponse,"listLiveWorkspaceSessionsForResponse");async function searchWorkspaceSessionsForResponse(workspaceCwd,query,options={},readOptions={}){readOptions.signal?.throwIfAborted();const runtimeBaseDir=new Storage(workspaceCwd,readOptions.runtimeBaseDir).getRuntimeBaseDir();return Storage.runWithResolvedRuntimeBaseDir(runtimeBaseDir,async()=>{const sessionService=new SessionService(workspaceCwd);const hits=await sessionService.searchSessionContent(query,{...options.maxResults!==void 0?{maxResults:options.maxResults}:{},...readOptions.signal?{signal:readOptions.signal}:{}});const bySessionId=new Map;const organizationSnapshot=await createSessionOrganizationService(workspaceCwd).readSnapshot();readOptions.signal?.throwIfAborted();for(const hit of hits){readOptions.signal?.throwIfAborted();const item=await sessionService.getSessionListItem(hit.sessionId);if(item&&!isHiddenCatalogSource(item.sourceType))bySessionId.set(hit.sessionId,applyOrganization(toSummary(item),organizationSnapshot.sessions.get(hit.sessionId)))}await enrichWorktreeSidecars(bySessionId,sessionService,"active",readOptions.signal);await enrichPrSidecars(bySessionId,sessionService,"active",readOptions.signal);readOptions.signal?.throwIfAborted();const results=[];for(const hit of hits){const session=bySessionId.get(hit.sessionId);if(session)results.push({session,snippet:hit.snippet})}return{results}})}__name(searchWorkspaceSessionsForResponse,"searchWorkspaceSessionsForResponse");async function getWorkspaceSessionInfoForResponse(bridge,workspaceCwd,options={}){const counts=await new SessionService(workspaceCwd).getSessionInfoCounts({excludeSourceTypes:[...HIDDEN_CATALOG_SOURCE_TYPES]});return{active:counts.active,archived:counts.archived,total:counts.total,...options.includeLive===false?{}:{live:bridge.listWorkspaceSessions(workspaceCwd).filter(session=>!isHiddenCatalogSource(session.sourceType)).length},expensive:true,cost:"disk_scan",...counts.truncated?{truncated:true}:{}}}__name(getWorkspaceSessionInfoForResponse,"getWorkspaceSessionInfoForResponse");function parseSessionPageSizeQuery(raw){if(typeof raw!=="string")return void 0;const trimmed=raw.trim();if(!/^[+-]?\d+$/.test(trimmed))return void 0;const parsed=Number.parseInt(trimmed,10);if(!Number.isFinite(parsed))return void 0;if(Number.isSafeInteger(parsed))return parsed;return trimmed.startsWith("-")?1:MAX_SESSION_PAGE_SIZE}__name(parseSessionPageSizeQuery,"parseSessionPageSizeQuery");init_esbuild_shims();import fs2 from"node:fs";init_esbuild_shims();import{access}from"node:fs/promises";function isBoundTask(task){return typeof task.sessionId==="string"&&task.sessionId.length>0}__name(isBoundTask,"isBoundTask");async function disableTasksForSessions(projectRoot,sessionIds,options={}){if(sessionIds.length===0)return;const targets=new Set(sessionIds);await updateCronTasks(projectRoot,tasks=>{let changed=false;const next=tasks.map(task=>{if(isBoundTask(task)&&targets.has(task.sessionId)&&task.enabled!==false){changed=true;return{...task,enabled:false,disabledByArchive:true}}return task});return changed?next:tasks},options)}__name(disableTasksForSessions,"disableTasksForSessions");async function enableTasksForSessions(projectRoot,sessionIds,now=Date.now(),options={}){if(sessionIds.length===0)return;const targets=new Set(sessionIds);await updateCronTasks(projectRoot,tasks=>{let changed=false;const next=tasks.map(task=>{if(isBoundTask(task)&&targets.has(task.sessionId)&&task.enabled===false&&task.disabledByArchive===true){changed=true;const resumed={...task,enabled:true};delete resumed.disabledByArchive;const minute=now-now%6e4;if(resumed.recurring){resumed.lastFiredAt=minute}else{resumed.createdAt=now;resumed.lastFiredAt=minute}return resumed}return task});return changed?next:tasks},options)}__name(enableTasksForSessions,"enableTasksForSessions");async function removeTasksForSessions(projectRoot,sessionIds,options={}){if(sessionIds.length===0)return;try{await access(getCronFilePath(projectRoot))}catch(error){if(error.code==="ENOENT")return;throw error}const targets=new Set(sessionIds.map(cronTaskSessionDeletionId));const removedIds=[];await updateCronTasks(projectRoot,tasks=>{const next=tasks.filter(task=>{if(!isBoundTask(task)||!targets.has(cronTaskSessionDeletionId(task.sessionId)))return true;removedIds.push(task.id);return false});return next.length===tasks.length?tasks:next},{...options,deletionIds:__name(()=>[...removedIds,...targets],"deletionIds")})}__name(removeTasksForSessions,"removeTasksForSessions");init_esbuild_shims();import fs from"node:fs";import*as fsp3 from"node:fs/promises";import path7 from"node:path";init_esbuild_shims();var worktreeOwnershipOpTails=new Map;async function acquireWorktreeOwnershipOp(worktreeKey){const previous=worktreeOwnershipOpTails.get(worktreeKey);let releaseGate;const gate=new Promise(resolve4=>{releaseGate=resolve4});const tail=(previous??Promise.resolve()).then(()=>gate);worktreeOwnershipOpTails.set(worktreeKey,tail);if(previous){await previous}let released=false;return()=>{if(released)return;released=true;releaseGate();if(worktreeOwnershipOpTails.get(worktreeKey)===tail){worktreeOwnershipOpTails.delete(worktreeKey)}}}__name(acquireWorktreeOwnershipOp,"acquireWorktreeOwnershipOp");function canonicalPath(candidate){try{return fs.realpathSync(candidate)}catch{return candidate}}__name(canonicalPath,"canonicalPath");function logWarning(message){writeStderrLine(`qwen serve: ${message}`)}__name(logWarning,"logWarning");function logWorktreeCleanupPreserve(sessionId,reason){logWarning(`worktree cleanup preserved checkout action=delete session=${safeLogValue(sessionId)} reason=${safeLogValue(reason)}`)}__name(logWorktreeCleanupPreserve,"logWorktreeCleanupPreserve");async function preclassifyWorktreeCleanup(service,sessionId,runtimeWorkspaceCwd){let sidecarPath=service.getWorktreeSessionPath(sessionId);let sidecar=await readWorktreeSessionStrict(sidecarPath);if(sidecar.state==="missing"){const archivedPath=service.getWorktreeSessionPathForArchiveState(sessionId,"archived");if(archivedPath!==sidecarPath){sidecarPath=archivedPath;sidecar=await readWorktreeSessionStrict(sidecarPath)}}if(sidecar.state==="missing")return void 0;if(sidecar.state==="invalid"){logWorktreeCleanupPreserve(sessionId,`unreadable sidecar (${sidecar.reason})`);return void 0}const session=sidecar.session;if(session.workspaceCwd===void 0)return void 0;if(session.supersededBy!==void 0)return void 0;if(!path7.isAbsolute(session.workspaceCwd)||!path7.isAbsolute(session.originalCwd)){logWorktreeCleanupPreserve(sessionId,"sidecar base is not an absolute path");return void 0}if(runtimeWorkspaceCwd!==void 0){if(canonicalPath(session.workspaceCwd)!==canonicalPath(runtimeWorkspaceCwd)){logWorktreeCleanupPreserve(sessionId,"sidecar belongs to another workspace");return void 0}const workspaceRoots=[canonicalPath(runtimeWorkspaceCwd)];try{const repoTop=await new GitWorktreeService(runtimeWorkspaceCwd).getRepoTopLevel();if(repoTop&&canonicalPath(repoTop)!==workspaceRoots[0]){workspaceRoots.push(canonicalPath(repoTop))}}catch{}if(!workspaceRoots.includes(canonicalPath(session.originalCwd))){logWorktreeCleanupPreserve(sessionId,"sidecar original cwd is outside the accepted roots");return void 0}}const activeDir=path7.dirname(service.getWorktreeSessionPath(sessionId));const archivedDir=path7.dirname(service.getWorktreeSessionPathForArchiveState(sessionId,"archived"));const ownDir=path7.dirname(sidecarPath);const otherStateSidecarDir=ownDir===activeDir?archivedDir:activeDir;return{sessionId,sidecar:session,sidecarPath,lockKey:canonicalPath(session.worktreePath),...otherStateSidecarDir!==ownDir?{otherStateSidecarDir}:{}}}__name(preclassifyWorktreeCleanup,"preclassifyWorktreeCleanup");function acquireWorktreeCleanupLock(plan){return acquireWorktreeOwnershipOp(plan.lockKey)}__name(acquireWorktreeCleanupLock,"acquireWorktreeCleanupLock");async function worktreeAllowedRoots(workspaceCwd,originalCwd){const roots=new Set;for(const base of[workspaceCwd,originalCwd]){if(!path7.isAbsolute(base))continue;roots.add(path7.join(base,".qwen","worktrees"));try{const repoTop=await new GitWorktreeService(base).getRepoTopLevel();if(repoTop){roots.add(path7.join(repoTop,".qwen","worktrees"))}}catch{}}return[...roots]}__name(worktreeAllowedRoots,"worktreeAllowedRoots");var SIDECAR_SUFFIX=".worktree.json";async function findLiveSessionNamingCheckout(dir,lockKey,isSessionLive){let entries;try{entries=await fsp3.readdir(dir)}catch(error){if(error.code==="ENOENT")return void 0;return`sidecar scan failed: ${error instanceof Error?error.message:String(error)}`}for(const entry of entries){if(!entry.endsWith(SIDECAR_SUFFIX))continue;const other=await readWorktreeSessionStrict(path7.join(dir,entry));if(other.state==="missing")continue;if(other.state==="invalid")return`unreadable sibling sidecar ${entry}`;if(canonicalPath(other.session.worktreePath)!==lockKey)continue;const otherId=entry.slice(0,-SIDECAR_SUFFIX.length);if(isSessionLive(otherId)){return`session ${otherId} naming the checkout is still live`}}return void 0}__name(findLiveSessionNamingCheckout,"findLiveSessionNamingCheckout");async function verifyWorktreeCleanupOwnership(plan,isSessionLive){const{sessionId,sidecar}=plan;const locked=await readWorktreeSessionStrict(plan.sidecarPath);if(locked.state!=="valid"){return{ok:false,reason:locked.state==="missing"?"sidecar disappeared before delete":`unreadable sidecar (${locked.reason})`}}const current=locked.session;if(current.workspaceCwd===void 0||current.supersededBy!==void 0||current.slug!==sidecar.slug||current.worktreePath!==sidecar.worktreePath||current.originalCwd!==sidecar.originalCwd||current.workspaceCwd!==sidecar.workspaceCwd){return{ok:false,reason:"sidecar changed before delete"}}const marker=await readWorktreeSessionMarkerStrict(plan.lockKey);if(marker.state!=="valid"||marker.sessionId!==sessionId){return{ok:false,reason:marker.state==="valid"?"marker names another session":`marker ${marker.state}`}}const allowedRoots=await worktreeAllowedRoots(current.workspaceCwd,current.originalCwd);const contained=allowedRoots.some(root=>{try{const realRoot=fs.realpathSync(root);return plan.lockKey===realRoot||plan.lockKey.startsWith(realRoot+path7.sep)}catch{return false}});if(!contained){return{ok:false,reason:"checkout outside workspace worktree roots"}}const chatsDir=path7.dirname(plan.sidecarPath);const ownFile=path7.basename(plan.sidecarPath);let entries;try{entries=await fsp3.readdir(chatsDir)}catch(error){return{ok:false,reason:`sidecar scan failed: ${error instanceof Error?error.message:String(error)}`}}const tombstoneIds=[];let olderTombstone=false;for(const entry of entries){if(!entry.endsWith(SIDECAR_SUFFIX)||entry===ownFile)continue;const other=await readWorktreeSessionStrict(path7.join(chatsDir,entry));if(other.state==="missing")continue;if(other.state==="invalid"){return{ok:false,reason:`unreadable sibling sidecar ${entry}`}}if(canonicalPath(other.session.worktreePath)!==plan.lockKey)continue;if(other.session.supersededBy===void 0){return{ok:false,reason:`checkout shared with ${entry}`}}tombstoneIds.push(entry.slice(0,-SIDECAR_SUFFIX.length));if(other.session.supersededBy!==sessionId)olderTombstone=true}if(olderTombstone){for(const otherId of tombstoneIds){if(isSessionLive(otherId)){return{ok:false,reason:`superseded session ${otherId} is still live`}}}if(plan.otherStateSidecarDir!==void 0){const otherState=await findLiveSessionNamingCheckout(plan.otherStateSidecarDir,plan.lockKey,isSessionLive);if(otherState!==void 0)return{ok:false,reason:otherState}}}const removalTarget=canonicalPath(new GitWorktreeService(current.originalCwd).getUserWorktreePath(current.slug));if(removalTarget!==plan.lockKey){return{ok:false,reason:"slug does not resolve to the verified checkout"}}plan.sidecar=current;return{ok:true}}__name(verifyWorktreeCleanupOwnership,"verifyWorktreeCleanupOwnership");async function checkoutStillPopulated(worktreePath){try{return(await fsp3.readdir(worktreePath)).length>0}catch{return false}}__name(checkoutStillPopulated,"checkoutStillPopulated");async function executeWorktreeCleanup(plan){const{sessionId,sidecar}=plan;const marker=await readWorktreeSessionMarkerStrict(plan.lockKey);if(marker.state!=="valid"||marker.sessionId!==sessionId){logWorktreeCleanupPreserve(sessionId,"marker changed after delete");return}if(await worktreeHasWork(plan.lockKey)){logWorktreeCleanupPreserve(sessionId,"checkout has uncommitted work");return}const result=await new GitWorktreeService(sidecar.originalCwd).removeUserWorktree(sidecar.slug,{deleteBranch:true});if(!result.success){const errorText=result.error??"unknown error";if(await checkoutStillPopulated(plan.lockKey)){logWorktreeCleanupPreserve(sessionId,`checkout removal failed: ${errorText}`)}else{logWarning(`worktree cleanup removal failed, checkout may be partially deleted action=delete session=${safeLogValue(sessionId)} reason=${safeLogValue(errorText)}`)}return}if(result.branchPreserved){logWarning(`worktree cleanup removed checkout but kept branch action=delete session=${safeLogValue(sessionId)} slug=${safeLogValue(sidecar.slug)} branch=${safeLogValue(sidecar.worktreeBranch)} reason=unmerged commits`)}}__name(executeWorktreeCleanup,"executeWorktreeCleanup");var DaemonDrainingError=class extends Error{static{__name(this,"DaemonDrainingError")}name="DaemonDrainingError";code="daemon_draining";constructor(){super("The daemon is draining and no longer accepts session maintenance.")}};var SessionArchiveCoordinator=class{static{__name(this,"SessionArchiveCoordinator")}exclusive=new Set;shared=new Map;sharedDrains=new Map;maintenanceSealed=false;activeMaintenance=0;maintenanceDrain;assertNotTransitioning(sessionId){if(this.exclusive.has(normalizeSessionIdForLookup(sessionId))){throw new SessionArchivingError(sessionId)}}async runExclusiveMany(sessionIds,fn){if(this.maintenanceSealed){throw new DaemonDrainingError}const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];for(const sessionId of uniqueSessionIds){this.assertNotTransitioning(sessionId);if((this.shared.get(sessionId)??0)>0){throw new SessionArchivingError(sessionId,"shared")}}for(const sessionId of uniqueSessionIds){this.exclusive.add(sessionId)}this.activeMaintenance++;try{return await fn()}finally{for(const sessionId of uniqueSessionIds){this.exclusive.delete(sessionId)}this.activeMaintenance--;if(this.activeMaintenance===0){this.maintenanceDrain?.resolve();this.maintenanceDrain=void 0}}}async runExclusiveAfterShared(rawSessionId,fn){if(this.maintenanceSealed){throw new DaemonDrainingError}const sessionId=normalizeSessionIdForLookup(rawSessionId);this.assertNotTransitioning(sessionId);this.exclusive.add(sessionId);this.activeMaintenance++;try{const sharedCount=this.shared.get(sessionId)??0;if(sharedCount>0){let drain=this.sharedDrains.get(sessionId);if(!drain){let resolve4;const promise=new Promise(done=>{resolve4=done});drain={promise,resolve:resolve4};this.sharedDrains.set(sessionId,drain)}await drain.promise}return await fn()}finally{this.sharedDrains.delete(sessionId);this.exclusive.delete(sessionId);this.activeMaintenance--;if(this.activeMaintenance===0){this.maintenanceDrain?.resolve();this.maintenanceDrain=void 0}}}sealMaintenanceAndWait(){this.maintenanceSealed=true;if(this.activeMaintenance===0){return Promise.resolve()}if(!this.maintenanceDrain){let resolve4;const promise=new Promise(done=>{resolve4=done});this.maintenanceDrain={promise,resolve:resolve4}}return this.maintenanceDrain.promise}async runSharedMany(sessionIds,fn){if(this.maintenanceSealed){throw new DaemonDrainingError}const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];for(const sessionId of uniqueSessionIds){this.assertNotTransitioning(sessionId)}for(const sessionId of uniqueSessionIds){this.shared.set(sessionId,(this.shared.get(sessionId)??0)+1)}this.activeMaintenance++;try{return await fn()}finally{for(const sessionId of uniqueSessionIds){const count=(this.shared.get(sessionId)??1)-1;if(count<=0){this.shared.delete(sessionId);this.sharedDrains.get(sessionId)?.resolve();this.sharedDrains.delete(sessionId)}else{this.shared.set(sessionId,count)}}this.activeMaintenance--;if(this.activeMaintenance===0){this.maintenanceDrain?.resolve();this.maintenanceDrain=void 0}}}};async function runWithDaemonWriterLease(params){const{action,sessionId,service,mutate,mutationAppliedAfterError,afterMutationApplied}=params;let lease;try{const leaseOptions={processKind:"daemon",reclaimPolicy:"never",takeoverPolicy:"certified"};try{lease=await service.acquireSessionWriterLease(sessionId,leaseOptions)}catch(error){if(!(error instanceof SessionWriterUnavailableError)&&!(error instanceof SessionTranscriptChangedError)){throw error}lease=await service.acquireSealedManagedMaintenanceLease(sessionId)??await service.acquireSessionMaintenanceLease(sessionId,leaseOptions)}}catch(error){return{mutationApplied:false,error}}let value;let mutationApplied=false;let mutationError;try{const mutation=await mutate(()=>lease.assertOwnedAndUnchanged(),()=>lease.assertCleanupOwned());value=mutation.value;mutationApplied=mutation.mutationApplied}catch(error){mutationError=error;try{mutationApplied=await mutationAppliedAfterError()}catch{mutationApplied=false}}let maintenanceError;if(mutationApplied){try{await afterMutationApplied()}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=${action} workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}}let releaseError;try{await lease.release()}catch(error){releaseError=error}if(releaseError!==void 0){logMaintenanceLeaseReleaseFailure({action,workspace:service.getProjectRoot(),sessionId,error:releaseError,mutationApplied});if(mutationError!==void 0){logSessionArchiveWarning(`session maintenance mutation also failed action=${action} workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(mutationError))}`)}return{mutationApplied,error:releaseError,maintenanceError}}if(mutationError!==void 0){return{mutationApplied,error:mutationError,maintenanceError}}return{value,mutationApplied,maintenanceError}}__name(runWithDaemonWriterLease,"runWithDaemonWriterLease");function logMaintenanceLeaseReleaseFailure(params){const errorKind=typeof params.error==="object"&&params.error!==null&&typeof params.error.errorKind==="string"?params.error.errorKind:"unknown";logSessionArchiveWarning(`session maintenance lease release failed action=${params.action} workspace=${safeLogValue(params.workspace)} session=${safeLogValue(params.sessionId)} errorKind=${safeLogValue(errorKind)} mutationApplied=${params.mutationApplied}`)}__name(logMaintenanceLeaseReleaseFailure,"logMaintenanceLeaseReleaseFailure");async function classifySessionLocation(service,sessionId){return service.getMaintainableSessionLocation(sessionId)}__name(classifySessionLocation,"classifySessionLocation");function sessionLocationError(sessionId){const error=new SessionConflictError(sessionId);error.message=`Session "${sessionId}" exists in both active and archived directories. Retry with resolveConflicts: true to keep one copy.`;return error}__name(sessionLocationError,"sessionLocationError");function updateScheduledTaskForMaintenance(service,sessionId,action,assertCanMutate){if(action==="archive"){return disableTasksForSessions(service.getProjectRoot(),[sessionId],{assertCanCommit:assertCanMutate})}if(action==="unarchive"){return enableTasksForSessions(service.getProjectRoot(),[sessionId],Date.now(),{assertCanCommit:assertCanMutate})}return removeTasksForSessions(service.getProjectRoot(),[sessionId],{assertCanCommit:assertCanMutate})}__name(updateScheduledTaskForMaintenance,"updateScheduledTaskForMaintenance");async function deletePersistedSessionWithLease(service,sessionId,assertCanMutate){const initialLocation=await classifySessionLocation(service,sessionId);if(initialLocation===void 0){let maintenanceError;try{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"delete",assertCanMutate)}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=delete workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}return{kind:"notFound",mutationApplied:false,maintenanceError}}const mutation=await runWithDaemonWriterLease({action:"delete",sessionId,service,mutate:__name(async(assertOwnedAndUnchanged,assertCleanupOwned)=>{const lockedLocation=await classifySessionLocation(service,sessionId);if(lockedLocation===void 0){return{value:"notFound",mutationApplied:false}}const removed=await service.removeSession(sessionId,{assertStorageUnchanged:assertOwnedAndUnchanged,assertCanMutate,assertCleanupOwned});return{value:removed?"removed":"notFound",mutationApplied:removed}},"mutate"),mutationAppliedAfterError:__name(async()=>await classifySessionLocation(service,sessionId)===void 0,"mutationAppliedAfterError"),afterMutationApplied:__name(async()=>{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"delete",assertCanMutate)},"afterMutationApplied")});if(mutation.error!==void 0){return{kind:"error",error:mutation.error,mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}return{kind:mutation.value??"notFound",mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}__name(deletePersistedSessionWithLease,"deletePersistedSessionWithLease");async function deleteDaemonSessions(params){const{sessionIds,service,bridge,coordinator,coordinatorLockHeld=false,assertCanMutate,runtimeWorkspaceCwd,onError}=params;const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];if(!coordinatorLockHeld){for(const sessionId of uniqueSessionIds){coordinator.assertNotTransitioning(sessionId)}}const isSessionLive=__name(candidate=>{if(!bridge.getSessionSummary)return true;try{bridge.getSessionSummary(normalizeSessionIdForLookup(candidate));return true}catch(error){return!(isSessionNotFoundError(error)&&error.code!=="session_closing")}},"isSessionLive");const runWithWorktreeCleanup=__name(async(sessionId,mutateSession)=>{const activeSidecarPath=service.getWorktreeSessionPath(sessionId);const archivedSidecarPath=service.getWorktreeSessionPathForArchiveState(sessionId,"archived");if(!fs2.existsSync(activeSidecarPath)&&(archivedSidecarPath===activeSidecarPath||!fs2.existsSync(archivedSidecarPath))){return coordinator.runExclusiveMany([sessionId],mutateSession)}const cleanupPlan=await preclassifyWorktreeCleanup(service,sessionId,runtimeWorkspaceCwd);if(!cleanupPlan){return coordinator.runExclusiveMany([sessionId],mutateSession)}const releaseCleanupLock=await acquireWorktreeCleanupLock(cleanupPlan);try{const ownership=await verifyWorktreeCleanupOwnership(cleanupPlan,isSessionLive);if(!ownership.ok){logWorktreeCleanupPreserve(sessionId,ownership.reason)}const result=await coordinator.runExclusiveMany([sessionId],mutateSession);if(ownership.ok&&result.kind==="removed"){try{assertCanMutate?.();await executeWorktreeCleanup(cleanupPlan)}catch(error){logWorktreeCleanupPreserve(sessionId,`cleanup execution failed: ${errorMessage(error)}`)}}return result}finally{releaseCleanupLock()}},"runWithWorktreeCleanup");const results=await Promise.all(uniqueSessionIds.map(async sessionId=>{try{const mutateSession=__name(async()=>{assertCanMutate?.();const removePersistedSession=__name(async()=>{const result=await deletePersistedSessionWithLease(service,sessionId,assertCanMutate);if(result.kind==="error"){onError?.({phase:"remove",sessionId,error:errorMessage(result.error)});return result}try{if(assertCanMutate){await bridge.deleteSessionAttachments(sessionId,{assertCanCommit:assertCanMutate})}else{await bridge.deleteSessionAttachments(sessionId)}return result}catch(error){onError?.({phase:"delete",sessionId,error:errorMessage(error)});return{kind:"error",error,mutationApplied:result.mutationApplied,maintenanceError:result.maintenanceError}}},"removePersistedSession");try{await bridge.closeSession(sessionId)}catch(error){if(isSessionNotFoundError(error)&&error.code!=="session_closing"){return await removePersistedSession()}onError?.({phase:"close",sessionId,error:errorMessage(error)});return{kind:"error",error,mutationApplied:false}}return await removePersistedSession()},"mutateSession");return await(coordinatorLockHeld?mutateSession():runWithWorktreeCleanup(sessionId,mutateSession))}catch(error){if(error instanceof DaemonDrainingError){throw error}onError?.({phase:"delete",sessionId,error:errorMessage(error)});return{kind:"error",error,mutationApplied:false}}}));const removed=[];const notFound=[];const errors=[];for(let i=0;i<results.length;i++){const sessionId=uniqueSessionIds[i];const result=results[i];if(result.kind==="removed"){removed.push(sessionId)}else if(result.kind==="notFound"){notFound.push(sessionId)}else{errors.push({sessionId,error:errorMessage(result.error)})}if(result.maintenanceError!==void 0){errors.push({sessionId,error:"Scheduled task lifecycle update failed."})}}return{removed,notFound,errors}}__name(deleteDaemonSessions,"deleteDaemonSessions");async function deleteDaemonSessionIfOrphan(params){const{sessionId,service,bridge,coordinator}=params;coordinator.assertNotTransitioning(sessionId);const result=await coordinator.runExclusiveMany([sessionId],async()=>{let killed=false;try{killed=await bridge.killSession(sessionId,{requireZeroAttaches:true})}catch(error){if(!isSessionNotFoundError(error))throw error;killed=true}if(!killed){try{bridge.getSessionSummary(sessionId);return void 0}catch(error){if(!isSessionNotFoundError(error))throw error}}const removal=await deletePersistedSessionWithLease(service,sessionId);if(removal.kind!=="error"){await bridge.deleteSessionAttachments(sessionId)}return removal});if(result===void 0){return false}if(result.kind==="error"){throw result.error}bridge.markSessionCatalogChanged();return true}__name(deleteDaemonSessionIfOrphan,"deleteDaemonSessionIfOrphan");async function assertSessionLoadable(workspaceCwd,sessionId,runtimeBaseDir,options={}){const service=new SessionService(workspaceCwd,{runtimeBaseDir});const location=await service.getSessionLocation(sessionId);if(location==="archived"){throw new SessionArchivedError(sessionId)}if(location==="conflict"){if(options.allowActiveConflict){try{await service.findSessionIdIgnoringCase(sessionId)}catch(error){if(error instanceof SessionIdCaseConflictError&&error.reason==="case_conflict"&&error.candidateSessionId===sessionId){return"active"}if(!(error instanceof SessionIdCaseConflictError))throw error}}throw new SessionConflictError(sessionId)}return location}__name(assertSessionLoadable,"assertSessionLoadable");async function resolveSessionIdForRestore(service,sessionId){try{return await service.findSessionIdIgnoringCase(sessionId)}catch(error){if(error instanceof SessionIdCaseConflictError){if(error.candidateSessionId===sessionId)return sessionId;throw new SessionConflictError(sessionId)}throw error}}__name(resolveSessionIdForRestore,"resolveSessionIdForRestore");async function assertSessionRestorable(workspaceCwd,sessionId,requestedSessionId,runtimeBaseDir){const location=await new SessionService(workspaceCwd,{runtimeBaseDir}).getSessionLocation(sessionId);if(location==="archived"){throw new SessionArchivedError(sessionId)}if(location==="conflict"){if(sessionId!==requestedSessionId){throw new SessionConflictError(requestedSessionId)}return"active"}return location}__name(assertSessionRestorable,"assertSessionRestorable");async function assertSessionArchived(workspaceCwd,sessionId,runtimeBaseDir){const location=await new SessionService(workspaceCwd,{runtimeBaseDir}).getSessionLocation(sessionId);if(location==="active"){throw new SessionNotArchivedError(sessionId)}if(location==="conflict"){throw new SessionConflictError(sessionId)}if(location===void 0){throw new SessionNotFoundError(sessionId)}}__name(assertSessionArchived,"assertSessionArchived");function isSessionNotFoundError(err){return err instanceof SessionNotFoundError||err instanceof Error&&err.name==="SessionNotFoundError"}__name(isSessionNotFoundError,"isSessionNotFoundError");function logSessionArchiveResult(action,result){const changedLabel=action==="archive"?"archived":"unarchived";const alreadyLabel=action==="archive"?"alreadyArchived":"alreadyActive";const details=[`requested=${result.requested.length} requestedIds=${formatSessionIds(result.requested)}`,`${changedLabel}=${result.changed.length} ${changedLabel}Ids=${formatSessionIds(result.changed)}`,`${alreadyLabel}=${result.already.length} ${alreadyLabel}Ids=${formatSessionIds(result.already)}`,`notFound=${result.notFound.length} notFoundIds=${formatSessionIds(result.notFound)}`,`errors=${result.errors.length} errorIds=${formatSessionErrors(result.errors)}`].join(" ");writeStderrLine(`qwen serve: sessions ${action} result ${details}`)}__name(logSessionArchiveResult,"logSessionArchiveResult");function formatSessionIds(sessionIds){return`[${sessionIds.map(sessionId=>safeLogValue(sessionId)).join(",")}]`}__name(formatSessionIds,"formatSessionIds");function formatSessionErrors(errors){return`[${errors.map(({sessionId,error})=>`${safeLogValue(sessionId)}:${safeLogValue(errorMessage(error))}`).join(",")}]`}__name(formatSessionErrors,"formatSessionErrors");function errorMessage(error){return error instanceof Error?error.message:String(error)}__name(errorMessage,"errorMessage");function logSessionArchiveWarning(message){writeStderrLine(`qwen serve: ${sanitizeLogLine(message)}`)}__name(logSessionArchiveWarning,"logSessionArchiveWarning");function sanitizeLogLine(message){return message.replace(LOG_LINE_UNSAFE_RE," ").slice(0,4096)}__name(sanitizeLogLine,"sanitizeLogLine");async function archiveDaemonSessions(params){const{sessionIds,service,bridge,coordinator,coordinatorLockHeld=false,resolveConflicts=false,requireIdle=false,assertCanMutate}=params;const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];if(!coordinatorLockHeld){for(const sessionId of uniqueSessionIds){coordinator.assertNotTransitioning(sessionId)}}const results=await Promise.all(uniqueSessionIds.map(async sessionId=>{try{const mutateSession=__name(async()=>{assertCanMutate?.();try{await bridge.closeSession(sessionId,void 0,{requireAgentClose:true,requireIdle})}catch(error){if(!isSessionNotFoundError(error)||error.code==="session_closing"){return{kind:"error",error,mutationApplied:false}}}const initialLocation=await classifySessionLocation(service,sessionId);if(initialLocation===void 0){return{kind:"notFound",mutationApplied:false}}if(initialLocation==="conflict"&&!resolveConflicts){return{kind:"error",error:sessionLocationError(sessionId),mutationApplied:false}}const mutation=await runWithDaemonWriterLease({action:"archive",sessionId,service,mutate:__name(async(assertOwnedAndUnchanged,assertCleanupOwned)=>{const lockedLocation=await classifySessionLocation(service,sessionId);if(lockedLocation===void 0){return{value:"notFound",mutationApplied:false}}if(lockedLocation==="conflict"&&!resolveConflicts){throw sessionLocationError(sessionId)}const result=await service.archiveSessions([sessionId],{resolveConflicts,assertStorageUnchanged:assertOwnedAndUnchanged,assertCanMutate,assertCleanupOwned});if(result.errors[0])throw result.errors[0].error;if(result.archived.length>0){return{value:result.resolvedConflicts.length?"resolvedConflict":"archived",mutationApplied:true}}return{value:result.alreadyArchived.length>0?"alreadyArchived":"notFound",mutationApplied:false}},"mutate"),mutationAppliedAfterError:__name(async()=>await classifySessionLocation(service,sessionId)==="archived","mutationAppliedAfterError"),afterMutationApplied:__name(async()=>{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"archive",assertCanMutate)},"afterMutationApplied")});if(mutation.error!==void 0){return{kind:"error",error:mutation.error,mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}let maintenanceError=mutation.maintenanceError;if(mutation.value==="alreadyArchived"){try{await updateScheduledTaskForMaintenance(service,sessionId,"archive",assertCanMutate)}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=archive workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}}return{kind:mutation.value??"notFound",mutationApplied:mutation.mutationApplied,maintenanceError}},"mutateSession");return await(coordinatorLockHeld?mutateSession():coordinator.runExclusiveMany([sessionId],mutateSession))}catch(error){if(error instanceof DaemonDrainingError){throw error}return{kind:"error",error,mutationApplied:false,maintenanceError:void 0}}}));const archived=[];const alreadyArchived=[];const resolvedConflicts=[];const notFound=[];const errors=[];for(let i=0;i<results.length;i++){const sessionId=uniqueSessionIds[i];const result=results[i];if(result.kind==="archived")archived.push(sessionId);else if(result.kind==="resolvedConflict"){archived.push(sessionId);resolvedConflicts.push(sessionId)}else if(result.kind==="alreadyArchived"){alreadyArchived.push(sessionId)}else if(result.kind==="notFound")notFound.push(sessionId);else errors.push({sessionId,error:result.error});if("maintenanceError"in result&&result.maintenanceError!==void 0){errors.push({sessionId,error:result.maintenanceError})}}logSessionArchiveResult("archive",{requested:uniqueSessionIds,changed:archived,already:alreadyArchived,notFound,errors});return{archived,alreadyArchived,resolvedConflicts,notFound,errors}}__name(archiveDaemonSessions,"archiveDaemonSessions");async function unarchiveDaemonSessions(params){const{sessionIds,service,coordinator,coordinatorLockHeld=false,resolveConflicts=false,assertCanMutate}=params;const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];if(!coordinatorLockHeld){for(const sessionId of uniqueSessionIds){coordinator.assertNotTransitioning(sessionId)}}const results=await Promise.all(uniqueSessionIds.map(async sessionId=>{try{const mutateSession=__name(async()=>{assertCanMutate?.();const initialLocation=await classifySessionLocation(service,sessionId);if(initialLocation===void 0){return{kind:"notFound",mutationApplied:false}}if(initialLocation==="conflict"&&!resolveConflicts){return{kind:"error",error:sessionLocationError(sessionId),mutationApplied:false}}const mutation=await runWithDaemonWriterLease({action:"unarchive",sessionId,service,mutate:__name(async(assertOwnedAndUnchanged,assertCleanupOwned)=>{const lockedLocation=await classifySessionLocation(service,sessionId);if(lockedLocation===void 0){return{value:"notFound",mutationApplied:false}}if(lockedLocation==="conflict"&&!resolveConflicts){throw sessionLocationError(sessionId)}const result=await service.unarchiveSessions([sessionId],{resolveConflicts,assertStorageUnchanged:assertOwnedAndUnchanged,assertCanMutate,assertCleanupOwned});if(result.errors[0])throw result.errors[0].error;if(result.unarchived.length>0){return{value:result.resolvedConflicts.length?"resolvedConflict":"unarchived",mutationApplied:true}}return{value:result.alreadyActive.length>0?"alreadyActive":"notFound",mutationApplied:false}},"mutate"),mutationAppliedAfterError:__name(async()=>await classifySessionLocation(service,sessionId)==="active","mutationAppliedAfterError"),afterMutationApplied:__name(async()=>{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"unarchive",assertCanMutate)},"afterMutationApplied")});if(mutation.error!==void 0){return{kind:"error",error:mutation.error,mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}let maintenanceError=mutation.maintenanceError;if(mutation.value==="alreadyActive"){try{await updateScheduledTaskForMaintenance(service,sessionId,"unarchive",assertCanMutate)}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=unarchive workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}}return{kind:mutation.value??"notFound",mutationApplied:mutation.mutationApplied,maintenanceError}},"mutateSession");return await(coordinatorLockHeld?mutateSession():coordinator.runExclusiveMany([sessionId],mutateSession))}catch(error){if(error instanceof DaemonDrainingError){throw error}return{kind:"error",error,mutationApplied:false,maintenanceError:void 0}}}));const unarchived=[];const alreadyActive=[];const resolvedConflicts=[];const notFound=[];const errors=[];for(let i=0;i<results.length;i++){const sessionId=uniqueSessionIds[i];const result=results[i];if(result.kind==="unarchived")unarchived.push(sessionId);else if(result.kind==="resolvedConflict"){unarchived.push(sessionId);resolvedConflicts.push(sessionId)}else if(result.kind==="alreadyActive")alreadyActive.push(sessionId);else if(result.kind==="notFound")notFound.push(sessionId);else errors.push({sessionId,error:result.error});if(result.maintenanceError!==void 0){errors.push({sessionId,error:result.maintenanceError})}}logSessionArchiveResult("unarchive",{requested:uniqueSessionIds,changed:unarchived,already:alreadyActive,notFound,errors});return{unarchived,alreadyActive,resolvedConflicts,notFound,errors}}__name(unarchiveDaemonSessions,"unarchiveDaemonSessions");init_esbuild_shims();import{execFile}from"node:child_process";import{promisify}from"node:util";var execFileAsync=promisify(execFile);var a1AvailabilityVerified=false;var defaultA1Exec=__name(async(args,options)=>{const{stdout}=await execFileAsync("a1",[...args],{...options,encoding:"utf8",windowsHide:true});return{stdout}},"defaultA1Exec");var a1Exec=defaultA1Exec;var A1_TIMEOUT_MS=2e4;var A1_MAX_BUFFER=16*1024*1024;var GIT_ORIGIN_TIMEOUT_MS=5e3;var A1_VERSION_TIMEOUT_MS=1e4;var A1_ERROR_MESSAGE_MAX=512;var AONE_DETAIL_URL_HOST="code.alibaba-inc.com";var AONE_MAX_MR_VIEW_CALLS_PER_RUN=25;var AoneCliUnavailableError=class extends Error{static{__name(this,"AoneCliUnavailableError")}};var AoneCommandError=class extends Error{static{__name(this,"AoneCommandError")}};function mapAoneMrState(raw){switch(raw?.toLowerCase()){case"merged":return"merged";case"closed":return"closed";default:return"open"}}__name(mapAoneMrState,"mapAoneMrState");async function resolveAoneWorkspaceRepo(workspaceCwd,env){const gitRoot=findGitRoot(workspaceCwd);if(!gitRoot)return void 0;let origin;try{({stdout:origin}=await execFileAsync("git",["remote","get-url","origin"],{cwd:gitRoot,timeout:GIT_ORIGIN_TIMEOUT_MS,encoding:"utf8",windowsHide:true,env:gitEnv(env)}))}catch{return void 0}const identity=parseRemoteUrl(origin.trim());if(!identity||!isAoneCanonicalHost(identity.host))return void 0;return{gitRoot,repoPath:identity.groupPath}}__name(resolveAoneWorkspaceRepo,"resolveAoneWorkspaceRepo");function isAoneDetailUrlForRepo(repoPath,number,url){return canonicalSessionPrUrl(url)===canonicalSessionPrUrl(`https://${AONE_DETAIL_URL_HOST}/${repoPath}/codereview/${number}`)}__name(isAoneDetailUrlForRepo,"isAoneDetailUrlForRepo");function isA1ErrorObject(value){return typeof value==="object"&&value!==null&&value["schemaVersion"]==="a1.error/v1"}__name(isA1ErrorObject,"isA1ErrorObject");function a1ErrorMessage(error){if(error?.killed===true){return`a1 timed out after ${A1_TIMEOUT_MS/1e3}s`}const stderr=error?.stderr;const raw=typeof stderr==="string"&&stderr.trim()?stderr:error instanceof Error?error.message:String(error);return raw.replace(/\s+/g," ").trim().slice(0,A1_ERROR_MESSAGE_MAX)}__name(a1ErrorMessage,"a1ErrorMessage");function assertA1Version(stdout){const triple=parseA1Version(stdout);const floor=parseA1Version(A1_MIN_VERSION);if(triple&&floor&&!a1VersionAtLeast(triple,floor)){throw new AoneCliUnavailableError(`a1 ${A1_MIN_VERSION}+ is required (found ${stdout.trim().split("\n")[0]}); upgrade from https://code.alibaba-inc.com/aone/a1`)}}__name(assertA1Version,"assertA1Version");async function runA1Json(args){let stdout;try{({stdout}=await a1Exec([...args,"--format","json"],{timeout:A1_TIMEOUT_MS,maxBuffer:A1_MAX_BUFFER}))}catch(error){if(error.code==="ENOENT"){throw new AoneCliUnavailableError("a1 CLI not installed; install it and run `a1 auth login`")}const errorStdout=error?.stdout;if(typeof errorStdout==="string"&&errorStdout.trim()){try{const parsed2=JSON.parse(errorStdout);if(isA1ErrorObject(parsed2)){throw new AoneCommandError(parsed2.message||"a1 command failed")}}catch(parseError){if(parseError instanceof AoneCommandError)throw parseError}}throw new AoneCommandError(a1ErrorMessage(error))}let parsed;try{parsed=JSON.parse(stdout)}catch{throw new AoneCommandError("a1 returned non-JSON output")}if(isA1ErrorObject(parsed)){throw new AoneCommandError(parsed.message||"a1 command failed")}return parsed}__name(runA1Json,"runA1Json");async function checkA1Available(){if(a1AvailabilityVerified)return;let stdout;try{({stdout}=await a1Exec(["--version"],{timeout:A1_VERSION_TIMEOUT_MS}))}catch(error){if(error.code==="ENOENT"){throw new AoneCliUnavailableError("a1 CLI not installed; install it and run `a1 auth login`")}return}assertA1Version(stdout);a1AvailabilityVerified=true}__name(checkA1Available,"checkA1Available");function hasControlCharacter(value){return Array.from(value).some(character=>{const code=character.charCodeAt(0);return code<=31||code===127})}__name(hasControlCharacter,"hasControlCharacter");function parseAoneMrView(raw,id){const mr=raw!==null&&typeof raw==="object"?raw["mergeRequest"]:void 0;if(mr===null||typeof mr!=="object"){throw new AoneCommandError("unexpected a1 mr view output")}const v=mr;const url=typeof v["detailUrl"]==="string"?v["detailUrl"]:"";if(!/^https?:\/\//i.test(url)){throw new AoneCommandError("a1 mr view returned no detailUrl")}if(url.length>SESSION_PR_URL_MAX_LENGTH){throw new AoneCommandError("a1 mr view returned an oversized detailUrl")}if(hasControlCharacter(url)){throw new AoneCommandError("a1 mr view returned a malformed detailUrl")}return{number:id,url,state:mapAoneMrState(typeof v["state"]==="string"?v["state"]:void 0)}}__name(parseAoneMrView,"parseAoneMrView");async function viewAoneMergeRequest(repoPath,id){await checkA1Available();const parsed=await runA1Json(["repo","mr","view",String(id),"--repo",repoPath]);return parseAoneMrView(parsed,id)}__name(viewAoneMergeRequest,"viewAoneMergeRequest");var defaultAoneMrBackend={view:viewAoneMergeRequest};init_esbuild_shims();import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";var execFileAsync2=promisify2(execFile2);var GIT_TIMEOUT_MS=1e4;async function cloneWorktreesOf(cwd){const opts={timeout:GIT_TIMEOUT_MS,windowsHide:true,env:{...sanitizedGitEnv(),GIT_TERMINAL_PROMPT:"0"}};try{const{stdout}=await execFileAsync2("git",["-C",cwd,"worktree","list","--porcelain","-z"],opts);return parseWorktreePaths(stdout)}catch{try{const{stdout}=await execFileAsync2("git",["-C",cwd,"worktree","list","--porcelain"],opts);const first=stdout.split("\n").find(line=>line.startsWith("worktree "));return first?[first.slice("worktree ".length).replace(/\r$/,"")]:[]}catch{return[]}}}__name(cloneWorktreesOf,"cloneWorktreesOf");async function listAutofixPrWatches(cwd,assertGenerationOpen){assertGenerationOpen?.();const worktrees=await cloneWorktreesOf(cwd);assertGenerationOpen?.();if(worktrees.length===0)return{v:1,available:false,watches:[]};const root=worktrees[0];const outcome=runStatus({roots:worktrees,git:false,session:null});const redactError=__name(error=>{let redacted=error;for(const worktree of worktrees){redacted=redacted.split(worktree).join("<worktree>")}return redacted.replace(/autofix-pr-\d+-state\.json/g,"<state-file>")},"redactError");return{v:1,available:true,root,now:outcome.now,watches:outcome.watches.map(({thisSession:_session,worktreePath:_path,gitTrusted:_trusted,worktreeWork:_work,pushTarget:_target,...watch})=>watch),...outcome.unreadable?{unreadable:outcome.unreadable.map(({pr,error})=>({pr,error:redactError(error)}))}:{}}}__name(listAutofixPrWatches,"listAutofixPrWatches");async function respond(res,cwd,assertGenerationOpen){applyReadHeaders(res);try{res.status(200).json(await listAutofixPrWatches(cwd,assertGenerationOpen))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`autofix-pr watches of ${cwd}: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Could not read the autofix-pr watches of this workspace",code:"autofix_pr_watches_failed"})}}__name(respond,"respond");function registerAutofixPrWatchesRoutes(app,deps){app.get("/autofix-pr/watches",async(_req,res)=>{if(deps.isWorkspaceTrusted&&!deps.isWorkspaceTrusted()){sendUntrustedWorkspaceResponse(res);return}await respond(res,deps.boundWorkspace,deps.captureGenerationAssertion?.())})}__name(registerAutofixPrWatchesRoutes,"registerAutofixPrWatchesRoutes");function registerWorkspaceQualifiedAutofixPrWatchesRoutes(app,deps){app.get("/workspaces/:workspace/autofix-pr/watches",async(req,res)=>{const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return;if(!requireTrustedWorkspaceRuntime(runtime,res))return;await respond(res,runtime.workspaceCwd,()=>runtime.generationGuard?.assertOpen())})}__name(registerWorkspaceQualifiedAutofixPrWatchesRoutes,"registerWorkspaceQualifiedAutofixPrWatchesRoutes");init_esbuild_shims();import{stat}from"node:fs/promises";import{dirname as dirname3,join as join3}from"node:path";init_esbuild_shims();function prWatchKey(url,pr){const repoKey=repoKeyFromWebUrl(url);return repoKey===void 0?void 0:`${repoKey}#${pr}`}__name(prWatchKey,"prWatchKey");function shellWords(input){const words=[];let current="";let started=false;let i=0;const push=__name(()=>{if(started)words.push(current);current="";started=false},"push");while(i<input.length){const ch=input[i];if(ch==="'"){started=true;i+=1;while(i<input.length&&input[i]!=="'"){current+=input[i];i+=1}if(i>=input.length)return void 0;i+=1;continue}if(ch==='"'){started=true;i+=1;while(i<input.length&&input[i]!=='"'){const c=input[i];if(c==="\\"){const next=input[i+1];if(next===void 0)return void 0;if(next==="\n"){i+=2;continue}if('$`"\\'.includes(next)){current+=next;i+=2;continue}current+=c;i+=1;continue}if(c==="$"||c==="`")return void 0;current+=c;i+=1}if(i>=input.length)return void 0;i+=1;continue}if(ch==="\\"){const next=input[i+1];if(next===void 0)return void 0;if(next==="\n"){i+=2;continue}started=true;current+=next;i+=2;continue}if(ch==="$"||ch==="`")return void 0;if("*?[]{}".includes(ch))return void 0;if(";|&><()".includes(ch)||ch==="\n")return void 0;if(ch==="#"&&!started)return words;if(ch===" "||ch===" "){push();i+=1;continue}started=true;current+=ch;i+=1}push();return words}__name(shellWords,"shellWords");function parseVerifyPrWatchGate(gate){const SCRIPT="verify-pr-watch-gate.mjs";if(!gate)return{kind:"none"};const tokens=shellWords(gate);if(tokens===void 0){return gate.includes(SCRIPT)?{kind:"unknown"}:{kind:"none"}}const isScriptWord=__name(token=>token===SCRIPT||token.endsWith(`/${SCRIPT}`),"isScriptWord");let commandIndex=0;while(commandIndex<tokens.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[commandIndex])){commandIndex+=1}const command=tokens[commandIndex];let scriptIndex=-1;if(command!==void 0&&isScriptWord(command)){scriptIndex=commandIndex}else if(command!==void 0&&(command==="node"||command==="node.exe"||command.endsWith("/node"))&&tokens[commandIndex+1]!==void 0&&isScriptWord(tokens[commandIndex+1])){scriptIndex=commandIndex+1}if(scriptIndex===-1){return tokens.some(token=>token.includes(SCRIPT))?{kind:"unknown"}:{kind:"none"}}let pr;let repo;for(let i=scriptIndex+1;i<tokens.length;i++){const token=tokens[i];if(token==="--check"||token==="--claim"||token==="--release"){return{kind:"none"}}if(token==="--repo"||token==="--cli"||token==="--state-root"){const value=tokens[++i];if(token==="--repo")repo=value;continue}if(!token.startsWith("-")&&pr===void 0){const value=Number(token);if(!Number.isInteger(value)||value<=0)return{kind:"none"};pr=value}}if(pr===void 0)return{kind:"none"};if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)){return{kind:"none"}}return{kind:"watch",repo,pr}}__name(parseVerifyPrWatchGate,"parseVerifyPrWatchGate");async function collectActivePrWatches(workspaceCwd){const watches=new Map;const add=__name((sessionId,key)=>{let set=watches.get(sessionId);if(!set){set=new Set;watches.set(sessionId,set)}set.add(key)},"add");try{const listing=await listAutofixPrWatches(workspaceCwd);if(!listing.available||listing.unreadable!==void 0&&listing.unreadable.length>0){return void 0}for(const watch of listing.watches){if(watch.session&&watch.stopped===null&&watch.ended===null){const key=prWatchKey(watch.url,watch.pr);if(key!==void 0)add(watch.session,key)}}}catch{return void 0}try{const tasks=await readCronTasks(workspaceCwd);let remoteHost;let remoteResolved=false;for(const task of tasks){if(task.enabled===false||!task.recurring||!task.sessionId){continue}const parsed=parseVerifyPrWatchGate(task.gate);if(parsed.kind==="unknown")return void 0;if(parsed.kind==="watch"){if(!remoteResolved){const remoteUrl=await fetchRemoteWebUrl(workspaceCwd);remoteHost=remoteUrl===void 0?void 0:repoKeyFromWebUrl(remoteUrl)?.split("/")[0];remoteResolved=true}if(remoteHost===void 0)return void 0;const key=prWatchKey(`https://${remoteHost}/${parsed.repo}/pull/${parsed.pr}`,parsed.pr);if(key!==void 0)add(task.sessionId,key)}}}catch{return void 0}return watches}__name(collectActivePrWatches,"collectActivePrWatches");function validTimestamp(value){return value!==void 0&&!Number.isNaN(Date.parse(value))?value:void 0}__name(validTimestamp,"validTimestamp");function projectPrs(prs){return prs.map(pr=>({number:pr.number,url:pr.url,...pr.state!==void 0?{state:pr.state}:{},...pr.role!==void 0?{role:pr.role}:{}}))}__name(projectPrs,"projectPrs");async function resolveAttribution(sessionService,sessionId,prPath,liveSummary){const item=await sessionService.getSessionListItem(sessionId,"active");const sourceType=item?.sourceType??liveSummary?.sourceType;if(isHiddenCatalogSource(sourceType))return{kind:"hidden"};if(item===void 0){let stats;try{stats=await stat(join3(dirname3(prPath),`${sessionId}.jsonl`))}catch(err){if(err.code!=="ENOENT")throw err}if(stats!==void 0&&(!stats.isFile()||stats.size>0)){return{kind:"unreadable"}}if(stats===void 0&&liveSummary===void 0&&await sessionService.getSessionListItem(sessionId,"archived")!==void 0){return{kind:"archived"}}}const liveActivity=validTimestamp(liveSummary?.updatedAt)??(item===void 0?validTimestamp(liveSummary?.createdAt):void 0);const updatedAt=laterActivityTimestamp(liveActivity,item?new Date(item.mtime).toISOString():void 0);return{kind:"ok",...sourceType!==void 0?{sourceType}:{},...updatedAt!==void 0?{updatedAt}:{}}}__name(resolveAttribution,"resolveAttribution");async function scanWorkspaceBindings(runtime,out){const sessionService=createWorkspaceRuntimeSessionService(runtime);const sessionIds=sessionService.listSessionIdsWithPrSidecar("active");let live=new Map;let liveReadFailed=false;try{live=new Map(runtime.bridge.listWorkspaceSessions(runtime.workspaceCwd).map(summary=>[summary.sessionId,summary]))}catch(err){liveReadFailed=true;process.stderr.write(`[serve] PR bindings scan: live session list unavailable in workspace ${runtime.workspaceCwd}, live-only bindings may be missing from this answer (partial): ${sanitizeLogText(err instanceof Error?err.message:String(err),200)}
3
+ import{classifyTopLevelConversationSource}from"./chunk-7M5JT3ID.js";import{A1_MIN_VERSION,a1VersionAtLeast,parseA1Version}from"./chunk-U3ZLJQMS.js";import{parseWorktreePaths,runStatus}from"./chunk-NL62UQDW.js";import{isAoneCanonicalHost,parseRemoteUrl}from"./chunk-F2L3WXJO.js";import{sanitizedGitEnv}from"./chunk-7GYFDPEP.js";import{PathMutexRegistry}from"./chunk-TCKM7S2Z.js";import{createSessionOrganizationService}from"./chunk-P5RBFVMP.js";import{HIDDEN_CATALOG_SOURCE_TYPES,isHiddenCatalogSource}from"./chunk-DHYCGKLG.js";import{safeLogValue}from"./chunk-SVGTUGV2.js";import{createWorkspaceRuntimeSessionService,getWorkspaceRouteContext,requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeFromParam,sendGenerationClosedError,sendUntrustedWorkspaceResponse,setWorkspaceRouteContext}from"./chunk-ZF56DRDP.js";import{normalizeSessionIdForLookup,parseCallerSuppliedSessionId}from"./chunk-LGFF5PJA.js";import{EVENT_SCHEMA_VERSION}from"./chunk-OFWAMIMB.js";import{SessionArchivedError,SessionArchivingError,SessionConflictError,SessionNotArchivedError,SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{canonicalizeWorkspace,canonicalizeWorkspaces}from"./chunk-L5UULTGF.js";import{sanitizeLogText}from"./chunk-6WGM7K6B.js";import{loadIgnoreRules}from"./chunk-CXPRHT3E.js";import{readWorktreeSession,readWorktreeSessionStrict}from"./chunk-NGQDWVC6.js";import{GROUP_COLOR_OPTIONS,SESSION_PR_LIST_LIMIT,SESSION_PR_URL_MAX_LENGTH,SessionIdCaseConflictError,SessionOrganizationError,SessionService,SessionTranscriptChangedError,SessionWriterUnavailableError,StandardFileSystemService,canonicalSessionPrUrl,detectLineEnding,encodeTextFileContentAsync,fetchRemoteWebUrl,readSessionPrsDetailed,repoKeyFromWebUrl,toSessionPrInfo}from"./chunk-3NR3JBMA.js";import{cronTaskSessionDeletionId,getCronFilePath,readCronTasks,updateCronTasks}from"./chunk-DXUYBMFK.js";import{GitWorktreeService,gitEnv,readWorktreeSessionMarker,readWorktreeSessionMarkerStrict,worktreeHasWork}from"./chunk-B4ZATWBT.js";import{glob}from"./chunk-OBOU4ZZM.js";import{findGitRoot}from"./chunk-744VRMDB.js";import{CursorNotAtLineBoundaryError,LargeNonUtf8TextError,TextScanBudgetExceededError,decodeBufferWithEncodingInfoAsync,isUtf8CompatibleEncoding,isWithinRoot}from"./chunk-TQGZS3WN.js";import{addDaemonRequestAttribute}from"./chunk-ZBWKMYJX.js";import{LOG_LINE_UNSAFE_RE,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*as path5 from"node:path";init_esbuild_shims();init_esbuild_shims();import{promises as fsp}from"node:fs";import*as path from"node:path";init_esbuild_shims();var DEFAULT_STATUS_BY_KIND={path_outside_workspace:400,symlink_escape:400,path_not_found:404,binary_file:422,file_too_large:413,hash_mismatch:409,file_already_exists:409,text_not_found:422,ambiguous_text_match:422,untrusted_workspace:403,permission_denied:403,io_error:503,internal_error:500,parse_error:400};var FsError=class extends Error{static{__name(this,"FsError")}kind;status;hint;constructor(kind,message,options){super(message,options?.cause===void 0?void 0:{cause:options.cause});this.name="FsError";this.kind=kind;this.status=options?.status??DEFAULT_STATUS_BY_KIND[kind];this.hint=options?.hint}};function isFsError(err){return err instanceof FsError}__name(isFsError,"isFsError");function wrapAsFsError(err,fallbackKind="internal_error"){if(err instanceof FsError)return err;const errno=err?.code;const message=err instanceof Error?err.message:"unknown filesystem error";switch(errno){case"ENOENT":return new FsError("path_not_found",message,{cause:err});case"EACCES":case"EPERM":return new FsError("permission_denied",message,{cause:err});case"ELOOP":return new FsError("symlink_escape",message,{cause:err,hint:"symlink chain forms a cycle or exceeds SYMLOOP_MAX"});case"EISDIR":return new FsError("parse_error",message,{cause:err,hint:"EISDIR \u2014 path is a directory but a regular file was expected"});case"ENOTDIR":return new FsError("parse_error",message,{cause:err,hint:"ENOTDIR \u2014 a path component is a regular file but a directory was expected"});case"ENOSPC":return new FsError("io_error",message,{cause:err,hint:"filesystem is full (df -h reporting 100%)"});case"EIO":return new FsError("io_error",message,{cause:err,hint:"underlying I/O error (failing disk or kernel-level fault)"});case"EBUSY":case"ETXTBSY":return new FsError("io_error",message,{cause:err,hint:"file is busy; another process holds an exclusive handle"});case"ENAMETOOLONG":return new FsError("io_error",message,{cause:err,hint:"path exceeds the OS PATH_MAX"});case"EMFILE":case"ENFILE":return new FsError("io_error",message,{cause:err,hint:"too many open files; daemon is at file-descriptor limit"});default:return new FsError(fallbackKind,message,{cause:err})}}__name(wrapAsFsError,"wrapAsFsError");var ENOENT_TOLERATING_INTENTS=new Set(["write","stat"]);function hasSuspiciousPathPattern(p){if(process.platform==="win32"){const colonIndex=p.indexOf(":",2);if(colonIndex!==-1)return true}if(process.platform==="win32"&&/~\d+/.test(p))return true;if(p.startsWith("\\\\?\\")||p.startsWith("\\\\.\\")||p.startsWith("//?/")||p.startsWith("//./")){return true}if(p.startsWith("\\\\")&&p.length>2&&p[2]!=="\\"||p.startsWith("//")&&p.length>2&&p[2]!=="/"){return true}if(/(^|\/|\\)\.{3,}(\/|\\|$)/.test(p))return true;for(const seg of p.split(/[\\/]/)){if(seg===""||seg==="."||seg==="..")continue;if(/[.\s]+$/.test(seg))return true;if(/(^|\.)(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i.test(seg)){return true}}return false}__name(hasSuspiciousPathPattern,"hasSuspiciousPathPattern");var MAX_ANCESTOR_HOPS=40;var CANONICAL_BOUND_CACHE=new Map;function canonicalizeBoundWorkspaceCached(boundWorkspace){const cached=CANONICAL_BOUND_CACHE.get(boundWorkspace);if(cached!==void 0)return cached;const canonical=canonicalizeWorkspace(boundWorkspace);CANONICAL_BOUND_CACHE.set(boundWorkspace,canonical);return canonical}__name(canonicalizeBoundWorkspaceCached,"canonicalizeBoundWorkspaceCached");function canonicalizeBoundWorkspacesCached(boundWorkspaces){const inputs=typeof boundWorkspaces==="string"?[boundWorkspaces]:boundWorkspaces;if(inputs.length===0){throw new FsError("parse_error","boundWorkspaces must include at least one workspace root")}const out=[];const seen=new Set;for(const workspace of inputs){const canonical=canonicalizeBoundWorkspaceCached(workspace);if(seen.has(canonical))continue;seen.add(canonical);out.push(canonical)}return out}__name(canonicalizeBoundWorkspacesCached,"canonicalizeBoundWorkspacesCached");function findContainingWorkspace(absolute,boundWorkspaces){let match;for(const workspace of boundWorkspaces){if(isWithinRoot(absolute,workspace)&&(match===void 0||workspace.length>match.length)){match=workspace}}return match}__name(findContainingWorkspace,"findContainingWorkspace");async function findExistingAncestor(absolute){let current=absolute;const tailParts=[];for(let i=0;i<MAX_ANCESTOR_HOPS;i++){let stat2=null;try{stat2=await fsp.stat(current)}catch(err){const code=err?.code;if(code==="ENOENT"||code==="ENOTDIR"){}else{throw err}}if(stat2){if(tailParts.length>0&&!stat2.isDirectory()){throw new FsError("parse_error",`path component is not a directory: ${absolute}`,{hint:"a non-directory file occupies a path segment"})}return{ancestor:current,tail:tailParts.join(path.sep)}}const parent=path.dirname(current);if(parent===current){throw new FsError("path_not_found",`no existing ancestor for ${absolute}`)}tailParts.unshift(path.basename(current));current=parent}throw new FsError("path_not_found",`path traversal exceeded ${MAX_ANCESTOR_HOPS} hops while finding ancestor`,{hint:"path is too deeply nested or filesystem is responding unexpectedly"})}__name(findExistingAncestor,"findExistingAncestor");async function resolveWithinWorkspace(input,boundWorkspaces,intent){if(typeof input!=="string"||input.length===0){throw new FsError("parse_error","path must be a non-empty string")}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace",`path contains suspicious pattern: ${input}`,{hint:"paths with NTFS ADS, 8.3 short names, UNC prefixes, or trailing dots are rejected outright"})}const boundCanonicals=canonicalizeBoundWorkspacesCached(boundWorkspaces);const primary=boundCanonicals[0];if(primary===void 0){throw new FsError("parse_error","boundWorkspaces must include at least one workspace root")}const absolute=path.resolve(primary,input);let boundCanonical=findContainingWorkspace(absolute,boundCanonicals);let preResolvedCanonical;if(boundCanonical===void 0&&path.isAbsolute(input)){try{preResolvedCanonical=await fsp.realpath(absolute);boundCanonical=findContainingWorkspace(preResolvedCanonical,boundCanonicals)}catch(err){const code=err?.code;if(code==="ENOENT"||code==="ENOTDIR"){try{const{ancestor,tail}=await findExistingAncestor(absolute);const ancestorReal=await fsp.realpath(ancestor);const canonicalCandidate=tail?path.join(ancestorReal,tail):ancestorReal;boundCanonical=findContainingWorkspace(canonicalCandidate,boundCanonicals);if(boundCanonical!==void 0){const finalPathIsSymlink=await fsp.lstat(absolute).then(stat2=>stat2.isSymbolicLink()).catch(lstatErr=>{if(lstatErr.code==="ENOENT"||lstatErr.code==="ENOTDIR"){return false}throw lstatErr});if(!finalPathIsSymlink&&ENOENT_TOLERATING_INTENTS.has(intent)){preResolvedCanonical=canonicalCandidate}}}catch(innerErr){const innerCode=innerErr?.code;if(innerCode!=="ENOENT"&&innerCode!=="ENOTDIR"){throw innerErr}}}else{throw err}}}if(boundCanonical===void 0){throw new FsError("path_outside_workspace",`path escapes workspace: ${input}`)}let canonical;try{canonical=preResolvedCanonical??await fsp.realpath(absolute)}catch(err){const code=err?.code;if(code==="ENOENT"&&ENOENT_TOLERATING_INTENTS.has(intent)){let symlinkResolvedCanonical=null;try{let cursor=absolute;const visitedInodes=new Set;let firstHopTarget=null;let resolvedFully=false;for(let hop=0;hop<MAX_ANCESTOR_HOPS;hop++){let linkStat;try{linkStat=await fsp.lstat(cursor)}catch(lstatErr){const lcode=lstatErr?.code;if(lcode==="ENOENT"||lcode==="ENOTDIR"){resolvedFully=true;break}throw lstatErr}if(!linkStat.isSymbolicLink()){resolvedFully=true;break}const ino=typeof linkStat.ino==="bigint"?linkStat.ino:BigInt(linkStat.ino);if(ino!==0n&&visitedInodes.has(ino)){throw new FsError("symlink_escape",`symlink cycle detected at ${cursor}`,{hint:"symlink loops back onto a previously visited inode"})}if(ino!==0n)visitedInodes.add(ino);const target=await fsp.readlink(cursor);const absTarget=path.isAbsolute(target)?target:path.resolve(path.dirname(cursor),target);if(firstHopTarget===null)firstHopTarget=target;cursor=absTarget}if(!resolvedFully){throw new FsError("symlink_escape",`symlink chain exceeded ${MAX_ANCESTOR_HOPS} hops for ${input}`,{hint:"symlink chain is too long or contains a cycle"})}if(firstHopTarget!==null){const{ancestor:targetAncestor,tail:targetTail}=await findExistingAncestor(cursor);const targetAncestorReal=await fsp.realpath(targetAncestor);const canonicalTarget=targetTail?path.join(targetAncestorReal,targetTail):targetAncestorReal;if(!boundCanonicals.some(root=>isWithinRoot(canonicalTarget,root))){throw new FsError("symlink_escape",`dangling symlink target escapes workspace: ${input}`,{hint:"symlink chain leaves the workspace; enable QWEN_AUDIT_RAW_PATHS for the resolved target"})}symlinkResolvedCanonical=canonicalTarget}}catch(err2){if(err2 instanceof FsError)throw err2;const code2=err2?.code;if(code2!=="ENOENT")throw err2}if(symlinkResolvedCanonical!==null){canonical=symlinkResolvedCanonical}else{const{ancestor,tail}=await findExistingAncestor(absolute);const ancestorReal=await fsp.realpath(ancestor);canonical=tail?path.join(ancestorReal,tail):ancestorReal}}else if(code==="ENOENT"){throw new FsError("path_not_found",`path does not exist: ${input}`,{cause:err})}else if(code==="ELOOP"){throw new FsError("symlink_escape",`symlink loop or chain too long for ${input}`,{cause:err,hint:"a symlink in the path forms a cycle or exceeds SYMLOOP_MAX"})}else if(code==="EACCES"){throw new FsError("permission_denied",`permission denied resolving ${input}`,{cause:err})}else{throw err}}if(!boundCanonicals.some(root=>isWithinRoot(canonical,root))){const kind=canonical!==absolute?"symlink_escape":"path_outside_workspace";throw new FsError(kind,kind==="symlink_escape"?`symlink resolves outside workspace: ${input}`:`path escapes workspace: ${input}`)}return canonical}__name(resolveWithinWorkspace,"resolveWithinWorkspace");init_esbuild_shims();import*as path2 from"node:path";var MAX_READ_BYTES=256*1024;var MAX_TEXT_SCAN_BYTES=8*1024*1024;var MAX_WRITE_BYTES=5*1024*1024;var MAX_UPLOAD_BYTES=50*1024*1024;var BINARY_PROBE_BYTES=4096;function shouldIgnore(absolute,boundWorkspace,ignore,kind="file"){const rel=path2.relative(boundWorkspace,absolute);if(rel===""||rel.startsWith(".."))return{ignored:false};const fileFilter=ignore.getFileFilter();const dirFilter=ignore.getDirectoryFilter();if(kind==="directory"){const withSlash=rel.endsWith("/")?rel:`${rel}/`;if(dirFilter(withSlash))return{ignored:true,category:"directory"};if(fileFilter(rel))return{ignored:true,category:"file"};return{ignored:false}}if(fileFilter(rel))return{ignored:true,category:"file"};if(dirFilter(rel))return{ignored:true,category:"directory"};return{ignored:false}}__name(shouldIgnore,"shouldIgnore");function assertTrustedForIntent(trusted,intent){if(trusted)return;switch(intent){case"read":case"list":case"glob":case"stat":return;case"write":case"edit":case"delete":throw new FsError("untrusted_workspace",`workspace is not trusted; ${intent} operations are forbidden`,{hint:"mark the folder as trusted in the daemon configuration to allow writes"});default:{const _exhaustive=intent;throw new FsError("untrusted_workspace",`workspace is not trusted; intent "${String(_exhaustive)}" is not classified`,{hint:"unknown intent reached the trust gate; classify it in policy.ts"})}}}__name(assertTrustedForIntent,"assertTrustedForIntent");function enforceReadSize(fileBytes,maxBytes=MAX_READ_BYTES){if(fileBytes<=maxBytes){return{bytesToRead:fileBytes,truncated:false}}return{bytesToRead:maxBytes,truncated:true}}__name(enforceReadSize,"enforceReadSize");function enforceWriteSize(bytes,maxBytes=MAX_WRITE_BYTES){if(bytes>maxBytes){throw new FsError("file_too_large",`payload of ${bytes} bytes exceeds write limit of ${maxBytes} bytes`,{hint:"split the write into smaller chunks or raise the daemon limit"})}}__name(enforceWriteSize,"enforceWriteSize");init_esbuild_shims();import{createHash}from"node:crypto";import*as path3 from"node:path";var FS_ACCESS_EVENT_TYPE="fs.access";var FS_DENIED_EVENT_TYPE="fs.denied";function hashPath(absolute){return createHash("sha256").update(absolute).digest("hex").slice(0,16)}__name(hashPath,"hashPath");var CROSS_DRIVE_RELPATH="<cross-drive>";function relForAudit(raw,boundWorkspace){const rel=path3.isAbsolute(raw)?path3.relative(boundWorkspace,raw):raw;return path3.isAbsolute(rel)?CROSS_DRIVE_RELPATH:rel}__name(relForAudit,"relForAudit");function rawPathsEnabled(){return process.env["QWEN_AUDIT_RAW_PATHS"]==="1"}__name(rawPathsEnabled,"rawPathsEnabled");function createAuditPublisher(deps){const includeRawPaths=deps.includeRawPaths??rawPathsEnabled();const{emit,boundWorkspace}=deps;return{recordAccess(ctx,record){const absolute=String(record.absolute);const payload={kind:FS_ACCESS_EVENT_TYPE,intent:record.intent,route:ctx.route,pathHash:hashPath(absolute),durationMs:record.durationMs};if(ctx.sessionId)payload.sessionId=ctx.sessionId;if(record.sizeBytes!==void 0)payload.sizeBytes=record.sizeBytes;if(record.truncated)payload.truncated=true;if(record.matchedIgnore)payload.matchedIgnore=record.matchedIgnore;if(record.operation!==void 0)payload.operation=record.operation;if(record.pattern!==void 0&&includeRawPaths){payload.pattern=record.pattern}if(includeRawPaths){payload.relPath=relForAudit(absolute,boundWorkspace)}emit({v:EVENT_SCHEMA_VERSION,type:FS_ACCESS_EVENT_TYPE,data:payload,originatorClientId:ctx.originatorClientId})},recordDenied(ctx,record){const probe=path3.isAbsolute(record.input)?record.input:path3.resolve(boundWorkspace,record.input);const payload={kind:FS_DENIED_EVENT_TYPE,intent:record.intent,route:ctx.route,pathHash:hashPath(probe),errorKind:record.errorKind};if(ctx.sessionId)payload.sessionId=ctx.sessionId;if(record.hint)payload.hint=record.hint;if(record.message&&includeRawPaths){payload.message=record.message}if(record.pattern!==void 0&&includeRawPaths){payload.pattern=record.pattern}if(includeRawPaths){payload.relPath=relForAudit(record.input,boundWorkspace)}emit({v:EVENT_SCHEMA_VERSION,type:FS_DENIED_EVENT_TYPE,data:payload,originatorClientId:ctx.originatorClientId})}}}__name(createAuditPublisher,"createAuditPublisher");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import{constants as fsConstants,promises as fsp2}from"node:fs";import*as path4 from"node:path";init_esbuild_shims();var CURSOR_VERSION=1;var MAX_TEXT_CURSOR_CHARS=1024;function encodeTextCursor(state){return Buffer.from(JSON.stringify({v:CURSOR_VERSION,...state}),"utf8").toString("base64url")}__name(encodeTextCursor,"encodeTextCursor");function decodeTextCursor(cursor){if(cursor.length===0||cursor.length>MAX_TEXT_CURSOR_CHARS){throw new FsError("parse_error",`cursor must be a non-empty string of at most ${MAX_TEXT_CURSOR_CHARS} characters`,{hint:"pass a cursor returned by a previous read"})}let parsed;try{parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"))}catch{throw new FsError("parse_error","cursor is not a valid read cursor",{hint:"pass a cursor returned by a previous read"})}if(typeof parsed!=="object"||parsed===null){throw new FsError("parse_error","cursor is not a valid read cursor",{hint:"pass a cursor returned by a previous read"})}const raw=parsed;const off=raw["off"];const size=raw["size"];const dev=raw["dev"];const ino=raw["ino"];if(raw["v"]!==CURSOR_VERSION||!Number.isSafeInteger(off)||off<0||!Number.isSafeInteger(size)||size<0||typeof dev!=="string"||typeof ino!=="string"){throw new FsError("parse_error","cursor is not a valid read cursor",{hint:"pass a cursor returned by a previous read"})}return{off,size,dev,ino}}__name(decodeTextCursor,"decodeTextCursor");function assertCursorMatchesFile(cursor,stats,path8){if(String(stats.dev)!==cursor.dev||String(stats.ino)!==cursor.ino||stats.size<cursor.size){throw new FsError("hash_mismatch",`cursor no longer matches the file it was issued for: ${path8}`,{hint:"re-read the file from the beginning to get a fresh cursor"})}}__name(assertCursorMatchesFile,"assertCursorMatchesFile");var OWNER_ONLY_NEW_FILE_MODE=384;function resolveNewFileModeBits(policy,umask){return policy==="system"?438&~(umask??process.umask()):OWNER_ONLY_NEW_FILE_MODE}__name(resolveNewFileModeBits,"resolveNewFileModeBits");function createWorkspaceFileSystemFactory(deps){const boundWorkspaces=canonicalizeWorkspaces(deps.boundWorkspaces);if(boundWorkspaces.length===0){throw new Error("WorkspaceFileSystem requires at least one workspace root")}assertNoNestedWorkspaces(boundWorkspaces);const primaryWorkspace=boundWorkspaces[0];const workspaces=boundWorkspaces.map(workspace=>{const ignore=deps.ignore??loadIgnoreRules({projectRoot:workspace,useGitignore:true,useQwenignore:true,...deps.customIgnoreFiles!==void 0?{customIgnoreFiles:deps.customIgnoreFiles}:{},ignoreDirs:[]});Object.freeze(ignore);return{path:workspace,ignore}});const audit=createAuditPublisher({emit:deps.emit,boundWorkspace:primaryWorkspace,includeRawPaths:deps.includeRawPaths});const lowFs=new StandardFileSystemService;const pathLocks=deps.pathLocks??new PathMutexRegistry;const newFileMode=deps.newFileMode??"owner";const forRequest=__name(ctx=>new WorkspaceFileSystemImpl({primaryWorkspace,workspaces,trusted:deps.trusted,audit,ctx,lowFs,pathLocks,generationGuard:deps.generationGuard,newFileMode}),"forRequest");return{assertCanWrite(){deps.generationGuard?.assertOpen();assertTrustedForIntent(deps.trusted,"write")},forRequest,async writeSameHostToolText(ctx,request){try{deps.generationGuard?.assertOpen()}catch(err){throw recordSameHostToolWriteDenied(audit,ctx,request.path,err)}let resolved;try{resolved=await resolveWithinWorkspace(request.path,workspaces.map(workspace=>workspace.path),"write");deps.generationGuard?.assertOpen()}catch(err){if(!(err instanceof FsError&&err.kind==="path_outside_workspace")){throw recordSameHostToolWriteDenied(audit,ctx,request.path,err)}try{await writeSameHostToolTextOutsideWorkspace({request,trusted:deps.trusted,audit,ctx,pathLocks,generationGuard:deps.generationGuard,newFileMode});return}catch(outsideErr){throw recordSameHostToolWriteDenied(audit,ctx,request.path,outsideErr)}}try{await forRequest(ctx).writeTextOverwrite(resolved,request.content)}catch(err){if(isWorkspaceGenerationClosedError(err)){recordSameHostToolWriteDenied(audit,ctx,request.path,err)}throw err}}}}__name(createWorkspaceFileSystemFactory,"createWorkspaceFileSystemFactory");async function writeSameHostToolTextOutsideWorkspace(deps){const start=performance.now();deps.generationGuard?.assertOpen();assertTrustedForIntent(deps.trusted,"write");enforceWriteSize(Buffer.byteLength(deps.request.content,"utf-8"));const target=await resolveSameHostToolWriteTarget(deps.request.path);await deps.pathLocks.runExclusive(target,async()=>{deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(void 0,deps.request.meta??{});const content=meta.bom&&deps.request.content.charCodeAt(0)===65279?deps.request.content.slice(1):deps.request.content;const result=await atomicWriteTextResolvedFile({target,content,mode:"overwrite",meta,newFileModeBits:resolveNewFileModeBits(deps.newFileMode),assertGenerationOpen:__name(()=>deps.generationGuard?.assertOpen(),"assertGenerationOpen")});deps.audit.recordAccess(deps.ctx,{intent:"write",absolute:target,durationMs:performance.now()-start,sizeBytes:result.sizeBytes})})}__name(writeSameHostToolTextOutsideWorkspace,"writeSameHostToolTextOutsideWorkspace");async function resolveSameHostToolWriteTarget(input){if(!path4.isAbsolute(input)){throw new FsError("path_outside_workspace",`same-host external tool write requires an absolute path: ${input}`)}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace",`path contains suspicious pattern: ${input}`)}let leaf;try{leaf=await fsp2.lstat(input,{bigint:true})}catch(err){if(err?.code!=="ENOENT"){throw err}const parent=await fsp2.realpath(path4.dirname(input));const parentStat=await fsp2.lstat(parent,{bigint:true});if(!parentStat.isDirectory()){throw new FsError("parse_error",`parent path is not a directory: ${parent}`)}return path4.join(parent,path4.basename(input))}if(leaf.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be overwritten: ${input}`,{hint:"resolve the target explicitly before writing"})}if(!leaf.isFile()){throw new FsError("parse_error",`path is not a regular file: ${input}`)}const canonical=await fsp2.realpath(input);const canonicalStat=await fsp2.lstat(canonical,{bigint:true});if(!canonicalStat.isFile()){throw new FsError("parse_error",`canonical path is not a regular file: ${canonical}`)}assertSameFile(leaf,canonicalStat,input,"write");return canonical}__name(resolveSameHostToolWriteTarget,"resolveSameHostToolWriteTarget");function isWorkspaceGenerationClosedError(error){return error instanceof Error&&"code"in error&&error.code==="workspace_generation_closed"}__name(isWorkspaceGenerationClosedError,"isWorkspaceGenerationClosedError");function recordSameHostToolWriteDenied(audit,ctx,input,error){const fsError=wrapAsFsError(error);audit.recordDenied(ctx,{intent:"write",input,errorKind:fsError.kind,hint:fsError.hint,message:fsError.message});return isWorkspaceGenerationClosedError(error)&&error instanceof Error?error:fsError}__name(recordSameHostToolWriteDenied,"recordSameHostToolWriteDenied");function assertNoNestedWorkspaces(workspaces){for(let i=0;i<workspaces.length;i++){const a=workspaces[i];if(a===void 0)continue;for(let j=i+1;j<workspaces.length;j++){const b=workspaces[j];if(b===void 0)continue;if(isWithinRoot(a,b)||isWithinRoot(b,a)){throw new Error(`Nested workspace roots are not supported: ${JSON.stringify(a)} and ${JSON.stringify(b)}`)}}}}__name(assertNoNestedWorkspaces,"assertNoNestedWorkspaces");var WorkspaceFileSystemImpl=class{constructor(deps){this.deps=deps}static{__name(this,"WorkspaceFileSystemImpl")}workspaceForPath(p){let match;for(const workspace of this.deps.workspaces){if(isWithinRoot(p,workspace.path)&&(match===void 0||workspace.path.length>match.path.length)){match=workspace}}return match}ignoreVerdict(p,kind="file"){const workspace=this.workspaceForPath(p);if(!workspace)return{ignored:false};return shouldIgnore(p,workspace.path,workspace.ignore,kind)}async resolve(input,intent){try{this.deps.generationGuard?.assertOpen();const resolved=await resolveWithinWorkspace(input,this.deps.workspaces.map(workspace=>workspace.path),intent);this.deps.generationGuard?.assertOpen();return resolved}catch(err){throw this.recordAndWrap(err,intent,input)}}async stat(p){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"stat");const st=await fsp2.lstat(p);this.deps.generationGuard?.assertOpen();const out={kind:kindFromStatLike(st),sizeBytes:st.size,modifiedMs:st.mtimeMs};this.deps.audit.recordAccess(this.deps.ctx,{intent:"stat",absolute:p,durationMs:performance.now()-start,sizeBytes:st.size});return out}catch(err){throw this.recordAndWrap(err,"stat",p)}}async readText(p,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"read");if(opts.line!==void 0&&(!Number.isSafeInteger(opts.line)||opts.line<1)){throw new FsError("parse_error",`line must be a positive integer, got ${opts.line}`)}if(opts.limit!==void 0&&(!Number.isSafeInteger(opts.limit)||opts.limit<1)){throw new FsError("parse_error",`limit must be a positive integer, got ${opts.limit}`)}if(opts.cursor!==void 0&&opts.line!==void 0){throw new FsError("parse_error","cursor and line are mutually exclusive; a cursor already encodes where to resume")}if(opts.maxBytes!==void 0&&(!Number.isSafeInteger(opts.maxBytes)||opts.maxBytes<1||opts.maxBytes>MAX_READ_BYTES)){throw new FsError("parse_error",`maxBytes must be a positive integer in [1, ${MAX_READ_BYTES}], got ${opts.maxBytes}`)}const snapshot=await readTextFromResolvedFile(p,opts,this.deps.lowFs);this.deps.generationGuard?.assertOpen();const ignoreVerdict=this.ignoreVerdict(p,"file");const meta=snapshot.meta;if(ignoreVerdict.ignored)meta.matchedIgnore=ignoreVerdict.category;this.deps.audit.recordAccess(this.deps.ctx,{intent:"read",absolute:p,durationMs:performance.now()-start,sizeBytes:meta.sizeBytes,truncated:meta.truncated,matchedIgnore:meta.matchedIgnore});return{content:snapshot.content,meta}}catch(err){throw this.recordAndWrap(err,"read",p)}}async readBytes(p,opts={}){const out=await this.readBytesWindow(p,opts);return out.buffer}async readBytesWindow(p,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"read");const offset=opts.offset??0;const maxBytes=opts.maxBytes??MAX_READ_BYTES;if(!Number.isSafeInteger(offset)||offset<0){throw new FsError("parse_error",`offset must be a non-negative integer, got ${offset}`)}if(!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>MAX_READ_BYTES){throw new FsError("parse_error",`maxBytes must be a positive integer in [1, ${MAX_READ_BYTES}], got ${maxBytes}`)}const pre=await fsp2.lstat(p);if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${p}`)}const fh=await fsp2.open(p,"r");let st;let buf;try{st=await fh.stat();assertSameFile(pre,st,p,"read");const available=Math.max(0,st.size-offset);const toRead=Math.min(maxBytes,available);buf=Buffer.allocUnsafe(toRead);if(toRead>0){const read=await fh.read(buf,0,toRead,offset);buf=read.bytesRead===toRead?buf:buf.subarray(0,read.bytesRead)}const afterRead=await fh.stat();assertSameFile(st,afterRead,p,"read");if(afterRead.size!==st.size||afterRead.mtimeMs!==st.mtimeMs){throw new FsError("hash_mismatch",`file changed during read: ${p}`,{hint:"retry after re-reading the latest file hash"})}}finally{await fh.close()}await assertInodeStableAfterRead(p,st.ino);this.deps.generationGuard?.assertOpen();const fullWindow=offset===0&&buf.length===st.size;const out={buffer:buf,sizeBytes:st.size,returnedBytes:buf.length,offset,truncated:!fullWindow,...fullWindow?{hash:hashBuffer(buf)}:{}};this.deps.audit.recordAccess(this.deps.ctx,{intent:"read",absolute:p,durationMs:performance.now()-start,sizeBytes:buf.length,truncated:out.truncated});return out}catch(err){throw this.recordAndWrap(err,"read",p)}}async list(p,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"list");if(opts.maxEntries!==void 0&&(!Number.isSafeInteger(opts.maxEntries)||opts.maxEntries<1)){throw new FsError("parse_error",`maxEntries must be a positive integer, got ${opts.maxEntries}`)}const entries=[];const dir=await fsp2.opendir(p);for await(const d of dir){this.deps.generationGuard?.assertOpen();const childAbs=path4.join(p,d.name);const kind=kindFromStatLike(d);const verdict=this.ignoreVerdict(childAbs,kind==="directory"?"directory":"file");if(verdict.ignored&&!opts.includeIgnored)continue;entries.push({name:d.name,kind,ignored:verdict.ignored});if(opts.maxEntries!==void 0&&entries.length>=opts.maxEntries){break}}this.deps.generationGuard?.assertOpen();this.deps.audit.recordAccess(this.deps.ctx,{intent:"list",absolute:p,durationMs:performance.now()-start,sizeBytes:entries.length,truncated:opts.maxEntries!==void 0&&entries.length>=opts.maxEntries});return entries}catch(err){throw this.recordAndWrap(err,"list",p)}}async glob(pattern,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"glob");if(pattern.split(/[\\/]/).some(seg=>seg==="..")){throw new FsError("parse_error",`glob pattern may not contain '..' segments: ${pattern}`)}if(path4.isAbsolute(pattern)||/^[A-Za-z]:[\\/]/.test(pattern)||pattern.startsWith("\\\\")||pattern.startsWith("//")){throw new FsError("parse_error",`glob pattern must be workspace-relative: ${pattern}`,{hint:'pass a relative pattern such as "src/**/*.ts"'})}const searchRoots=[];if(opts.cwd===void 0){for(const workspace of this.deps.workspaces){searchRoots.push({cwd:workspace.path,workspace})}}else{const cwd=opts.cwd;let cwdReal;const directWorkspace=this.workspaceForPath(cwd);if(directWorkspace&&cwd===directWorkspace.path){cwdReal=cwd}else{try{cwdReal=await fsp2.realpath(path4.resolve(cwd))}catch(err){const code=err?.code;if(code==="ENOENT"){throw new FsError("path_not_found",`glob cwd does not exist: ${cwd}`,{cause:err})}throw err}}const workspace=this.workspaceForPath(cwdReal);if(!workspace){throw new FsError("path_outside_workspace",`glob cwd is outside workspace: ${cwd}`,{hint:"opts.cwd must be a path obtained from fs.resolve()"})}searchRoots.push({cwd:cwdReal,workspace})}const out=[];const seenCanonicals=new Set;const max=opts.maxResults??Number.POSITIVE_INFINITY;let escapedCount=0;let permissionErrorCount=0;let transientErrorCount=0;const globErrors=[];let successfulGlobRoots=0;for(const searchRoot of searchRoots){this.deps.generationGuard?.assertOpen();if(out.length>=max)break;let matches;try{await fsp2.access(searchRoot.cwd,fsConstants.R_OK|fsConstants.X_OK);const rootStat=await fsp2.stat(searchRoot.cwd);if(!rootStat.isDirectory()){const err=new Error(`glob workspace root is not a directory: ${searchRoot.cwd}`);err.code="ENOTDIR";throw err}matches=await glob(pattern,{cwd:searchRoot.cwd,nodir:false,absolute:true,dot:true,ignore:["**/node_modules/**","**/.git/**"]})}catch(err){globErrors.push(err);this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:errorKindForRealpathFailure(err),hint:`glob failed for workspace root: ${errorCode(err)??"unknown error"}`,pattern});continue}successfulGlobRoots+=1;for(const hit of matches){this.deps.generationGuard?.assertOpen();if(out.length>=max)break;const absolute=path4.resolve(hit);let canonical;try{canonical=await fsp2.realpath(absolute)}catch(err){const code=errorCode(err);if(code==="ENOENT"||code==="ELOOP"){escapedCount+=1}else if(code==="EACCES"||code==="EPERM"){permissionErrorCount+=1}else{transientErrorCount+=1}continue}const inAnyWorkspace=this.deps.workspaces.some(workspace=>isWithinRoot(canonical,workspace.path));if(!inAnyWorkspace){escapedCount+=1;continue}if(seenCanonicals.has(canonical))continue;let dirent=null;try{dirent=await fsp2.lstat(canonical)}catch{dirent=null}const kind=dirent?.isDirectory()?"directory":"file";const verdict=this.ignoreVerdict(canonical,kind);if(verdict.ignored&&!opts.includeIgnored)continue;seenCanonicals.add(canonical);out.push(canonical)}}if(globErrors.length>0&&successfulGlobRoots===0){if(globErrors.length===1)throw globErrors[0];throw new AggregateError(globErrors,"glob failed for all workspace roots")}if(escapedCount>0){this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:"symlink_escape",hint:`glob filtered ${escapedCount} hit(s) that resolved outside workspace`,pattern})}if(permissionErrorCount>0){this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:"permission_denied",hint:`glob skipped ${permissionErrorCount} hit(s) due to EACCES/EPERM`,pattern})}if(transientErrorCount>0){this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:pattern,errorKind:"io_error",hint:`glob skipped ${transientErrorCount} hit(s) due to transient I/O errors`,pattern})}this.deps.generationGuard?.assertOpen();this.deps.audit.recordAccess(this.deps.ctx,{intent:"glob",absolute:this.deps.primaryWorkspace,durationMs:performance.now()-start,sizeBytes:out.length,pattern});return out}catch(err){throw this.recordAndWrap(err,"glob",pattern)}}async writeTextAtomic(p,content,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");validateWriteTextAtomicOptions(opts);const decodedSizeBytes=Buffer.byteLength(content,"utf-8");enforceWriteSize(decodedSizeBytes);const out=await this.deps.pathLocks.runExclusive(p,async()=>{const existingMeta=opts.mode==="replace"?await readExistingTextMeta(p,opts.expectedHash):void 0;if(opts.mode==="create"){await assertCreateTargetAbsent(p)}this.deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(existingMeta,opts);const result=await atomicWriteTextResolvedFile({target:p,content,mode:opts.mode,expectedHash:opts.expectedHash,meta,newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");if(verdict.ignored)meta.matchedIgnore=verdict.category;meta.sizeBytes=result.sizeBytes;meta.hash=result.hash;this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:meta.matchedIgnore});return{created:opts.mode==="create",sizeBytes:result.sizeBytes,hash:result.hash,meta}});return out}catch(err){throw this.recordAndWrap(err,"write",p)}}async writeTextOverwrite(p,content,opts={}){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const decodedSizeBytes=Buffer.byteLength(content,"utf-8");enforceWriteSize(decodedSizeBytes);const out=await this.deps.pathLocks.runExclusive(p,async()=>{let targetExisted=false;try{await fsp2.lstat(p);targetExisted=true}catch(err){if(err?.code!=="ENOENT"){throw err}}let existingMeta;try{existingMeta=await readExistingTextMeta(p)}catch(err){const code=err?.code;const kind=err?.kind;if(code!=="ENOENT"&&code!=="EACCES"&&code!=="EPERM"&&kind!=="file_too_large"&&kind!=="binary_file"){throw err}}this.deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(existingMeta,opts);const result=await atomicWriteTextResolvedFile({target:p,content,mode:"overwrite",meta,newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");if(verdict.ignored)meta.matchedIgnore=verdict.category;meta.sizeBytes=result.sizeBytes;meta.hash=result.hash;this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:meta.matchedIgnore});return{created:!targetExisted,sizeBytes:result.sizeBytes,hash:result.hash,meta}});return out}catch(err){throw this.recordAndWrap(err,"write",p)}}async writeText(p,content,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const sizeBytes=Buffer.byteLength(content,"utf-8");enforceWriteSize(sizeBytes);await assertNotSymlinkBeforeWrite(p);this.deps.generationGuard?.assertOpen();await this.deps.lowFs.writeTextFile({path:p,content,_meta:opts?buildWriteMeta(opts):void 0});const verdict=this.ignoreVerdict(p,"file");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes,matchedIgnore:verdict.ignored?verdict.category:void 0})}catch(err){throw this.recordAndWrap(err,"write",p)}}async editAtomic(p,oldText,newText,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"edit");if(!isContentHash(opts.expectedHash)){throw new FsError("parse_error","expectedHash must match sha256:<64 lowercase hex chars>")}if(typeof oldText!=="string"||oldText.length===0){throw new FsError("parse_error",`oldText must be a non-empty string for edit on ${p}`)}if(typeof newText!=="string"){throw new FsError("parse_error","newText must be a string")}const out=await this.deps.pathLocks.runExclusive(p,async()=>{const snapshot=await readTextSnapshotFromResolvedFile(p);if(snapshot.meta.hash!==opts.expectedHash){throw new FsError("hash_mismatch",`expected ${opts.expectedHash}, found ${snapshot.meta.hash}`,{hint:"re-read the file and retry with the latest hash"})}const current=snapshot.content;const occurrences=countOccurrences(current,oldText);if(occurrences===0){const snippet=oldText.length>80?oldText.slice(0,80)+"...":oldText;throw new FsError("text_not_found",`oldText not found in ${p}`,{hint:`searched for: ${JSON.stringify(snippet)}`})}if(occurrences>1){throw new FsError("ambiguous_text_match",`oldText appears ${occurrences} times in ${p}`,{hint:"pass a larger oldText span that occurs exactly once"})}const idx=current.indexOf(oldText);const next=current.slice(0,idx)+newText+current.slice(idx+oldText.length);enforceWriteSize(Buffer.byteLength(next,"utf-8"));this.deps.generationGuard?.assertOpen();const meta=mergeWriteMeta(snapshot.meta,{});const result=await atomicWriteTextResolvedFile({target:p,content:next,mode:"replace",expectedHash:opts.expectedHash,meta,newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");if(verdict.ignored)meta.matchedIgnore=verdict.category;meta.sizeBytes=result.sizeBytes;meta.hash=result.hash;this.deps.audit.recordAccess(this.deps.ctx,{intent:"edit",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:meta.matchedIgnore});return{writtenBytes:result.sizeBytes,hash:result.hash,meta}});return out}catch(err){throw this.recordAndWrap(err,"edit",p)}}async edit(p,oldText,newText,opts){if(opts?.expectedHash!==void 0){return this.editAtomic(p,oldText,newText,{expectedHash:opts.expectedHash})}const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"edit");if(oldText.length===0){throw new FsError("parse_error",`oldText must be a non-empty string for edit on ${p}`,{hint:"empty oldText would match at position 0 and silently prepend newText"})}return await this.deps.pathLocks.runExclusive(p,async()=>{const snapshot=await readTextSnapshotFromResolvedFile(p);const current=snapshot.content;const idx=current.indexOf(oldText);if(idx===-1){const snippet=oldText.length>80?oldText.slice(0,80)+"\u2026":oldText;throw new FsError("parse_error",`oldText not found in ${p}`,{hint:`edit() expects oldText to appear verbatim; searched for: ${JSON.stringify(snippet)}`})}const next=current.slice(0,idx)+newText+current.slice(idx+oldText.length);const writtenBytes=Buffer.byteLength(next,"utf-8");enforceWriteSize(writtenBytes);this.deps.generationGuard?.assertOpen();const result=await atomicWriteTextResolvedFile({target:p,content:next,mode:"overwrite",meta:mergeWriteMeta(snapshot.meta,{}),newFileModeBits:resolveNewFileModeBits(this.deps.newFileMode),assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");this.deps.audit.recordAccess(this.deps.ctx,{intent:"edit",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:verdict.ignored?verdict.category:void 0});return{writtenBytes:result.sizeBytes}})}catch(err){throw this.recordAndWrap(err,"edit",p)}}async writeBytesAtomic(p,data){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");enforceWriteSize(data.length,MAX_UPLOAD_BYTES);const out=await this.deps.pathLocks.runExclusive(p,async()=>{await assertCreateTargetAbsent(p);this.deps.generationGuard?.assertOpen();const result=await atomicPublishResolvedFile({target:p,buf:data,mode:"create",assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});const verdict=this.ignoreVerdict(p,"file");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:result.sizeBytes,matchedIgnore:verdict.ignored?verdict.category:void 0});return{sizeBytes:result.sizeBytes,hash:result.hash}});return out}catch(err){throw this.recordAndWrap(err,"write",p,{audit:!(isFsError(err)&&err.kind==="file_already_exists")})}}async deleteFile(input){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");const basename3=path4.basename(input);if(!input||input.includes("\0")||hasSuspiciousPathPattern(input)||input.endsWith("/")||input.endsWith(path4.sep)||basename3==="."||basename3===".."){throw new FsError("parse_error","Deletion requires a regular file path")}const parent=await resolveWithinWorkspace(path4.dirname(input),this.deps.workspaces.map(workspace=>workspace.path),"delete");const target=path4.join(parent,basename3);if(!this.workspaceForPath(target)||this.deps.workspaces.some(workspace=>workspace.path===target)){throw new FsError("path_outside_workspace","Cannot delete a workspace root")}return await this.deps.pathLocks.runExclusive(target,async()=>{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");if(await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","Deletion parent changed")}const stat2=await fsp2.lstat(target);if(!stat2.isFile()){throw new FsError(stat2.isSymbolicLink()?"symlink_escape":"parse_error","Only regular files can be deleted")}if(await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","Deletion parent changed")}this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");const verdict=this.ignoreVerdict(target,"file");await fsp2.unlink(target);this.deps.audit.recordAccess(this.deps.ctx,{intent:"delete",absolute:target,durationMs:performance.now()-start,sizeBytes:stat2.size,matchedIgnore:verdict.ignored?verdict.category:void 0});return target})}catch(err){throw this.recordAndWrap(err,"delete",input)}}async deleteDirectory(input){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");const basename3=path4.basename(input);if(!input||input.includes("\0")||input.endsWith("/")||input.endsWith(path4.sep)||basename3==="."||basename3===".."){throw new FsError("parse_error","Deletion requires a directory path")}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace","path contains a suspicious pattern")}const parent=await resolveWithinWorkspace(path4.dirname(input),this.deps.workspaces.map(workspace=>workspace.path),"delete");const target=path4.join(parent,basename3);if(!this.workspaceForPath(target)||this.deps.workspaces.some(workspace=>workspace.path===target)){throw new FsError("path_outside_workspace","Cannot delete a workspace root")}return await this.deps.pathLocks.runExclusive(target,async()=>{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");if(await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","Deletion parent changed")}const stat2=await fsp2.lstat(target);if(!stat2.isDirectory()){throw new FsError(stat2.isSymbolicLink()?"symlink_escape":"parse_error","Only directories can be deleted")}if(await fsp2.realpath(target)!==target){throw new FsError("symlink_escape","Deletion directory changed")}this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"delete");try{await fsp2.rm(target,{recursive:true,force:false})}catch(error){if(error.code==="ENOTEMPTY"){throw new FsError("io_error","Directory contents changed during removal",{cause:error,hint:"Retry deleting the directory."})}throw error}const verdict=this.ignoreVerdict(target,"directory");this.deps.audit.recordAccess(this.deps.ctx,{intent:"delete",operation:"rm",absolute:target,durationMs:performance.now()-start,matchedIgnore:verdict.ignored?verdict.category:void 0});return target})}catch(error){throw this.recordAndWrap(error,"delete",input)}}async createDirectory(input){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const basename3=path4.basename(input);if(!input||input.includes("\0")||input.endsWith("/")||input.endsWith(path4.sep)||basename3==="."||basename3===".."){throw new FsError("parse_error","path must name a new directory")}if(hasSuspiciousPathPattern(input)){throw new FsError("path_outside_workspace","path contains a suspicious pattern")}const parent=await resolveWithinWorkspace(path4.dirname(input),this.deps.workspaces.map(workspace=>workspace.path),"list");const target=path4.join(parent,basename3);return await this.deps.pathLocks.runExclusive(target,async()=>{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");try{const existing=await fsp2.lstat(target);if(existing.isSymbolicLink()){throw new FsError("symlink_escape","directory path is a symlink")}throw new FsError("file_already_exists","path already exists")}catch(error){if(error.code!=="ENOENT")throw error}const parentStat=await fsp2.lstat(parent);if(!parentStat.isDirectory()||await fsp2.realpath(parent)!==parent){throw new FsError("symlink_escape","directory parent changed")}this.deps.generationGuard?.assertOpen();try{await fsp2.mkdir(target,{mode:493})}catch(error){if(error.code==="EEXIST"){throw new FsError("file_already_exists","path already exists")}throw error}if(!(await fsp2.lstat(target)).isDirectory()){throw new FsError("symlink_escape","created directory changed")}const verdict=this.ignoreVerdict(target,"directory");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",operation:"mkdir",absolute:target,durationMs:performance.now()-start,sizeBytes:0,matchedIgnore:verdict.ignored?verdict.category:void 0});return target})}catch(error){throw this.recordAndWrap(error,"write",input)}}async mkdir(p,opts){const start=performance.now();try{this.deps.generationGuard?.assertOpen();assertTrustedForIntent(this.deps.trusted,"write");const out=await this.deps.pathLocks.runExclusive(p,async()=>{await ensureResolvedDirectory(p,{recursive:opts?.recursive??false,assertGenerationOpen:__name(()=>this.deps.generationGuard?.assertOpen(),"assertGenerationOpen")});this.deps.generationGuard?.assertOpen();const verdict=this.ignoreVerdict(p,"directory");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:p,durationMs:performance.now()-start,sizeBytes:0,operation:"mkdir",matchedIgnore:verdict.ignored?verdict.category:void 0});return void 0});return out}catch(err){throw this.recordAndWrap(err,"write",p)}}recordAndWrap(err,intent,input,opts){if(err instanceof Error&&"code"in err&&err.code==="workspace_generation_closed"){return err}const fs3=wrapAsFsError(err);if(opts?.audit===false){return fs3}this.deps.audit.recordDenied(this.deps.ctx,{intent,input,errorKind:fs3.kind,hint:fs3.hint,message:fs3.message,pattern:intent==="glob"?input:void 0});return fs3}};var CONTENT_HASH_RE=/^sha256:[0-9a-f]{64}$/;function isContentHash(value){return typeof value==="string"&&CONTENT_HASH_RE.test(value)}__name(isContentHash,"isContentHash");function validateWriteTextAtomicOptions(opts){if(opts.mode!=="create"&&opts.mode!=="replace"){throw new FsError("parse_error",'mode must be either "create" or "replace" (use writeTextOverwrite() for unconditional overwrites)')}if(opts.expectedHash!==void 0&&!isContentHash(opts.expectedHash)){throw new FsError("parse_error","expectedHash must match sha256:<64 lowercase hex chars>")}if(opts.mode==="replace"&&opts.expectedHash===void 0){throw new FsError("parse_error",'expectedHash is required when mode is "replace"')}if(opts.lineEnding!==void 0&&opts.lineEnding!=="lf"&&opts.lineEnding!=="crlf"){throw new FsError("parse_error",'lineEnding must be "lf" or "crlf"')}}__name(validateWriteTextAtomicOptions,"validateWriteTextAtomicOptions");async function readTextFromResolvedFile(p,opts,lowFs){const pre=await fsp2.lstat(p);if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink: ${p}`,{hint:"re-resolve the target file instead of reading through a link"})}if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${p}`)}if(opts.cursor!==void 0){return readTextCursorWindowFromResolvedFile(p,pre,opts,lowFs)}const wantsWindow=opts.limit!==void 0||opts.maxBytes!==void 0||opts.line!==void 0;if(pre.size>MAX_READ_BYTES&&wantsWindow){return readLargeTextWindowFromResolvedFile(p,pre,opts,lowFs)}return readTextSnapshotFromResolvedFile(p,opts,pre)}__name(readTextFromResolvedFile,"readTextFromResolvedFile");async function readTextSnapshotFromResolvedFile(p,opts={},knownPre){const pre=knownPre??await fsp2.lstat(p);if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink: ${p}`,{hint:"re-resolve the target file instead of reading through a link"})}if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${p}`)}if(pre.size>MAX_READ_BYTES){throw new FsError("file_too_large",`file of ${pre.size} bytes exceeds read cap of ${MAX_READ_BYTES} bytes`,{hint:"use a finite line limit for large UTF-8 text, or readBytes for explicit byte-windowed access"})}const raw=await readStableRegularFileBuffer(p,pre);if(looksBinary(raw)){throw new FsError("binary_file",`binary file: ${p}`,{hint:"use readBytes for binary content"})}const decoded=await decodeBufferWithEncodingInfoAsync(raw);const startLineIndex=opts.line!==void 0?opts.line-1:0;const sliced=sliceDecodedText(decoded.content,startLineIndex,opts.limit??Number.POSITIVE_INFINITY);const maxOutputBytes=opts.maxBytes??MAX_READ_BYTES;const sizeOutcome=enforceReadSize(raw.length,maxOutputBytes);let content=sliced.content;let byteTruncated=false;const meta={encoding:decoded.encoding,bom:decoded.bom,lineEnding:detectLineEnding(decoded.content),sizeBytes:raw.length,originalLineCount:sliced.originalLineCount,hash:hashBuffer(raw)};const output=Buffer.from(content,"utf-8");if(output.length>maxOutputBytes){content=safeUtf8Truncate(output,maxOutputBytes).toString("utf-8");meta.truncated=true;byteTruncated=true}if(sizeOutcome.truncated){meta.truncated=true}if(opts.limit!==void 0&&Number.isFinite(opts.limit)&&sliced.originalLineCount>opts.limit+startLineIndex){meta.truncated=true}const pageableLineCount=sliced.originalLineCount-(decoded.content.endsWith("\n")?1:0);meta.hasMore=byteTruncated||sliced.endLine<pageableLineCount;const bomBytes=decoded.bom?3:0;const decodedBytesMatchSource=isUtf8CompatibleEncoding(decoded.encoding)&&Buffer.from(decoded.content,"utf-8").equals(raw.subarray(bomBytes));if(meta.hasMore&&!byteTruncated&&decodedBytesMatchSource){const startByte=bomBytes+sliced.startByteOffset;const contentBytes=Buffer.byteLength(content,"utf-8");const nextOffset=startByte+contentBytes+1;if(nextOffset<raw.length){meta.nextCursor=encodeTextCursor({off:nextOffset,size:raw.length,dev:String(pre.dev),ino:String(pre.ino)})}}return{content,meta}}__name(readTextSnapshotFromResolvedFile,"readTextSnapshotFromResolvedFile");function assertStreamWindowStable(before,after,p,reason){const beforeSize=toBigInt(before.size);const afterSize=toBigInt(after.size);if(afterSize<beforeSize||afterSize===beforeSize&&(after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs)){throw new FsError("hash_mismatch",`${reason}: ${p}`,{hint:"retry after re-reading the latest file"})}}__name(assertStreamWindowStable,"assertStreamWindowStable");async function readTextCursorWindowFromResolvedFile(p,pre,opts,lowFs){const cursor=decodeTextCursor(opts.cursor);const fh=await fsp2.open(p,"r");let opened;let afterRead;let window;let primaryError;let hasPrimaryError=false;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");assertStreamWindowStable(pre,opened,p,"file changed before read");assertCursorMatchesFile(cursor,opened,p);try{const probe=Buffer.alloc(Math.min(BINARY_PROBE_BYTES,opened.size));if(probe.length>0){const{bytesRead}=await fh.read(probe,0,probe.length,0);if(looksBinary(probe.subarray(0,bytesRead))){throw new FsError("binary_file",`binary file: ${p}`,{hint:"use readBytes for binary content"})}}window=await lowFs.readTextCursorFromHandle({fileHandle:fh,startOffset:cursor.off,fileSize:opened.size,maxOutputBytes:opts.maxBytes??MAX_READ_BYTES,maxSnapBytes:MAX_TEXT_SCAN_BYTES,...opts.limit!==void 0?{limit:opts.limit}:{}})}catch(err){hasPrimaryError=true;primaryError=err}afterRead=await fh.stat()}finally{await fh.close()}if(opened===void 0||afterRead===void 0){throw new FsError("internal_error",`failed to stat opened file: ${p}`)}const post=await fsp2.lstat(p);if(post.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink during read: ${p}`,{hint:"TOCTOU swap detected via post-read lstat"})}assertSameFile(opened,afterRead,p,"read");assertStreamWindowStable(opened,afterRead,p,"file changed during read");assertSameFile(opened,post,p,"read");assertStreamWindowStable(opened,post,p,"file changed during read");if(hasPrimaryError){if(primaryError instanceof LargeNonUtf8TextError){throw new FsError("binary_file",primaryError.message,{cause:primaryError,hint:"convert the file to UTF-8, or use readBytes for the raw bytes"})}if(primaryError instanceof CursorNotAtLineBoundaryError){throw new FsError("parse_error",primaryError.message,{cause:primaryError,hint:"pass a cursor returned by a previous read"})}throw primaryError}if(window===void 0){throw new FsError("internal_error",`cursor text read returned no result: ${p}`)}const meta={encoding:window.encoding,bom:window.bom,lineEnding:window.lineEnding,sizeBytes:opened.size,truncated:true,hasMore:window.nextOffset!==void 0||window.truncatedByBytes===true};if(window.nextOffset!==void 0){meta.nextCursor=encodeTextCursor({off:window.nextOffset,size:opened.size,dev:String(opened.dev),ino:String(opened.ino)})}return{content:window.content,meta}}__name(readTextCursorWindowFromResolvedFile,"readTextCursorWindowFromResolvedFile");async function readLargeTextWindowFromResolvedFile(p,pre,opts,lowFs){const fh=await fsp2.open(p,"r");let opened;let afterRead;let result;let primaryError;let hasPrimaryError=false;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");assertStreamWindowStable(pre,opened,p,"file changed before read");try{const probe=Buffer.alloc(Math.min(BINARY_PROBE_BYTES,opened.size));if(probe.length>0){const{bytesRead}=await fh.read(probe,0,probe.length,0);if(looksBinary(probe.subarray(0,bytesRead))){throw new FsError("binary_file",`binary file: ${p}`,{hint:"use readBytes for binary content"})}}result=await lowFs.readTextFileFromHandle({fileHandle:fh,fileSize:opened.size,limit:opts.limit??Number.POSITIVE_INFINITY,line:opts.line!==void 0?opts.line-1:0,maxOutputBytes:opts.maxBytes??MAX_READ_BYTES,maxScanBytes:MAX_TEXT_SCAN_BYTES})}catch(err){hasPrimaryError=true;primaryError=err}afterRead=await fh.stat()}finally{await fh.close()}if(opened===void 0||afterRead===void 0){throw new FsError("internal_error",`failed to stat opened file: ${p}`)}const post=await fsp2.lstat(p);if(post.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink during read: ${p}`,{hint:"TOCTOU swap detected via post-read lstat"})}assertSameFile(opened,afterRead,p,"read");assertStreamWindowStable(opened,afterRead,p,"file changed during read");assertSameFile(opened,post,p,"read");assertStreamWindowStable(opened,post,p,"file changed during read");if(hasPrimaryError){if(primaryError instanceof LargeNonUtf8TextError){throw new FsError("binary_file",primaryError.message,{cause:primaryError,hint:"convert the file to UTF-8, or use readBytes for the raw bytes"})}if(primaryError instanceof TextScanBudgetExceededError){throw new FsError("file_too_large",primaryError.message,{cause:primaryError,hint:`line offsets are resolved by scanning from byte 0 and stop after ${MAX_TEXT_SCAN_BYTES} bytes; page with the cursor from a shallower read to reach this offset in O(1), or use readBytes for raw bytes`})}throw primaryError}if(result===void 0){throw new FsError("internal_error",`large text range read returned no result: ${p}`)}const content=result.content;const readMeta=result._meta;const meta={encoding:readMeta?.encoding,bom:readMeta?.bom,lineEnding:readMeta?.lineEnding??detectLineEnding(content),sizeBytes:opened.size,truncated:true,hasMore:readMeta?.nextByteOffset!==void 0||readMeta?.truncatedByBytes===true};if(readMeta?.nextByteOffset!==void 0){meta.nextCursor=encodeTextCursor({off:readMeta.nextByteOffset,size:opened.size,dev:String(opened.dev),ino:String(opened.ino)})}if(readMeta?.originalLineCountExact===true&&readMeta?.originalLineCount!==void 0){meta.originalLineCount=readMeta.originalLineCount}return{content,meta}}__name(readLargeTextWindowFromResolvedFile,"readLargeTextWindowFromResolvedFile");async function readStableRegularFileBuffer(p,pre){const fh=await fsp2.open(p,"r");let opened;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");if(opened.size>MAX_READ_BYTES){throw new FsError("file_too_large",`file of ${opened.size} bytes exceeds read cap of ${MAX_READ_BYTES} bytes`,{hint:"use a finite line limit for large UTF-8 text, or readBytes for explicit byte-windowed access"})}const out=Buffer.alloc(opened.size);let offset=0;while(offset<opened.size){const read=await fh.read(out,offset,opened.size-offset,offset);if(read.bytesRead===0)break;offset+=read.bytesRead}const afterRead=await fh.stat();assertSameFile(opened,afterRead,p,"read");if(afterRead.size!==opened.size||afterRead.mtimeMs!==opened.mtimeMs){throw new FsError("hash_mismatch",`file changed during read: ${p}`,{hint:"retry after re-reading the latest file hash"})}const post=await fsp2.lstat(p);assertSameFile(pre,post,p,"read");if(post.size!==opened.size||post.mtimeMs!==opened.mtimeMs){throw new FsError("hash_mismatch",`file changed during read: ${p}`,{hint:"retry after re-reading the latest file hash"})}return offset===out.length?out:out.subarray(0,offset)}finally{await fh.close()}}__name(readStableRegularFileBuffer,"readStableRegularFileBuffer");function sliceDecodedText(content,startLine,limit){const lines=content.split("\n");const originalLineCount=lines.length;const endLine=Math.min(startLine+limit,originalLineCount);const actualStartLine=Math.min(startLine,originalLineCount);let startByteOffset=0;for(let i=0;i<actualStartLine;i++){startByteOffset+=Buffer.byteLength(lines[i],"utf-8")+1}return{content:lines.slice(actualStartLine,endLine).join("\n"),originalLineCount,startByteOffset,endLine}}__name(sliceDecodedText,"sliceDecodedText");function looksBinary(buf){if(buf.length===0)return false;const bomProbe=buf.subarray(0,Math.min(4,buf.length));const hasUnicodeBom=bomProbe.length>=4&&(bomProbe[0]===255&&bomProbe[1]===254&&bomProbe[2]===0&&bomProbe[3]===0||bomProbe[0]===0&&bomProbe[1]===0&&bomProbe[2]===254&&bomProbe[3]===255)||bomProbe.length>=3&&bomProbe[0]===239&&bomProbe[1]===187&&bomProbe[2]===191||bomProbe.length>=2&&(bomProbe[0]===255&&bomProbe[1]===254||bomProbe[0]===254&&bomProbe[1]===255);if(hasUnicodeBom)return false;const sampleLength=Math.min(4096,buf.length);let nonPrintableCount=0;for(let i=0;i<sampleLength;i++){if(buf[i]===0)return true;if(buf[i]<9||buf[i]>13&&buf[i]<32){nonPrintableCount++}}return nonPrintableCount/sampleLength>.3}__name(looksBinary,"looksBinary");async function readExistingTextMeta(p,expectedHash){const snapshot=await readTextSnapshotFromResolvedFile(p);if(expectedHash!==void 0&&snapshot.meta.hash!==expectedHash){throw new FsError("hash_mismatch",`expected ${expectedHash}, found ${snapshot.meta.hash}`,{hint:"re-read the file and retry with the latest hash"})}return snapshot.meta}__name(readExistingTextMeta,"readExistingTextMeta");function mergeWriteMeta(existing,opts){return{encoding:opts.encoding??existing?.encoding??"utf-8",bom:opts.bom??existing?.bom??false,lineEnding:opts.lineEnding??existing?.lineEnding??"lf"}}__name(mergeWriteMeta,"mergeWriteMeta");async function atomicWriteTextResolvedFile(input){const buf=await encodeTextFileContentAsync(input.target,input.content,buildWriteMeta(input.meta));enforceWriteSize(buf.length);return atomicPublishResolvedFile({target:input.target,buf,mode:input.mode,expectedHash:input.expectedHash,newFileModeBits:input.newFileModeBits,assertGenerationOpen:input.assertGenerationOpen})}__name(atomicWriteTextResolvedFile,"atomicWriteTextResolvedFile");async function ensureResolvedDirectory(target,opts){const assertRealDirectory=__name(async p=>{const st=await fsp2.lstat(p);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`directory path is a symlink: ${p}`,{hint:"re-resolve the target after detecting symlink swaps"})}if(!st.isDirectory()){throw new FsError("parse_error",`path exists and is not a directory: ${p}`)}},"assertRealDirectory");const assertParentNotSymlink=__name(async p=>{const parent=path4.dirname(p);const st=await fsp2.lstat(parent);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`directory parent is a symlink: ${parent}`,{hint:"re-resolve the target after detecting symlink swaps"})}},"assertParentNotSymlink");try{await assertRealDirectory(target);return}catch(err){if(isFsError(err))throw err;if(err.code!=="ENOENT")throw err}if(!opts.recursive){opts.assertGenerationOpen();await assertParentNotSymlink(target);try{await fsp2.mkdir(target,{mode:493})}catch(err){if(err.code!=="EEXIST")throw err}await assertRealDirectory(target);return}const missing=[];let current=target;while(true){try{await assertRealDirectory(current);break}catch(err){if(isFsError(err))throw err;if(err.code!=="ENOENT")throw err;missing.push(current);const parent=path4.dirname(current);if(parent===current)throw err;current=parent}}for(const entry of missing.reverse()){opts.assertGenerationOpen();await assertParentNotSymlink(entry);try{await fsp2.mkdir(entry,{mode:493})}catch(err){if(err.code!=="EEXIST")throw err}await assertRealDirectory(entry)}}__name(ensureResolvedDirectory,"ensureResolvedDirectory");async function atomicPublishResolvedFile(input){const target=input.target;const parent=path4.dirname(target);const parentStat=await fsp2.lstat(parent);if(parentStat.isSymbolicLink()){throw new FsError("symlink_escape",`parent path is a symlink: ${parent}`,{hint:"re-resolve the target after detecting parent-symlink swaps"})}if(!parentStat.isDirectory()){throw new FsError("parse_error",`parent path is not a directory: ${parent}`)}const tmpSuffix=`.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;const tmpNameMaxBytes=255;const tmpBaseMaxBytes=tmpNameMaxBytes-1-Buffer.byteLength(tmpSuffix,"utf-8");let tmpBase=path4.basename(target);if(Buffer.byteLength(tmpBase,"utf-8")>tmpBaseMaxBytes){tmpBase=safeUtf8Truncate(Buffer.from(tmpBase,"utf-8"),tmpBaseMaxBytes).toString("utf-8")}const tmpPath=path4.join(parent,`.${tmpBase}${tmpSuffix}`);let tempLive=false;let tempHandle;let tempStat;try{tempHandle=await reserveTempFile(tmpPath);tempLive=true;const written=await writeBufferToTemp({tmpPath,buf:input.buf,handle:tempHandle});tempStat=written.stat;const targetState=await assertAtomicTargetPrecondition({target,mode:input.mode,expectedHash:input.expectedHash});await chmodHandleBestEffort(tempHandle,targetState.mode??input.newFileModeBits??OWNER_ONLY_NEW_FILE_MODE);await assertTempPathMatchesStat(tmpPath,tempStat);await tempHandle.close();tempHandle=void 0;await assertTempPathMatchesStat(tmpPath,tempStat);input.assertGenerationOpen?.();if(input.mode==="create"){await publishCreateNoClobber(tmpPath,target)}else{await renameWithRetryLocal(tmpPath,target,3,50)}tempLive=false;await fsyncParentDirBestEffort(parent);return written}catch(err){await tempHandle?.close().catch(()=>void 0);if(tempLive){try{await fsp2.unlink(tmpPath)}catch{}}throw err}}__name(atomicPublishResolvedFile,"atomicPublishResolvedFile");async function reserveTempFile(tmpPath){return fsp2.open(tmpPath,"wx",384)}__name(reserveTempFile,"reserveTempFile");async function writeBufferToTemp(input){await input.handle.writeFile(input.buf);await syncHandleBestEffort(input.handle);const st=await fsp2.lstat(input.tmpPath);const opened=await input.handle.stat();assertSameFile(opened,st,input.tmpPath,"write");if(st.isSymbolicLink()){throw new FsError("symlink_escape",`temporary path became a symlink: ${input.tmpPath}`,{hint:"temp-file race detected before final rename"})}if(!st.isFile()){throw new FsError("parse_error",`temporary path is not a regular file: ${input.tmpPath}`)}return{sizeBytes:input.buf.length,hash:hashBuffer(input.buf),stat:st}}__name(writeBufferToTemp,"writeBufferToTemp");async function assertCreateTargetAbsent(target){try{const st=await fsp2.lstat(target);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be created over: ${target}`,{hint:"remove the symlink or resolve the target explicitly"})}throw new FsError("file_already_exists",`file already exists: ${target}`)}catch(err){const code=err?.code;if(code==="ENOENT")return;throw err}}__name(assertCreateTargetAbsent,"assertCreateTargetAbsent");async function assertAtomicTargetPrecondition(input){if(input.mode==="create"){await assertCreateTargetAbsent(input.target);return{}}if(input.mode==="overwrite"){let pre2;try{pre2=await fsp2.lstat(input.target)}catch(err){if(err?.code==="ENOENT"){return{}}throw err}if(pre2.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be overwritten atomically: ${input.target}`,{hint:"re-resolve the target file instead of writing through a link"})}if(!pre2.isFile()){throw new FsError("parse_error",`path is not a regular file: ${input.target}`)}return{mode:pre2.mode&4095}}if(!isContentHash(input.expectedHash)){throw new FsError("parse_error",'expectedHash is required when mode is "replace"')}const pre=await fsp2.lstat(input.target);if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path is a symlink and cannot be replaced atomically: ${input.target}`,{hint:"re-resolve the target file instead of writing through a link"})}if(!pre.isFile()){throw new FsError("parse_error",`path is not a regular file: ${input.target}`)}const actual=await hashRegularFileAtPath(input.target,pre);if(actual!==input.expectedHash){throw new FsError("hash_mismatch",`expected ${input.expectedHash}, found ${actual}`,{hint:"re-read the file and retry with the latest hash"})}return{mode:pre.mode&4095}}__name(assertAtomicTargetPrecondition,"assertAtomicTargetPrecondition");async function hashRegularFileAtPath(p,pre){const fh=await fsp2.open(p,"r");const hash=createHash2("sha256");let opened;try{opened=await fh.stat();assertSameFile(pre,opened,p,"read");const buf=Buffer.allocUnsafe(64*1024);let offset=0;while(offset<opened.size){const read=await fh.read(buf,0,Math.min(buf.length,opened.size-offset),offset);if(read.bytesRead===0)break;hash.update(buf.subarray(0,read.bytesRead));offset+=read.bytesRead}}finally{await fh.close()}if(opened===void 0){throw new FsError("internal_error",`failed to stat opened file: ${p}`)}const post=await fsp2.lstat(p);assertSameFile(pre,post,p,"read");if(post.size!==opened.size||post.mtimeMs!==opened.mtimeMs){throw new FsError("hash_mismatch",`file changed during hash: ${p}`,{hint:"retry after re-reading the latest file hash"})}return`sha256:${hash.digest("hex")}`}__name(hashRegularFileAtPath,"hashRegularFileAtPath");function hashBuffer(buf){return`sha256:${createHash2("sha256").update(buf).digest("hex")}`}__name(hashBuffer,"hashBuffer");function assertSameFile(pre,post,p,intent){const preDev=toBigInt(pre.dev);const postDev=toBigInt(post.dev);const preIno=toBigInt(pre.ino);const postIno=toBigInt(post.ino);if(preDev!==0n&&postDev!==0n&&preIno!==0n&&postIno!==0n&&(preDev!==postDev||preIno!==postIno)){throw new FsError("symlink_escape",`path changed during ${intent}: ${p}`,{hint:"TOCTOU swap detected via device/inode comparison"})}}__name(assertSameFile,"assertSameFile");function toBigInt(value){return typeof value==="bigint"?value:BigInt(value)}__name(toBigInt,"toBigInt");async function syncHandleBestEffort(fh){try{await fh.sync()}catch{}}__name(syncHandleBestEffort,"syncHandleBestEffort");async function fsyncParentDirBestEffort(parent){let fh;try{fh=await fsp2.open(parent,"r");await fh.sync()}catch{}finally{await fh?.close().catch(()=>void 0)}}__name(fsyncParentDirBestEffort,"fsyncParentDirBestEffort");async function chmodHandleBestEffort(fh,mode){try{await fh.chmod(mode)}catch{}}__name(chmodHandleBestEffort,"chmodHandleBestEffort");async function assertTempPathMatchesStat(tmpPath,expected){const st=await fsp2.lstat(tmpPath);if(st.isSymbolicLink()){throw new FsError("symlink_escape",`temporary path is a symlink: ${tmpPath}`,{hint:"temp-file race detected before final rename"})}if(!st.isFile()){throw new FsError("parse_error",`temporary path is not a regular file: ${tmpPath}`)}assertSameFile(expected,st,tmpPath,"write")}__name(assertTempPathMatchesStat,"assertTempPathMatchesStat");async function publishCreateNoClobber(tmpPath,target){try{await fsp2.link(tmpPath,target)}catch(err){const code=err?.code;if(code==="EEXIST"){throw new FsError("file_already_exists",`file already exists: ${target}`)}throw err}await fsp2.unlink(tmpPath).catch(()=>void 0)}__name(publishCreateNoClobber,"publishCreateNoClobber");async function renameWithRetryLocal(src,dest,retries,delayMs){for(let attempt=0;attempt<=retries;attempt++){try{await fsp2.rename(src,dest);return}catch(err){const code=err?.code;const retryable=code==="EPERM"||code==="EACCES";if(!retryable||attempt===retries)throw err;await new Promise(resolve4=>setTimeout(resolve4,delayMs*2**attempt))}}}__name(renameWithRetryLocal,"renameWithRetryLocal");function countOccurrences(haystack,needle){let count=0;let index=0;while(true){const found=haystack.indexOf(needle,index);if(found===-1)return count;count+=1;index=found+needle.length}}__name(countOccurrences,"countOccurrences");function safeUtf8Truncate(buf,maxBytes){if(buf.length<=maxBytes)return buf;let end=maxBytes;while(end>0&&(buf[end]&192)===128)end--;return buf.subarray(0,end)}__name(safeUtf8Truncate,"safeUtf8Truncate");async function assertInodeStableAfterRead(p,preIno){const post=await fsp2.lstat(p);if(post.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink during read: ${p}`,{hint:"TOCTOU swap detected via post-read lstat"})}const preNum=toBigInt(preIno);const postNum=toBigInt(post.ino);if(preNum!==0n&&postNum!==0n&&preNum!==postNum){throw new FsError("symlink_escape",`path inode changed during read: ${p}`,{hint:"TOCTOU swap detected via inode comparison"})}}__name(assertInodeStableAfterRead,"assertInodeStableAfterRead");async function assertNotSymlinkBeforeWrite(p){let pre;try{pre=await fsp2.lstat(p)}catch(err){const code=err?.code;if(code==="ENOENT")return;throw err}if(pre.isSymbolicLink()){throw new FsError("symlink_escape",`path was replaced with a symlink before write: ${p}`,{hint:"TOCTOU swap detected via pre-write lstat \u2014 re-resolve before retrying"})}}__name(assertNotSymlinkBeforeWrite,"assertNotSymlinkBeforeWrite");function kindFromStatLike(s){if(s.isSymbolicLink())return"symlink";if(s.isDirectory())return"directory";if(s.isFile())return"file";return"other"}__name(kindFromStatLike,"kindFromStatLike");function errorCode(err){return err?.code}__name(errorCode,"errorCode");function errorKindForRealpathFailure(err){const code=errorCode(err);if(code==="EACCES"||code==="EPERM")return"permission_denied";if(code==="ENOENT"||code==="ELOOP")return"symlink_escape";return"io_error"}__name(errorKindForRealpathFailure,"errorKindForRealpathFailure");function buildWriteMeta(opts){const meta={};if(opts.bom!==void 0)meta["bom"]=opts.bom;if(opts.encoding)meta["encoding"]=opts.encoding;if(opts.lineEnding)meta["lineEnding"]=opts.lineEnding;return Object.keys(meta).length>0?meta:void 0}__name(buildWriteMeta,"buildWriteMeta");var MAX_LIST_ENTRIES=2e3;var MAX_FILE_LINE_LIMIT=2e3;var DEFAULT_FILE_BYTES_MAX_BYTES=64*1024;var DEFAULT_GLOB_MAX_RESULTS=5e3;var MAX_GLOB_MAX_RESULTS=5e4;function applyReadHeaders(res){res.set("Cache-Control","no-store");res.set("X-Content-Type-Options","nosniff")}__name(applyReadHeaders,"applyReadHeaders");function sendFsError(res,err,route){applyReadHeaders(res);if(sendGenerationClosedError(res,err))return;if(isFsError(err)){const fs3=err;res.status(fs3.status).json({errorKind:fs3.kind,error:fs3.message,hint:fs3.hint,status:fs3.status});return}writeStderrLine(`qwen serve: ${route} unexpected error: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({errorKind:"internal_error",error:err instanceof Error?err.message:String(err),status:500})}__name(sendFsError,"sendFsError");function parseIntInRange(raw,min,max){if(raw===void 0)return void 0;if(typeof raw!=="string"||!/^\d+$/.test(raw))return null;const n=Number.parseInt(raw,10);if(!Number.isSafeInteger(n)||n<min||n>max)return null;return n}__name(parseIntInRange,"parseIntInRange");function parseBoolFlag(raw){return raw==="1"||raw==="true"}__name(parseBoolFlag,"parseBoolFlag");function requireStringQuery(res,raw,name,route){if(typeof raw!=="string"||raw.length===0){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`${name} query parameter is required`,status:400});writeStderrLine(`qwen serve: ${route} rejected request missing required ?${name}`);return null}return raw}__name(requireStringQuery,"requireStringQuery");function routeName(req,legacyRoute){const context=getWorkspaceRouteContext(req);if(!context)return legacyRoute;return`${context.routePrefix}${legacyRoute.slice("GET ".length)}`}__name(routeName,"routeName");function getFsFactory(req,res){const context=getWorkspaceRouteContext(req);if(context)return context.runtime.routeFileSystemFactory;const factory=req.app.locals.fsFactory;if(!factory){applyReadHeaders(res);res.status(500).json({errorKind:"internal_error",error:"workspace filesystem factory is not configured",status:500});return null}return factory}__name(getFsFactory,"getFsFactory");async function handleGetFile(req,res,deps){const ROUTE=routeName(req,"GET /file");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const maxBytes=parseIntInRange(req.query["maxBytes"],1,256*1024);if(maxBytes===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:"`maxBytes` must be a positive integer in [1, 262144]",status:400});return}const line=parseIntInRange(req.query["line"],1,Number.MAX_SAFE_INTEGER);if(line===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:"`line` must be a positive integer",status:400});return}const limit=parseIntInRange(req.query["limit"],1,MAX_FILE_LINE_LIMIT);if(limit===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`limit\` must be a positive integer in [1, ${MAX_FILE_LINE_LIMIT}]`,status:400});return}const rawCursor=req.query["cursor"];if(rawCursor!==void 0&&(typeof rawCursor!=="string"||rawCursor.length===0||rawCursor.length>MAX_TEXT_CURSOR_CHARS)){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`cursor\` must be a non-empty string of at most ${MAX_TEXT_CURSOR_CHARS} characters`,status:400});return}const cursor=rawCursor;const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"read");const out=await fs3.readText(resolved,{maxBytes,line,limit,cursor});const returnedBytes=Buffer.byteLength(out.content,"utf-8");applyReadHeaders(res);res.status(200).json({kind:"file",path:workspaceRelative(req,resolved),content:out.content,encoding:out.meta.encoding??"utf-8",bom:out.meta.bom===true,lineEnding:out.meta.lineEnding,sizeBytes:out.meta.sizeBytes??returnedBytes,returnedBytes,truncated:out.meta.truncated===true,hash:out.meta.hash,matchedIgnore:out.meta.matchedIgnore??null,originalLineCount:out.meta.originalLineCount??null,nextCursor:out.meta.nextCursor??null,hasMore:out.meta.hasMore===true})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetFile,"handleGetFile");async function handleGetFileBytes(req,res,deps){const ROUTE=routeName(req,"GET /file/bytes");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const offset=parseIntInRange(req.query["offset"],0,Number.MAX_SAFE_INTEGER);if(offset===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:"`offset` must be a non-negative safe integer",status:400});return}const maxBytes=parseIntInRange(req.query["maxBytes"],1,MAX_READ_BYTES);if(maxBytes===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`maxBytes\` must be a positive integer in [1, ${MAX_READ_BYTES}]`,status:400});return}const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"read");const out=await fs3.readBytesWindow(resolved,{offset:offset??0,maxBytes:maxBytes??DEFAULT_FILE_BYTES_MAX_BYTES});applyReadHeaders(res);res.status(200).json({kind:"file_bytes",path:workspaceRelative(req,resolved),offset:out.offset,sizeBytes:out.sizeBytes,returnedBytes:out.returnedBytes,truncated:out.truncated,contentBase64:out.buffer.toString("base64"),...out.hash?{hash:out.hash}:{}})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetFileBytes,"handleGetFileBytes");async function handleGetStat(req,res,deps){const ROUTE=routeName(req,"GET /stat");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"stat");const st=await fs3.stat(resolved);applyReadHeaders(res);res.status(200).json({kind:"stat",path:workspaceRelative(req,resolved),type:st.kind,sizeBytes:st.sizeBytes,modifiedMs:st.modifiedMs})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetStat,"handleGetStat");async function handleGetList(req,res,deps){const ROUTE=routeName(req,"GET /list");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const queryPath=requireStringQuery(res,req.query["path"],"path",ROUTE);if(queryPath===null)return;const includeIgnored=parseBoolFlag(req.query["includeIgnored"]);const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});try{const resolved=await fs3.resolve(queryPath,"list");const entries=await fs3.list(resolved,{includeIgnored,maxEntries:MAX_LIST_ENTRIES+1});let truncated=false;let returned=entries;if(returned.length>MAX_LIST_ENTRIES){returned=returned.slice(0,MAX_LIST_ENTRIES);truncated=true}applyReadHeaders(res);res.status(200).json({kind:"list",path:workspaceRelative(req,resolved),entries:returned,truncated,matchedIgnore:null})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetList,"handleGetList");async function handleGetGlob(req,res,deps){const ROUTE=routeName(req,"GET /glob");const factory=getFsFactory(req,res);if(!factory)return;const clientId=deps.parseClientId(req,res);if(clientId===null)return;const pattern=requireStringQuery(res,req.query["pattern"],"pattern",ROUTE);if(pattern===null)return;const includeIgnored=parseBoolFlag(req.query["includeIgnored"]);const maxResults=parseIntInRange(req.query["maxResults"],1,MAX_GLOB_MAX_RESULTS);if(maxResults===null){applyReadHeaders(res);res.status(400).json({errorKind:"parse_error",error:`\`maxResults\` must be a positive integer in [1, ${MAX_GLOB_MAX_RESULTS}]`,status:400});return}const cwdRaw=req.query["cwd"];const cwdString=typeof cwdRaw==="string"&&cwdRaw.length>0?cwdRaw:void 0;const fs3=factory.forRequest({originatorClientId:clientId??void 0,route:ROUTE});const start=performance.now();try{const cwdResolved=cwdString?await fs3.resolve(cwdString,"list"):void 0;const cap=maxResults??DEFAULT_GLOB_MAX_RESULTS;const probe=await fs3.glob(pattern,{cwd:cwdResolved,includeIgnored,maxResults:cap+1});const truncated=probe.truncated===true||probe.length>cap;const trimmed=truncated?probe.slice(0,cap):probe;const relMatches=trimmed.map(m=>workspaceRelative(req,m));applyReadHeaders(res);res.status(200).json({kind:"glob",pattern,cwd:cwdString??"",matches:relMatches,count:relMatches.length,truncated,durationMs:Math.round(performance.now()-start)})}catch(err){sendFsError(res,err,ROUTE)}}__name(handleGetGlob,"handleGetGlob");function workspaceRelative(req,resolved){const boundWorkspace=getWorkspaceRouteContext(req)?.runtime.workspaceCwd??req.app.locals.boundWorkspace;if(!boundWorkspace){throw new Error("bound workspace is not configured")}let rel=path5.relative(boundWorkspace,resolved);if(isOutsideWorkspaceRelative(rel)){try{rel=path5.relative(canonicalizeWorkspace(boundWorkspace),resolved)}catch{throw new FsError("path_outside_workspace","path resolved outside workspace")}}if(isOutsideWorkspaceRelative(rel)){throw new FsError("path_outside_workspace","path resolved outside workspace")}if(rel==="")return".";return path5.sep==="/"?rel:rel.split(path5.sep).join("/")}__name(workspaceRelative,"workspaceRelative");function isOutsideWorkspaceRelative(rel){return rel===".."||rel.startsWith(`..${path5.sep}`)||path5.isAbsolute(rel)}__name(isOutsideWorkspaceRelative,"isOutsideWorkspaceRelative");function registerWorkspaceFileReadRoutes(app,deps){app.get("/file",(req,res)=>handleGetFile(req,res,deps));app.get("/file/bytes",(req,res)=>handleGetFileBytes(req,res,deps));app.get("/stat",(req,res)=>handleGetStat(req,res,deps));app.get("/list",(req,res)=>handleGetList(req,res,deps));app.get("/glob",(req,res)=>handleGetGlob(req,res,deps))}__name(registerWorkspaceFileReadRoutes,"registerWorkspaceFileReadRoutes");function registerWorkspaceQualifiedFileReadRoutes(app,deps){const resolve4=__name((req,res)=>{const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return false;setWorkspaceRouteContext(req,{runtime,routePrefix:"GET /workspaces/:workspace"});return true},"resolve");app.get("/workspaces/:workspace/file",(req,res)=>{if(!resolve4(req,res))return;void handleGetFile(req,res,deps)});app.get("/workspaces/:workspace/file/bytes",(req,res)=>{if(!resolve4(req,res))return;void handleGetFileBytes(req,res,deps)});app.get("/workspaces/:workspace/stat",(req,res)=>{if(!resolve4(req,res))return;void handleGetStat(req,res,deps)});app.get("/workspaces/:workspace/list",(req,res)=>{if(!resolve4(req,res))return;void handleGetList(req,res,deps)});app.get("/workspaces/:workspace/glob",(req,res)=>{if(!resolve4(req,res))return;void handleGetGlob(req,res,deps)})}__name(registerWorkspaceQualifiedFileReadRoutes,"registerWorkspaceQualifiedFileReadRoutes");init_esbuild_shims();init_esbuild_shims();import path6 from"node:path";var PersistedSessionListCache=class{constructor(ttlMs,maxRetainedSummaries){this.ttlMs=ttlMs;this.maxRetainedSummaries=maxRetainedSummaries}static{__name(this,"PersistedSessionListCache")}slots=new Map;retainedSummaries=0;lookup(scope,loader,options={}){options.signal?.throwIfAborted();const key=this.key(scope);let slot=this.slots.get(key);if(!slot){slot={generation:0};this.slots.set(key,slot)}const now=Date.now();if(slot.value){const cacheAgeMs=Math.max(0,now-slot.value.completedAt);if(cacheAgeMs<this.ttlMs){const snapshot=slot.value.snapshot;return{status:"cache_hit",promise:Promise.resolve().then(()=>{options.signal?.throwIfAborted();return snapshot}),cacheAgeMs}}this.removeValue(slot)}if(slot.inFlight!==void 0&&slot.inFlight.generation===slot.generation&&!slot.inFlight.controller.signal.aborted){return{status:"single_flight",promise:this.attachWaiter(key,slot,slot.inFlight,options.signal)}}const generation=slot.generation;const controller=new AbortController;const load={generation,controller,promise:void 0,waiterCount:0,settled:false};const managed=Promise.resolve().then(()=>{controller.signal.throwIfAborted();return loader(controller.signal)}).then(snapshot=>{load.settled=true;const current=this.slots.get(key);if(current===slot&&current.inFlight===load){current.inFlight=void 0;if(current.generation===generation&&!controller.signal.aborted&&snapshot.sessions.length<=this.maxRetainedSummaries){this.installValue(key,current,snapshot)}else if(current.value===void 0){this.slots.delete(key)}}return snapshot},error=>{load.settled=true;const current=this.slots.get(key);if(current===slot&&current.inFlight===load){current.inFlight=void 0;if(current.value===void 0)this.slots.delete(key)}throw error});load.promise=managed;slot.inFlight=load;return{status:"scan",promise:this.attachWaiter(key,slot,load,options.signal)}}invalidate(scope){const key=this.key(scope);const slot=this.slots.get(key);if(!slot)return;slot.generation+=1;this.removeValue(slot);if(slot.inFlight===void 0)this.slots.delete(key)}clear(){for(const slot of this.slots.values()){if(slot.value)clearTimeout(slot.value.expiryTimer)}this.slots.clear();this.retainedSummaries=0}installValue(key,slot,snapshot){const completedAt=Date.now();this.evictFor(snapshot.sessions.length);const remainingTtlMs=Math.max(0,this.ttlMs-(Date.now()-completedAt));const expiryTimer=setTimeout(()=>{const current=this.slots.get(key);if(current!==slot||current.value?.expiryTimer!==expiryTimer){return}this.removeValue(current);if(current.inFlight===void 0)this.slots.delete(key)},remainingTtlMs);if(typeof expiryTimer.unref==="function")expiryTimer.unref();const value={snapshot,completedAt,expiryTimer};slot.value=value;this.retainedSummaries+=snapshot.sessions.length}evictFor(incomingSummaries){while(this.retainedSummaries+incomingSummaries>this.maxRetainedSummaries){let oldest;for(const[key,slot]of this.slots){if(slot.value&&(oldest===void 0||slot.value.completedAt<oldest.completedAt)){oldest={key,slot,completedAt:slot.value.completedAt}}}if(!oldest)return;this.removeValue(oldest.slot);if(oldest.slot.inFlight===void 0)this.slots.delete(oldest.key)}}removeValue(slot){const value=slot.value;if(!value)return;clearTimeout(value.expiryTimer);this.retainedSummaries-=value.snapshot.sessions.length;slot.value=void 0}attachWaiter(key,slot,load,signal){load.waiterCount+=1;return new Promise((resolve4,reject)=>{let settled=false;const settle=__name(finish=>{if(settled)return;settled=true;signal?.removeEventListener("abort",onAbort);load.waiterCount-=1;if(load.waiterCount===0&&!load.settled){load.controller.abort(new DOMException("No active session list waiters","AbortError"));const current=this.slots.get(key);if(current===slot&&current.inFlight===load){current.inFlight=void 0;if(current.value===void 0)this.slots.delete(key)}}finish()},"settle");const onAbort=__name(()=>{if(load.settled)return;settle(()=>reject(signal?.reason))},"onAbort");signal?.addEventListener("abort",onAbort,{once:true});if(signal?.aborted)onAbort();void load.promise.then(snapshot=>settle(()=>resolve4(snapshot)),error=>settle(()=>reject(error)))})}key(scope){return JSON.stringify([path6.resolve(scope.runtimeBaseDir),scope.workspaceCwd,scope.archiveState])}};init_esbuild_shims();function laterActivityTimestamp(live,persisted){const liveTime=live===void 0?Number.NaN:Date.parse(live);const persistedTime=persisted===void 0?Number.NaN:Date.parse(persisted);const liveValid=Number.isFinite(liveTime);const persistedValid=Number.isFinite(persistedTime);if(liveValid&&persistedValid){return liveTime>=persistedTime?live:persisted}if(liveValid)return live;if(persistedValid)return persisted;return live??persisted}__name(laterActivityTimestamp,"laterActivityTimestamp");var DEFAULT_SESSION_PAGE_SIZE=20;var MAX_SESSION_PAGE_SIZE=100;var MAX_ORGANIZED_SESSIONS=5e4;var MAX_EMITTED_CURSOR_SESSION_IDS=64;var PERSISTED_SESSION_LIST_CACHE_TTL_MS=2e3;var persistedSessionListCache=new PersistedSessionListCache(PERSISTED_SESSION_LIST_CACHE_TTL_MS,MAX_ORGANIZED_SESSIONS);function invalidateWorkspaceSessionListCache(options){for(const archiveState of options.archiveStates){persistedSessionListCache.invalidate({runtimeBaseDir:options.runtimeBaseDir,workspaceCwd:options.workspaceCwd,archiveState})}}__name(invalidateWorkspaceSessionListCache,"invalidateWorkspaceSessionListCache");var InvalidCursorError=class extends Error{static{__name(this,"InvalidCursorError")}constructor(cursor,kind="numeric"){super(`Invalid cursor: "${cursor}" is not a valid ${kind} cursor`);this.name="InvalidCursorError"}};function isPersistedSessionCursor(cursor){if(cursor==="")return false;const trimmed=cursor.trim();if(trimmed==="")return false;const parts=trimmed.split("|");if(parts.length===2&&parts[0].trim()!==""&&parts[1].length>0){const mtime=Number(parts[0]);if(Number.isFinite(mtime)&&mtime>=0)return true}const parsed=Number(trimmed);return Number.isFinite(parsed)&&parsed>=0&&parsed<=Number.MAX_SAFE_INTEGER}__name(isPersistedSessionCursor,"isPersistedSessionCursor");function parseSessionCursor(cursor){if(cursor==="")return void 0;if(!isPersistedSessionCursor(cursor)){throw new InvalidCursorError(cursor,"persisted")}const trimmed=cursor.trim();const parsed=Number(trimmed);return Number.isFinite(parsed)?parsed:trimmed}__name(parseSessionCursor,"parseSessionCursor");function parseEmittedSessionIds(value){if(value===void 0)return[];if(!Array.isArray(value)||value.some(id=>typeof id!=="string"||id.length===0)){return void 0}return value}__name(parseEmittedSessionIds,"parseEmittedSessionIds");function parseOrganizedCursor(cursor,expected){if(cursor==="")return void 0;try{const decoded=Buffer.from(cursor,"base64url").toString("utf8");const parsed=JSON.parse(decoded);const last=parsed.last;if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)||typeof last!=="object"||last===null||Array.isArray(last)||typeof last.isPinned!=="boolean"||typeof last.activityTime!=="number"||!Number.isFinite(last.activityTime)||typeof last.sessionId!=="string"||last.sessionId.length===0||parsed.catalogKind!==void 0&&parsed.catalogKind!=="organized"||parsed.paginateMerged!==void 0&&parsed.paginateMerged!==expected.paginateMerged||(parsed.sortBy??"updatedAt")!==(expected.sortBy??"updatedAt")||parsed.group!==expected.group||parsed.archiveState!==expected.archiveState||parsed.sourceType!==expected.sourceType||parsed.sourceId!==expected.sourceId||parsed.conversationKind!==expected.conversationKind){throw new Error("invalid organized cursor")}const emitted=parseEmittedSessionIds(parsed.emitted);if(emitted===void 0){throw new Error("invalid organized cursor")}return{last,emitted}}catch{throw new InvalidCursorError(cursor,"organized")}}__name(parseOrganizedCursor,"parseOrganizedCursor");function encodeOrganizedCursor(last,group,archiveState,paginateMerged,sourceType,sourceId,conversationKind,emitted=[],sortBy){return Buffer.from(JSON.stringify({catalogKind:"organized",sortBy,paginateMerged,group,archiveState,sourceType,sourceId,conversationKind,last,...emitted.length>0?{emitted}:{}}),"utf8").toString("base64url")}__name(encodeOrganizedCursor,"encodeOrganizedCursor");function parseLiveSessionCursor(cursor){if(cursor==="")return void 0;try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)||typeof parsed.activityTime!=="number"||!Number.isFinite(parsed.activityTime)||typeof parsed.sessionId!=="string"||parsed.sessionId.length===0){throw new Error("invalid live cursor")}return parsed}catch{throw new InvalidCursorError(cursor,"live")}}__name(parseLiveSessionCursor,"parseLiveSessionCursor");function encodeLiveSessionCursor(last){return Buffer.from(JSON.stringify(last),"utf8").toString("base64url")}__name(encodeLiveSessionCursor,"encodeLiveSessionCursor");function matchesSessionMetadataSource(session,filter){if(filter.conversationKind==="standalone-top-level"&&classifyTopLevelConversationSource(session)?.kind!=="standalone"){return false}const sourceTypeMatches=filter.sourceType===void 0||session.sourceType===filter.sourceType||filter.sourceType==="default"&&(session.sourceType===void 0||session.sourceType==="qwen-live");return sourceTypeMatches&&(filter.sourceId===void 0||session.sourceId===filter.sourceId)}__name(matchesSessionMetadataSource,"matchesSessionMetadataSource");function parseMetadataSessionCursor(cursor,expected){if(cursor==="")return void 0;try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));const last=parsed.last;if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)||typeof last!=="object"||last===null||Array.isArray(last)||typeof last.activityTime!=="number"||!Number.isFinite(last.activityTime)||typeof last.sessionId!=="string"||last.sessionId.length===0||parsed.catalogKind!==void 0&&parsed.catalogKind!=="metadata"||parsed.paginateMerged!==void 0&&parsed.paginateMerged!==expected.paginateMerged||(parsed.sortBy??"updatedAt")!==(expected.sortBy??"updatedAt")||parsed.parentSessionId!==expected.parentSessionId||parsed.sourceType!==expected.sourceType||parsed.sourceId!==expected.sourceId||parsed.conversationKind!==expected.conversationKind||parsed.archiveState!==expected.archiveState){throw new Error("invalid metadata cursor")}const emitted=parseEmittedSessionIds(parsed.emitted);if(emitted===void 0){throw new Error("invalid metadata cursor")}return{last:{activityTime:last.activityTime,sessionId:last.sessionId},emitted}}catch{throw new InvalidCursorError(cursor,expected.parentSessionId!==void 0?"parent":"metadata")}}__name(parseMetadataSessionCursor,"parseMetadataSessionCursor");function encodeMetadataSessionCursor(last,filter,archiveState,paginateMerged,emitted=[]){return Buffer.from(JSON.stringify({catalogKind:"metadata",paginateMerged,...filter,archiveState,last,...emitted.length>0?{emitted}:{}}),"utf8").toString("base64url")}__name(encodeMetadataSessionCursor,"encodeMetadataSessionCursor");async function enrichWorktreeSidecars(bySessionId,sessionService,archiveState="active",signal){for(const[sessionId,summary]of bySessionId){signal?.throwIfAborted();if(summary.worktree)continue;let sidecar;try{const sidecarPath=sessionService.getWorktreeSessionPathForArchiveState(sessionId,archiveState);sidecar=signal?await readWorktreeSession(sidecarPath,{signal}):await readWorktreeSession(sidecarPath)}catch{signal?.throwIfAborted();sidecar=null}if(sidecar&&await readWorktreeSessionMarker(sidecar.worktreePath)===sessionId){bySessionId.set(sessionId,{...summary,worktree:{slug:sidecar.slug,path:sidecar.worktreePath,branch:sidecar.worktreeBranch}})}}}__name(enrichWorktreeSidecars,"enrichWorktreeSidecars");async function enrichPrSidecars(bySessionId,sessionService,archiveState,signal){for(const[sessionId,summary]of bySessionId){signal?.throwIfAborted();let result;try{const sidecarPath=sessionService.getPrSessionPathForArchiveState(sessionId,archiveState);result=signal?await readSessionPrsDetailed(sidecarPath,{signal}):await readSessionPrsDetailed(sidecarPath)}catch{signal?.throwIfAborted();result={status:"invalid"}}if(result.status==="ok"){bySessionId.set(sessionId,{...summary,prs:sidecarToPrInfos(result.prs)})}}}__name(enrichPrSidecars,"enrichPrSidecars");function toSummary(item){return{sessionId:item.sessionId,workspaceCwd:item.cwd,createdAt:item.startTime,updatedAt:new Date(item.mtime).toISOString(),displayName:item.customTitle||item.prompt,...item.customTitle&&item.titleSource?{titleSource:item.titleSource}:{},...item.parentSessionId?{parentSessionId:item.parentSessionId}:{},...item.sourceType?{sourceType:item.sourceType}:{},...item.sourceId!==void 0?{sourceId:item.sourceId}:{},clientCount:0,hasActivePrompt:false,isArchived:item.isArchived===true}}__name(toSummary,"toSummary");function mergeLiveSessionSummary(existing,live){const merged={...existing,...live,createdAt:existing.createdAt,displayName:live.displayName??existing.displayName,parentSessionId:existing.parentSessionId??live.parentSessionId,sourceType:existing.sourceType??live.sourceType,sourceId:existing.sourceType!==void 0?existing.sourceId:live.sourceId,updatedAt:laterActivityTimestamp(live.updatedAt,existing.updatedAt),clientCount:live.clientCount,hasActivePrompt:live.hasActivePrompt,backgroundTurn:live.backgroundTurn,hasRunningBackgroundTasks:live.hasRunningBackgroundTasks,isArchived:false};if(existing.prs||live.prs){merged.prs=mergeSummaryPrs(existing.prs,live.prs)}return merged}__name(mergeLiveSessionSummary,"mergeLiveSessionSummary");function sidecarToPrInfos(sidecar){return sidecar.map(toSessionPrInfo)}__name(sidecarToPrInfos,"sidecarToPrInfos");function mergeSummaryPrs(persistedPrs,livePrs){const live=livePrs??[];const persisted=persistedPrs??[];const liveByNumber=new Map(live.map(l=>[l.number,l]));const persistedNumbers=new Set(persisted.map(p=>p.number));const consumedLive=new Set;const ordered=[];for(const p of persisted){const liveEntry=liveByNumber.get(p.number);if(!liveEntry){ordered.push(p);continue}const samePr=canonicalSessionPrUrl(p.url)===canonicalSessionPrUrl(liveEntry.url);const matchedTwinExists=persisted.some(q=>q.number===p.number&&canonicalSessionPrUrl(q.url)===canonicalSessionPrUrl(liveEntry.url));if(!samePr&&matchedTwinExists)continue;if(consumedLive.has(p.number))continue;consumedLive.add(p.number);ordered.push(samePr?{...liveEntry,...p.state?{state:p.state}:{},...p.issues?{issues:p.issues}:{}}:p)}for(const liveEntry of live){if(!persistedNumbers.has(liveEntry.number)&&persisted.length<SESSION_PR_LIST_LIMIT){ordered.push(liveEntry)}}return ordered.slice(-SESSION_PR_LIST_LIMIT)}__name(mergeSummaryPrs,"mergeSummaryPrs");async function liveOnlySummary(live,sessionService,signal){const summary={...live,createdAt:live.createdAt,clientCount:live.clientCount,hasActivePrompt:live.hasActivePrompt,backgroundTurn:live.backgroundTurn,hasRunningBackgroundTasks:live.hasRunningBackgroundTasks,isArchived:false};let result;try{const sidecarPath=sessionService.getPrSessionPathForArchiveState(live.sessionId,"active");result=signal?await readSessionPrsDetailed(sidecarPath,{signal}):await readSessionPrsDetailed(sidecarPath)}catch{signal?.throwIfAborted();result={status:"invalid"}}if(result.status==="ok"){summary.prs=mergeSummaryPrs(sidecarToPrInfos(result.prs),live.prs)}return summary}__name(liveOnlySummary,"liveOnlySummary");function clonePersistedSummary(session){return{...session,...session.worktree?{worktree:{...session.worktree}}:{}}}__name(clonePersistedSummary,"clonePersistedSummary");async function loadAllPersistedSummaries(sessionService,archiveState,signal){const scanStartedAt=performance.now();signal.throwIfAborted();const sessions=[];let truncated=false;let scanPages=0;let cursor;do{scanPages+=1;const page=await sessionService.listSessions({cursor,size:1e4,archiveState,signal,excludeSourceTypes:[...HIDDEN_CATALOG_SOURCE_TYPES]});signal.throwIfAborted();const remaining=MAX_ORGANIZED_SESSIONS-sessions.length;sessions.push(...page.items.slice(0,remaining).map(toSummary));cursor=page.nextCursor;if(page.items.length===0){break}if(page.items.length>remaining||sessions.length>=MAX_ORGANIZED_SESSIONS&&cursor!==void 0){writeStderrLine(`qwen serve: organized session list truncated at ${MAX_ORGANIZED_SESSIONS} sessions`);truncated=true;break}}while(cursor!==void 0);const bySessionId=new Map(sessions.map(session=>[session.sessionId,session]));await enrichWorktreeSidecars(bySessionId,sessionService,archiveState,signal);await enrichPrSidecars(bySessionId,sessionService,archiveState,signal);signal.throwIfAborted();return{sessions:[...bySessionId.values()],truncated,scanPages,scanDurationMs:Math.max(0,performance.now()-scanStartedAt)}}__name(loadAllPersistedSummaries,"loadAllPersistedSummaries");async function listAllPersistedSummaries(sessionService,workspaceCwd,archiveState,runtimeBaseDir,queryKind,signal){const lookup=persistedSessionListCache.lookup({runtimeBaseDir,workspaceCwd,archiveState},loadSignal=>loadAllPersistedSummaries(sessionService,archiveState,loadSignal),{signal});addDaemonRequestAttribute("qwen-code.daemon.session_list.cache_status",lookup.status);addDaemonRequestAttribute("qwen-code.daemon.session_list.archive_state",archiveState);addDaemonRequestAttribute("qwen-code.daemon.session_list.query_kind",queryKind);if(lookup.cacheAgeMs!==void 0){addDaemonRequestAttribute("qwen-code.daemon.session_list.cache_age_ms",lookup.cacheAgeMs)}const snapshot=await lookup.promise;signal?.throwIfAborted();addDaemonRequestAttribute("qwen-code.daemon.session_list.persisted_sessions",snapshot.sessions.length);addDaemonRequestAttribute("qwen-code.daemon.session_list.scan_pages",snapshot.scanPages);addDaemonRequestAttribute("qwen-code.daemon.session_list.truncated",snapshot.truncated);if(lookup.status!=="cache_hit"){addDaemonRequestAttribute("qwen-code.daemon.session_list.scan_duration_ms",snapshot.scanDurationMs)}return snapshot}__name(listAllPersistedSummaries,"listAllPersistedSummaries");function getSummaryActivityTime(session,sortBy){if(sortBy==="lastUserPromptAt"){const time2=Date.parse(session.lastUserPromptAt??"");return Number.isFinite(time2)?time2:Number.MIN_SAFE_INTEGER}const time=Date.parse(session.updatedAt??session.createdAt);return Number.isFinite(time)?time:0}__name(getSummaryActivityTime,"getSummaryActivityTime");function getLiveSessionCursorKey(session,sortBy){return{activityTime:getSummaryActivityTime(session,sortBy),sessionId:session.sessionId}}__name(getLiveSessionCursorKey,"getLiveSessionCursorKey");function compareLiveSessionCursorKeys(a,b){const byTime=b.activityTime-a.activityTime;if(byTime!==0)return byTime;return a.sessionId.localeCompare(b.sessionId)}__name(compareLiveSessionCursorKeys,"compareLiveSessionCursorKeys");function compareOrganizedSessions(activityTimeById,a,b){return compareOrganizedCursorKeys(getOrganizedCursorKey(activityTimeById,a),getOrganizedCursorKey(activityTimeById,b))}__name(compareOrganizedSessions,"compareOrganizedSessions");function getOrganizedCursorKey(activityTimeById,session){return{isPinned:session.isPinned===true,activityTime:activityTimeById.get(session.sessionId)??0,sessionId:session.sessionId}}__name(getOrganizedCursorKey,"getOrganizedCursorKey");function compareOrganizedCursorKeys(a,b){const byPinned=Number(b.isPinned)-Number(a.isPinned);if(byPinned!==0)return byPinned;const byTime=b.activityTime-a.activityTime;if(byTime!==0)return byTime;return a.sessionId.localeCompare(b.sessionId)}__name(compareOrganizedCursorKeys,"compareOrganizedCursorKeys");function nextEmittedSessionIds(options){const candidates=new Set(options.carried);for(const row of options.page){if(options.liveSessionIds.has(row.sessionId)){candidates.add(row.sessionId)}}const kept=[];for(const sessionId of candidates){const row=options.listedById.get(sessionId);if(!row){kept.push({sessionId,persistedTime:Number.NEGATIVE_INFINITY});continue}const persistedTime=options.persistedTimeById.get(sessionId);if(persistedTime===void 0){kept.push({sessionId,persistedTime:Number.NEGATIVE_INFINITY});continue}if(options.reenters(row,persistedTime)){kept.push({sessionId,persistedTime})}}if(kept.length>MAX_EMITTED_CURSOR_SESSION_IDS){kept.sort((a,b)=>a.persistedTime-b.persistedTime);kept.length=MAX_EMITTED_CURSOR_SESSION_IDS}return kept.map(entry=>entry.sessionId)}__name(nextEmittedSessionIds,"nextEmittedSessionIds");function applyOrganization(session,organization){return{...session,groupId:organization?.groupId??null,color:organization?.color??null,isPinned:organization?.isPinned===true,...organization?.pinnedAt!==void 0?{pinnedAt:organization.pinnedAt}:{}}}__name(applyOrganization,"applyOrganization");async function listOrganizedWorkspaceSessionsForResponse(bridge,workspaceCwd,options,pageSize,readOptions){const archiveState=options.archiveState??"active";const sessionService=new SessionService(workspaceCwd);const organizationService=createSessionOrganizationService(workspaceCwd);readOptions.signal?.throwIfAborted();const snapshot=await organizationService.readSnapshot();readOptions.signal?.throwIfAborted();const knownGroupIds=new Set(snapshot.groups.map(group2=>group2.id));const group=options.group??"all";if(group!=="all"&&group!=="pinned"&&group!=="ungrouped"&&!knownGroupIds.has(group)){throw new SessionOrganizationError(`Group not found: ${group}`,"group_not_found","group")}const cursor=options.cursor!==void 0?parseOrganizedCursor(options.cursor,{paginateMerged:readOptions.paginateMerged===true,group,sortBy:options.sortBy,archiveState,sourceType:options.sourceType,sourceId:options.sourceId,conversationKind:options.conversationKind}):void 0;const cursorKey=cursor?.last;const emittedBeforePage=new Set(cursor?.emitted??[]);const isFirstPage=cursorKey===void 0;let liveMergeFailed=false;const bySessionId=new Map;const persisted=await listAllPersistedSummaries(sessionService,workspaceCwd,archiveState,readOptions.runtimeBaseDir,"organized",readOptions.signal);readOptions.signal?.throwIfAborted();for(const session of persisted.sessions){bySessionId.set(session.sessionId,applyOrganization(clonePersistedSummary(session),snapshot.sessions.get(session.sessionId)))}const persistedTimeById=new Map(persisted.sessions.map(session=>[session.sessionId,getSummaryActivityTime(session)]));const liveSessionIds=new Set;if(readOptions.mergeLive!==false&&archiveState!=="archived"){try{const liveSessions=bridge.listWorkspaceSessions(workspaceCwd);for(const live of liveSessions){liveSessionIds.add(live.sessionId);const existing=bySessionId.get(live.sessionId);const organization=snapshot.sessions.get(live.sessionId);if(existing){bySessionId.set(live.sessionId,applyOrganization(mergeLiveSessionSummary(existing,live),organization))}else if((isFirstPage||readOptions.paginateMerged||options.sortBy==="lastUserPromptAt")&&(!persisted.truncated||!await(readOptions.signal?sessionService.sessionExists(live.sessionId,{signal:readOptions.signal}):sessionService.sessionExists(live.sessionId)))){bySessionId.set(live.sessionId,applyOrganization(await liveOnlySummary(live,sessionService,readOptions.signal),organization))}}}catch(error){readOptions.signal?.throwIfAborted();liveMergeFailed=true;writeStderrLine(`qwen serve: organized session list live merge failed; using persisted sessions only: ${error instanceof Error?error.message:String(error)}`)}}const filtered=[...bySessionId.values()].filter(session=>{if(isHiddenCatalogSource(session.sourceType))return false;if(!matchesSessionMetadataSource(session,options))return false;if(group==="all")return true;if(group==="pinned")return session.isPinned===true;if(group==="ungrouped")return session.groupId==null&&session.color==null;return session.color==null&&session.groupId===group});readOptions.signal?.throwIfAborted();if(options.sortBy==="lastUserPromptAt"){await enrichPromptTimes(filtered,sessionService,archiveState,readOptions,true);for(const session of filtered)persistedTimeById.set(session.sessionId,getSummaryActivityTime(session,options.sortBy))}const activityTimeById=new Map(filtered.map(session=>[session.sessionId,getSummaryActivityTime(session,options.sortBy)]));filtered.sort((a,b)=>compareOrganizedSessions(activityTimeById,a,b));readOptions.signal?.throwIfAborted();const afterCursor=cursorKey===void 0?filtered:filtered.filter(session=>!emittedBeforePage.has(session.sessionId)&&compareOrganizedCursorKeys(cursorKey,getOrganizedCursorKey(activityTimeById,session))<0);const page=afterCursor.slice(0,pageSize);let nextCursor;if(page.length<afterCursor.length){const boundary=getOrganizedCursorKey(activityTimeById,page[page.length-1]);const emitted=nextEmittedSessionIds({carried:emittedBeforePage,page,liveSessionIds,listedById:new Map(filtered.map(session=>[session.sessionId,session])),persistedTimeById,reenters:__name((row,persistedTime)=>[true,false].some(isPinned=>compareOrganizedCursorKeys(boundary,{isPinned,activityTime:persistedTime,sessionId:row.sessionId})<0),"reenters")});nextCursor=encodeOrganizedCursor(boundary,group,archiveState,readOptions.paginateMerged===true,options.sourceType,options.sourceId,options.conversationKind,emitted,options.sortBy)}return{sessions:page,...readOptions.includeGroups?{groups:{groups:snapshot.groups,colorOptions:[...GROUP_COLOR_OPTIONS]}}:{},...nextCursor!==void 0?{nextCursor}:{},...liveMergeFailed?{liveMergeFailed:true}:{},...persisted.truncated?{truncated:true}:{}}}__name(listOrganizedWorkspaceSessionsForResponse,"listOrganizedWorkspaceSessionsForResponse");async function listWorkspaceSessionsByMetadataForResponse(bridge,workspaceCwd,options,pageSize,filter,readOptions){const archiveState=options.archiveState??"active";const sessionService=new SessionService(workspaceCwd);const bySessionId=new Map;const persisted=await listAllPersistedSummaries(sessionService,workspaceCwd,archiveState,readOptions.runtimeBaseDir,"metadata",readOptions.signal);readOptions.signal?.throwIfAborted();const canonicalizeStandaloneIds=filter.conversationKind==="standalone-top-level";const conflictedStandaloneIds=new Set;const persistedTimeById=new Map;for(const session of persisted.sessions){let sessionId=session.sessionId;if(canonicalizeStandaloneIds){const parsed=parseCallerSuppliedSessionId(sessionId);if(parsed.kind!=="valid")continue;sessionId=parsed.sessionId;if(conflictedStandaloneIds.has(sessionId))continue;if(bySessionId.has(sessionId)){bySessionId.delete(sessionId);persistedTimeById.delete(sessionId);conflictedStandaloneIds.add(sessionId);continue}}bySessionId.set(sessionId,{...clonePersistedSummary(session),sessionId});persistedTimeById.set(sessionId,getSummaryActivityTime(session))}const liveSessionIds=new Set;let liveMergeFailed=false;if(readOptions.mergeLive!==false&&archiveState!=="archived"){try{for(const live of bridge.listWorkspaceSessions(workspaceCwd)){let sessionId=live.sessionId;if(canonicalizeStandaloneIds){const parsed=parseCallerSuppliedSessionId(sessionId);if(parsed.kind!=="valid"||conflictedStandaloneIds.has(parsed.sessionId)){continue}sessionId=parsed.sessionId}const canonicalLive=sessionId===live.sessionId?live:{...live,sessionId};liveSessionIds.add(sessionId);const existing=bySessionId.get(sessionId);if(existing){bySessionId.set(sessionId,mergeLiveSessionSummary(existing,canonicalLive))}else if(!persisted.truncated||!await(readOptions.signal?sessionService.sessionExists(sessionId,{signal:readOptions.signal}):sessionService.sessionExists(sessionId))){bySessionId.set(sessionId,await liveOnlySummary(canonicalLive,sessionService,readOptions.signal))}}}catch(error){readOptions.signal?.throwIfAborted();liveMergeFailed=true;writeStderrLine(`qwen serve: session metadata filter live merge failed; using persisted sessions only: ${error instanceof Error?error.message:String(error)}`)}}const matches=[...bySessionId.values()].filter(session=>!isHiddenCatalogSource(session.sourceType)&&(filter.parentSessionId===void 0||session.parentSessionId===filter.parentSessionId)&&matchesSessionMetadataSource(session,filter));readOptions.signal?.throwIfAborted();const cursor=options.cursor!==void 0&&options.cursor!==""?parseMetadataSessionCursor(options.cursor,{paginateMerged:readOptions.paginateMerged===true,...filter,archiveState}):void 0;if(options.sortBy==="lastUserPromptAt"){await enrichPromptTimes(matches,sessionService,archiveState,readOptions,true);for(const session of matches)persistedTimeById.set(session.sessionId,getSummaryActivityTime(session,options.sortBy))}matches.sort((a,b)=>compareLiveSessionCursorKeys(getLiveSessionCursorKey(a,options.sortBy),getLiveSessionCursorKey(b,options.sortBy)));const cursorKey=cursor?.last;const emittedBeforePage=new Set(cursor?.emitted??[]);const afterCursor=cursorKey===void 0?matches:matches.filter(session=>!emittedBeforePage.has(session.sessionId)&&compareLiveSessionCursorKeys(cursorKey,getLiveSessionCursorKey(session,options.sortBy))<0);const page=afterCursor.slice(0,pageSize);let nextCursor;if(page.length<afterCursor.length){const boundary=getLiveSessionCursorKey(page[page.length-1],options.sortBy);const emitted=nextEmittedSessionIds({carried:emittedBeforePage,page,liveSessionIds,listedById:new Map(matches.map(session=>[session.sessionId,session])),persistedTimeById,reenters:__name((row,persistedTime)=>compareLiveSessionCursorKeys(boundary,{activityTime:persistedTime,sessionId:row.sessionId})<0,"reenters")});nextCursor=encodeMetadataSessionCursor(boundary,filter,archiveState,readOptions.paginateMerged===true,emitted)}return{sessions:page,...nextCursor!==void 0?{nextCursor}:{},...liveMergeFailed?{liveMergeFailed:true}:{},...persisted.truncated?{truncated:true}:{}}}__name(listWorkspaceSessionsByMetadataForResponse,"listWorkspaceSessionsByMetadataForResponse");function waitForQuestionTime(promise,signal){if(!signal)return promise;return new Promise((resolve4,reject)=>{const abort=__name(()=>{signal.removeEventListener("abort",abort);reject(signal.reason)},"abort");signal.addEventListener("abort",abort,{once:true});if(signal.aborted)abort();void promise.then(value=>{signal.removeEventListener("abort",abort);resolve4(value)},error=>{signal.removeEventListener("abort",abort);reject(error)})})}__name(waitForQuestionTime,"waitForQuestionTime");async function listWorkspaceSessionsForResponse(bridge,workspaceCwd,options,readOptions={}){readOptions.signal?.throwIfAborted();const runtimeBaseDir=new Storage(workspaceCwd,readOptions.runtimeBaseDir).getRuntimeBaseDir();const result=await Storage.runWithResolvedRuntimeBaseDir(runtimeBaseDir,()=>listWorkspaceSessionsForResponseInRuntime(bridge,workspaceCwd,options,{...readOptions.mergeLive!==void 0?{mergeLive:readOptions.mergeLive}:{},...readOptions.paginateMerged!==void 0?{paginateMerged:readOptions.paginateMerged}:{},...readOptions.includeGroups!==void 0?{includeGroups:readOptions.includeGroups}:{},...readOptions.signal!==void 0?{signal:readOptions.signal}:{},runtimeBaseDir}));readOptions.signal?.throwIfAborted();if(options?.sortBy!=="lastUserPromptAt"){await enrichPromptTimes(result.sessions,new SessionService(workspaceCwd,{runtimeBaseDir}),options?.archiveState??"active",readOptions)}return result}__name(listWorkspaceSessionsForResponse,"listWorkspaceSessionsForResponse");async function enrichPromptTimes(sessions,service,archiveState,readOptions,preferCache=false){let nextIndex=0;await Promise.all(Array.from({length:Math.min(2,sessions.length)},async()=>{while(nextIndex<sessions.length){readOptions.signal?.throwIfAborted();const session=sessions[nextIndex++];try{session.lastUserPromptAt=await waitForQuestionTime(preferCache?service.getLastUserPromptAt(session.sessionId,archiveState,{preferCache:true}):service.getLastUserPromptAt(session.sessionId,archiveState),readOptions.signal)}catch{readOptions.signal?.throwIfAborted();session.lastUserPromptAt=void 0}}}));readOptions.signal?.throwIfAborted()}__name(enrichPromptTimes,"enrichPromptTimes");async function listWorkspaceSessionsForResponseInRuntime(bridge,workspaceCwd,options,readOptions){readOptions.signal?.throwIfAborted();const rawSize=options?.size;const requestedSize=typeof rawSize==="number"&&Number.isSafeInteger(rawSize)?rawSize:DEFAULT_SESSION_PAGE_SIZE;const pageSize=Math.min(Math.max(requestedSize,1),MAX_SESSION_PAGE_SIZE);if(options?.view==="organized"){return listOrganizedWorkspaceSessionsForResponse(bridge,workspaceCwd,options,pageSize,readOptions)}if(readOptions.paginateMerged||options?.sortBy==="lastUserPromptAt"||options?.parentSessionId!==void 0||options?.sourceType!==void 0||options?.conversationKind!==void 0){return listWorkspaceSessionsByMetadataForResponse(bridge,workspaceCwd,options??{},pageSize,{...options?.sortBy!==void 0?{sortBy:options.sortBy}:{},...options?.parentSessionId!==void 0?{parentSessionId:options.parentSessionId}:{},...options?.sourceType!==void 0?{sourceType:options.sourceType}:{},...options?.sourceId!==void 0?{sourceId:options.sourceId}:{},...options?.conversationKind!==void 0?{conversationKind:options.conversationKind}:{}},readOptions)}let persistedCursor;if(options?.cursor!=null){persistedCursor=parseSessionCursor(options.cursor)}const isFirstPage=persistedCursor===void 0;const sessionService=new SessionService(workspaceCwd);const archiveState=options?.archiveState??"active";const persisted=await sessionService.listSessions({cursor:persistedCursor,size:pageSize,archiveState,excludeSourceTypes:[...HIDDEN_CATALOG_SOURCE_TYPES],...readOptions.signal?{signal:readOptions.signal}:{}});readOptions.signal?.throwIfAborted();const bySessionId=new Map;for(const item of persisted.items){bySessionId.set(item.sessionId,toSummary(item))}await enrichWorktreeSidecars(bySessionId,sessionService,archiveState,readOptions.signal);await enrichPrSidecars(bySessionId,sessionService,archiveState,readOptions.signal);readOptions.signal?.throwIfAborted();if(archiveState==="archived"||readOptions.mergeLive===false){const sessions2=[...bySessionId.values()];const nextCursor2=persisted.nextCursor!=null?String(persisted.nextCursor):void 0;return{sessions:sessions2,nextCursor:nextCursor2}}const liveSessions=bridge.listWorkspaceSessions(workspaceCwd).filter(session=>!isHiddenCatalogSource(session.sourceType));for(const live of liveSessions){const existing=bySessionId.get(live.sessionId);if(existing){bySessionId.set(live.sessionId,mergeLiveSessionSummary(existing,live))}else if(isFirstPage&&(persisted.nextCursor==null||!await(readOptions.signal?sessionService.sessionExists(live.sessionId,{signal:readOptions.signal}):sessionService.sessionExists(live.sessionId)))){bySessionId.set(live.sessionId,await liveOnlySummary(live,sessionService,readOptions.signal))}}const sessions=[...bySessionId.values()].sort((a,b)=>{const aTime=Date.parse(a.updatedAt??a.createdAt);const bTime=Date.parse(b.updatedAt??b.createdAt);return bTime-aTime});readOptions.signal?.throwIfAborted();const nextCursor=persisted.nextCursor!=null?String(persisted.nextCursor):void 0;return{sessions,nextCursor}}__name(listWorkspaceSessionsForResponseInRuntime,"listWorkspaceSessionsForResponseInRuntime");async function listLiveWorkspaceSessionsForResponse(bridge,workspaceCwd,options,readOptions={}){const runtimeBaseDir=new Storage(workspaceCwd,readOptions.runtimeBaseDir).getRuntimeBaseDir();return Storage.runWithResolvedRuntimeBaseDir(runtimeBaseDir,async()=>{const rawSize=options?.size;const requestedSize=typeof rawSize==="number"&&Number.isSafeInteger(rawSize)?rawSize:DEFAULT_SESSION_PAGE_SIZE;const pageSize=Math.min(Math.max(requestedSize,1),MAX_SESSION_PAGE_SIZE);const cursorKey=options?.cursor!==void 0?parseLiveSessionCursor(options.cursor):void 0;const sessions=bridge.listWorkspaceSessions(workspaceCwd).filter(session=>!isHiddenCatalogSource(session.sourceType)).sort((a,b)=>compareLiveSessionCursorKeys(getLiveSessionCursorKey(a),getLiveSessionCursorKey(b)));const afterCursor=cursorKey===void 0?sessions:sessions.filter(session=>compareLiveSessionCursorKeys(cursorKey,getLiveSessionCursorKey(session))<0);const page=afterCursor.slice(0,pageSize);const sessionService=new SessionService(workspaceCwd);const enriched=await Promise.all(page.map(summary=>liveOnlySummary(summary,sessionService,readOptions.signal)));const nextCursor=page.length<afterCursor.length?encodeLiveSessionCursor(getLiveSessionCursorKey(page[page.length-1])):void 0;return{sessions:enriched,...nextCursor!==void 0?{nextCursor}:{}}})}__name(listLiveWorkspaceSessionsForResponse,"listLiveWorkspaceSessionsForResponse");async function searchWorkspaceSessionsForResponse(workspaceCwd,query,options={},readOptions={}){readOptions.signal?.throwIfAborted();const runtimeBaseDir=new Storage(workspaceCwd,readOptions.runtimeBaseDir).getRuntimeBaseDir();return Storage.runWithResolvedRuntimeBaseDir(runtimeBaseDir,async()=>{const sessionService=new SessionService(workspaceCwd);const hits=await sessionService.searchSessionContent(query,{...options.maxResults!==void 0?{maxResults:options.maxResults}:{},...readOptions.signal?{signal:readOptions.signal}:{}});const bySessionId=new Map;const organizationSnapshot=await createSessionOrganizationService(workspaceCwd).readSnapshot();readOptions.signal?.throwIfAborted();for(const hit of hits){readOptions.signal?.throwIfAborted();const item=await sessionService.getSessionListItem(hit.sessionId);if(item&&!isHiddenCatalogSource(item.sourceType))bySessionId.set(hit.sessionId,applyOrganization(toSummary(item),organizationSnapshot.sessions.get(hit.sessionId)))}await enrichWorktreeSidecars(bySessionId,sessionService,"active",readOptions.signal);await enrichPrSidecars(bySessionId,sessionService,"active",readOptions.signal);readOptions.signal?.throwIfAborted();const results=[];for(const hit of hits){const session=bySessionId.get(hit.sessionId);if(session)results.push({session,snippet:hit.snippet})}return{results}})}__name(searchWorkspaceSessionsForResponse,"searchWorkspaceSessionsForResponse");async function getWorkspaceSessionInfoForResponse(bridge,workspaceCwd,options={}){const counts=await new SessionService(workspaceCwd).getSessionInfoCounts({excludeSourceTypes:[...HIDDEN_CATALOG_SOURCE_TYPES]});return{active:counts.active,archived:counts.archived,total:counts.total,...options.includeLive===false?{}:{live:bridge.listWorkspaceSessions(workspaceCwd).filter(session=>!isHiddenCatalogSource(session.sourceType)).length},expensive:true,cost:"disk_scan",...counts.truncated?{truncated:true}:{}}}__name(getWorkspaceSessionInfoForResponse,"getWorkspaceSessionInfoForResponse");function parseSessionPageSizeQuery(raw){if(typeof raw!=="string")return void 0;const trimmed=raw.trim();if(!/^[+-]?\d+$/.test(trimmed))return void 0;const parsed=Number.parseInt(trimmed,10);if(!Number.isFinite(parsed))return void 0;if(Number.isSafeInteger(parsed))return parsed;return trimmed.startsWith("-")?1:MAX_SESSION_PAGE_SIZE}__name(parseSessionPageSizeQuery,"parseSessionPageSizeQuery");init_esbuild_shims();import fs2 from"node:fs";init_esbuild_shims();import{access}from"node:fs/promises";function isBoundTask(task){return typeof task.sessionId==="string"&&task.sessionId.length>0}__name(isBoundTask,"isBoundTask");async function disableTasksForSessions(projectRoot,sessionIds,options={}){if(sessionIds.length===0)return;const targets=new Set(sessionIds);await updateCronTasks(projectRoot,tasks=>{let changed=false;const next=tasks.map(task=>{if(isBoundTask(task)&&targets.has(task.sessionId)&&task.enabled!==false){changed=true;return{...task,enabled:false,disabledByArchive:true}}return task});return changed?next:tasks},options)}__name(disableTasksForSessions,"disableTasksForSessions");async function enableTasksForSessions(projectRoot,sessionIds,now=Date.now(),options={}){if(sessionIds.length===0)return;const targets=new Set(sessionIds);await updateCronTasks(projectRoot,tasks=>{let changed=false;const next=tasks.map(task=>{if(isBoundTask(task)&&targets.has(task.sessionId)&&task.enabled===false&&task.disabledByArchive===true){changed=true;const resumed={...task,enabled:true};delete resumed.disabledByArchive;const minute=now-now%6e4;if(resumed.recurring){resumed.lastFiredAt=minute}else{resumed.createdAt=now;resumed.lastFiredAt=minute}return resumed}return task});return changed?next:tasks},options)}__name(enableTasksForSessions,"enableTasksForSessions");async function removeTasksForSessions(projectRoot,sessionIds,options={}){if(sessionIds.length===0)return;try{await access(getCronFilePath(projectRoot))}catch(error){if(error.code==="ENOENT")return;throw error}const targets=new Set(sessionIds.map(cronTaskSessionDeletionId));const removedIds=[];await updateCronTasks(projectRoot,tasks=>{const next=tasks.filter(task=>{if(!isBoundTask(task)||!targets.has(cronTaskSessionDeletionId(task.sessionId)))return true;removedIds.push(task.id);return false});return next.length===tasks.length?tasks:next},{...options,deletionIds:__name(()=>[...removedIds,...targets],"deletionIds")})}__name(removeTasksForSessions,"removeTasksForSessions");init_esbuild_shims();import fs from"node:fs";import*as fsp3 from"node:fs/promises";import path7 from"node:path";init_esbuild_shims();var worktreeOwnershipOpTails=new Map;async function acquireWorktreeOwnershipOp(worktreeKey){const previous=worktreeOwnershipOpTails.get(worktreeKey);let releaseGate;const gate=new Promise(resolve4=>{releaseGate=resolve4});const tail=(previous??Promise.resolve()).then(()=>gate);worktreeOwnershipOpTails.set(worktreeKey,tail);if(previous){await previous}let released=false;return()=>{if(released)return;released=true;releaseGate();if(worktreeOwnershipOpTails.get(worktreeKey)===tail){worktreeOwnershipOpTails.delete(worktreeKey)}}}__name(acquireWorktreeOwnershipOp,"acquireWorktreeOwnershipOp");function canonicalPath(candidate){try{return fs.realpathSync(candidate)}catch{return candidate}}__name(canonicalPath,"canonicalPath");function logWarning(message){writeStderrLine(`qwen serve: ${message}`)}__name(logWarning,"logWarning");function logWorktreeCleanupPreserve(sessionId,reason){logWarning(`worktree cleanup preserved checkout action=delete session=${safeLogValue(sessionId)} reason=${safeLogValue(reason)}`)}__name(logWorktreeCleanupPreserve,"logWorktreeCleanupPreserve");async function preclassifyWorktreeCleanup(service,sessionId,runtimeWorkspaceCwd){let sidecarPath=service.getWorktreeSessionPath(sessionId);let sidecar=await readWorktreeSessionStrict(sidecarPath);if(sidecar.state==="missing"){const archivedPath=service.getWorktreeSessionPathForArchiveState(sessionId,"archived");if(archivedPath!==sidecarPath){sidecarPath=archivedPath;sidecar=await readWorktreeSessionStrict(sidecarPath)}}if(sidecar.state==="missing")return void 0;if(sidecar.state==="invalid"){logWorktreeCleanupPreserve(sessionId,`unreadable sidecar (${sidecar.reason})`);return void 0}const session=sidecar.session;if(session.workspaceCwd===void 0)return void 0;if(session.supersededBy!==void 0)return void 0;if(!path7.isAbsolute(session.workspaceCwd)||!path7.isAbsolute(session.originalCwd)){logWorktreeCleanupPreserve(sessionId,"sidecar base is not an absolute path");return void 0}if(runtimeWorkspaceCwd!==void 0){if(canonicalPath(session.workspaceCwd)!==canonicalPath(runtimeWorkspaceCwd)){logWorktreeCleanupPreserve(sessionId,"sidecar belongs to another workspace");return void 0}const workspaceRoots=[canonicalPath(runtimeWorkspaceCwd)];try{const repoTop=await new GitWorktreeService(runtimeWorkspaceCwd).getRepoTopLevel();if(repoTop&&canonicalPath(repoTop)!==workspaceRoots[0]){workspaceRoots.push(canonicalPath(repoTop))}}catch{}if(!workspaceRoots.includes(canonicalPath(session.originalCwd))){logWorktreeCleanupPreserve(sessionId,"sidecar original cwd is outside the accepted roots");return void 0}}const activeDir=path7.dirname(service.getWorktreeSessionPath(sessionId));const archivedDir=path7.dirname(service.getWorktreeSessionPathForArchiveState(sessionId,"archived"));const ownDir=path7.dirname(sidecarPath);const otherStateSidecarDir=ownDir===activeDir?archivedDir:activeDir;return{sessionId,sidecar:session,sidecarPath,lockKey:canonicalPath(session.worktreePath),...otherStateSidecarDir!==ownDir?{otherStateSidecarDir}:{}}}__name(preclassifyWorktreeCleanup,"preclassifyWorktreeCleanup");function acquireWorktreeCleanupLock(plan){return acquireWorktreeOwnershipOp(plan.lockKey)}__name(acquireWorktreeCleanupLock,"acquireWorktreeCleanupLock");async function worktreeAllowedRoots(workspaceCwd,originalCwd){const roots=new Set;for(const base of[workspaceCwd,originalCwd]){if(!path7.isAbsolute(base))continue;roots.add(path7.join(base,".qwen","worktrees"));try{const repoTop=await new GitWorktreeService(base).getRepoTopLevel();if(repoTop){roots.add(path7.join(repoTop,".qwen","worktrees"))}}catch{}}return[...roots]}__name(worktreeAllowedRoots,"worktreeAllowedRoots");var SIDECAR_SUFFIX=".worktree.json";async function findLiveSessionNamingCheckout(dir,lockKey,isSessionLive){let entries;try{entries=await fsp3.readdir(dir)}catch(error){if(error.code==="ENOENT")return void 0;return`sidecar scan failed: ${error instanceof Error?error.message:String(error)}`}for(const entry of entries){if(!entry.endsWith(SIDECAR_SUFFIX))continue;const other=await readWorktreeSessionStrict(path7.join(dir,entry));if(other.state==="missing")continue;if(other.state==="invalid")return`unreadable sibling sidecar ${entry}`;if(canonicalPath(other.session.worktreePath)!==lockKey)continue;const otherId=entry.slice(0,-SIDECAR_SUFFIX.length);if(isSessionLive(otherId)){return`session ${otherId} naming the checkout is still live`}}return void 0}__name(findLiveSessionNamingCheckout,"findLiveSessionNamingCheckout");async function verifyWorktreeCleanupOwnership(plan,isSessionLive){const{sessionId,sidecar}=plan;const locked=await readWorktreeSessionStrict(plan.sidecarPath);if(locked.state!=="valid"){return{ok:false,reason:locked.state==="missing"?"sidecar disappeared before delete":`unreadable sidecar (${locked.reason})`}}const current=locked.session;if(current.workspaceCwd===void 0||current.supersededBy!==void 0||current.slug!==sidecar.slug||current.worktreePath!==sidecar.worktreePath||current.originalCwd!==sidecar.originalCwd||current.workspaceCwd!==sidecar.workspaceCwd){return{ok:false,reason:"sidecar changed before delete"}}const marker=await readWorktreeSessionMarkerStrict(plan.lockKey);if(marker.state!=="valid"||marker.sessionId!==sessionId){return{ok:false,reason:marker.state==="valid"?"marker names another session":`marker ${marker.state}`}}const allowedRoots=await worktreeAllowedRoots(current.workspaceCwd,current.originalCwd);const contained=allowedRoots.some(root=>{try{const realRoot=fs.realpathSync(root);return plan.lockKey===realRoot||plan.lockKey.startsWith(realRoot+path7.sep)}catch{return false}});if(!contained){return{ok:false,reason:"checkout outside workspace worktree roots"}}const chatsDir=path7.dirname(plan.sidecarPath);const ownFile=path7.basename(plan.sidecarPath);let entries;try{entries=await fsp3.readdir(chatsDir)}catch(error){return{ok:false,reason:`sidecar scan failed: ${error instanceof Error?error.message:String(error)}`}}const tombstoneIds=[];let olderTombstone=false;for(const entry of entries){if(!entry.endsWith(SIDECAR_SUFFIX)||entry===ownFile)continue;const other=await readWorktreeSessionStrict(path7.join(chatsDir,entry));if(other.state==="missing")continue;if(other.state==="invalid"){return{ok:false,reason:`unreadable sibling sidecar ${entry}`}}if(canonicalPath(other.session.worktreePath)!==plan.lockKey)continue;if(other.session.supersededBy===void 0){return{ok:false,reason:`checkout shared with ${entry}`}}tombstoneIds.push(entry.slice(0,-SIDECAR_SUFFIX.length));if(other.session.supersededBy!==sessionId)olderTombstone=true}if(olderTombstone){for(const otherId of tombstoneIds){if(isSessionLive(otherId)){return{ok:false,reason:`superseded session ${otherId} is still live`}}}if(plan.otherStateSidecarDir!==void 0){const otherState=await findLiveSessionNamingCheckout(plan.otherStateSidecarDir,plan.lockKey,isSessionLive);if(otherState!==void 0)return{ok:false,reason:otherState}}}const removalTarget=canonicalPath(new GitWorktreeService(current.originalCwd).getUserWorktreePath(current.slug));if(removalTarget!==plan.lockKey){return{ok:false,reason:"slug does not resolve to the verified checkout"}}plan.sidecar=current;return{ok:true}}__name(verifyWorktreeCleanupOwnership,"verifyWorktreeCleanupOwnership");async function checkoutStillPopulated(worktreePath){try{return(await fsp3.readdir(worktreePath)).length>0}catch{return false}}__name(checkoutStillPopulated,"checkoutStillPopulated");async function executeWorktreeCleanup(plan){const{sessionId,sidecar}=plan;const marker=await readWorktreeSessionMarkerStrict(plan.lockKey);if(marker.state!=="valid"||marker.sessionId!==sessionId){logWorktreeCleanupPreserve(sessionId,"marker changed after delete");return}if(await worktreeHasWork(plan.lockKey)){logWorktreeCleanupPreserve(sessionId,"checkout has uncommitted work");return}const result=await new GitWorktreeService(sidecar.originalCwd).removeUserWorktree(sidecar.slug,{deleteBranch:true});if(!result.success){const errorText=result.error??"unknown error";if(await checkoutStillPopulated(plan.lockKey)){logWorktreeCleanupPreserve(sessionId,`checkout removal failed: ${errorText}`)}else{logWarning(`worktree cleanup removal failed, checkout may be partially deleted action=delete session=${safeLogValue(sessionId)} reason=${safeLogValue(errorText)}`)}return}if(result.branchPreserved){logWarning(`worktree cleanup removed checkout but kept branch action=delete session=${safeLogValue(sessionId)} slug=${safeLogValue(sidecar.slug)} branch=${safeLogValue(sidecar.worktreeBranch)} reason=unmerged commits`)}}__name(executeWorktreeCleanup,"executeWorktreeCleanup");var DaemonDrainingError=class extends Error{static{__name(this,"DaemonDrainingError")}name="DaemonDrainingError";code="daemon_draining";constructor(){super("The daemon is draining and no longer accepts session maintenance.")}};var SessionArchiveCoordinator=class{static{__name(this,"SessionArchiveCoordinator")}exclusive=new Set;shared=new Map;sharedDrains=new Map;maintenanceSealed=false;activeMaintenance=0;maintenanceDrain;assertNotTransitioning(sessionId){if(this.exclusive.has(normalizeSessionIdForLookup(sessionId))){throw new SessionArchivingError(sessionId)}}async runExclusiveMany(sessionIds,fn){if(this.maintenanceSealed){throw new DaemonDrainingError}const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];for(const sessionId of uniqueSessionIds){this.assertNotTransitioning(sessionId);if((this.shared.get(sessionId)??0)>0){throw new SessionArchivingError(sessionId,"shared")}}for(const sessionId of uniqueSessionIds){this.exclusive.add(sessionId)}this.activeMaintenance++;try{return await fn()}finally{for(const sessionId of uniqueSessionIds){this.exclusive.delete(sessionId)}this.activeMaintenance--;if(this.activeMaintenance===0){this.maintenanceDrain?.resolve();this.maintenanceDrain=void 0}}}async runExclusiveAfterShared(rawSessionId,fn){if(this.maintenanceSealed){throw new DaemonDrainingError}const sessionId=normalizeSessionIdForLookup(rawSessionId);this.assertNotTransitioning(sessionId);this.exclusive.add(sessionId);this.activeMaintenance++;try{const sharedCount=this.shared.get(sessionId)??0;if(sharedCount>0){let drain=this.sharedDrains.get(sessionId);if(!drain){let resolve4;const promise=new Promise(done=>{resolve4=done});drain={promise,resolve:resolve4};this.sharedDrains.set(sessionId,drain)}await drain.promise}return await fn()}finally{this.sharedDrains.delete(sessionId);this.exclusive.delete(sessionId);this.activeMaintenance--;if(this.activeMaintenance===0){this.maintenanceDrain?.resolve();this.maintenanceDrain=void 0}}}sealMaintenanceAndWait(){this.maintenanceSealed=true;if(this.activeMaintenance===0){return Promise.resolve()}if(!this.maintenanceDrain){let resolve4;const promise=new Promise(done=>{resolve4=done});this.maintenanceDrain={promise,resolve:resolve4}}return this.maintenanceDrain.promise}async runSharedMany(sessionIds,fn){if(this.maintenanceSealed){throw new DaemonDrainingError}const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];for(const sessionId of uniqueSessionIds){this.assertNotTransitioning(sessionId)}for(const sessionId of uniqueSessionIds){this.shared.set(sessionId,(this.shared.get(sessionId)??0)+1)}this.activeMaintenance++;try{return await fn()}finally{for(const sessionId of uniqueSessionIds){const count=(this.shared.get(sessionId)??1)-1;if(count<=0){this.shared.delete(sessionId);this.sharedDrains.get(sessionId)?.resolve();this.sharedDrains.delete(sessionId)}else{this.shared.set(sessionId,count)}}this.activeMaintenance--;if(this.activeMaintenance===0){this.maintenanceDrain?.resolve();this.maintenanceDrain=void 0}}}};async function runWithDaemonWriterLease(params){const{action,sessionId,service,mutate,mutationAppliedAfterError,afterMutationApplied}=params;let lease;try{const leaseOptions={processKind:"daemon",reclaimPolicy:"never",takeoverPolicy:"certified"};try{lease=await service.acquireSessionWriterLease(sessionId,leaseOptions)}catch(error){if(!(error instanceof SessionWriterUnavailableError)&&!(error instanceof SessionTranscriptChangedError)){throw error}lease=await service.acquireSealedManagedMaintenanceLease(sessionId)??await service.acquireSessionMaintenanceLease(sessionId,leaseOptions)}}catch(error){return{mutationApplied:false,error}}let value;let mutationApplied=false;let mutationError;try{const mutation=await mutate(()=>lease.assertOwnedAndUnchanged(),()=>lease.assertCleanupOwned());value=mutation.value;mutationApplied=mutation.mutationApplied}catch(error){mutationError=error;try{mutationApplied=await mutationAppliedAfterError()}catch{mutationApplied=false}}let maintenanceError;if(mutationApplied){try{await afterMutationApplied()}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=${action} workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}}let releaseError;try{await lease.release()}catch(error){releaseError=error}if(releaseError!==void 0){logMaintenanceLeaseReleaseFailure({action,workspace:service.getProjectRoot(),sessionId,error:releaseError,mutationApplied});if(mutationError!==void 0){logSessionArchiveWarning(`session maintenance mutation also failed action=${action} workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(mutationError))}`)}return{mutationApplied,error:releaseError,maintenanceError}}if(mutationError!==void 0){return{mutationApplied,error:mutationError,maintenanceError}}return{value,mutationApplied,maintenanceError}}__name(runWithDaemonWriterLease,"runWithDaemonWriterLease");function logMaintenanceLeaseReleaseFailure(params){const errorKind=typeof params.error==="object"&&params.error!==null&&typeof params.error.errorKind==="string"?params.error.errorKind:"unknown";logSessionArchiveWarning(`session maintenance lease release failed action=${params.action} workspace=${safeLogValue(params.workspace)} session=${safeLogValue(params.sessionId)} errorKind=${safeLogValue(errorKind)} mutationApplied=${params.mutationApplied}`)}__name(logMaintenanceLeaseReleaseFailure,"logMaintenanceLeaseReleaseFailure");async function classifySessionLocation(service,sessionId){return service.getMaintainableSessionLocation(sessionId)}__name(classifySessionLocation,"classifySessionLocation");function sessionLocationError(sessionId){const error=new SessionConflictError(sessionId);error.message=`Session "${sessionId}" exists in both active and archived directories. Retry with resolveConflicts: true to keep one copy.`;return error}__name(sessionLocationError,"sessionLocationError");function updateScheduledTaskForMaintenance(service,sessionId,action,assertCanMutate){if(action==="archive"){return disableTasksForSessions(service.getProjectRoot(),[sessionId],{assertCanCommit:assertCanMutate})}if(action==="unarchive"){return enableTasksForSessions(service.getProjectRoot(),[sessionId],Date.now(),{assertCanCommit:assertCanMutate})}return removeTasksForSessions(service.getProjectRoot(),[sessionId],{assertCanCommit:assertCanMutate})}__name(updateScheduledTaskForMaintenance,"updateScheduledTaskForMaintenance");async function deletePersistedSessionWithLease(service,sessionId,assertCanMutate){const initialLocation=await classifySessionLocation(service,sessionId);if(initialLocation===void 0){let maintenanceError;try{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"delete",assertCanMutate)}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=delete workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}return{kind:"notFound",mutationApplied:false,maintenanceError}}const mutation=await runWithDaemonWriterLease({action:"delete",sessionId,service,mutate:__name(async(assertOwnedAndUnchanged,assertCleanupOwned)=>{const lockedLocation=await classifySessionLocation(service,sessionId);if(lockedLocation===void 0){return{value:"notFound",mutationApplied:false}}const removed=await service.removeSession(sessionId,{assertStorageUnchanged:assertOwnedAndUnchanged,assertCanMutate,assertCleanupOwned});return{value:removed?"removed":"notFound",mutationApplied:removed}},"mutate"),mutationAppliedAfterError:__name(async()=>await classifySessionLocation(service,sessionId)===void 0,"mutationAppliedAfterError"),afterMutationApplied:__name(async()=>{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"delete",assertCanMutate)},"afterMutationApplied")});if(mutation.error!==void 0){return{kind:"error",error:mutation.error,mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}return{kind:mutation.value??"notFound",mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}__name(deletePersistedSessionWithLease,"deletePersistedSessionWithLease");async function deleteDaemonSessions(params){const{sessionIds,service,bridge,coordinator,coordinatorLockHeld=false,assertCanMutate,runtimeWorkspaceCwd,onError}=params;const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];if(!coordinatorLockHeld){for(const sessionId of uniqueSessionIds){coordinator.assertNotTransitioning(sessionId)}}const isSessionLive=__name(candidate=>{if(!bridge.getSessionSummary)return true;try{bridge.getSessionSummary(normalizeSessionIdForLookup(candidate));return true}catch(error){return!(isSessionNotFoundError(error)&&error.code!=="session_closing")}},"isSessionLive");const runWithWorktreeCleanup=__name(async(sessionId,mutateSession)=>{const activeSidecarPath=service.getWorktreeSessionPath(sessionId);const archivedSidecarPath=service.getWorktreeSessionPathForArchiveState(sessionId,"archived");if(!fs2.existsSync(activeSidecarPath)&&(archivedSidecarPath===activeSidecarPath||!fs2.existsSync(archivedSidecarPath))){return coordinator.runExclusiveMany([sessionId],mutateSession)}const cleanupPlan=await preclassifyWorktreeCleanup(service,sessionId,runtimeWorkspaceCwd);if(!cleanupPlan){return coordinator.runExclusiveMany([sessionId],mutateSession)}const releaseCleanupLock=await acquireWorktreeCleanupLock(cleanupPlan);try{const ownership=await verifyWorktreeCleanupOwnership(cleanupPlan,isSessionLive);if(!ownership.ok){logWorktreeCleanupPreserve(sessionId,ownership.reason)}const result=await coordinator.runExclusiveMany([sessionId],mutateSession);if(ownership.ok&&result.kind==="removed"){try{assertCanMutate?.();await executeWorktreeCleanup(cleanupPlan)}catch(error){logWorktreeCleanupPreserve(sessionId,`cleanup execution failed: ${errorMessage(error)}`)}}return result}finally{releaseCleanupLock()}},"runWithWorktreeCleanup");const results=await Promise.all(uniqueSessionIds.map(async sessionId=>{try{const mutateSession=__name(async()=>{assertCanMutate?.();const removePersistedSession=__name(async()=>{const result=await deletePersistedSessionWithLease(service,sessionId,assertCanMutate);if(result.kind==="error"){onError?.({phase:"remove",sessionId,error:errorMessage(result.error)});return result}try{if(assertCanMutate){await bridge.deleteSessionAttachments(sessionId,{assertCanCommit:assertCanMutate})}else{await bridge.deleteSessionAttachments(sessionId)}return result}catch(error){onError?.({phase:"delete",sessionId,error:errorMessage(error)});return{kind:"error",error,mutationApplied:result.mutationApplied,maintenanceError:result.maintenanceError}}},"removePersistedSession");try{await bridge.closeSession(sessionId)}catch(error){if(isSessionNotFoundError(error)&&error.code!=="session_closing"){return await removePersistedSession()}onError?.({phase:"close",sessionId,error:errorMessage(error)});return{kind:"error",error,mutationApplied:false}}return await removePersistedSession()},"mutateSession");return await(coordinatorLockHeld?mutateSession():runWithWorktreeCleanup(sessionId,mutateSession))}catch(error){if(error instanceof DaemonDrainingError){throw error}onError?.({phase:"delete",sessionId,error:errorMessage(error)});return{kind:"error",error,mutationApplied:false}}}));const removed=[];const notFound=[];const errors=[];for(let i=0;i<results.length;i++){const sessionId=uniqueSessionIds[i];const result=results[i];if(result.kind==="removed"){removed.push(sessionId)}else if(result.kind==="notFound"){notFound.push(sessionId)}else{errors.push({sessionId,error:errorMessage(result.error)})}if(result.maintenanceError!==void 0){errors.push({sessionId,error:"Scheduled task lifecycle update failed."})}}return{removed,notFound,errors}}__name(deleteDaemonSessions,"deleteDaemonSessions");async function deleteDaemonSessionIfOrphan(params){const{sessionId,service,bridge,coordinator}=params;coordinator.assertNotTransitioning(sessionId);const result=await coordinator.runExclusiveMany([sessionId],async()=>{let killed=false;try{killed=await bridge.killSession(sessionId,{requireZeroAttaches:true})}catch(error){if(!isSessionNotFoundError(error))throw error;killed=true}if(!killed){try{bridge.getSessionSummary(sessionId);return void 0}catch(error){if(!isSessionNotFoundError(error))throw error}}const removal=await deletePersistedSessionWithLease(service,sessionId);if(removal.kind!=="error"){await bridge.deleteSessionAttachments(sessionId)}return removal});if(result===void 0){return false}if(result.kind==="error"){throw result.error}bridge.markSessionCatalogChanged();return true}__name(deleteDaemonSessionIfOrphan,"deleteDaemonSessionIfOrphan");async function assertSessionLoadable(workspaceCwd,sessionId,runtimeBaseDir,options={}){const service=new SessionService(workspaceCwd,{runtimeBaseDir});const location=await service.getSessionLocation(sessionId);if(location==="archived"){throw new SessionArchivedError(sessionId)}if(location==="conflict"){if(options.allowActiveConflict){try{await service.findSessionIdIgnoringCase(sessionId)}catch(error){if(error instanceof SessionIdCaseConflictError&&error.reason==="case_conflict"&&error.candidateSessionId===sessionId){return"active"}if(!(error instanceof SessionIdCaseConflictError))throw error}}throw new SessionConflictError(sessionId)}return location}__name(assertSessionLoadable,"assertSessionLoadable");async function resolveSessionIdForRestore(service,sessionId){try{return await service.findSessionIdIgnoringCase(sessionId)}catch(error){if(error instanceof SessionIdCaseConflictError){if(error.candidateSessionId===sessionId)return sessionId;throw new SessionConflictError(sessionId)}throw error}}__name(resolveSessionIdForRestore,"resolveSessionIdForRestore");async function assertSessionRestorable(workspaceCwd,sessionId,requestedSessionId,runtimeBaseDir){const location=await new SessionService(workspaceCwd,{runtimeBaseDir}).getSessionLocation(sessionId);if(location==="archived"){throw new SessionArchivedError(sessionId)}if(location==="conflict"){if(sessionId!==requestedSessionId){throw new SessionConflictError(requestedSessionId)}return"active"}return location}__name(assertSessionRestorable,"assertSessionRestorable");async function assertSessionArchived(workspaceCwd,sessionId,runtimeBaseDir){const location=await new SessionService(workspaceCwd,{runtimeBaseDir}).getSessionLocation(sessionId);if(location==="active"){throw new SessionNotArchivedError(sessionId)}if(location==="conflict"){throw new SessionConflictError(sessionId)}if(location===void 0){throw new SessionNotFoundError(sessionId)}}__name(assertSessionArchived,"assertSessionArchived");function isSessionNotFoundError(err){return err instanceof SessionNotFoundError||err instanceof Error&&err.name==="SessionNotFoundError"}__name(isSessionNotFoundError,"isSessionNotFoundError");function logSessionArchiveResult(action,result){const changedLabel=action==="archive"?"archived":"unarchived";const alreadyLabel=action==="archive"?"alreadyArchived":"alreadyActive";const details=[`requested=${result.requested.length} requestedIds=${formatSessionIds(result.requested)}`,`${changedLabel}=${result.changed.length} ${changedLabel}Ids=${formatSessionIds(result.changed)}`,`${alreadyLabel}=${result.already.length} ${alreadyLabel}Ids=${formatSessionIds(result.already)}`,`notFound=${result.notFound.length} notFoundIds=${formatSessionIds(result.notFound)}`,`errors=${result.errors.length} errorIds=${formatSessionErrors(result.errors)}`].join(" ");writeStderrLine(`qwen serve: sessions ${action} result ${details}`)}__name(logSessionArchiveResult,"logSessionArchiveResult");function formatSessionIds(sessionIds){return`[${sessionIds.map(sessionId=>safeLogValue(sessionId)).join(",")}]`}__name(formatSessionIds,"formatSessionIds");function formatSessionErrors(errors){return`[${errors.map(({sessionId,error})=>`${safeLogValue(sessionId)}:${safeLogValue(errorMessage(error))}`).join(",")}]`}__name(formatSessionErrors,"formatSessionErrors");function errorMessage(error){return error instanceof Error?error.message:String(error)}__name(errorMessage,"errorMessage");function logSessionArchiveWarning(message){writeStderrLine(`qwen serve: ${sanitizeLogLine(message)}`)}__name(logSessionArchiveWarning,"logSessionArchiveWarning");function sanitizeLogLine(message){return message.replace(LOG_LINE_UNSAFE_RE," ").slice(0,4096)}__name(sanitizeLogLine,"sanitizeLogLine");async function archiveDaemonSessions(params){const{sessionIds,service,bridge,coordinator,coordinatorLockHeld=false,resolveConflicts=false,requireIdle=false,assertCanMutate}=params;const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];if(!coordinatorLockHeld){for(const sessionId of uniqueSessionIds){coordinator.assertNotTransitioning(sessionId)}}const results=await Promise.all(uniqueSessionIds.map(async sessionId=>{try{const mutateSession=__name(async()=>{assertCanMutate?.();try{await bridge.closeSession(sessionId,void 0,{requireAgentClose:true,requireIdle})}catch(error){if(!isSessionNotFoundError(error)||error.code==="session_closing"){return{kind:"error",error,mutationApplied:false}}}const initialLocation=await classifySessionLocation(service,sessionId);if(initialLocation===void 0){return{kind:"notFound",mutationApplied:false}}if(initialLocation==="conflict"&&!resolveConflicts){return{kind:"error",error:sessionLocationError(sessionId),mutationApplied:false}}const mutation=await runWithDaemonWriterLease({action:"archive",sessionId,service,mutate:__name(async(assertOwnedAndUnchanged,assertCleanupOwned)=>{const lockedLocation=await classifySessionLocation(service,sessionId);if(lockedLocation===void 0){return{value:"notFound",mutationApplied:false}}if(lockedLocation==="conflict"&&!resolveConflicts){throw sessionLocationError(sessionId)}const result=await service.archiveSessions([sessionId],{resolveConflicts,assertStorageUnchanged:assertOwnedAndUnchanged,assertCanMutate,assertCleanupOwned});if(result.errors[0])throw result.errors[0].error;if(result.archived.length>0){return{value:result.resolvedConflicts.length?"resolvedConflict":"archived",mutationApplied:true}}return{value:result.alreadyArchived.length>0?"alreadyArchived":"notFound",mutationApplied:false}},"mutate"),mutationAppliedAfterError:__name(async()=>await classifySessionLocation(service,sessionId)==="archived","mutationAppliedAfterError"),afterMutationApplied:__name(async()=>{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"archive",assertCanMutate)},"afterMutationApplied")});if(mutation.error!==void 0){return{kind:"error",error:mutation.error,mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}let maintenanceError=mutation.maintenanceError;if(mutation.value==="alreadyArchived"){try{await updateScheduledTaskForMaintenance(service,sessionId,"archive",assertCanMutate)}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=archive workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}}return{kind:mutation.value??"notFound",mutationApplied:mutation.mutationApplied,maintenanceError}},"mutateSession");return await(coordinatorLockHeld?mutateSession():coordinator.runExclusiveMany([sessionId],mutateSession))}catch(error){if(error instanceof DaemonDrainingError){throw error}return{kind:"error",error,mutationApplied:false,maintenanceError:void 0}}}));const archived=[];const alreadyArchived=[];const resolvedConflicts=[];const notFound=[];const errors=[];for(let i=0;i<results.length;i++){const sessionId=uniqueSessionIds[i];const result=results[i];if(result.kind==="archived")archived.push(sessionId);else if(result.kind==="resolvedConflict"){archived.push(sessionId);resolvedConflicts.push(sessionId)}else if(result.kind==="alreadyArchived"){alreadyArchived.push(sessionId)}else if(result.kind==="notFound")notFound.push(sessionId);else errors.push({sessionId,error:result.error});if("maintenanceError"in result&&result.maintenanceError!==void 0){errors.push({sessionId,error:result.maintenanceError})}}logSessionArchiveResult("archive",{requested:uniqueSessionIds,changed:archived,already:alreadyArchived,notFound,errors});return{archived,alreadyArchived,resolvedConflicts,notFound,errors}}__name(archiveDaemonSessions,"archiveDaemonSessions");async function unarchiveDaemonSessions(params){const{sessionIds,service,coordinator,coordinatorLockHeld=false,resolveConflicts=false,assertCanMutate}=params;const uniqueSessionIds=[...new Set(sessionIds.map(normalizeSessionIdForLookup))];if(!coordinatorLockHeld){for(const sessionId of uniqueSessionIds){coordinator.assertNotTransitioning(sessionId)}}const results=await Promise.all(uniqueSessionIds.map(async sessionId=>{try{const mutateSession=__name(async()=>{assertCanMutate?.();const initialLocation=await classifySessionLocation(service,sessionId);if(initialLocation===void 0){return{kind:"notFound",mutationApplied:false}}if(initialLocation==="conflict"&&!resolveConflicts){return{kind:"error",error:sessionLocationError(sessionId),mutationApplied:false}}const mutation=await runWithDaemonWriterLease({action:"unarchive",sessionId,service,mutate:__name(async(assertOwnedAndUnchanged,assertCleanupOwned)=>{const lockedLocation=await classifySessionLocation(service,sessionId);if(lockedLocation===void 0){return{value:"notFound",mutationApplied:false}}if(lockedLocation==="conflict"&&!resolveConflicts){throw sessionLocationError(sessionId)}const result=await service.unarchiveSessions([sessionId],{resolveConflicts,assertStorageUnchanged:assertOwnedAndUnchanged,assertCanMutate,assertCleanupOwned});if(result.errors[0])throw result.errors[0].error;if(result.unarchived.length>0){return{value:result.resolvedConflicts.length?"resolvedConflict":"unarchived",mutationApplied:true}}return{value:result.alreadyActive.length>0?"alreadyActive":"notFound",mutationApplied:false}},"mutate"),mutationAppliedAfterError:__name(async()=>await classifySessionLocation(service,sessionId)==="active","mutationAppliedAfterError"),afterMutationApplied:__name(async()=>{assertCanMutate?.();await updateScheduledTaskForMaintenance(service,sessionId,"unarchive",assertCanMutate)},"afterMutationApplied")});if(mutation.error!==void 0){return{kind:"error",error:mutation.error,mutationApplied:mutation.mutationApplied,maintenanceError:mutation.maintenanceError}}let maintenanceError=mutation.maintenanceError;if(mutation.value==="alreadyActive"){try{await updateScheduledTaskForMaintenance(service,sessionId,"unarchive",assertCanMutate)}catch(error){maintenanceError=error;logSessionArchiveWarning(`scheduled task lifecycle update failed action=unarchive workspace=${safeLogValue(service.getProjectRoot())} session=${safeLogValue(sessionId)} error=${safeLogValue(errorMessage(error))}`)}}return{kind:mutation.value??"notFound",mutationApplied:mutation.mutationApplied,maintenanceError}},"mutateSession");return await(coordinatorLockHeld?mutateSession():coordinator.runExclusiveMany([sessionId],mutateSession))}catch(error){if(error instanceof DaemonDrainingError){throw error}return{kind:"error",error,mutationApplied:false,maintenanceError:void 0}}}));const unarchived=[];const alreadyActive=[];const resolvedConflicts=[];const notFound=[];const errors=[];for(let i=0;i<results.length;i++){const sessionId=uniqueSessionIds[i];const result=results[i];if(result.kind==="unarchived")unarchived.push(sessionId);else if(result.kind==="resolvedConflict"){unarchived.push(sessionId);resolvedConflicts.push(sessionId)}else if(result.kind==="alreadyActive")alreadyActive.push(sessionId);else if(result.kind==="notFound")notFound.push(sessionId);else errors.push({sessionId,error:result.error});if(result.maintenanceError!==void 0){errors.push({sessionId,error:result.maintenanceError})}}logSessionArchiveResult("unarchive",{requested:uniqueSessionIds,changed:unarchived,already:alreadyActive,notFound,errors});return{unarchived,alreadyActive,resolvedConflicts,notFound,errors}}__name(unarchiveDaemonSessions,"unarchiveDaemonSessions");init_esbuild_shims();import{execFile}from"node:child_process";import{promisify}from"node:util";var execFileAsync=promisify(execFile);var a1AvailabilityVerified=false;var defaultA1Exec=__name(async(args,options)=>{const{stdout}=await execFileAsync("a1",[...args],{...options,encoding:"utf8",windowsHide:true});return{stdout}},"defaultA1Exec");var a1Exec=defaultA1Exec;var A1_TIMEOUT_MS=2e4;var A1_MAX_BUFFER=16*1024*1024;var GIT_ORIGIN_TIMEOUT_MS=5e3;var A1_VERSION_TIMEOUT_MS=1e4;var A1_ERROR_MESSAGE_MAX=512;var AONE_DETAIL_URL_HOST="code.alibaba-inc.com";var AONE_MAX_MR_VIEW_CALLS_PER_RUN=25;var AoneCliUnavailableError=class extends Error{static{__name(this,"AoneCliUnavailableError")}};var AoneCommandError=class extends Error{static{__name(this,"AoneCommandError")}};function mapAoneMrState(raw){switch(raw?.toLowerCase()){case"merged":return"merged";case"closed":return"closed";default:return"open"}}__name(mapAoneMrState,"mapAoneMrState");async function resolveAoneWorkspaceRepo(workspaceCwd,env){const gitRoot=findGitRoot(workspaceCwd);if(!gitRoot)return void 0;let origin;try{({stdout:origin}=await execFileAsync("git",["remote","get-url","origin"],{cwd:gitRoot,timeout:GIT_ORIGIN_TIMEOUT_MS,encoding:"utf8",windowsHide:true,env:gitEnv(env)}))}catch{return void 0}const identity=parseRemoteUrl(origin.trim());if(!identity||!isAoneCanonicalHost(identity.host))return void 0;return{gitRoot,repoPath:identity.groupPath}}__name(resolveAoneWorkspaceRepo,"resolveAoneWorkspaceRepo");function isAoneDetailUrlForRepo(repoPath,number,url){return canonicalSessionPrUrl(url)===canonicalSessionPrUrl(`https://${AONE_DETAIL_URL_HOST}/${repoPath}/codereview/${number}`)}__name(isAoneDetailUrlForRepo,"isAoneDetailUrlForRepo");function isA1ErrorObject(value){return typeof value==="object"&&value!==null&&value["schemaVersion"]==="a1.error/v1"}__name(isA1ErrorObject,"isA1ErrorObject");function a1ErrorMessage(error){if(error?.killed===true){return`a1 timed out after ${A1_TIMEOUT_MS/1e3}s`}const stderr=error?.stderr;const raw=typeof stderr==="string"&&stderr.trim()?stderr:error instanceof Error?error.message:String(error);return raw.replace(/\s+/g," ").trim().slice(0,A1_ERROR_MESSAGE_MAX)}__name(a1ErrorMessage,"a1ErrorMessage");function assertA1Version(stdout){const triple=parseA1Version(stdout);const floor=parseA1Version(A1_MIN_VERSION);if(triple&&floor&&!a1VersionAtLeast(triple,floor)){throw new AoneCliUnavailableError(`a1 ${A1_MIN_VERSION}+ is required (found ${stdout.trim().split("\n")[0]}); upgrade from https://code.alibaba-inc.com/aone/a1`)}}__name(assertA1Version,"assertA1Version");async function runA1Json(args){let stdout;try{({stdout}=await a1Exec([...args,"--format","json"],{timeout:A1_TIMEOUT_MS,maxBuffer:A1_MAX_BUFFER}))}catch(error){if(error.code==="ENOENT"){throw new AoneCliUnavailableError("a1 CLI not installed; install it and run `a1 auth login`")}const errorStdout=error?.stdout;if(typeof errorStdout==="string"&&errorStdout.trim()){try{const parsed2=JSON.parse(errorStdout);if(isA1ErrorObject(parsed2)){throw new AoneCommandError(parsed2.message||"a1 command failed")}}catch(parseError){if(parseError instanceof AoneCommandError)throw parseError}}throw new AoneCommandError(a1ErrorMessage(error))}let parsed;try{parsed=JSON.parse(stdout)}catch{throw new AoneCommandError("a1 returned non-JSON output")}if(isA1ErrorObject(parsed)){throw new AoneCommandError(parsed.message||"a1 command failed")}return parsed}__name(runA1Json,"runA1Json");async function checkA1Available(){if(a1AvailabilityVerified)return;let stdout;try{({stdout}=await a1Exec(["--version"],{timeout:A1_VERSION_TIMEOUT_MS}))}catch(error){if(error.code==="ENOENT"){throw new AoneCliUnavailableError("a1 CLI not installed; install it and run `a1 auth login`")}return}assertA1Version(stdout);a1AvailabilityVerified=true}__name(checkA1Available,"checkA1Available");function hasControlCharacter(value){return Array.from(value).some(character=>{const code=character.charCodeAt(0);return code<=31||code===127})}__name(hasControlCharacter,"hasControlCharacter");function parseAoneMrView(raw,id){const mr=raw!==null&&typeof raw==="object"?raw["mergeRequest"]:void 0;if(mr===null||typeof mr!=="object"){throw new AoneCommandError("unexpected a1 mr view output")}const v=mr;const url=typeof v["detailUrl"]==="string"?v["detailUrl"]:"";if(!/^https?:\/\//i.test(url)){throw new AoneCommandError("a1 mr view returned no detailUrl")}if(url.length>SESSION_PR_URL_MAX_LENGTH){throw new AoneCommandError("a1 mr view returned an oversized detailUrl")}if(hasControlCharacter(url)){throw new AoneCommandError("a1 mr view returned a malformed detailUrl")}return{number:id,url,state:mapAoneMrState(typeof v["state"]==="string"?v["state"]:void 0)}}__name(parseAoneMrView,"parseAoneMrView");async function viewAoneMergeRequest(repoPath,id){await checkA1Available();const parsed=await runA1Json(["repo","mr","view",String(id),"--repo",repoPath]);return parseAoneMrView(parsed,id)}__name(viewAoneMergeRequest,"viewAoneMergeRequest");var defaultAoneMrBackend={view:viewAoneMergeRequest};init_esbuild_shims();import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";var execFileAsync2=promisify2(execFile2);var GIT_TIMEOUT_MS=1e4;async function cloneWorktreesOf(cwd){const opts={timeout:GIT_TIMEOUT_MS,windowsHide:true,env:{...sanitizedGitEnv(),GIT_TERMINAL_PROMPT:"0"}};try{const{stdout}=await execFileAsync2("git",["-C",cwd,"worktree","list","--porcelain","-z"],opts);return parseWorktreePaths(stdout)}catch{try{const{stdout}=await execFileAsync2("git",["-C",cwd,"worktree","list","--porcelain"],opts);const first=stdout.split("\n").find(line=>line.startsWith("worktree "));return first?[first.slice("worktree ".length).replace(/\r$/,"")]:[]}catch{return[]}}}__name(cloneWorktreesOf,"cloneWorktreesOf");async function listAutofixPrWatches(cwd,assertGenerationOpen){assertGenerationOpen?.();const worktrees=await cloneWorktreesOf(cwd);assertGenerationOpen?.();if(worktrees.length===0)return{v:1,available:false,watches:[]};const root=worktrees[0];const outcome=runStatus({roots:worktrees,git:false,session:null});const redactError=__name(error=>{let redacted=error;for(const worktree of worktrees){redacted=redacted.split(worktree).join("<worktree>")}return redacted.replace(/autofix-pr-\d+-state\.json/g,"<state-file>")},"redactError");return{v:1,available:true,root,now:outcome.now,watches:outcome.watches.map(({thisSession:_session,worktreePath:_path,gitTrusted:_trusted,worktreeWork:_work,pushTarget:_target,...watch})=>watch),...outcome.unreadable?{unreadable:outcome.unreadable.map(({pr,error})=>({pr,error:redactError(error)}))}:{}}}__name(listAutofixPrWatches,"listAutofixPrWatches");async function respond(res,cwd,assertGenerationOpen){applyReadHeaders(res);try{res.status(200).json(await listAutofixPrWatches(cwd,assertGenerationOpen))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`autofix-pr watches of ${cwd}: ${err instanceof Error?err.message:String(err)}`);res.status(500).json({error:"Could not read the autofix-pr watches of this workspace",code:"autofix_pr_watches_failed"})}}__name(respond,"respond");function registerAutofixPrWatchesRoutes(app,deps){app.get("/autofix-pr/watches",async(_req,res)=>{if(deps.isWorkspaceTrusted&&!deps.isWorkspaceTrusted()){sendUntrustedWorkspaceResponse(res);return}await respond(res,deps.boundWorkspace,deps.captureGenerationAssertion?.())})}__name(registerAutofixPrWatchesRoutes,"registerAutofixPrWatchesRoutes");function registerWorkspaceQualifiedAutofixPrWatchesRoutes(app,deps){app.get("/workspaces/:workspace/autofix-pr/watches",async(req,res)=>{const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return;if(!requireTrustedWorkspaceRuntime(runtime,res))return;await respond(res,runtime.workspaceCwd,()=>runtime.generationGuard?.assertOpen())})}__name(registerWorkspaceQualifiedAutofixPrWatchesRoutes,"registerWorkspaceQualifiedAutofixPrWatchesRoutes");init_esbuild_shims();import{stat}from"node:fs/promises";import{dirname as dirname3,join as join3}from"node:path";init_esbuild_shims();function prWatchKey(url,pr){const repoKey=repoKeyFromWebUrl(url);return repoKey===void 0?void 0:`${repoKey}#${pr}`}__name(prWatchKey,"prWatchKey");function shellWords(input){const words=[];let current="";let started=false;let i=0;const push=__name(()=>{if(started)words.push(current);current="";started=false},"push");while(i<input.length){const ch=input[i];if(ch==="'"){started=true;i+=1;while(i<input.length&&input[i]!=="'"){current+=input[i];i+=1}if(i>=input.length)return void 0;i+=1;continue}if(ch==='"'){started=true;i+=1;while(i<input.length&&input[i]!=='"'){const c=input[i];if(c==="\\"){const next=input[i+1];if(next===void 0)return void 0;if(next==="\n"){i+=2;continue}if('$`"\\'.includes(next)){current+=next;i+=2;continue}current+=c;i+=1;continue}if(c==="$"||c==="`")return void 0;current+=c;i+=1}if(i>=input.length)return void 0;i+=1;continue}if(ch==="\\"){const next=input[i+1];if(next===void 0)return void 0;if(next==="\n"){i+=2;continue}started=true;current+=next;i+=2;continue}if(ch==="$"||ch==="`")return void 0;if("*?[]{}".includes(ch))return void 0;if(";|&><()".includes(ch)||ch==="\n")return void 0;if(ch==="#"&&!started)return words;if(ch===" "||ch===" "){push();i+=1;continue}started=true;current+=ch;i+=1}push();return words}__name(shellWords,"shellWords");function parseVerifyPrWatchGate(gate){const SCRIPT="verify-pr-watch-gate.mjs";if(!gate)return{kind:"none"};const tokens=shellWords(gate);if(tokens===void 0){return gate.includes(SCRIPT)?{kind:"unknown"}:{kind:"none"}}const isScriptWord=__name(token=>token===SCRIPT||token.endsWith(`/${SCRIPT}`),"isScriptWord");let commandIndex=0;while(commandIndex<tokens.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[commandIndex])){commandIndex+=1}const command=tokens[commandIndex];let scriptIndex=-1;if(command!==void 0&&isScriptWord(command)){scriptIndex=commandIndex}else if(command!==void 0&&(command==="node"||command==="node.exe"||command.endsWith("/node"))&&tokens[commandIndex+1]!==void 0&&isScriptWord(tokens[commandIndex+1])){scriptIndex=commandIndex+1}if(scriptIndex===-1){return tokens.some(token=>token.includes(SCRIPT))?{kind:"unknown"}:{kind:"none"}}let pr;let repo;for(let i=scriptIndex+1;i<tokens.length;i++){const token=tokens[i];if(token==="--check"||token==="--claim"||token==="--release"){return{kind:"none"}}if(token==="--repo"||token==="--cli"||token==="--state-root"){const value=tokens[++i];if(token==="--repo")repo=value;continue}if(!token.startsWith("-")&&pr===void 0){const value=Number(token);if(!Number.isInteger(value)||value<=0)return{kind:"none"};pr=value}}if(pr===void 0)return{kind:"none"};if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)){return{kind:"none"}}return{kind:"watch",repo,pr}}__name(parseVerifyPrWatchGate,"parseVerifyPrWatchGate");async function collectActivePrWatches(workspaceCwd){const watches=new Map;const add=__name((sessionId,key)=>{let set=watches.get(sessionId);if(!set){set=new Set;watches.set(sessionId,set)}set.add(key)},"add");try{const listing=await listAutofixPrWatches(workspaceCwd);if(!listing.available||listing.unreadable!==void 0&&listing.unreadable.length>0){return void 0}for(const watch of listing.watches){if(watch.session&&watch.stopped===null&&watch.ended===null){const key=prWatchKey(watch.url,watch.pr);if(key!==void 0)add(watch.session,key)}}}catch{return void 0}try{const tasks=await readCronTasks(workspaceCwd);let remoteHost;let remoteResolved=false;for(const task of tasks){if(task.enabled===false||!task.recurring||!task.sessionId){continue}const parsed=parseVerifyPrWatchGate(task.gate);if(parsed.kind==="unknown")return void 0;if(parsed.kind==="watch"){if(!remoteResolved){const remoteUrl=await fetchRemoteWebUrl(workspaceCwd);remoteHost=remoteUrl===void 0?void 0:repoKeyFromWebUrl(remoteUrl)?.split("/")[0];remoteResolved=true}if(remoteHost===void 0)return void 0;const key=prWatchKey(`https://${remoteHost}/${parsed.repo}/pull/${parsed.pr}`,parsed.pr);if(key!==void 0)add(task.sessionId,key)}}}catch{return void 0}return watches}__name(collectActivePrWatches,"collectActivePrWatches");function validTimestamp(value){return value!==void 0&&!Number.isNaN(Date.parse(value))?value:void 0}__name(validTimestamp,"validTimestamp");function projectPrs(prs){return prs.map(pr=>({number:pr.number,url:pr.url,...pr.state!==void 0?{state:pr.state}:{},...pr.role!==void 0?{role:pr.role}:{}}))}__name(projectPrs,"projectPrs");async function resolveAttribution(sessionService,sessionId,prPath,liveSummary){const item=await sessionService.getSessionListItem(sessionId,"active");const sourceType=item?.sourceType??liveSummary?.sourceType;if(isHiddenCatalogSource(sourceType))return{kind:"hidden"};if(item===void 0){let stats;try{stats=await stat(join3(dirname3(prPath),`${sessionId}.jsonl`))}catch(err){if(err.code!=="ENOENT")throw err}if(stats!==void 0&&(!stats.isFile()||stats.size>0)){return{kind:"unreadable"}}if(stats===void 0&&liveSummary===void 0&&await sessionService.getSessionListItem(sessionId,"archived")!==void 0){return{kind:"archived"}}}const liveActivity=validTimestamp(liveSummary?.updatedAt)??(item===void 0?validTimestamp(liveSummary?.createdAt):void 0);const updatedAt=laterActivityTimestamp(liveActivity,item?new Date(item.mtime).toISOString():void 0);return{kind:"ok",...sourceType!==void 0?{sourceType}:{},...updatedAt!==void 0?{updatedAt}:{}}}__name(resolveAttribution,"resolveAttribution");async function scanWorkspaceBindings(runtime,out){const sessionService=createWorkspaceRuntimeSessionService(runtime);const sessionIds=sessionService.listSessionIdsWithPrSidecar("active");let live=new Map;let liveReadFailed=false;try{live=new Map(runtime.bridge.listWorkspaceSessions(runtime.workspaceCwd).map(summary=>[summary.sessionId,summary]))}catch(err){liveReadFailed=true;process.stderr.write(`[serve] PR bindings scan: live session list unavailable in workspace ${runtime.workspaceCwd}, live-only bindings may be missing from this answer (partial): ${sanitizeLogText(err instanceof Error?err.message:String(err),200)}
4
4
  `)}const rows=new Map;const failures=[];let examined=sessionIds.length;const unknown=new Set;for(const sessionId of sessionIds){try{if(!await sessionService.sessionPrSidecarBelongsToCurrentProject(sessionId,"active")){continue}const prPath=sessionService.getPrSessionPathForArchiveState(sessionId,"active");const attribution=await resolveAttribution(sessionService,sessionId,prPath,live.get(sessionId));if(attribution.kind==="hidden"||attribution.kind==="archived"){continue}if(attribution.kind==="unreadable"){unknown.add(sessionId);failures.push({sessionId,cause:"transcript could not be read"});continue}const sidecar=await readSessionPrsDetailed(prPath);if(sidecar.status==="absent")continue;if(sidecar.status==="invalid"){unknown.add(sessionId);failures.push({sessionId,cause:"sidecar is invalid JSON or failed the shape check"});continue}if(sidecar.prs.length===0){rows.set(sessionId,{sessionId,workspaceCwd:runtime.workspaceCwd,prs:[]});continue}rows.set(sessionId,{sessionId,workspaceCwd:runtime.workspaceCwd,...attribution.sourceType!==void 0?{sourceType:attribution.sourceType}:{},...attribution.updatedAt!==void 0?{updatedAt:attribution.updatedAt}:{},prs:projectPrs(sidecar.prs)})}catch(err){unknown.add(sessionId);failures.push({sessionId,cause:err instanceof Error?err.message:String(err)})}}for(const[sessionId,summary]of live){if(unknown.has(sessionId)||!summary.prs?.length)continue;const row=rows.get(sessionId);if(row!==void 0){if(row.prs.length===0||row.prs.length>=SESSION_PR_LIST_LIMIT){continue}const known=new Set(row.prs.map(pr=>pr.number));row.prs.push(...projectPrs(summary.prs.filter(pr=>!known.has(pr.number))));row.prs=row.prs.slice(-SESSION_PR_LIST_LIMIT);continue}examined+=1;try{const attribution=await resolveAttribution(sessionService,sessionId,sessionService.getPrSessionPathForArchiveState(sessionId,"active"),summary);if(attribution.kind==="hidden"||attribution.kind==="archived"){continue}if(attribution.kind==="unreadable"){failures.push({sessionId,cause:"transcript could not be read"});continue}rows.set(sessionId,{sessionId,workspaceCwd:runtime.workspaceCwd,...attribution.sourceType!==void 0?{sourceType:attribution.sourceType}:{},...attribution.updatedAt!==void 0?{updatedAt:attribution.updatedAt}:{},prs:projectPrs(summary.prs).slice(-SESSION_PR_LIST_LIMIT)})}catch(err){failures.push({sessionId,cause:err instanceof Error?err.message:String(err)})}}const watches=await collectActivePrWatches(runtime.workspaceCwd);if(watches===void 0){process.stderr.write(`[serve] PR bindings scan: watch detection unavailable in workspace ${runtime.workspaceCwd}, entries carry no watching flag (fail-open)
5
5
  `)}else{for(const row of rows.values()){const sessionWatches=watches.get(row.sessionId);for(const pr of row.prs){const key=prWatchKey(pr.url,pr.number);if(key===void 0)continue;pr.watching=sessionWatches?.has(key)??false}}}out.push(...rows.values());if(failures.length>0){const first=failures[0];process.stderr.write(`[serve] PR bindings scan: ${failures.length} of ${examined} sessions could not be read in workspace ${runtime.workspaceCwd}, answer partial (first: ${sanitizeLogText(first.sessionId,64)}: ${sanitizeLogText(first.cause,200)})
6
6
  `)}return liveReadFailed||failures.length>0}__name(scanWorkspaceBindings,"scanWorkspaceBindings");function registerSessionPrBindingsRoutes(app,deps){app.get("/sessions/pr-bindings",async(_req,res)=>{const route="GET /sessions/pr-bindings";try{const bindings=[];let partial=false;for(const entry of deps.workspaceRegistry.listAllEntries()){const runtime=entry.current?.runtime;if(!runtime){process.stderr.write(`[serve] PR bindings scan: workspace ${entry.workspaceCwd} has no runtime (state ${entry.state}), answer partial