@hostclubeos/miraos 0.0.1-beta → 0.0.5-beta

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 (417) hide show
  1. package/bundled/app-store-compliance/SKILL.md +58 -0
  2. package/bundled/bug-hunter/NOTICE +17 -0
  3. package/bundled/bug-hunter/SKILL.md +65 -0
  4. package/bundled/superpowers/NOTICE +11 -0
  5. package/bundled/superpowers/SKILL.md +43 -0
  6. package/bundled/superpowers/references/brainstorming/SKILL.md +316 -0
  7. package/bundled/superpowers/references/brainstorming/builder-check-prompt.md +23 -0
  8. package/bundled/superpowers/references/brainstorming/scripts/frame-template.html +213 -0
  9. package/bundled/superpowers/references/brainstorming/scripts/helper.js +167 -0
  10. package/bundled/superpowers/references/brainstorming/scripts/server.cjs +723 -0
  11. package/bundled/superpowers/references/brainstorming/scripts/start-server.sh +216 -0
  12. package/bundled/superpowers/references/brainstorming/scripts/stop-server.sh +120 -0
  13. package/bundled/superpowers/references/brainstorming/visual-companion.md +299 -0
  14. package/bundled/superpowers/references/diagnosing-superpowers/SKILL.md +120 -0
  15. package/bundled/superpowers/references/diagnosing-superpowers/prompts/analyst-common.md +38 -0
  16. package/bundled/superpowers/references/diagnosing-superpowers/prompts/cost-and-time.md +28 -0
  17. package/bundled/superpowers/references/diagnosing-superpowers/prompts/plan-adherence.md +29 -0
  18. package/bundled/superpowers/references/diagnosing-superpowers/prompts/quality-evidence.md +26 -0
  19. package/bundled/superpowers/references/diagnosing-superpowers/prompts/repeated-work.md +30 -0
  20. package/bundled/superpowers/references/diagnosing-superpowers/prompts/request-conflicts.md +20 -0
  21. package/bundled/superpowers/references/diagnosing-superpowers/prompts/scrub-audit.md +33 -0
  22. package/bundled/superpowers/references/diagnosing-superpowers/prompts/scrub.md +29 -0
  23. package/bundled/superpowers/references/diagnosing-superpowers/prompts/similar-session.md +38 -0
  24. package/bundled/superpowers/references/diagnosing-superpowers/prompts/skill-timeline.md +30 -0
  25. package/bundled/superpowers/references/diagnosing-superpowers/prompts/stumbles.md +28 -0
  26. package/bundled/superpowers/references/diagnosing-superpowers/references/context-safety.md +22 -0
  27. package/bundled/superpowers/references/diagnosing-superpowers/references/github-issues.md +47 -0
  28. package/bundled/superpowers/references/diagnosing-superpowers/references/redaction-policy.md +34 -0
  29. package/bundled/superpowers/references/diagnosing-superpowers/references/session-discovery.md +31 -0
  30. package/bundled/superpowers/references/diagnosing-superpowers/templates/bundle-README.md +77 -0
  31. package/bundled/superpowers/references/diagnosing-superpowers/templates/case.md +64 -0
  32. package/bundled/superpowers/references/diagnosing-superpowers/templates/issue.md +70 -0
  33. package/bundled/superpowers/references/diagnosing-superpowers/templates/report.md +82 -0
  34. package/bundled/superpowers/references/dispatching-parallel-agents/SKILL.md +167 -0
  35. package/bundled/superpowers/references/executing-plans/SKILL.md +323 -0
  36. package/bundled/superpowers/references/executing-plans/scripts/task-done +55 -0
  37. package/bundled/superpowers/references/executing-plans/scripts/task-start +32 -0
  38. package/bundled/superpowers/references/finishing-a-development-branch/SKILL.md +225 -0
  39. package/bundled/superpowers/references/receiving-code-review/SKILL.md +205 -0
  40. package/bundled/superpowers/references/requesting-code-review/SKILL.md +95 -0
  41. package/bundled/superpowers/references/requesting-code-review/code-reviewer.md +198 -0
  42. package/bundled/superpowers/references/subagent-driven-development/SKILL.md +339 -0
  43. package/bundled/superpowers/references/subagent-driven-development/implementer-prompt.md +154 -0
  44. package/bundled/superpowers/references/subagent-driven-development/re-review-prompt.md +116 -0
  45. package/bundled/superpowers/references/subagent-driven-development/references/batching.md +11 -0
  46. package/bundled/superpowers/references/subagent-driven-development/references/cannot-verify.md +10 -0
  47. package/bundled/superpowers/references/subagent-driven-development/references/final-review.md +49 -0
  48. package/bundled/superpowers/references/subagent-driven-development/references/fix-loop.md +77 -0
  49. package/bundled/superpowers/references/subagent-driven-development/references/handling-reports.md +15 -0
  50. package/bundled/superpowers/references/subagent-driven-development/references/preflight.md +26 -0
  51. package/bundled/superpowers/references/subagent-driven-development/references/resuming.md +12 -0
  52. package/bundled/superpowers/references/subagent-driven-development/scripts/review-package +64 -0
  53. package/bundled/superpowers/references/subagent-driven-development/scripts/sdd-repo +54 -0
  54. package/bundled/superpowers/references/subagent-driven-development/scripts/sdd-workspace +110 -0
  55. package/bundled/superpowers/references/subagent-driven-development/scripts/task-brief +108 -0
  56. package/bundled/superpowers/references/subagent-driven-development/task-reviewer-prompt.md +209 -0
  57. package/bundled/superpowers/references/systematic-debugging/SKILL.md +283 -0
  58. package/bundled/superpowers/references/systematic-debugging/condition-based-waiting-example.ts +159 -0
  59. package/bundled/superpowers/references/systematic-debugging/condition-based-waiting.md +115 -0
  60. package/bundled/superpowers/references/systematic-debugging/defense-in-depth.md +122 -0
  61. package/bundled/superpowers/references/systematic-debugging/find-polluter.sh +72 -0
  62. package/bundled/superpowers/references/systematic-debugging/root-cause-tracing.md +169 -0
  63. package/bundled/superpowers/references/test-driven-development/SKILL.md +330 -0
  64. package/bundled/superpowers/references/test-driven-development/writing-good-tests.md +198 -0
  65. package/bundled/superpowers/references/using-git-worktrees/SKILL.md +167 -0
  66. package/bundled/superpowers/references/using-superpowers/SKILL.md +65 -0
  67. package/bundled/superpowers/references/using-superpowers/references/antigravity-tools.md +23 -0
  68. package/bundled/superpowers/references/using-superpowers/references/claude-code-tools.md +29 -0
  69. package/bundled/superpowers/references/using-superpowers/references/codex-tools.md +108 -0
  70. package/bundled/superpowers/references/using-superpowers/references/gemini-tools.md +63 -0
  71. package/bundled/superpowers/references/using-superpowers/references/hermes-tools.md +56 -0
  72. package/bundled/superpowers/references/using-superpowers/references/muse-tools.md +35 -0
  73. package/bundled/superpowers/references/using-superpowers/references/pi-tools.md +16 -0
  74. package/bundled/superpowers/references/verification-before-completion/SKILL.md +120 -0
  75. package/bundled/superpowers/references/writing-plans/SKILL.md +204 -0
  76. package/bundled/superpowers/references/writing-skills/SKILL.md +399 -0
  77. package/bundled/superpowers/references/writing-skills/references/CLAUDE_MD_TESTING.md +189 -0
  78. package/bundled/superpowers/references/writing-skills/references/anthropic-best-practices.md +1150 -0
  79. package/bundled/superpowers/references/writing-skills/references/bulletproofing.md +80 -0
  80. package/bundled/superpowers/references/writing-skills/references/discovery.md +201 -0
  81. package/bundled/superpowers/references/writing-skills/references/flowcharts.md +37 -0
  82. package/bundled/superpowers/references/writing-skills/references/graphviz-conventions.dot +172 -0
  83. package/bundled/superpowers/references/writing-skills/references/persuasion-principles.md +187 -0
  84. package/bundled/superpowers/references/writing-skills/references/testing-skills-with-subagents.md +384 -0
  85. package/bundled/superpowers/references/writing-skills/render-graphs.js +169 -0
  86. package/bundled/swarm/SKILL.md +47 -0
  87. package/chunks/{MaxSizedBox-4XZJGJCR.js → MaxSizedBox-CBUPHLMW.js} +1 -1
  88. package/chunks/{StandaloneSessionPicker-YUWFI6WT.js → StandaloneSessionPicker-EXZJQKTK.js} +1 -1
  89. package/chunks/{acp-subagent-executor-7BGJRBWA.js → acp-subagent-executor-BMIXP52W.js} +1 -1
  90. package/chunks/{acpAgent-DO3DYSKS.js → acpAgent-UHWDA3W7.js} +3 -3
  91. package/chunks/{advisor-ZMSGPCRF.js → advisor-5RUG3VFZ.js} +1 -1
  92. package/chunks/{agent-ZMZLTEBG.js → agent-SGQ7AEZI.js} +1 -1
  93. package/chunks/{agent-headless-5COOZKMA.js → agent-headless-ZGCZ2DA7.js} +1 -1
  94. package/chunks/{agent-host-client-L2ROWXVT.js → agent-host-client-HY5GPSHM.js} +1 -1
  95. package/chunks/{agent-host-connections-A4UGANXV.js → agent-host-connections-KGTBS37X.js} +1 -1
  96. package/chunks/{autofix-pr-N3M7IGHT.js → autofix-pr-E62FC67X.js} +1 -1
  97. package/chunks/{autofix-pr-VWZPABZQ.js → autofix-pr-TRI4NMYI.js} +1 -1
  98. package/chunks/{batch-RTO7FWGG.js → batch-OUC6FGCQ.js} +1 -1
  99. package/chunks/{bridge-ZZ2GF4DM.js → bridge-FLEIBB5V.js} +1 -1
  100. package/chunks/{bwrap-execution-6NIUP47A.js → bwrap-execution-VLHJWP4O.js} +1 -1
  101. package/chunks/{channel-settings-store-Y5HXLPQF.js → channel-settings-store-QG6HREVH.js} +1 -1
  102. package/chunks/{chunk-FXFSZ7QF.js → chunk-23543L6E.js} +1 -1
  103. package/chunks/{chunk-NM5TUAPJ.js → chunk-2GVKPBW5.js} +1 -1
  104. package/chunks/{chunk-DPKN7TSL.js → chunk-2QYFSBJY.js} +1 -1
  105. package/chunks/{chunk-NMB6IBA7.js → chunk-2TDRP3IX.js} +1 -1
  106. package/chunks/{chunk-ZE5YXIAJ.js → chunk-2VW4HXVF.js} +1 -1
  107. package/chunks/{chunk-FQXNP7EE.js → chunk-2ZWVSKPK.js} +1 -1
  108. package/chunks/{chunk-SBFKWNC3.js → chunk-3GJ56V2J.js} +1 -1
  109. package/chunks/{chunk-7JU5ZJJ7.js → chunk-3KFLO5W3.js} +1 -1
  110. package/chunks/{chunk-P4ZCOMZS.js → chunk-3MBYQYPC.js} +1 -1
  111. package/chunks/{chunk-FHGGT7VE.js → chunk-4346FNTB.js} +1 -1
  112. package/chunks/{chunk-IKQHFQ74.js → chunk-4GNHXVJZ.js} +1 -1
  113. package/chunks/{chunk-2FD2BYUZ.js → chunk-4IVYVCCU.js} +3 -3
  114. package/chunks/{chunk-ZEIWENJU.js → chunk-4KIFAVR2.js} +1 -1
  115. package/chunks/{chunk-YSWDQYJU.js → chunk-4MGTY3CJ.js} +1 -1
  116. package/chunks/{chunk-3LS3HVJA.js → chunk-4WYKHP7Q.js} +1 -1
  117. package/chunks/{chunk-MWGGXT4P.js → chunk-56PVVXUG.js} +1 -1
  118. package/chunks/{chunk-J4KLD52D.js → chunk-62DMHXLL.js} +1 -1
  119. package/chunks/{chunk-TALEJQWF.js → chunk-66DZADDA.js} +1 -1
  120. package/chunks/{chunk-GOEBFMO2.js → chunk-6RDYPRV6.js} +1 -1
  121. package/chunks/{chunk-5HNCGRMZ.js → chunk-724YPZRX.js} +1 -1
  122. package/chunks/{chunk-HA6K73R7.js → chunk-744QTJR2.js} +2 -2
  123. package/chunks/{chunk-SCQWVHLA.js → chunk-7F5IYTVE.js} +1 -1
  124. package/chunks/{chunk-TDM5PKRC.js → chunk-7VP4KALB.js} +1 -1
  125. package/chunks/{chunk-QWOBTVIO.js → chunk-7W5DOBKY.js} +1 -1
  126. package/chunks/{chunk-UL5A63VS.js → chunk-AE6E2YKY.js} +1 -1
  127. package/chunks/{chunk-J2DA7XAM.js → chunk-AIAYQAPA.js} +1 -1
  128. package/chunks/{chunk-3XFUS57Z.js → chunk-AIGBQN6R.js} +1 -1
  129. package/chunks/{chunk-BVYNPYGP.js → chunk-AJ75BPTA.js} +6 -1
  130. package/chunks/{chunk-LEZ3AZJI.js → chunk-ATVRF62A.js} +1 -1
  131. package/chunks/{chunk-DW4HTZVZ.js → chunk-BX3KM7OK.js} +1 -1
  132. package/chunks/{chunk-4UVQYN33.js → chunk-CUY6CVSL.js} +1 -1
  133. package/chunks/{chunk-RRXNG7AI.js → chunk-D3QZNIFB.js} +6 -6
  134. package/chunks/{chunk-5PZ4EFXH.js → chunk-D3YOXHQF.js} +1 -1
  135. package/chunks/{chunk-L66KXTVG.js → chunk-DABLVQXV.js} +1 -1
  136. package/chunks/{chunk-6AA5DYMC.js → chunk-DMM5LJWL.js} +2 -2
  137. package/chunks/{chunk-TWCQNRBQ.js → chunk-DNYXZVBT.js} +1 -1
  138. package/chunks/{chunk-HCIFQTQ4.js → chunk-E6LRCLLE.js} +2 -2
  139. package/chunks/{chunk-L44CUCID.js → chunk-EF3HUB7S.js} +1 -1
  140. package/chunks/{chunk-WQEJL3HN.js → chunk-EW3EVEYN.js} +1 -1
  141. package/chunks/{chunk-RMATGKAM.js → chunk-FC7SJIAS.js} +1 -1
  142. package/chunks/{chunk-4NQCOITC.js → chunk-FK5L2WVV.js} +1 -1
  143. package/chunks/{chunk-EMRZ722U.js → chunk-FRADUGRC.js} +1 -1
  144. package/chunks/{chunk-T2O3JMRH.js → chunk-FS67DOZQ.js} +1 -1
  145. package/chunks/{chunk-27MEJGPT.js → chunk-FXANOHXI.js} +5 -5
  146. package/chunks/{chunk-VCLKQDTV.js → chunk-GLQWA4W2.js} +1 -1
  147. package/chunks/{chunk-STPD3MIX.js → chunk-GOZ5FAUV.js} +1 -1
  148. package/chunks/{chunk-POX6TDCX.js → chunk-GTQULDIL.js} +1 -1
  149. package/chunks/{chunk-SR6MFJYO.js → chunk-GY4ID3EB.js} +1 -1
  150. package/chunks/{chunk-IJDGB3GP.js → chunk-H65ZVST6.js} +1 -1
  151. package/chunks/{chunk-6MWOHNU7.js → chunk-HASJX2YS.js} +1 -1
  152. package/chunks/{chunk-TJVI2L24.js → chunk-HSN5QUS7.js} +1 -1
  153. package/chunks/{chunk-7A42KF7G.js → chunk-HZ4L4MDM.js} +1 -1
  154. package/chunks/{chunk-WXVU3W2Q.js → chunk-IC42HQCH.js} +1 -1
  155. package/chunks/{chunk-NSA4ZO4V.js → chunk-IF3SWUYT.js} +1 -1
  156. package/chunks/{chunk-AGVUBA2V.js → chunk-J773THNP.js} +1 -1
  157. package/chunks/{chunk-ETYFIFMT.js → chunk-JDHMSERR.js} +1 -1
  158. package/chunks/{chunk-GNJTCOX3.js → chunk-JIQVUYBI.js} +1 -1
  159. package/chunks/{chunk-F5LMCQ2K.js → chunk-JJDF5FHA.js} +1 -1
  160. package/chunks/{chunk-TSI3G7JM.js → chunk-JQOLNQQN.js} +1 -1
  161. package/chunks/{chunk-ERUWCPGL.js → chunk-JQYPRANX.js} +1 -1
  162. package/chunks/{chunk-IW5GJAOR.js → chunk-K7KY7FIB.js} +1 -1
  163. package/chunks/{chunk-P2CUOX2Q.js → chunk-K7VOBDFT.js} +1 -1
  164. package/chunks/{chunk-SNGI5OD7.js → chunk-KK6SQPYG.js} +1 -1
  165. package/chunks/{chunk-HVAOQB42.js → chunk-KNW2OD46.js} +1 -1
  166. package/chunks/{chunk-GQSVGUOU.js → chunk-KP77CL5U.js} +1 -1
  167. package/chunks/{chunk-G6EIN5FW.js → chunk-KYK53GFP.js} +1 -1
  168. package/chunks/{chunk-432LPP2J.js → chunk-MQWKOOSR.js} +1 -1
  169. package/chunks/{chunk-XMIUDKGO.js → chunk-MUS4ADP7.js} +2 -2
  170. package/chunks/{chunk-IVHSWYWP.js → chunk-MYS5NQXO.js} +1 -1
  171. package/chunks/{chunk-FCOVJQX7.js → chunk-N4RIISOE.js} +1 -1
  172. package/chunks/{chunk-FCB7X7TI.js → chunk-NCBA52SB.js} +1 -1
  173. package/chunks/{chunk-GNV3UOVR.js → chunk-NGH27AWP.js} +1 -1
  174. package/chunks/{chunk-YM7CPT6W.js → chunk-NKWATWMD.js} +2 -2
  175. package/chunks/{chunk-R4HUU27E.js → chunk-NVD63O5H.js} +1 -1
  176. package/chunks/{chunk-WNT3ND65.js → chunk-NYM67KKZ.js} +2 -2
  177. package/chunks/{chunk-F6MHDBMX.js → chunk-O6Z3KO6R.js} +1 -1
  178. package/chunks/{chunk-RPMW55YH.js → chunk-OV2J3OED.js} +1 -1
  179. package/chunks/{chunk-RGOWOT3Z.js → chunk-P42MFWO2.js} +1 -1
  180. package/chunks/{chunk-XREDCQA5.js → chunk-P5543CFV.js} +1 -1
  181. package/chunks/{chunk-RHFRL6CB.js → chunk-PFECH6U6.js} +1 -1
  182. package/chunks/{chunk-3SQ76U4F.js → chunk-PFKTTUGS.js} +6 -6
  183. package/chunks/{chunk-XU5D2FKZ.js → chunk-PGKFDR73.js} +1 -1
  184. package/chunks/{chunk-LTUKVA3O.js → chunk-PQOQONLN.js} +1 -1
  185. package/chunks/{chunk-E7PL6EYK.js → chunk-PVHBBTAU.js} +1 -1
  186. package/chunks/{chunk-SKLO2WHR.js → chunk-PXBJPUGN.js} +1 -1
  187. package/chunks/{chunk-BCY6VYWQ.js → chunk-QEIX42MZ.js} +1 -1
  188. package/chunks/{chunk-MEUP65FI.js → chunk-QTCO5I4C.js} +1 -1
  189. package/chunks/{chunk-3KM4JL4Y.js → chunk-RBA3TP7L.js} +1 -1
  190. package/chunks/{chunk-R3H2AN4X.js → chunk-RKFNQQNA.js} +1 -1
  191. package/chunks/{chunk-RBYRJBQV.js → chunk-RNPVWQ3V.js} +1 -1
  192. package/chunks/{chunk-G7KBHT53.js → chunk-RRMTSVGU.js} +1 -1
  193. package/chunks/{chunk-W5YMSMZG.js → chunk-RWFOQXPU.js} +1 -1
  194. package/chunks/{chunk-R32F7IAM.js → chunk-SCHCTQCG.js} +1 -1
  195. package/chunks/{chunk-MC47YWMG.js → chunk-SHKSVOTG.js} +1 -1
  196. package/chunks/{chunk-YPG2SMZS.js → chunk-SK3QOQR4.js} +1 -1
  197. package/chunks/{chunk-5SFSOCHV.js → chunk-T3A53XMM.js} +1 -1
  198. package/chunks/{chunk-3SCCBDDE.js → chunk-T5PDEAU5.js} +1 -1
  199. package/chunks/{chunk-PIHZPQYO.js → chunk-T5XGTSQU.js} +1 -1
  200. package/chunks/{chunk-J4SZAKAX.js → chunk-TFITRCIC.js} +1 -1
  201. package/chunks/{chunk-THO23XWK.js → chunk-TLZM3DMY.js} +1 -1
  202. package/chunks/{chunk-Y6PDX4C4.js → chunk-TU5QHOJC.js} +1 -1
  203. package/chunks/{chunk-FFE5LIA6.js → chunk-TWJ4XBED.js} +1 -1
  204. package/chunks/{chunk-K6I2EP3G.js → chunk-UNJYVYTC.js} +1 -1
  205. package/chunks/{chunk-KSWZ6FTA.js → chunk-UOYXBAN7.js} +1 -1
  206. package/chunks/{chunk-GGXMABF2.js → chunk-USR2Y7B3.js} +1 -1
  207. package/chunks/{chunk-6O6IED5M.js → chunk-UWMLSAQY.js} +1 -1
  208. package/chunks/{chunk-OGPOUNG7.js → chunk-V5Z6OEKJ.js} +1 -1
  209. package/chunks/{chunk-MWMYT4PK.js → chunk-VBJV7T47.js} +1 -1
  210. package/chunks/{chunk-BAHNLZJQ.js → chunk-VF2UWWI2.js} +1 -1
  211. package/chunks/{chunk-MVF4MYTY.js → chunk-VJUTDS6C.js} +1 -1
  212. package/chunks/{chunk-A42T2FGM.js → chunk-W2ZVZ6LS.js} +1 -1
  213. package/chunks/{chunk-V6ZOOFZ3.js → chunk-W6IOHGWW.js} +1 -1
  214. package/chunks/{chunk-I5FHTXDB.js → chunk-WC72OWF2.js} +2 -2
  215. package/chunks/{chunk-XW5ZOTPK.js → chunk-WJLHLFIR.js} +1 -1
  216. package/chunks/{chunk-T4P4FF3I.js → chunk-WZTO3EYG.js} +1 -1
  217. package/chunks/{chunk-IUUWYEF5.js → chunk-XZNF4YNN.js} +1 -1
  218. package/chunks/{chunk-N7OJZ7AS.js → chunk-YN6WXB6B.js} +1 -1
  219. package/chunks/{chunk-PJUXHD2F.js → chunk-YVN32EUM.js} +1 -1
  220. package/chunks/{chunk-B7XMOQLO.js → chunk-Z4JY3HGO.js} +1 -1
  221. package/chunks/{chunk-AIIV662S.js → chunk-ZOWMHZWO.js} +1 -1
  222. package/chunks/{codex-subagent-executor-AR4Q5IHV.js → codex-subagent-executor-UCDGQFTR.js} +1 -1
  223. package/chunks/{config-utils-5S5PZQ5S.js → config-utils-Z6F4DVLG.js} +1 -1
  224. package/chunks/{contextCommand-YEZP3P4L.js → contextCommand-HMVZT56Y.js} +1 -1
  225. package/chunks/{core-runtime-LISS3YR4.js → core-runtime-AV7CJXOL.js} +1 -1
  226. package/chunks/{create-sub-session-FCB4YENT.js → create-sub-session-NNKVHZKT.js} +1 -1
  227. package/chunks/{cron-create-E2PZGYSL.js → cron-create-HWZDFVPA.js} +1 -1
  228. package/chunks/{daemon-git-worktree-guard-23KFZWC5.js → daemon-git-worktree-guard-Q3C45X7T.js} +1 -1
  229. package/chunks/{daemon-status-provider-KU7B5BBQ.js → daemon-status-provider-F6KB2LNG.js} +1 -1
  230. package/chunks/{daemon-trust-policy-FL3DDA6T.js → daemon-trust-policy-6D4KJANB.js} +1 -1
  231. package/chunks/{daemon-trust-policy-monitor-FCCK3YHW.js → daemon-trust-policy-monitor-BZ46W4IA.js} +1 -1
  232. package/chunks/{deferred-core-runtime-BCJU6YQI.js → deferred-core-runtime-YC5XIWEI.js} +1 -1
  233. package/chunks/{display-image-ZHNLZCK7.js → display-image-LAGHQ4RY.js} +1 -1
  234. package/chunks/{edit-SXQ5HK4W.js → edit-LOWDEKPX.js} +1 -1
  235. package/chunks/{enterPlanMode-NX6SOALP.js → enterPlanMode-NGSATDRH.js} +1 -1
  236. package/chunks/{environment-GFCR2C43.js → environment-CVIB5DW4.js} +1 -1
  237. package/chunks/{errors-WZJPHSEP.js → errors-USKSVZFO.js} +1 -1
  238. package/chunks/{execute-sandbox-VZ4OKFCC.js → execute-sandbox-KNRRYQ52.js} +1 -1
  239. package/chunks/{execution-sandbox-config-XQNSHI7G.js → execution-sandbox-config-XBW3PXDA.js} +1 -1
  240. package/chunks/{execution-tool-XPHUDQJ4.js → execution-tool-QSJLRU5N.js} +1 -1
  241. package/chunks/{execution-worker-6RXFIQH4.js → execution-worker-TQEIC4AJ.js} +1 -1
  242. package/chunks/{exitPlanMode-LP3D7M5M.js → exitPlanMode-AW2HOTIK.js} +1 -1
  243. package/chunks/{fast-path-2D5QZRQW.js → fast-path-DWPD5EGQ.js} +1 -1
  244. package/chunks/{glob-JFH2DTI7.js → glob-7U6FQSWZ.js} +1 -1
  245. package/chunks/{goal-tools-UL3O364Y.js → goal-tools-5ZB6GPCJ.js} +1 -1
  246. package/chunks/{handleAutoUpdate-MYD2LZXQ.js → handleAutoUpdate-MLUFTWFP.js} +1 -1
  247. package/chunks/{i18n-LDINZEX3.js → i18n-QAPQLOC3.js} +1 -1
  248. package/chunks/{initializer-LLXI4EVO.js → initializer-B27IZ7K4.js} +1 -1
  249. package/chunks/{installationInfo-4FS5ROEO.js → installationInfo-SAMHABWV.js} +1 -1
  250. package/chunks/{interactive-mod-session-UFB2CURW.js → interactive-mod-session-7LQ5CYUR.js} +1 -1
  251. package/chunks/{landlock-execution-3T5Y3SFY.js → landlock-execution-2BJ56FDV.js} +1 -1
  252. package/chunks/{list-45PFXWOV.js → list-TDMJQDQO.js} +1 -1
  253. package/chunks/{llm-VIFUT34L.js → llm-RBI7KXDE.js} +4 -4
  254. package/chunks/{loadedSettingsAdapter-3MNB7PHB.js → loadedSettingsAdapter-ZQK5KMEW.js} +1 -1
  255. package/chunks/{local-TBDN3BOU.js → local-HSG47CNJ.js} +1 -1
  256. package/chunks/{local-execution-environment-PNRU2WTJ.js → local-execution-environment-WJVCE26F.js} +1 -1
  257. package/chunks/{loggingContentGenerator-JA22TIC4.js → loggingContentGenerator-ALSG42YA.js} +1 -1
  258. package/chunks/{loop-wakeup-BXKFVB7H.js → loop-wakeup-LFU4LDJM.js} +1 -1
  259. package/chunks/{manage-memory-BMKA64KG.js → manage-memory-FBL6CHX2.js} +1 -1
  260. package/chunks/{managed-execution-engine-PVXRANOE.js → managed-execution-engine-FX7FDAWW.js} +1 -1
  261. package/chunks/{managed-local-serve-H5BEBXVR.js → managed-local-serve-YE4JDFNP.js} +1 -1
  262. package/chunks/{managed-npm-update-JGC5W6SL.js → managed-npm-update-2MKV7UOI.js} +1 -1
  263. package/chunks/{managed-runtime-attestation-worker-KCUQIRVR.js → managed-runtime-attestation-worker-DBAHM5MN.js} +1 -1
  264. package/chunks/{managed-runtime-bootstrap-HCN3NINM.js → managed-runtime-bootstrap-SHEXUEZN.js} +1 -1
  265. package/chunks/{managed-runtime-session-worker-G4TB3S5M.js → managed-runtime-session-worker-YN4KML7A.js} +1 -1
  266. package/chunks/{managed-runtime-ssh-worker-4WSWY2MH.js → managed-runtime-ssh-worker-BZNJV7IB.js} +1 -1
  267. package/chunks/{managed-session-authority-H5USCQ6W.js → managed-session-authority-MFEINLXC.js} +1 -1
  268. package/chunks/{mcp-WXNSQID6.js → mcp-TS5PX5FY.js} +1 -1
  269. package/chunks/{memory-E5SQH3NJ.js → memory-JTDN5AEA.js} +1 -1
  270. package/chunks/{model-call-collection-PULBNXXQ.js → model-call-collection-TNBMD3YL.js} +1 -1
  271. package/chunks/{model-configuration-SJEIOQGZ.js → model-configuration-6KTQQTMO.js} +1 -1
  272. package/chunks/{modelConfigUtils-WJ27GPGB.js → modelConfigUtils-LCZZ3EQU.js} +1 -1
  273. package/chunks/{monitor-N25QQU7J.js → monitor-KCCNIKLE.js} +1 -1
  274. package/chunks/{nonInteractiveCli-E6RLP7AG.js → nonInteractiveCli-BXHX6EIU.js} +1 -1
  275. package/chunks/{nonInteractiveToolExecutor-Z5JBEIAW.js → nonInteractiveToolExecutor-R5CTTWKD.js} +1 -1
  276. package/chunks/{notebook-edit-WVLO2EUN.js → notebook-edit-KIWE2XOA.js} +1 -1
  277. package/chunks/{omni-RKVYBBQI.js → omni-IFTMWBMU.js} +1 -1
  278. package/chunks/{openaiContentGenerator-2G2XB3DF.js → openaiContentGenerator-XP3VPU6C.js} +1 -1
  279. package/chunks/{openaiResponsesContentGenerator-344BTMHF.js → openaiResponsesContentGenerator-ZJ6C22EA.js} +1 -1
  280. package/chunks/{pidfile-KS6QFQIJ.js → pidfile-42P24JIA.js} +1 -1
  281. package/chunks/{processUtils-U45GFMXN.js → processUtils-I2XOO5U2.js} +1 -1
  282. package/chunks/{prompt-terminal-ledger-HAK6RGOC.js → prompt-terminal-ledger-7EW46VQ4.js} +1 -1
  283. package/chunks/{reactive-degrade-S7C6GXHH.js → reactive-degrade-O4JO7MOX.js} +1 -1
  284. package/chunks/{read-file-RG5ZNNCH.js → read-file-VGC4O7F2.js} +1 -1
  285. package/chunks/{record-source-6J47E2DW.js → record-source-VX26ZO6I.js} +1 -1
  286. package/chunks/{request-shutdown-SCU5TN5V.js → request-shutdown-P7227UEF.js} +1 -1
  287. package/chunks/{resumeHistoryUtils-CDDEU4RO.js → resumeHistoryUtils-QMVIHQRW.js} +1 -1
  288. package/chunks/{review-H6FLIVJV.js → review-PC4IDLCG.js} +1 -1
  289. package/chunks/{ripGrep-XEDOYGPA.js → ripGrep-JY4PZABK.js} +1 -1
  290. package/chunks/{run-qwen-serve-ODBFOM6H.js → run-qwen-serve-XRWVWOZK.js} +1 -1
  291. package/chunks/{runtime-SCINDTK2.js → runtime-OL7B72CH.js} +1 -1
  292. package/chunks/{runtime-shell-policy-77EFLSNG.js → runtime-shell-policy-TXAWAOBK.js} +1 -1
  293. package/chunks/{sandboxConfig-WE7GXTES.js → sandboxConfig-EJTMWZHD.js} +1 -1
  294. package/chunks/{scheduled-tasks-4HL6GKQ4.js → scheduled-tasks-XQSZWZXG.js} +1 -1
  295. package/chunks/{scheduler-ETHKOB4B.js → scheduler-3TIRZEVB.js} +1 -1
  296. package/chunks/{search-memory-R4O5AIEV.js → search-memory-P5KOTUVV.js} +1 -1
  297. package/chunks/{send-message-SBQSBXDW.js → send-message-KFSKFXLX.js} +1 -1
  298. package/chunks/{serve-TRAGNNK6.js → serve-JCUT4WK7.js} +1 -1
  299. package/chunks/{server-BXVHT3XW.js → server-HMTRZJF7.js} +3 -3
  300. package/chunks/{session-A6NV4RLU.js → session-RGLZU6KY.js} +1 -1
  301. package/chunks/{session-attachments-root-WU56VFQN.js → session-attachments-root-O3YQ7HWD.js} +1 -1
  302. package/chunks/{session-execution-engine-selector-MG2ZDK25.js → session-execution-engine-selector-LZBHS3UO.js} +1 -1
  303. package/chunks/{session-pr-refresh-HQOHASVU.js → session-pr-refresh-L5Z5WCXS.js} +1 -1
  304. package/chunks/{sessionService-XBFZRVW6.js → sessionService-MMPZUN5X.js} +1 -1
  305. package/chunks/{settings-HDG72SDU.js → settings-7PYHXPN4.js} +1 -1
  306. package/chunks/{shell-VNVPTXQO.js → shell-E6QLKRVU.js} +1 -1
  307. package/chunks/{skill-4VDNIMOV.js → skill-55IZUUM5.js} +1 -1
  308. package/chunks/{skill-settings-VKC2ATCK.js → skill-settings-A2M5BPH7.js} +1 -1
  309. package/chunks/{spawnChannel-RB5Q6Z4U.js → spawnChannel-KWU26CB7.js} +1 -1
  310. package/chunks/{standalone-update-QDH63IIS.js → standalone-update-32WYZ3BJ.js} +1 -1
  311. package/chunks/{start-opentui-ui-VULNQJ3L.js → start-opentui-ui-YNTPK7LX.js} +2 -2
  312. package/chunks/{startInteractiveUI-XZATGHLR.js → startInteractiveUI-MWA2VYTJ.js} +2 -2
  313. package/chunks/{task-create-ODLLJ5EF.js → task-create-67YBESBR.js} +1 -1
  314. package/chunks/{task-update-ZNWF5QPF.js → task-update-DLBXOE5R.js} +1 -1
  315. package/chunks/{team-create-CUJXJ2ZS.js → team-create-ARICYIQB.js} +1 -1
  316. package/chunks/{team-plan-approval-36LS5SZD.js → team-plan-approval-JPRE6Q3R.js} +1 -1
  317. package/chunks/{terminal-image-renderer-FYGH5GYJ.js → terminal-image-renderer-HVIZ2VNE.js} +1 -1
  318. package/chunks/{theme-manager-AMNU6BMN.js → theme-manager-UEPLIBUP.js} +1 -1
  319. package/chunks/{tool-call-E635LKSC.js → tool-call-EFJKXI3Z.js} +1 -1
  320. package/chunks/{tool-result-media-USCQTGHC.js → tool-result-media-LMIYNXSD.js} +1 -1
  321. package/chunks/{tool-search-FNTAT2ZW.js → tool-search-D7HQTRQG.js} +1 -1
  322. package/chunks/{total-session-admission-6P5YNVII.js → total-session-admission-67QMR44O.js} +1 -1
  323. package/chunks/{trustedFolders-7SPIYZSS.js → trustedFolders-HARYVS3F.js} +1 -1
  324. package/chunks/{update-relaunch-ZYID7ZKA.js → update-relaunch-NVNPOK5J.js} +1 -1
  325. package/chunks/{updateCheck-A3JUVWQV.js → updateCheck-7NMXUCTN.js} +1 -1
  326. package/chunks/{upload-config-DT3IQPC7.js → upload-config-W2SICJ32.js} +1 -1
  327. package/chunks/{useAutoAcceptIndicator-OS64SJOW.js → useAutoAcceptIndicator-ELMIP4TJ.js} +1 -1
  328. package/chunks/{validateNonInterActiveAuth-SJLXPGT4.js → validateNonInterActiveAuth-3433WFLE.js} +1 -1
  329. package/chunks/{version-CD2O2AJ7.js → version-XCFKTEY3.js} +1 -1
  330. package/chunks/{web-fetch-CQZMLBDV.js → web-fetch-537RS6IX.js} +1 -1
  331. package/chunks/{web-search-47YZU3PO.js → web-search-O27MYFSW.js} +1 -1
  332. package/chunks/{workflow-ROHRWGL5.js → workflow-6QF4RMYM.js} +1 -1
  333. package/chunks/{workflow-ancestor-trust-YSFNC6J5.js → workflow-ancestor-trust-CABLU3VV.js} +1 -1
  334. package/chunks/{workspace-agents-P4T5564B.js → workspace-agents-5WP3PY7W.js} +1 -1
  335. package/chunks/{workspace-providers-status-GZOJR5XX.js → workspace-providers-status-7G2EJJEO.js} +1 -1
  336. package/chunks/{workspace-recovery-worker-C4KTT7J5.js → workspace-recovery-worker-ICCIDEWU.js} +1 -1
  337. package/chunks/{workspace-registration-store-2WDVL42M.js → workspace-registration-store-WHXMNQQQ.js} +1 -1
  338. package/chunks/{workspace-registry-2V2LYFXO.js → workspace-registry-NXBODLYH.js} +1 -1
  339. package/chunks/{workspace-runtime-coordinator-7OH4M6FV.js → workspace-runtime-coordinator-CJXS273B.js} +1 -1
  340. package/chunks/{workspace-service-353F3S2A.js → workspace-service-HUDE2RXN.js} +1 -1
  341. package/chunks/{workspace-skills-status-A5FRCJJF.js → workspace-skills-status-FJC6U62F.js} +1 -1
  342. package/chunks/{workspace-trust-reconciler-N4AKVBD4.js → workspace-trust-reconciler-ZIQ3A5ZB.js} +1 -1
  343. package/chunks/{write-file-XOIVQYGC.js → write-file-652YGG7I.js} +1 -1
  344. package/chunks/{zoom-image-ACTDUJ4C.js → zoom-image-YEH4O74G.js} +1 -1
  345. package/cli.js +2 -2
  346. package/execution-worker.js +1 -1
  347. package/export-transcript-document.js +1 -1
  348. package/package.json +2 -2
  349. package/web-shell/assets/{PierreFilePreview-DR46bTX6.js → PierreFilePreview-DEhWK46v.js} +1 -1
  350. package/web-shell/assets/{SpreadsheetPreview-zgxr-aKy.js → SpreadsheetPreview-C-GgIuPX.js} +1 -1
  351. package/web-shell/assets/{WorkspaceFileBrowser-BEoibHvP.js → WorkspaceFileBrowser-64vDYikf.js} +1 -1
  352. package/web-shell/assets/{abnfDiagram-VCTEODGH-Cba-rfLM.js → abnfDiagram-VCTEODGH-C2WWURam.js} +1 -1
  353. package/web-shell/assets/{agents-route-DexLhLcH.js → agents-route-j5ba59xn.js} +1 -1
  354. package/web-shell/assets/{arc-BLxikpdy.js → arc-Bkr_-GVn.js} +1 -1
  355. package/web-shell/assets/{architectureDiagram-5GKGNRK7-BMaIAoGQ.js → architectureDiagram-5GKGNRK7-D_v_wDDW.js} +1 -1
  356. package/web-shell/assets/{blockDiagram-NRAW4CY4-CGSbuIDn.js → blockDiagram-NRAW4CY4-Csxc3YNo.js} +1 -1
  357. package/web-shell/assets/{c4Diagram-UCG6FXSJ-DVwZ8MO2.js → c4Diagram-UCG6FXSJ-PXryoJCB.js} +1 -1
  358. package/web-shell/assets/channel-6Pj4KPAs.js +1 -0
  359. package/web-shell/assets/{chunk-2Q5K7J3B-BzKDWtZ3.js → chunk-2Q5K7J3B-DwK5UBHI.js} +1 -1
  360. package/web-shell/assets/{chunk-5VM5RSS4-C8SFBHFV.js → chunk-5VM5RSS4-BC1hvD6_.js} +1 -1
  361. package/web-shell/assets/{chunk-F27PBJKO-D8brpDvU.js → chunk-F27PBJKO-iFe0IxfJ.js} +1 -1
  362. package/web-shell/assets/{chunk-G27WJ6UU-Cilx_eO_.js → chunk-G27WJ6UU-ROSuKRxI.js} +1 -1
  363. package/web-shell/assets/{chunk-JWPE2WC7-CeplW23S.js → chunk-JWPE2WC7-CYHS6PxA.js} +1 -1
  364. package/web-shell/assets/{chunk-LCL6LL3I-BUO5XSSe.js → chunk-LCL6LL3I-D5bFMqCy.js} +1 -1
  365. package/web-shell/assets/{chunk-POPQ4Y6H-DPo869nv.js → chunk-POPQ4Y6H-BJh77MGv.js} +1 -1
  366. package/web-shell/assets/{chunk-SVP7TREG-DhfIj0Jt.js → chunk-SVP7TREG-Cs81aYft.js} +1 -1
  367. package/web-shell/assets/{chunk-XXDRQBXY-B72Tsbdi.js → chunk-XXDRQBXY-DqDbN44E.js} +1 -1
  368. package/web-shell/assets/classDiagram-DTDB5LWJ-BaTUuuB8.js +1 -0
  369. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BaTUuuB8.js +1 -0
  370. package/web-shell/assets/{cose-bilkent-JH36ORCC-8EANR5K4.js → cose-bilkent-JH36ORCC-DhjrwADJ.js} +1 -1
  371. package/web-shell/assets/{cynefin-OW5HDTMX-Cj3uoFr9.js → cynefin-OW5HDTMX-Dh7t-_3M.js} +1 -1
  372. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-CHwRYcv9.js → cynefinDiagram-5FMLGOSQ-5J4kto0C.js} +1 -1
  373. package/web-shell/assets/{dagre-3AP2YEHR-B50MDk4E.js → dagre-3AP2YEHR-28AdbIcl.js} +1 -1
  374. package/web-shell/assets/{diagram-S7CK7UJ4-Fbk8W4Ks.js → diagram-S7CK7UJ4-DmksuoIf.js} +1 -1
  375. package/web-shell/assets/{diagram-UQ7AKVKN-CNeEtpni.js → diagram-UQ7AKVKN-DUjgQ8Fg.js} +1 -1
  376. package/web-shell/assets/{diagram-VSXAHHWV-CYXiWI4p.js → diagram-VSXAHHWV-DUe_FpG-.js} +1 -1
  377. package/web-shell/assets/{diagram-VX7I27RA-CF7R7hGA.js → diagram-VX7I27RA-CJJ70teK.js} +1 -1
  378. package/web-shell/assets/{diagram-Z3DM3KII-DZzHpEub.js → diagram-Z3DM3KII-BgABlJO4.js} +1 -1
  379. package/web-shell/assets/{docx-preview-CjpeB47y.js → docx-preview-BMBWboRx.js} +1 -1
  380. package/web-shell/assets/{ebnfDiagram-PWID7BFC-CtH0z2j9.js → ebnfDiagram-PWID7BFC-B3nK_Lh7.js} +1 -1
  381. package/web-shell/assets/{erDiagram-SSCWMZ5O-D51BQ445.js → erDiagram-SSCWMZ5O-DCTdCWlu.js} +1 -1
  382. package/web-shell/assets/{flowDiagram-A5DVABFB-B1-3lJwP.js → flowDiagram-A5DVABFB-CPxk2UUl.js} +1 -1
  383. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-iMw3jNW5.js → ganttDiagram-EL5Y4UJY-WZzMAKht.js} +1 -1
  384. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D_KI4JVS.js → gitGraphDiagram-WWUBYQGX-DKcO5ugU.js} +1 -1
  385. package/web-shell/assets/{index-D1oIEFvH.js → index-CkRLMu1y.js} +6 -6
  386. package/web-shell/assets/{index-iouf3mnZ.js → index-Dbm3-Fps.js} +1 -1
  387. package/web-shell/assets/{infoDiagram-RXCK75RN-CwG9MQQq.js → infoDiagram-RXCK75RN-CJX5DzdL.js} +1 -1
  388. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-C99w6R-O.js → ishikawaDiagram-5VMMS53U-fF0Id5B6.js} +1 -1
  389. package/web-shell/assets/{journeyDiagram-EYS64GPL--T5XVhJh.js → journeyDiagram-EYS64GPL-BOAezBVe.js} +1 -1
  390. package/web-shell/assets/{kanban-definition-3QL26DDD-Cs-rGYgZ.js → kanban-definition-3QL26DDD-DdNBof9J.js} +1 -1
  391. package/web-shell/assets/{layout-BHU2s0xS.js → layout-CXX3l5w0.js} +1 -1
  392. package/web-shell/assets/{linear-DbLtsa7_.js → linear-Dnaccp-S.js} +1 -1
  393. package/web-shell/assets/{mermaid.core-CTBkTEXb.js → mermaid.core-BzdC3B6T.js} +6 -6
  394. package/web-shell/assets/{mindmap-definition-FBJOCRG2-RWLGqkYd.js → mindmap-definition-FBJOCRG2-D-gMUzLw.js} +1 -1
  395. package/web-shell/assets/{pegDiagram-XKGWAZYB-DIQRWxNr.js → pegDiagram-XKGWAZYB-B9n1WVZq.js} +1 -1
  396. package/web-shell/assets/{pieDiagram-E7YTZNPT-Dg9VHqU0.js → pieDiagram-E7YTZNPT-ok49U0zT.js} +1 -1
  397. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-BFeuB7Iq.js → quadrantDiagram-AXDQQJYC-DJKha-v3.js} +1 -1
  398. package/web-shell/assets/{railroadDiagram-O6MQD6OU-DbO9AYto.js → railroadDiagram-O6MQD6OU-DjL4pl7y.js} +1 -1
  399. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-ClpOYbUE.js → requirementDiagram-EFPCY7ZU-BpmmRw3A.js} +1 -1
  400. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CaHmNc0O.js → sankeyDiagram-P5KCCOFB-KpteHB8X.js} +1 -1
  401. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-4r32bqWv.js → sequenceDiagram-WJ2MYXX4-COMghCpA.js} +1 -1
  402. package/web-shell/assets/{sizeCapture-X5ZJPWSS-CGXqc7rW.js → sizeCapture-X5ZJPWSS-5fEwJD-n.js} +1 -1
  403. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DuAO60my.js → stateDiagram-HBIQ2CUA-CnC7oXvs.js} +1 -1
  404. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-V_cfZFBL.js +1 -0
  405. package/web-shell/assets/{swimlanes-XN3QIQJK-DUQMHZRn.js → swimlanes-XN3QIQJK-bVlhZdve.js} +1 -1
  406. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-25wVg0WL.js +8 -0
  407. package/web-shell/assets/{timeline-definition-24CTP7MA-DNCSPOxv.js → timeline-definition-24CTP7MA-CBvYgMu5.js} +1 -1
  408. package/web-shell/assets/{vennDiagram-4TSXK5OY-Bxh1Z0T6.js → vennDiagram-4TSXK5OY-CUTYvV1j.js} +1 -1
  409. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-D6fuN1bA.js → wardleyDiagram-VM6X3IG4-Djl4gxCB.js} +1 -1
  410. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-DkwTa8kZ.js → xychartDiagram-S5SC5T6Z-BcJZtI2X.js} +1 -1
  411. package/web-shell/index.html +1 -1
  412. package/web-shell/sw.js +1 -1
  413. package/web-shell/assets/channel-CvkbH6SO.js +0 -1
  414. package/web-shell/assets/classDiagram-DTDB5LWJ-DuyseBqE.js +0 -1
  415. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DuyseBqE.js +0 -1
  416. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BjIYif-p.js +0 -1
  417. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DZB3DqrF.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{BACKSLASH_ENTER_DETECTION_WINDOW_MS,CHAR_CODE_ESC,KITTY_CTRL_C,KITTY_KEYCODE_BACKSPACE,KITTY_KEYCODE_ENTER,KITTY_KEYCODE_NUMPAD_ENTER,KITTY_KEYCODE_TAB,KITTY_MODIFIER_BASE,KITTY_MODIFIER_EVENT_TYPES_OFFSET,MAX_KITTY_SEQUENCE_LENGTH,MODIFIER_ALT_BIT,MODIFIER_CTRL_BIT,MODIFIER_SHIFT_BIT,MODIFIER_SUPER_BIT,clipboardHasImage}from"./chunk-P2CUOX2Q.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{use_stdin_default,use_stdout_default}from"./chunk-YIJNS5IJ.js";import{require_react}from"./chunk-5QKDV4CD.js";import{noteInteraction}from"./chunk-UGLQO5K7.js";import{KittySequenceOverflowEvent,logKittySequenceOverflow}from"./chunk-MJEL7DIE.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_react4=__toESM(require_react(),1);init_esbuild_shims();var import_react2=__toESM(require_react(),1);import readline from"node:readline";import{PassThrough}from"node:stream";init_esbuild_shims();var ESC="\x1B";var SGR_EVENT_PREFIX=`${ESC}[<`;var X11_EVENT_PREFIX=`${ESC}[M`;var MAX_SGR_MOUSE_SEQUENCE_LENGTH=50;var SGR_MOUSE_REGEX=/^\x1b\[<(\d+);(\d+);(\d+)([mM])/;function getEventName(buttonCode,isRelease){const isMove=(buttonCode&32)!==0;if(buttonCode===66)return"scroll-left";if(buttonCode===67)return"scroll-right";if((buttonCode&64)===64){return(buttonCode&1)===0?"scroll-up":"scroll-down"}if(isMove)return"move";const button=buttonCode&3;const type=isRelease?"release":"press";switch(button){case 0:return`left-${type}`;case 1:return`middle-${type}`;case 2:return`right-${type}`;default:return null}}__name(getEventName,"getEventName");function buttonFromCode(code){switch(code&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}__name(buttonFromCode,"buttonFromCode");function parseSGRMouseEvent(buffer){const match=buffer.match(SGR_MOUSE_REGEX);if(!match)return null;const buttonCode=parseInt(match[1],10);const col=parseInt(match[2],10);const row=parseInt(match[3],10);const isRelease=match[4]==="m";const name=getEventName(buttonCode,isRelease);if(!name)return null;return{event:{name,col,row,shift:(buttonCode&4)!==0,meta:(buttonCode&8)!==0,ctrl:(buttonCode&16)!==0,button:buttonFromCode(buttonCode)},length:match[0].length}}__name(parseSGRMouseEvent,"parseSGRMouseEvent");var ENABLE_SGR_MOUSE={button:"\x1B[?1002h\x1B[?1006h",any:"\x1B[?1003h\x1B[?1006h"};var DISABLE_SGR_MOUSE={button:"\x1B[?1006l\x1B[?1002l",any:"\x1B[?1006l\x1B[?1003l"};function enableMouseEvents(stdout,tracking="button"){stdout.write(ENABLE_SGR_MOUSE[tracking])}__name(enableMouseEvents,"enableMouseEvents");function disableMouseEvents(stdout,tracking="button"){stdout.write(DISABLE_SGR_MOUSE[tracking])}__name(disableMouseEvents,"disableMouseEvents");init_esbuild_shims();var import_react=__toESM(require_react(),1);var ENABLE_FOCUS_REPORTING="\x1B[?1004h";var DISABLE_FOCUS_REPORTING="\x1B[?1004l";var FOCUS_IN="\x1B[I";var FOCUS_OUT="\x1B[O";var useFocus=__name(()=>{const{stdin}=use_stdin_default();const{stdout}=use_stdout_default();const[isFocused,setIsFocused]=(0,import_react.useState)(true);(0,import_react.useEffect)(()=>{const handleData=__name(data=>{const sequence=data.toString();const lastFocusIn=sequence.lastIndexOf(FOCUS_IN);const lastFocusOut=sequence.lastIndexOf(FOCUS_OUT);if(lastFocusIn>lastFocusOut){setIsFocused(true)}else if(lastFocusOut>lastFocusIn){setIsFocused(false)}},"handleData");stdout?.write(ENABLE_FOCUS_REPORTING);stdin?.on("data",handleData);return()=>{stdout?.write(DISABLE_FOCUS_REPORTING);stdin?.removeListener("data",handleData)}},[stdin,stdout]);useKeypress(_=>{if(!isFocused){setIsFocused(true)}},{isActive:true});return isFocused},"useFocus");var import_jsx_runtime=__toESM(require_jsx_runtime(),1);var ESC2="\x1B";var OPTION_COMPOSED_GLYPHS={"\u2020":"t","\u221A":"v"};var PASTE_MODE_PREFIX=`${ESC2}[200~`;var PASTE_MODE_SUFFIX=`${ESC2}[201~`;var KITTY_SEQUENCE_TIMEOUT_MS=200;var PASTE_IDLE_TIMEOUT_MS=1e3;var KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR={57399:"0",57400:"1",57401:"2",57402:"3",57403:"4",57404:"5",57405:"6",57406:"7",57407:"8",57408:"9",57409:".",57410:"/",57411:"*",57412:"-",57413:"+",57415:"=",57416:","};var KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME={57417:"left",57418:"right",57419:"up",57420:"down",57421:"pageup",57422:"pagedown",57423:"home",57424:"end",57425:"insert",57426:"delete"};var KeypressContext=(0,import_react2.createContext)(void 0);var debugLogger=createDebugLogger("KEYPRESS");function useKeypressContext(){const context=(0,import_react2.useContext)(KeypressContext);if(!context){throw new Error("useKeypressContext must be used within a KeypressProvider")}return context}__name(useKeypressContext,"useKeypressContext");function KeypressProvider({children,kittyProtocolEnabled,pasteWorkaround=false,config,debugKeystrokeLogging,initialCapturedInput}){const{stdin,setRawMode}=use_stdin_default();const subscribers=(0,import_react2.useRef)(new Set).current;const mouseSubscribers=(0,import_react2.useRef)(new Set).current;const[pasteProgress,setPasteProgress]=(0,import_react2.useState)({active:false,receivedBytes:0});const subscribe=(0,import_react2.useCallback)(handler=>{subscribers.add(handler)},[subscribers]);const unsubscribe=(0,import_react2.useCallback)(handler=>{subscribers.delete(handler)},[subscribers]);const subscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.add(handler)},[mouseSubscribers]);const unsubscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.delete(handler)},[mouseSubscribers]);(0,import_react2.useEffect)(()=>{setRawMode(true);const capturedInput=initialCapturedInput??Buffer.alloc(0);const keypressStream=new PassThrough;let usePassthrough=false;if(pasteWorkaround){usePassthrough=true}let isPaste=false;let pasteChunks=[];let pasteAlreadyFlushed=false;let pasteIdleTimeout=null;let lastPasteChunkAt=0;const kittySequenceBufferRef={current:""};let kittySequenceTimeout=null;let backslashTimeout=null;let waitingForEnterAfterBackslash=false;let rawDataBuffer=Buffer.alloc(0);let rawFlushTimeout=null;let swallowingSgrMouse=false;let sgrMouseBuffer="";let sgrMouseTimeout=null;const resetSgrMouse=__name(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}},"resetSgrMouse");const updateKittyBuffer=__name(value=>{kittySequenceBufferRef.current=value},"updateKittyBuffer");const clearKittyTimeout=__name(()=>{if(kittySequenceTimeout){clearTimeout(kittySequenceTimeout);kittySequenceTimeout=null}},"clearKittyTimeout");const startKittyTimeout=__name(()=>{clearKittyTimeout();kittySequenceTimeout=setTimeout(()=>{if(kittySequenceBufferRef.current){while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(parsed.length);broadcast(parsed.key);continue}const plain=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plain){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(plain.length);broadcast(plain.key);continue}break}if(kittySequenceBufferRef.current){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer timeout, clearing:",kittySequenceBufferRef.current)}kittySequenceBufferRef.current=""}}},KITTY_SEQUENCE_TIMEOUT_MS)},"startKittyTimeout");const clearKittyBufferAndTimeout=__name(()=>{clearKittyTimeout();kittySequenceBufferRef.current=""},"clearKittyBufferAndTimeout");const clearPasteIdleTimeout=__name(()=>{if(pasteIdleTimeout){clearTimeout(pasteIdleTimeout);pasteIdleTimeout=null}},"clearPasteIdleTimeout");const forceFlushStuckPaste=__name(()=>{clearPasteIdleTimeout();if(!isPaste&&pasteChunks.length===0)return;const buffered=pasteChunks.join("");isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}},"forceFlushStuckPaste");const onPasteIdleTimeout=__name(()=>{const idleFor=Date.now()-lastPasteChunkAt;if(idleFor>=PASTE_IDLE_TIMEOUT_MS){forceFlushStuckPaste()}else{pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS-idleFor)}},"onPasteIdleTimeout");const startPasteIdleTimeout=__name(()=>{lastPasteChunkAt=Date.now();if(pasteIdleTimeout)return;pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS)},"startPasteIdleTimeout");const createPrintableKey=__name(char=>{const printableName=char===" "?"space":/^[A-Za-z]$/.test(char)?char.toLowerCase():char;return{name:printableName,ctrl:false,meta:false,shift:false,paste:false,sequence:char,kittyProtocol:true}},"createPrintableKey");const parseKittyPrefix=__name(buffer=>{const revTabLegacy=new RegExp(`^${ESC2}\\[Z`);let m=buffer.match(revTabLegacy);if(m){return{key:{name:"tab",ctrl:false,meta:false,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const revTabParam=new RegExp(`^${ESC2}\\[1;(\\d+)Z`);m=buffer.match(revTabParam);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;return{key:{name:"tab",ctrl,meta:alt,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const arrowPrefix=new RegExp(`^${ESC2}\\[1;(\\d+)([ABCDHFPQSR])`);m=buffer.match(arrowPrefix);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const shift=(bits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const sym=m[2];const symbolToName={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"};const name=symbolToName[sym]||"";if(!name)return null;return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const csiUPrefix=new RegExp(`^${ESC2}\\[(\\d+)(?::\\d+)*(?:;(\\d+)(?::\\d+)*)?(?:;(\\d+))?([u~])`);m=buffer.match(csiUPrefix);if(m){let keyCode=parseInt(m[1],10);let modifiers=m[2]?parseInt(m[2],10):KITTY_MODIFIER_BASE;if(modifiers>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){modifiers-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const modifierBits=modifiers-KITTY_MODIFIER_BASE;const shift=(modifierBits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(modifierBits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(modifierBits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(modifierBits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const terminator=m[4];if(keyCode===CHAR_CODE_ESC&&terminator==="~"&&m[3]){keyCode=parseInt(m[3],10)}if(terminator==="~"){let name2=null;switch(keyCode){case 1:name2="home";break;case 2:name2="insert";break;case 3:name2="delete";break;case 4:name2="end";break;case 5:name2="pageup";break;case 6:name2="pagedown";break;default:break}if(name2){return{key:{name:name2,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const kittyKeyCodeToName={[CHAR_CODE_ESC]:"escape",[KITTY_KEYCODE_TAB]:"tab",[KITTY_KEYCODE_BACKSPACE]:"backspace",[KITTY_KEYCODE_ENTER]:"return",[KITTY_KEYCODE_NUMPAD_ENTER]:"return"};const name=kittyKeyCodeToName[keyCode];if(name){return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(!ctrl){const keypadChar=KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR[keyCode];if(keypadChar){return{key:{name:keypadChar,ctrl:false,meta:alt,shift,paste:false,sequence:keypadChar,kittyProtocol:true},length:m[0].length}}}const keypadName=KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME[keyCode];if(keypadName){return{key:{name:keypadName,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(terminator==="u"&&!ctrl&&keyCode>=32&&keyCode!==127&&keyCode<=1114111&&!(keyCode>=57344&&keyCode<=63743)){return{key:{...createPrintableKey(String.fromCodePoint(keyCode)),meta:alt,shift},length:m[0].length}}if(ctrl&&keyCode>="a".charCodeAt(0)&&keyCode<="z".charCodeAt(0)){const letter=String.fromCharCode(keyCode);return{key:{name:letter,ctrl:true,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const legacyFuncKey=new RegExp(`^${ESC2}\\[([ABCDHF])`);m=buffer.match(legacyFuncKey);if(m){const sym=m[1];const nameMap={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end"};const name=nameMap[sym];return{key:{name,ctrl:false,meta:false,shift:false,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}return null},"parseKittyPrefix");const getCompleteCsiSequenceLength=__name(buffer=>{if(!buffer.startsWith(`${ESC2}[`)){return null}for(let i=2;i<buffer.length;i++){const code=buffer.charCodeAt(i);if(code>=64&&code<=126){return i+1}if(code<32||code>63){return 0}}return null},"getCompleteCsiSequenceLength");const parsePlainTextPrefix=__name(buffer=>{if(!buffer||buffer.startsWith(ESC2)){return null}const[char]=Array.from(buffer);if(!char){return null}return{key:createPrintableKey(char),length:char.length}},"parsePlainTextPrefix");const broadcast=__name(key=>{noteInteraction();for(const handler of subscribers){handler(key)}},"broadcast");const TERMINAL_RESPONSE_RE=/^\x1b\[[?>][\d;]*[uc]$/;const handleKeypress=__name(async(_,key)=>{if(TERMINAL_RESPONSE_RE.test(key.sequence)){return}if(key.sequence===FOCUS_IN||key.sequence===FOCUS_OUT){return}if(isPaste){resetSgrMouse()}else if(swallowingSgrMouse){if(key.ctrl&&key.name==="c"){resetSgrMouse()}else if(key.name==="paste-start"){resetSgrMouse()}else{sgrMouseBuffer+=key.sequence;if(key.name==="m"||key.sequence==="M"){swallowingSgrMouse=false;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}const parsed=parseSGRMouseEvent(sgrMouseBuffer);if(parsed){for(const handler of mouseSubscribers){handler(parsed.event)}}sgrMouseBuffer=""}else if(sgrMouseBuffer.length>=MAX_SGR_MOUSE_SEQUENCE_LENGTH){resetSgrMouse()}return}}if(!isPaste&&key.sequence===`${ESC2}[<`){swallowingSgrMouse=true;sgrMouseBuffer=`${ESC2}[<`;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout)}sgrMouseTimeout=setTimeout(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";sgrMouseTimeout=null},KITTY_SEQUENCE_TIMEOUT_MS);return}const isCtrlCKey=key.ctrl&&key.name==="c"||key.sequence===`${ESC2}${KITTY_CTRL_C}`;if(isCtrlCKey){if(isPaste||pasteChunks.length>0){isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;clearPasteIdleTimeout()}if(kittySequenceBufferRef.current&&debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer cleared on Ctrl+C:",kittySequenceBufferRef.current)}clearKittyBufferAndTimeout();if(key.sequence===`${ESC2}${KITTY_CTRL_C}`){broadcast({name:"c",ctrl:true,meta:false,shift:false,paste:false,sequence:key.sequence,kittyProtocol:true})}else{broadcast(key)}return}if(key.name==="paste-start"){isPaste=true;pasteAlreadyFlushed=false;startPasteIdleTimeout();return}if(key.name==="paste-end"){clearPasteIdleTimeout();if(pasteAlreadyFlushed){pasteAlreadyFlushed=false;isPaste=false;pasteChunks=[];return}isPaste=false;const buffered=pasteChunks.join("");pasteChunks=[];if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}else{let clipboardImageUnavailable=false;const hasImage=await clipboardHasImage(()=>{clipboardImageUnavailable=true});broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:buffered})}return}if(isPaste){pasteChunks.push(key.sequence);startPasteIdleTimeout();return}if(key.name==="return"&&waitingForEnterAfterBackslash){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({...key,shift:true,sequence:"\r"});return}if(key.sequence==="\\"&&!key.name){waitingForEnterAfterBackslash=true;backslashTimeout=setTimeout(()=>{waitingForEnterAfterBackslash=false;backslashTimeout=null;broadcast(key)},BACKSLASH_ENTER_DETECTION_WINDOW_MS);return}if(waitingForEnterAfterBackslash&&key.name!=="return"){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({name:"",sequence:"\\",ctrl:false,meta:false,shift:false,paste:false})}if(["up","down","left","right"].includes(key.name)){broadcast(key);return}const isModifyOtherKeysSequence=key.sequence?.startsWith(`${ESC2}[27`)??false;if(kittyProtocolEnabled||kittySequenceBufferRef.current||isModifyOtherKeysSequence){if(kittySequenceBufferRef.current||key.sequence.startsWith(`${ESC2}[`)&&!key.sequence.startsWith(PASTE_MODE_PREFIX)&&!key.sequence.startsWith(PASTE_MODE_SUFFIX)&&!key.sequence.startsWith(FOCUS_IN)&&!key.sequence.startsWith(FOCUS_OUT)){updateKittyBuffer(kittySequenceBufferRef.current+key.sequence);startKittyTimeout();if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer accumulating:",kittySequenceBufferRef.current)}let bufferedInputHandled=false;while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){if(debugKeystrokeLogging){const parsedSequence=kittySequenceBufferRef.current.slice(0,parsed.length);if(kittySequenceBufferRef.current.length>parsed.length){debugLogger.debug("[DEBUG] Kitty sequence parsed successfully (prefix):",parsedSequence)}else{debugLogger.debug("[DEBUG] Kitty sequence parsed successfully:",parsedSequence)}}updateKittyBuffer(kittySequenceBufferRef.current.slice(parsed.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(parsed.key);bufferedInputHandled=true;continue}const completeUnsupportedCsiLength=getCompleteCsiSequenceLength(kittySequenceBufferRef.current);if(completeUnsupportedCsiLength){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Dropping unsupported complete CSI sequence:",kittySequenceBufferRef.current.slice(0,completeUnsupportedCsiLength))}updateKittyBuffer(kittySequenceBufferRef.current.slice(completeUnsupportedCsiLength));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}const plainTextPrefix=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plainTextPrefix){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Recovered plain text after kitty sequence:",plainTextPrefix.key.sequence)}updateKittyBuffer(kittySequenceBufferRef.current.slice(plainTextPrefix.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(plainTextPrefix.key);bufferedInputHandled=true;continue}const nextStart=kittySequenceBufferRef.current.indexOf(`${ESC2}[`,1);if(nextStart>0){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Skipping incomplete/invalid CSI prefix:",kittySequenceBufferRef.current.slice(0,nextStart))}updateKittyBuffer(kittySequenceBufferRef.current.slice(nextStart));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}break}if(bufferedInputHandled)return;if(config?.getDebugMode()||debugKeystrokeLogging){const codes=Array.from(kittySequenceBufferRef.current).map(ch=>ch.charCodeAt(0));debugLogger.warn("Kitty sequence buffer has char codes:",codes)}if(kittySequenceBufferRef.current.length>MAX_KITTY_SEQUENCE_LENGTH){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer overflow, clearing:",kittySequenceBufferRef.current)}if(config){const event=new KittySequenceOverflowEvent(kittySequenceBufferRef.current.length,kittySequenceBufferRef.current);logKittySequenceOverflow(config,event)}clearKittyBufferAndTimeout()}else{return}}}if(key.name==="return"&&key.sequence===`${ESC2}\r`){key.meta=true}const composedKeyName=Object.hasOwn(OPTION_COMPOSED_GLYPHS,key.sequence)?OPTION_COMPOSED_GLYPHS[key.sequence]:void 0;if(process.platform==="darwin"&&!isPaste&&composedKeyName){key.name=composedKeyName;key.meta=true}broadcast({...key,paste:isPaste})},"handleKeypress");const clearRawFlushTimeout=__name(()=>{if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}},"clearRawFlushTimeout");const createPasteKeyEvent=__name((name="",sequence="")=>({name,ctrl:false,meta:false,shift:false,paste:false,sequence}),"createPasteKeyEvent");const shouldFlushRawDataAsPaste=__name(data=>{if(data.includes(27))return false;const hasReturn=data.includes(13);const hasEmbeddedTab=data.length>1&&data.includes(9);const isSingleReturn=data.length<=2&&hasReturn;return!isSingleReturn&&(hasReturn||hasEmbeddedTab)},"shouldFlushRawDataAsPaste");const flushRawBuffer=__name(()=>{if(!rawDataBuffer.length){return}const pasteModePrefixBuffer=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuffer=Buffer.from(PASTE_MODE_SUFFIX);const data=rawDataBuffer;let cursor=0;while(cursor<data.length){const prefixPos=data.indexOf(pasteModePrefixBuffer,cursor);const suffixPos=data.indexOf(pasteModeSuffixBuffer,cursor);const hasPrefix=prefixPos!==-1&&prefixPos+pasteModePrefixBuffer.length<=data.length;const hasSuffix=suffixPos!==-1&&suffixPos+pasteModeSuffixBuffer.length<=data.length;let markerPos=-1;let markerLength=0;let markerType=null;if(hasPrefix&&(!hasSuffix||prefixPos<suffixPos)){markerPos=prefixPos;markerLength=pasteModePrefixBuffer.length;markerType="prefix"}else if(hasSuffix){markerPos=suffixPos;markerLength=pasteModeSuffixBuffer.length;markerType="suffix"}if(markerPos===-1){break}const nextData=data.slice(cursor,markerPos);if(nextData.length>0){keypressStream.write(nextData)}if(markerType==="prefix"){handleKeypress(void 0,createPasteKeyEvent("paste-start"))}else if(markerType==="suffix"){handleKeypress(void 0,createPasteKeyEvent("paste-end"))}cursor=markerPos+markerLength}rawDataBuffer=data.slice(cursor);if(rawDataBuffer.length===0){return}if(isPaste||!shouldFlushRawDataAsPaste(rawDataBuffer)){keypressStream.write(rawDataBuffer)}else{handleKeypress(void 0,createPasteKeyEvent("paste-start"));keypressStream.write(rawDataBuffer);handleKeypress(void 0,createPasteKeyEvent("paste-end"))}rawDataBuffer=Buffer.alloc(0);clearRawFlushTimeout()},"flushRawBuffer");const handleRawKeypress=__name(_data=>{const data=Buffer.isBuffer(_data)?_data:Buffer.from(_data,"utf8");rawDataBuffer=Buffer.concat([rawDataBuffer,data]);clearRawFlushTimeout();const isReturnChar=rawDataBuffer.length<=2&&rawDataBuffer.includes(13);if(isReturnChar){rawFlushTimeout=setTimeout(flushRawBuffer,100)}else{flushRawBuffer()}},"handleRawKeypress");const pasteModePrefixBuf=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuf=Buffer.from(PASTE_MODE_SUFFIX);function partialMarkerTailLength(chunk,marker,minLen=2){const maxCheck=Math.min(chunk.length,marker.length-1);for(let len=maxCheck;len>=minLen;len--){const tail=chunk.subarray(chunk.length-len);if(marker.subarray(0,len).equals(tail)){return len}}return 0}__name(partialMarkerTailLength,"partialMarkerTailLength");let rawStdinTail=Buffer.alloc(0);let rawPasteAccumulating=false;let rawPasteChunks=[];let rawPasteReceivedBytes=0;let rawPasteIdleTimeout=null;const clearRawPasteIdleTimeout=__name(()=>{if(rawPasteIdleTimeout){clearTimeout(rawPasteIdleTimeout);rawPasteIdleTimeout=null}},"clearRawPasteIdleTimeout");const forceFlushRawPaste=__name(()=>{clearRawPasteIdleTimeout();if(!rawPasteAccumulating&&rawPasteChunks.length===0&&rawStdinTail.length===0)return;if(rawStdinTail.length>0){rawPasteChunks.push(rawStdinTail);rawStdinTail=Buffer.alloc(0)}const content=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(content)},"forceFlushRawPaste");const startRawPasteIdleTimeout=__name(()=>{clearRawPasteIdleTimeout();rawPasteIdleTimeout=setTimeout(forceFlushRawPaste,PASTE_IDLE_TIMEOUT_MS)},"startRawPasteIdleTimeout");const broadcastPasteFromRaw=__name(content=>{pasteAlreadyFlushed=true;setPasteProgress({active:false,receivedBytes:0});const text=content.toString("utf-8");if(text.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:text})}else{let clipboardImageUnavailable=false;void clipboardHasImage(()=>{clipboardImageUnavailable=true}).then(hasImage=>{broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:""})})}},"broadcastPasteFromRaw");const handleStdinData=__name(data=>{const raw=Buffer.isBuffer(data)?data:Buffer.from(data,"utf8");const buf=rawStdinTail.length>0?Buffer.concat([rawStdinTail,raw]):raw;rawStdinTail=Buffer.alloc(0);let cursor=0;while(cursor<buf.length){if(rawPasteAccumulating){const suffixIdx=buf.indexOf(pasteModeSuffixBuf,cursor);if(suffixIdx===-1){const remaining=buf.subarray(cursor);const tailLen=partialMarkerTailLength(remaining,pasteModeSuffixBuf,1);const contentEnd=remaining.length-tailLen;if(contentEnd>0){const chunk=remaining.subarray(0,contentEnd);rawPasteChunks.push(chunk);rawPasteReceivedBytes+=chunk.length;setPasteProgress(prev=>({...prev,receivedBytes:rawPasteReceivedBytes}))}if(tailLen>0){rawStdinTail=Buffer.from(remaining.subarray(contentEnd))}startRawPasteIdleTimeout();cursor=buf.length}else{clearRawPasteIdleTimeout();if(suffixIdx>cursor){rawPasteChunks.push(buf.subarray(cursor,suffixIdx))}const pasteContent=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(pasteContent);cursor=suffixIdx+pasteModeSuffixBuf.length}}else{const prefixIdx=buf.indexOf(pasteModePrefixBuf,cursor);if(prefixIdx===-1){const remaining=buf.subarray(cursor);if(remaining.length>0){const tailLen=partialMarkerTailLength(remaining,pasteModePrefixBuf);if(tailLen>0){const safe=remaining.subarray(0,remaining.length-tailLen);if(safe.length>0)keypressStream.write(safe);rawStdinTail=Buffer.from(remaining.subarray(remaining.length-tailLen))}else{keypressStream.write(remaining)}}cursor=buf.length}else{if(prefixIdx>cursor){keypressStream.write(buf.subarray(cursor,prefixIdx))}rawPasteAccumulating=true;rawPasteChunks=[];rawPasteReceivedBytes=0;startRawPasteIdleTimeout();setPasteProgress({active:true,receivedBytes:0});cursor=prefixIdx+pasteModePrefixBuf.length}}}},"handleStdinData");let rl;if(usePassthrough){rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("data",handleRawKeypress)}else{rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("keypress",handleKeypress);stdin.on("data",handleStdinData)}let replayPending=false;if(capturedInput.length>0){debugLogger.debug(`Replaying ${capturedInput.length} bytes of captured input`);replayPending=true;setImmediate(()=>{if(!replayPending)return;try{stdin.emit("data",capturedInput)}catch(err){debugLogger.error("Failed to replay captured input:",err)}})}return()=>{replayPending=false;if(usePassthrough){keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleRawKeypress)}else{keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleStdinData)}rl.close();setRawMode(false);if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}clearKittyBufferAndTimeout();clearPasteIdleTimeout();clearRawPasteIdleTimeout();resetSgrMouse();if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}if(rawPasteAccumulating||rawPasteChunks.length>0){forceFlushRawPaste()}else if(isPaste){const buffered=pasteChunks.join("");if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}pasteChunks=[]}}},[stdin,setRawMode,kittyProtocolEnabled,debugKeystrokeLogging,pasteWorkaround,config,subscribers,mouseSubscribers,initialCapturedInput]);return(0,import_jsx_runtime.jsx)(KeypressContext.Provider,{value:{subscribe,unsubscribe,subscribeMouse,unsubscribeMouse,pasteWorkaround,pasteProgress},children})}__name(KeypressProvider,"KeypressProvider");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var import_jsx_runtime2=__toESM(require_jsx_runtime(),1);var ContextMenuContext=(0,import_react3.createContext)({menu:null,isMenuOpen:__name(()=>false,"isMenuOpen"),selectedIndex:0,openMenu:__name(()=>{},"openMenu"),closeMenu:__name(()=>{},"closeMenu"),setSelectedIndex:__name(()=>{},"setSelectedIndex"),executeIndex:__name(()=>{},"executeIndex")});var ContextMenuProvider=__name(({children,onMenuChange})=>{const[menu,setMenu]=(0,import_react3.useState)(null);const[selectedIndex,setSelectedIndexState]=(0,import_react3.useState)(0);const menuRef=(0,import_react3.useRef)(null);menuRef.current=menu;const isMenuOpen=(0,import_react3.useCallback)(()=>menuRef.current!==null,[]);const openMenu=(0,import_react3.useCallback)((items,position)=>{if(items.length===0)return;menuRef.current={items,position};onMenuChange?.(true);setMenu(menuRef.current);setSelectedIndexState(0)},[onMenuChange]);const closeMenu=(0,import_react3.useCallback)(()=>{menuRef.current=null;setMenu(null)},[]);(0,import_react3.useEffect)(()=>{onMenuChange?.(menu!==null)},[menu,onMenuChange]);const setSelectedIndex=(0,import_react3.useCallback)(index=>{setSelectedIndexState(index)},[]);const executeIndex=(0,import_react3.useCallback)(index=>{const current=menuRef.current;menuRef.current=null;setMenu(null);current?.items[index]?.onSelect()},[]);const value=(0,import_react3.useMemo)(()=>({menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex}),[menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex]);return(0,import_jsx_runtime2.jsx)(ContextMenuContext.Provider,{value,children})},"ContextMenuProvider");function useContextMenu(){return(0,import_react3.useContext)(ContextMenuContext)}__name(useContextMenu,"useContextMenu");function contextMenuSize(items){const longest=items.reduce((max,item)=>Math.max(max,item.label.length),0);return{width:longest+4,height:items.length+2}}__name(contextMenuSize,"contextMenuSize");function clampMenuPosition(desired,size,terminalColumns,terminalRows){return{x:Math.max(0,Math.min(desired.x,terminalColumns-size.width)),y:Math.max(0,Math.min(desired.y,terminalRows-size.height))}}__name(clampMenuPosition,"clampMenuPosition");function useKeypress(onKeypress,{isActive}){const{subscribe,unsubscribe}=useKeypressContext();const{menu,isMenuOpen}=useContextMenu();const onKeypressRef=(0,import_react4.useRef)(onKeypress);onKeypressRef.current=key=>{if(menu===null&&isMenuOpen())return;onKeypress(key)};const handleKeypress=(0,import_react4.useCallback)(key=>{onKeypressRef.current(key)},[]);(0,import_react4.useEffect)(()=>{if(!isActive){return}subscribe(handleKeypress);return()=>{unsubscribe(handleKeypress)}},[isActive,handleKeypress,subscribe,unsubscribe])}__name(useKeypress,"useKeypress");export{enableMouseEvents,disableMouseEvents,ContextMenuProvider,useContextMenu,contextMenuSize,clampMenuPosition,useKeypress,useFocus,useKeypressContext,KeypressProvider};
3
+ import{BACKSLASH_ENTER_DETECTION_WINDOW_MS,CHAR_CODE_ESC,KITTY_CTRL_C,KITTY_KEYCODE_BACKSPACE,KITTY_KEYCODE_ENTER,KITTY_KEYCODE_NUMPAD_ENTER,KITTY_KEYCODE_TAB,KITTY_MODIFIER_BASE,KITTY_MODIFIER_EVENT_TYPES_OFFSET,MAX_KITTY_SEQUENCE_LENGTH,MODIFIER_ALT_BIT,MODIFIER_CTRL_BIT,MODIFIER_SHIFT_BIT,MODIFIER_SUPER_BIT,clipboardHasImage}from"./chunk-K7VOBDFT.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{use_stdin_default,use_stdout_default}from"./chunk-YIJNS5IJ.js";import{require_react}from"./chunk-5QKDV4CD.js";import{noteInteraction}from"./chunk-UGLQO5K7.js";import{KittySequenceOverflowEvent,logKittySequenceOverflow}from"./chunk-MJEL7DIE.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_react4=__toESM(require_react(),1);init_esbuild_shims();var import_react2=__toESM(require_react(),1);import readline from"node:readline";import{PassThrough}from"node:stream";init_esbuild_shims();var ESC="\x1B";var SGR_EVENT_PREFIX=`${ESC}[<`;var X11_EVENT_PREFIX=`${ESC}[M`;var MAX_SGR_MOUSE_SEQUENCE_LENGTH=50;var SGR_MOUSE_REGEX=/^\x1b\[<(\d+);(\d+);(\d+)([mM])/;function getEventName(buttonCode,isRelease){const isMove=(buttonCode&32)!==0;if(buttonCode===66)return"scroll-left";if(buttonCode===67)return"scroll-right";if((buttonCode&64)===64){return(buttonCode&1)===0?"scroll-up":"scroll-down"}if(isMove)return"move";const button=buttonCode&3;const type=isRelease?"release":"press";switch(button){case 0:return`left-${type}`;case 1:return`middle-${type}`;case 2:return`right-${type}`;default:return null}}__name(getEventName,"getEventName");function buttonFromCode(code){switch(code&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}__name(buttonFromCode,"buttonFromCode");function parseSGRMouseEvent(buffer){const match=buffer.match(SGR_MOUSE_REGEX);if(!match)return null;const buttonCode=parseInt(match[1],10);const col=parseInt(match[2],10);const row=parseInt(match[3],10);const isRelease=match[4]==="m";const name=getEventName(buttonCode,isRelease);if(!name)return null;return{event:{name,col,row,shift:(buttonCode&4)!==0,meta:(buttonCode&8)!==0,ctrl:(buttonCode&16)!==0,button:buttonFromCode(buttonCode)},length:match[0].length}}__name(parseSGRMouseEvent,"parseSGRMouseEvent");var ENABLE_SGR_MOUSE={button:"\x1B[?1002h\x1B[?1006h",any:"\x1B[?1003h\x1B[?1006h"};var DISABLE_SGR_MOUSE={button:"\x1B[?1006l\x1B[?1002l",any:"\x1B[?1006l\x1B[?1003l"};function enableMouseEvents(stdout,tracking="button"){stdout.write(ENABLE_SGR_MOUSE[tracking])}__name(enableMouseEvents,"enableMouseEvents");function disableMouseEvents(stdout,tracking="button"){stdout.write(DISABLE_SGR_MOUSE[tracking])}__name(disableMouseEvents,"disableMouseEvents");init_esbuild_shims();var import_react=__toESM(require_react(),1);var ENABLE_FOCUS_REPORTING="\x1B[?1004h";var DISABLE_FOCUS_REPORTING="\x1B[?1004l";var FOCUS_IN="\x1B[I";var FOCUS_OUT="\x1B[O";var useFocus=__name(()=>{const{stdin}=use_stdin_default();const{stdout}=use_stdout_default();const[isFocused,setIsFocused]=(0,import_react.useState)(true);(0,import_react.useEffect)(()=>{const handleData=__name(data=>{const sequence=data.toString();const lastFocusIn=sequence.lastIndexOf(FOCUS_IN);const lastFocusOut=sequence.lastIndexOf(FOCUS_OUT);if(lastFocusIn>lastFocusOut){setIsFocused(true)}else if(lastFocusOut>lastFocusIn){setIsFocused(false)}},"handleData");stdout?.write(ENABLE_FOCUS_REPORTING);stdin?.on("data",handleData);return()=>{stdout?.write(DISABLE_FOCUS_REPORTING);stdin?.removeListener("data",handleData)}},[stdin,stdout]);useKeypress(_=>{if(!isFocused){setIsFocused(true)}},{isActive:true});return isFocused},"useFocus");var import_jsx_runtime=__toESM(require_jsx_runtime(),1);var ESC2="\x1B";var OPTION_COMPOSED_GLYPHS={"\u2020":"t","\u221A":"v"};var PASTE_MODE_PREFIX=`${ESC2}[200~`;var PASTE_MODE_SUFFIX=`${ESC2}[201~`;var KITTY_SEQUENCE_TIMEOUT_MS=200;var PASTE_IDLE_TIMEOUT_MS=1e3;var KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR={57399:"0",57400:"1",57401:"2",57402:"3",57403:"4",57404:"5",57405:"6",57406:"7",57407:"8",57408:"9",57409:".",57410:"/",57411:"*",57412:"-",57413:"+",57415:"=",57416:","};var KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME={57417:"left",57418:"right",57419:"up",57420:"down",57421:"pageup",57422:"pagedown",57423:"home",57424:"end",57425:"insert",57426:"delete"};var KeypressContext=(0,import_react2.createContext)(void 0);var debugLogger=createDebugLogger("KEYPRESS");function useKeypressContext(){const context=(0,import_react2.useContext)(KeypressContext);if(!context){throw new Error("useKeypressContext must be used within a KeypressProvider")}return context}__name(useKeypressContext,"useKeypressContext");function KeypressProvider({children,kittyProtocolEnabled,pasteWorkaround=false,config,debugKeystrokeLogging,initialCapturedInput}){const{stdin,setRawMode}=use_stdin_default();const subscribers=(0,import_react2.useRef)(new Set).current;const mouseSubscribers=(0,import_react2.useRef)(new Set).current;const[pasteProgress,setPasteProgress]=(0,import_react2.useState)({active:false,receivedBytes:0});const subscribe=(0,import_react2.useCallback)(handler=>{subscribers.add(handler)},[subscribers]);const unsubscribe=(0,import_react2.useCallback)(handler=>{subscribers.delete(handler)},[subscribers]);const subscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.add(handler)},[mouseSubscribers]);const unsubscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.delete(handler)},[mouseSubscribers]);(0,import_react2.useEffect)(()=>{setRawMode(true);const capturedInput=initialCapturedInput??Buffer.alloc(0);const keypressStream=new PassThrough;let usePassthrough=false;if(pasteWorkaround){usePassthrough=true}let isPaste=false;let pasteChunks=[];let pasteAlreadyFlushed=false;let pasteIdleTimeout=null;let lastPasteChunkAt=0;const kittySequenceBufferRef={current:""};let kittySequenceTimeout=null;let backslashTimeout=null;let waitingForEnterAfterBackslash=false;let rawDataBuffer=Buffer.alloc(0);let rawFlushTimeout=null;let swallowingSgrMouse=false;let sgrMouseBuffer="";let sgrMouseTimeout=null;const resetSgrMouse=__name(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}},"resetSgrMouse");const updateKittyBuffer=__name(value=>{kittySequenceBufferRef.current=value},"updateKittyBuffer");const clearKittyTimeout=__name(()=>{if(kittySequenceTimeout){clearTimeout(kittySequenceTimeout);kittySequenceTimeout=null}},"clearKittyTimeout");const startKittyTimeout=__name(()=>{clearKittyTimeout();kittySequenceTimeout=setTimeout(()=>{if(kittySequenceBufferRef.current){while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(parsed.length);broadcast(parsed.key);continue}const plain=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plain){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(plain.length);broadcast(plain.key);continue}break}if(kittySequenceBufferRef.current){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer timeout, clearing:",kittySequenceBufferRef.current)}kittySequenceBufferRef.current=""}}},KITTY_SEQUENCE_TIMEOUT_MS)},"startKittyTimeout");const clearKittyBufferAndTimeout=__name(()=>{clearKittyTimeout();kittySequenceBufferRef.current=""},"clearKittyBufferAndTimeout");const clearPasteIdleTimeout=__name(()=>{if(pasteIdleTimeout){clearTimeout(pasteIdleTimeout);pasteIdleTimeout=null}},"clearPasteIdleTimeout");const forceFlushStuckPaste=__name(()=>{clearPasteIdleTimeout();if(!isPaste&&pasteChunks.length===0)return;const buffered=pasteChunks.join("");isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}},"forceFlushStuckPaste");const onPasteIdleTimeout=__name(()=>{const idleFor=Date.now()-lastPasteChunkAt;if(idleFor>=PASTE_IDLE_TIMEOUT_MS){forceFlushStuckPaste()}else{pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS-idleFor)}},"onPasteIdleTimeout");const startPasteIdleTimeout=__name(()=>{lastPasteChunkAt=Date.now();if(pasteIdleTimeout)return;pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS)},"startPasteIdleTimeout");const createPrintableKey=__name(char=>{const printableName=char===" "?"space":/^[A-Za-z]$/.test(char)?char.toLowerCase():char;return{name:printableName,ctrl:false,meta:false,shift:false,paste:false,sequence:char,kittyProtocol:true}},"createPrintableKey");const parseKittyPrefix=__name(buffer=>{const revTabLegacy=new RegExp(`^${ESC2}\\[Z`);let m=buffer.match(revTabLegacy);if(m){return{key:{name:"tab",ctrl:false,meta:false,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const revTabParam=new RegExp(`^${ESC2}\\[1;(\\d+)Z`);m=buffer.match(revTabParam);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;return{key:{name:"tab",ctrl,meta:alt,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const arrowPrefix=new RegExp(`^${ESC2}\\[1;(\\d+)([ABCDHFPQSR])`);m=buffer.match(arrowPrefix);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const shift=(bits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const sym=m[2];const symbolToName={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"};const name=symbolToName[sym]||"";if(!name)return null;return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const csiUPrefix=new RegExp(`^${ESC2}\\[(\\d+)(?::\\d+)*(?:;(\\d+)(?::\\d+)*)?(?:;(\\d+))?([u~])`);m=buffer.match(csiUPrefix);if(m){let keyCode=parseInt(m[1],10);let modifiers=m[2]?parseInt(m[2],10):KITTY_MODIFIER_BASE;if(modifiers>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){modifiers-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const modifierBits=modifiers-KITTY_MODIFIER_BASE;const shift=(modifierBits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(modifierBits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(modifierBits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(modifierBits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const terminator=m[4];if(keyCode===CHAR_CODE_ESC&&terminator==="~"&&m[3]){keyCode=parseInt(m[3],10)}if(terminator==="~"){let name2=null;switch(keyCode){case 1:name2="home";break;case 2:name2="insert";break;case 3:name2="delete";break;case 4:name2="end";break;case 5:name2="pageup";break;case 6:name2="pagedown";break;default:break}if(name2){return{key:{name:name2,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const kittyKeyCodeToName={[CHAR_CODE_ESC]:"escape",[KITTY_KEYCODE_TAB]:"tab",[KITTY_KEYCODE_BACKSPACE]:"backspace",[KITTY_KEYCODE_ENTER]:"return",[KITTY_KEYCODE_NUMPAD_ENTER]:"return"};const name=kittyKeyCodeToName[keyCode];if(name){return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(!ctrl){const keypadChar=KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR[keyCode];if(keypadChar){return{key:{name:keypadChar,ctrl:false,meta:alt,shift,paste:false,sequence:keypadChar,kittyProtocol:true},length:m[0].length}}}const keypadName=KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME[keyCode];if(keypadName){return{key:{name:keypadName,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(terminator==="u"&&!ctrl&&keyCode>=32&&keyCode!==127&&keyCode<=1114111&&!(keyCode>=57344&&keyCode<=63743)){return{key:{...createPrintableKey(String.fromCodePoint(keyCode)),meta:alt,shift},length:m[0].length}}if(ctrl&&keyCode>="a".charCodeAt(0)&&keyCode<="z".charCodeAt(0)){const letter=String.fromCharCode(keyCode);return{key:{name:letter,ctrl:true,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const legacyFuncKey=new RegExp(`^${ESC2}\\[([ABCDHF])`);m=buffer.match(legacyFuncKey);if(m){const sym=m[1];const nameMap={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end"};const name=nameMap[sym];return{key:{name,ctrl:false,meta:false,shift:false,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}return null},"parseKittyPrefix");const getCompleteCsiSequenceLength=__name(buffer=>{if(!buffer.startsWith(`${ESC2}[`)){return null}for(let i=2;i<buffer.length;i++){const code=buffer.charCodeAt(i);if(code>=64&&code<=126){return i+1}if(code<32||code>63){return 0}}return null},"getCompleteCsiSequenceLength");const parsePlainTextPrefix=__name(buffer=>{if(!buffer||buffer.startsWith(ESC2)){return null}const[char]=Array.from(buffer);if(!char){return null}return{key:createPrintableKey(char),length:char.length}},"parsePlainTextPrefix");const broadcast=__name(key=>{noteInteraction();for(const handler of subscribers){handler(key)}},"broadcast");const TERMINAL_RESPONSE_RE=/^\x1b\[[?>][\d;]*[uc]$/;const handleKeypress=__name(async(_,key)=>{if(TERMINAL_RESPONSE_RE.test(key.sequence)){return}if(key.sequence===FOCUS_IN||key.sequence===FOCUS_OUT){return}if(isPaste){resetSgrMouse()}else if(swallowingSgrMouse){if(key.ctrl&&key.name==="c"){resetSgrMouse()}else if(key.name==="paste-start"){resetSgrMouse()}else{sgrMouseBuffer+=key.sequence;if(key.name==="m"||key.sequence==="M"){swallowingSgrMouse=false;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}const parsed=parseSGRMouseEvent(sgrMouseBuffer);if(parsed){for(const handler of mouseSubscribers){handler(parsed.event)}}sgrMouseBuffer=""}else if(sgrMouseBuffer.length>=MAX_SGR_MOUSE_SEQUENCE_LENGTH){resetSgrMouse()}return}}if(!isPaste&&key.sequence===`${ESC2}[<`){swallowingSgrMouse=true;sgrMouseBuffer=`${ESC2}[<`;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout)}sgrMouseTimeout=setTimeout(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";sgrMouseTimeout=null},KITTY_SEQUENCE_TIMEOUT_MS);return}const isCtrlCKey=key.ctrl&&key.name==="c"||key.sequence===`${ESC2}${KITTY_CTRL_C}`;if(isCtrlCKey){if(isPaste||pasteChunks.length>0){isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;clearPasteIdleTimeout()}if(kittySequenceBufferRef.current&&debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer cleared on Ctrl+C:",kittySequenceBufferRef.current)}clearKittyBufferAndTimeout();if(key.sequence===`${ESC2}${KITTY_CTRL_C}`){broadcast({name:"c",ctrl:true,meta:false,shift:false,paste:false,sequence:key.sequence,kittyProtocol:true})}else{broadcast(key)}return}if(key.name==="paste-start"){isPaste=true;pasteAlreadyFlushed=false;startPasteIdleTimeout();return}if(key.name==="paste-end"){clearPasteIdleTimeout();if(pasteAlreadyFlushed){pasteAlreadyFlushed=false;isPaste=false;pasteChunks=[];return}isPaste=false;const buffered=pasteChunks.join("");pasteChunks=[];if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}else{let clipboardImageUnavailable=false;const hasImage=await clipboardHasImage(()=>{clipboardImageUnavailable=true});broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:buffered})}return}if(isPaste){pasteChunks.push(key.sequence);startPasteIdleTimeout();return}if(key.name==="return"&&waitingForEnterAfterBackslash){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({...key,shift:true,sequence:"\r"});return}if(key.sequence==="\\"&&!key.name){waitingForEnterAfterBackslash=true;backslashTimeout=setTimeout(()=>{waitingForEnterAfterBackslash=false;backslashTimeout=null;broadcast(key)},BACKSLASH_ENTER_DETECTION_WINDOW_MS);return}if(waitingForEnterAfterBackslash&&key.name!=="return"){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({name:"",sequence:"\\",ctrl:false,meta:false,shift:false,paste:false})}if(["up","down","left","right"].includes(key.name)){broadcast(key);return}const isModifyOtherKeysSequence=key.sequence?.startsWith(`${ESC2}[27`)??false;if(kittyProtocolEnabled||kittySequenceBufferRef.current||isModifyOtherKeysSequence){if(kittySequenceBufferRef.current||key.sequence.startsWith(`${ESC2}[`)&&!key.sequence.startsWith(PASTE_MODE_PREFIX)&&!key.sequence.startsWith(PASTE_MODE_SUFFIX)&&!key.sequence.startsWith(FOCUS_IN)&&!key.sequence.startsWith(FOCUS_OUT)){updateKittyBuffer(kittySequenceBufferRef.current+key.sequence);startKittyTimeout();if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer accumulating:",kittySequenceBufferRef.current)}let bufferedInputHandled=false;while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){if(debugKeystrokeLogging){const parsedSequence=kittySequenceBufferRef.current.slice(0,parsed.length);if(kittySequenceBufferRef.current.length>parsed.length){debugLogger.debug("[DEBUG] Kitty sequence parsed successfully (prefix):",parsedSequence)}else{debugLogger.debug("[DEBUG] Kitty sequence parsed successfully:",parsedSequence)}}updateKittyBuffer(kittySequenceBufferRef.current.slice(parsed.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(parsed.key);bufferedInputHandled=true;continue}const completeUnsupportedCsiLength=getCompleteCsiSequenceLength(kittySequenceBufferRef.current);if(completeUnsupportedCsiLength){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Dropping unsupported complete CSI sequence:",kittySequenceBufferRef.current.slice(0,completeUnsupportedCsiLength))}updateKittyBuffer(kittySequenceBufferRef.current.slice(completeUnsupportedCsiLength));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}const plainTextPrefix=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plainTextPrefix){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Recovered plain text after kitty sequence:",plainTextPrefix.key.sequence)}updateKittyBuffer(kittySequenceBufferRef.current.slice(plainTextPrefix.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(plainTextPrefix.key);bufferedInputHandled=true;continue}const nextStart=kittySequenceBufferRef.current.indexOf(`${ESC2}[`,1);if(nextStart>0){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Skipping incomplete/invalid CSI prefix:",kittySequenceBufferRef.current.slice(0,nextStart))}updateKittyBuffer(kittySequenceBufferRef.current.slice(nextStart));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}break}if(bufferedInputHandled)return;if(config?.getDebugMode()||debugKeystrokeLogging){const codes=Array.from(kittySequenceBufferRef.current).map(ch=>ch.charCodeAt(0));debugLogger.warn("Kitty sequence buffer has char codes:",codes)}if(kittySequenceBufferRef.current.length>MAX_KITTY_SEQUENCE_LENGTH){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer overflow, clearing:",kittySequenceBufferRef.current)}if(config){const event=new KittySequenceOverflowEvent(kittySequenceBufferRef.current.length,kittySequenceBufferRef.current);logKittySequenceOverflow(config,event)}clearKittyBufferAndTimeout()}else{return}}}if(key.name==="return"&&key.sequence===`${ESC2}\r`){key.meta=true}const composedKeyName=Object.hasOwn(OPTION_COMPOSED_GLYPHS,key.sequence)?OPTION_COMPOSED_GLYPHS[key.sequence]:void 0;if(process.platform==="darwin"&&!isPaste&&composedKeyName){key.name=composedKeyName;key.meta=true}broadcast({...key,paste:isPaste})},"handleKeypress");const clearRawFlushTimeout=__name(()=>{if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}},"clearRawFlushTimeout");const createPasteKeyEvent=__name((name="",sequence="")=>({name,ctrl:false,meta:false,shift:false,paste:false,sequence}),"createPasteKeyEvent");const shouldFlushRawDataAsPaste=__name(data=>{if(data.includes(27))return false;const hasReturn=data.includes(13);const hasEmbeddedTab=data.length>1&&data.includes(9);const isSingleReturn=data.length<=2&&hasReturn;return!isSingleReturn&&(hasReturn||hasEmbeddedTab)},"shouldFlushRawDataAsPaste");const flushRawBuffer=__name(()=>{if(!rawDataBuffer.length){return}const pasteModePrefixBuffer=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuffer=Buffer.from(PASTE_MODE_SUFFIX);const data=rawDataBuffer;let cursor=0;while(cursor<data.length){const prefixPos=data.indexOf(pasteModePrefixBuffer,cursor);const suffixPos=data.indexOf(pasteModeSuffixBuffer,cursor);const hasPrefix=prefixPos!==-1&&prefixPos+pasteModePrefixBuffer.length<=data.length;const hasSuffix=suffixPos!==-1&&suffixPos+pasteModeSuffixBuffer.length<=data.length;let markerPos=-1;let markerLength=0;let markerType=null;if(hasPrefix&&(!hasSuffix||prefixPos<suffixPos)){markerPos=prefixPos;markerLength=pasteModePrefixBuffer.length;markerType="prefix"}else if(hasSuffix){markerPos=suffixPos;markerLength=pasteModeSuffixBuffer.length;markerType="suffix"}if(markerPos===-1){break}const nextData=data.slice(cursor,markerPos);if(nextData.length>0){keypressStream.write(nextData)}if(markerType==="prefix"){handleKeypress(void 0,createPasteKeyEvent("paste-start"))}else if(markerType==="suffix"){handleKeypress(void 0,createPasteKeyEvent("paste-end"))}cursor=markerPos+markerLength}rawDataBuffer=data.slice(cursor);if(rawDataBuffer.length===0){return}if(isPaste||!shouldFlushRawDataAsPaste(rawDataBuffer)){keypressStream.write(rawDataBuffer)}else{handleKeypress(void 0,createPasteKeyEvent("paste-start"));keypressStream.write(rawDataBuffer);handleKeypress(void 0,createPasteKeyEvent("paste-end"))}rawDataBuffer=Buffer.alloc(0);clearRawFlushTimeout()},"flushRawBuffer");const handleRawKeypress=__name(_data=>{const data=Buffer.isBuffer(_data)?_data:Buffer.from(_data,"utf8");rawDataBuffer=Buffer.concat([rawDataBuffer,data]);clearRawFlushTimeout();const isReturnChar=rawDataBuffer.length<=2&&rawDataBuffer.includes(13);if(isReturnChar){rawFlushTimeout=setTimeout(flushRawBuffer,100)}else{flushRawBuffer()}},"handleRawKeypress");const pasteModePrefixBuf=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuf=Buffer.from(PASTE_MODE_SUFFIX);function partialMarkerTailLength(chunk,marker,minLen=2){const maxCheck=Math.min(chunk.length,marker.length-1);for(let len=maxCheck;len>=minLen;len--){const tail=chunk.subarray(chunk.length-len);if(marker.subarray(0,len).equals(tail)){return len}}return 0}__name(partialMarkerTailLength,"partialMarkerTailLength");let rawStdinTail=Buffer.alloc(0);let rawPasteAccumulating=false;let rawPasteChunks=[];let rawPasteReceivedBytes=0;let rawPasteIdleTimeout=null;const clearRawPasteIdleTimeout=__name(()=>{if(rawPasteIdleTimeout){clearTimeout(rawPasteIdleTimeout);rawPasteIdleTimeout=null}},"clearRawPasteIdleTimeout");const forceFlushRawPaste=__name(()=>{clearRawPasteIdleTimeout();if(!rawPasteAccumulating&&rawPasteChunks.length===0&&rawStdinTail.length===0)return;if(rawStdinTail.length>0){rawPasteChunks.push(rawStdinTail);rawStdinTail=Buffer.alloc(0)}const content=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(content)},"forceFlushRawPaste");const startRawPasteIdleTimeout=__name(()=>{clearRawPasteIdleTimeout();rawPasteIdleTimeout=setTimeout(forceFlushRawPaste,PASTE_IDLE_TIMEOUT_MS)},"startRawPasteIdleTimeout");const broadcastPasteFromRaw=__name(content=>{pasteAlreadyFlushed=true;setPasteProgress({active:false,receivedBytes:0});const text=content.toString("utf-8");if(text.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:text})}else{let clipboardImageUnavailable=false;void clipboardHasImage(()=>{clipboardImageUnavailable=true}).then(hasImage=>{broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:""})})}},"broadcastPasteFromRaw");const handleStdinData=__name(data=>{const raw=Buffer.isBuffer(data)?data:Buffer.from(data,"utf8");const buf=rawStdinTail.length>0?Buffer.concat([rawStdinTail,raw]):raw;rawStdinTail=Buffer.alloc(0);let cursor=0;while(cursor<buf.length){if(rawPasteAccumulating){const suffixIdx=buf.indexOf(pasteModeSuffixBuf,cursor);if(suffixIdx===-1){const remaining=buf.subarray(cursor);const tailLen=partialMarkerTailLength(remaining,pasteModeSuffixBuf,1);const contentEnd=remaining.length-tailLen;if(contentEnd>0){const chunk=remaining.subarray(0,contentEnd);rawPasteChunks.push(chunk);rawPasteReceivedBytes+=chunk.length;setPasteProgress(prev=>({...prev,receivedBytes:rawPasteReceivedBytes}))}if(tailLen>0){rawStdinTail=Buffer.from(remaining.subarray(contentEnd))}startRawPasteIdleTimeout();cursor=buf.length}else{clearRawPasteIdleTimeout();if(suffixIdx>cursor){rawPasteChunks.push(buf.subarray(cursor,suffixIdx))}const pasteContent=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(pasteContent);cursor=suffixIdx+pasteModeSuffixBuf.length}}else{const prefixIdx=buf.indexOf(pasteModePrefixBuf,cursor);if(prefixIdx===-1){const remaining=buf.subarray(cursor);if(remaining.length>0){const tailLen=partialMarkerTailLength(remaining,pasteModePrefixBuf);if(tailLen>0){const safe=remaining.subarray(0,remaining.length-tailLen);if(safe.length>0)keypressStream.write(safe);rawStdinTail=Buffer.from(remaining.subarray(remaining.length-tailLen))}else{keypressStream.write(remaining)}}cursor=buf.length}else{if(prefixIdx>cursor){keypressStream.write(buf.subarray(cursor,prefixIdx))}rawPasteAccumulating=true;rawPasteChunks=[];rawPasteReceivedBytes=0;startRawPasteIdleTimeout();setPasteProgress({active:true,receivedBytes:0});cursor=prefixIdx+pasteModePrefixBuf.length}}}},"handleStdinData");let rl;if(usePassthrough){rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("data",handleRawKeypress)}else{rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("keypress",handleKeypress);stdin.on("data",handleStdinData)}let replayPending=false;if(capturedInput.length>0){debugLogger.debug(`Replaying ${capturedInput.length} bytes of captured input`);replayPending=true;setImmediate(()=>{if(!replayPending)return;try{stdin.emit("data",capturedInput)}catch(err){debugLogger.error("Failed to replay captured input:",err)}})}return()=>{replayPending=false;if(usePassthrough){keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleRawKeypress)}else{keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleStdinData)}rl.close();setRawMode(false);if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}clearKittyBufferAndTimeout();clearPasteIdleTimeout();clearRawPasteIdleTimeout();resetSgrMouse();if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}if(rawPasteAccumulating||rawPasteChunks.length>0){forceFlushRawPaste()}else if(isPaste){const buffered=pasteChunks.join("");if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}pasteChunks=[]}}},[stdin,setRawMode,kittyProtocolEnabled,debugKeystrokeLogging,pasteWorkaround,config,subscribers,mouseSubscribers,initialCapturedInput]);return(0,import_jsx_runtime.jsx)(KeypressContext.Provider,{value:{subscribe,unsubscribe,subscribeMouse,unsubscribeMouse,pasteWorkaround,pasteProgress},children})}__name(KeypressProvider,"KeypressProvider");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var import_jsx_runtime2=__toESM(require_jsx_runtime(),1);var ContextMenuContext=(0,import_react3.createContext)({menu:null,isMenuOpen:__name(()=>false,"isMenuOpen"),selectedIndex:0,openMenu:__name(()=>{},"openMenu"),closeMenu:__name(()=>{},"closeMenu"),setSelectedIndex:__name(()=>{},"setSelectedIndex"),executeIndex:__name(()=>{},"executeIndex")});var ContextMenuProvider=__name(({children,onMenuChange})=>{const[menu,setMenu]=(0,import_react3.useState)(null);const[selectedIndex,setSelectedIndexState]=(0,import_react3.useState)(0);const menuRef=(0,import_react3.useRef)(null);menuRef.current=menu;const isMenuOpen=(0,import_react3.useCallback)(()=>menuRef.current!==null,[]);const openMenu=(0,import_react3.useCallback)((items,position)=>{if(items.length===0)return;menuRef.current={items,position};onMenuChange?.(true);setMenu(menuRef.current);setSelectedIndexState(0)},[onMenuChange]);const closeMenu=(0,import_react3.useCallback)(()=>{menuRef.current=null;setMenu(null)},[]);(0,import_react3.useEffect)(()=>{onMenuChange?.(menu!==null)},[menu,onMenuChange]);const setSelectedIndex=(0,import_react3.useCallback)(index=>{setSelectedIndexState(index)},[]);const executeIndex=(0,import_react3.useCallback)(index=>{const current=menuRef.current;menuRef.current=null;setMenu(null);current?.items[index]?.onSelect()},[]);const value=(0,import_react3.useMemo)(()=>({menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex}),[menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex]);return(0,import_jsx_runtime2.jsx)(ContextMenuContext.Provider,{value,children})},"ContextMenuProvider");function useContextMenu(){return(0,import_react3.useContext)(ContextMenuContext)}__name(useContextMenu,"useContextMenu");function contextMenuSize(items){const longest=items.reduce((max,item)=>Math.max(max,item.label.length),0);return{width:longest+4,height:items.length+2}}__name(contextMenuSize,"contextMenuSize");function clampMenuPosition(desired,size,terminalColumns,terminalRows){return{x:Math.max(0,Math.min(desired.x,terminalColumns-size.width)),y:Math.max(0,Math.min(desired.y,terminalRows-size.height))}}__name(clampMenuPosition,"clampMenuPosition");function useKeypress(onKeypress,{isActive}){const{subscribe,unsubscribe}=useKeypressContext();const{menu,isMenuOpen}=useContextMenu();const onKeypressRef=(0,import_react4.useRef)(onKeypress);onKeypressRef.current=key=>{if(menu===null&&isMenuOpen())return;onKeypress(key)};const handleKeypress=(0,import_react4.useCallback)(key=>{onKeypressRef.current(key)},[]);(0,import_react4.useEffect)(()=>{if(!isActive){return}subscribe(handleKeypress);return()=>{unsubscribe(handleKeypress)}},[isActive,handleKeypress,subscribe,unsubscribe])}__name(useKeypress,"useKeypress");export{enableMouseEvents,disableMouseEvents,ContextMenuProvider,useContextMenu,contextMenuSize,clampMenuPosition,useKeypress,useFocus,useKeypressContext,KeypressProvider};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{sanitizeFilenameComponent}from"./chunk-3SQ76U4F.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getProjectHash,isSubpath}from"./chunk-2ZK2FGZQ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function safeTarget(target){if(/^[A-Za-z0-9._-]{55}~[0-9a-f]{8}$/.test(target))return target;const flat=target.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_");const stem=flat.replace(/^[._]+/,"")||"target";if(stem.length<=SAFE_TARGET_MAX)return stem;return`${stem.slice(0,SAFE_TARGET_MAX-9)}~${createHash("sha256").update(stem).digest("hex").slice(0,8)}`}__name(safeTarget,"safeTarget");var SAFE_TARGET_MAX=64;init_esbuild_shims();var CONTROL=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;var NEEDS_PRE_ESCAPE=/[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;function inertText(value,maxChars=200){const clipped=value.length>maxChars?value.slice(0,maxChars):value;const rendered=CONTROL.test(clipped)?JSON.stringify(clipped.replace(NEEDS_PRE_ESCAPE,c=>{const hex=c.codePointAt(0).toString(16).padStart(4,"0");return`\\u${hex}`})):clipped;return clipped.length<value.length?`${rendered}\u2026`:rendered}__name(inertText,"inertText");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,readdirSync as readdirSync3,realpathSync as realpathSync4,statSync as statSync3}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute3,join as join3,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";init_esbuild_shims();import{execFileSync,spawnSync as spawnSync2}from"node:child_process";init_esbuild_shims();import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,lstatSync,mkdirSync,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,rmSync,statSync as statSync2,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname,isAbsolute as isAbsolute2,join as join2,resolve,sep}from"node:path";init_esbuild_shims();import{existsSync,readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";init_esbuild_shims();var MAX_OLD_SPACE_FLAG="--max[-_]old[-_]space[-_]size";var HEAP_TOKEN_RE=new RegExp(`(?:^|\\s)${MAX_OLD_SPACE_FLAG}(?:=(\\d*)|\\s+(\\d+))?(?=\\s|$)`,"g");function heapFlagMb(options){let mb;for(const m of options.matchAll(HEAP_TOKEN_RE)){const value=m[1]||m[2];if(value)mb=Number(value)}return mb}__name(heapFlagMb,"heapFlagMb");function withoutHeapFlag(options){return options.replace(HEAP_TOKEN_RE,"").trim()}__name(withoutHeapFlag,"withoutHeapFlag");function raiseHeap(options,mb){if((heapFlagMb(options)??0)>=mb)return void 0;return`${withoutHeapFlag(options)} --max-old-space-size=${mb}`.trim()}__name(raiseHeap,"raiseHeap");var NPM_ENV_REF_RE=/(?<!\\)(\\*)\$\{([^${}]+)\}/g;function raiseNpmHeap(options,mb){return raiseHeap(options,mb)?.replace(NPM_ENV_REF_RE,(_,esc,name)=>`${esc}${esc}\\\${${name}}`)}__name(raiseNpmHeap,"raiseNpmHeap");var HEAP_BANNER_RE=/^FATAL ERROR: [^\n]*JavaScript heap out of memory/m;function heapBannerIn(raw){return HEAP_BANNER_RE.test(raw)}__name(heapBannerIn,"heapBannerIn");function ranOutOfHeap(r){return r.exitCode!==0&&(r.heapExhausted??heapBannerIn(r.output))}__name(ranOutOfHeap,"ranOutOfHeap");function killedFromOutside(r){return!r.timedOut&&r.spawnError===void 0&&(r.exitCode===137||r.exitCode===null&&r.signal==="SIGKILL")}__name(killedFromOutside,"killedFromOutside");init_esbuild_shims();function stripComments(src){return src.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,m=>m.startsWith("/")?" ":m)}__name(stripComments,"stripComments");function isWorkspaceMember(filePath,workspaceGlobs){return workspaceDirFor(filePath,workspaceGlobs)!==null}__name(isWorkspaceMember,"isWorkspaceMember");function workspaceDirFor(filePath,workspaceGlobs){const norm=filePath.replace(/^\.\//,"");let owner=null;const previous=[];for(const glob of workspaceGlobs){const negated=glob.startsWith("!");const g=glob.replace(/^!/,"").replace(/^\.\//,"").replace(/\/$/,"");let dir=null;if(g.endsWith("/*")){const base=g.slice(0,-2);if(norm.startsWith(`${base}/`)){const seg=norm.slice(base.length+1).split("/")[0];if(seg)dir=`${base}/${seg}`}}else if(norm===g||norm.startsWith(`${g}/`)){dir=g}if(dir===null)continue;if(!negated){if(dir!==owner){previous.push(owner);owner=dir}}else if(dir===owner){owner=previous.pop()??null}}return owner}__name(workspaceDirFor,"workspaceDirFor");function isNegationExcluded(filePath,workspaceGlobs){if(workspaceDirFor(filePath,workspaceGlobs)!==null)return false;const positives=workspaceGlobs.filter(g=>!g.startsWith("!"));return workspaceDirFor(filePath,positives)!==null}__name(isNegationExcluded,"isNegationExcluded");function hasUnmodeledWorkspaceGlob(globs){return globs.some(glob=>{const g=glob.replace(/^!/,"").replace(/^\.\//,"");if(!g.includes("*"))return false;return!/^[^*]+\/\*$/.test(g)})}__name(hasUnmodeledWorkspaceGlob,"hasUnmodeledWorkspaceGlob");function readWorkspaceGlobs(root){try{const pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const ws=pkg.workspaces;const globs=Array.isArray(ws)?ws:Array.isArray(ws?.packages)?ws.packages:[];return globs.filter(g=>typeof g==="string")}catch{return[]}}__name(readWorkspaceGlobs,"readWorkspaceGlobs");function readRootPackage(root){let pkg;try{pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"))}catch{return null}if(pkg===null)return null;const scripts=Object.keys(pkg.scripts??{});if(!scripts.includes("build")&&!scripts.includes("test"))return null;const scriptsText={};for(const[k,v]of Object.entries(pkg.scripts??{})){if(typeof v==="string")scriptsText[k]=v}return{dir:".",name:typeof pkg.name==="string"&&pkg.name?pkg.name:"root",scripts,deps:declaredDeps(pkg),scriptsText}}__name(readRootPackage,"readRootPackage");function scriptFansOut(text){return typeof text==="string"&&(/(^|\s)(--workspaces|--?ws)(?=[\s'"`]|$)/.test(text)||/\bpnpm\s+(-r|--recursive)(?=[\s'"`]|$)/.test(text))}__name(scriptFansOut,"scriptFansOut");var COMMAND_SEPARATOR_RE=/[;&|\n]+/;function chainsCommands(text){return text.split(COMMAND_SEPARATOR_RE).filter(c=>c.trim()!=="").length>1}__name(chainsCommands,"chainsCommands");var NODE_VALUE_FLAGS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--env-file-if-exists","--input-type","--title","--redirect-warnings","--watch-path","--diagnostic-dir","--report-dir","--cpu-prof-dir","--heap-prof-dir","--icu-data-dir","--openssl-config"]);var SCRIPT_RUNNERS=new Set(["node","tsx"]);var NODE_INLINE_FLAGS=new Set(["-e","--eval","-p","--print","-"]);function nodeScripts(text){const files=[];for(const command of text.split(COMMAND_SEPARATOR_RE)){const words=command.trim().split(/\s+/);const runner=words.findIndex(w=>SCRIPT_RUNNERS.has(w));for(let i=runner+1;i>0&&i<words.length;i++){const word=words[i];if(NODE_INLINE_FLAGS.has(word))break;if(word.startsWith("-")){if(NODE_VALUE_FLAGS.has(word))i++;continue}if(/^[\w@./-]+\.[cm]?[jt]s$/.test(word))files.push(word);break}}return files}__name(nodeScripts,"nodeScripts");function childProcessCommands(src){const commands=[];for(const m of stripComments(src).matchAll(/\b(?:exec|execSync|execFile|execFileSync|spawn|spawnSync)\s*\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g)){commands.push(m[1].slice(1,-1))}return commands}__name(childProcessCommands,"childProcessCommands");var MAX_HAND_OFF_SCRIPT_BYTES=1024*1024;function rootBuildFanOutScript(root,text){if(typeof text!=="string")return void 0;for(const file of nodeScripts(text)){try{const path=realpathSync(join(root,file));const inRoot=relative(realpathSync(root),path);if(inRoot.startsWith("..")||isAbsolute(inRoot))continue;const stat=statSync(path);if(!stat.isFile()||stat.size>MAX_HAND_OFF_SCRIPT_BYTES)continue;if(childProcessCommands(readFileSync(path,"utf8")).some(scriptFansOut))return file}catch{}}return void 0}__name(rootBuildFanOutScript,"rootBuildFanOutScript");function declaredBuildHeapMb(root){const text=readRootPackage(root)?.scriptsText["build"];if(typeof text!=="string")return void 0;let declared;for(const m of text.matchAll(/\bNODE_OPTIONS=(?:"([^"]*)"|'([^']*)'|(\S*))/g)){const mb=heapFlagMb(m[1]??m[2]??m[3]??"");if(mb!==void 0)declared=Math.max(declared??0,mb)}return declared}__name(declaredBuildHeapMb,"declaredBuildHeapMb");function declaredDeps(pkg){return[...Object.keys(pkg.dependencies??{}),...Object.keys(pkg.devDependencies??{}),...Object.keys(pkg.peerDependencies??{}),...Object.keys(pkg.optionalDependencies??{})]}__name(declaredDeps,"declaredDeps");function workspaceDirCandidates(root,globs){const dirs=new Set;for(const glob of globs){if(glob.startsWith("!"))continue;const g=glob.replace(/^\.\//,"").replace(/\/$/,"");if(g.endsWith("/*")){const base=g.slice(0,-2);let entries;try{entries=readdirSync(join(root,base),{withFileTypes:true}).filter(e=>e.isDirectory()||e.isSymbolicLink()&&existsSync(join(root,base,e.name,"package.json"))).map(e=>e.name)}catch{continue}for(const e of entries)dirs.add(`${base}/${e}`)}else{dirs.add(g)}}return[...dirs].sort()}__name(workspaceDirCandidates,"workspaceDirCandidates");function readWorkspacePackages(root){const globs=readWorkspaceGlobs(root);const packages=[];const skipped=[];for(const dir of workspaceDirCandidates(root,globs)){const manifest=join(root,dir,"package.json");if(!existsSync(manifest))continue;if(workspaceDirFor(`${dir}/package.json`,globs)!==dir){const positives=globs.filter(g=>!g.startsWith("!"));if(workspaceDirFor(`${dir}/package.json`,positives)===dir)continue;skipped.push(dir);continue}let pkg;try{pkg=JSON.parse(readFileSync(manifest,"utf8"))}catch{skipped.push(dir);continue}if(pkg===null||typeof pkg.name!=="string"||!pkg.name){skipped.push(dir);continue}packages.push({dir,name:pkg.name,scripts:Object.keys(pkg.scripts??{}),deps:declaredDeps(pkg)})}packages.sort((a,b)=>a.dir.localeCompare(b.dir));skipped.sort();return{packages,skipped}}__name(readWorkspacePackages,"readWorkspacePackages");function affectedWorkspaces(changedFiles,workspaceGlobs){const dirs=new Set;for(const f of changedFiles){const d=workspaceDirFor(f,workspaceGlobs);if(d)dirs.add(d)}return[...dirs].sort()}__name(affectedWorkspaces,"affectedWorkspaces");function dependencyEdges(packages){const byName=new Map;for(const p of packages){if(p.dir!=="."||!byName.has(p.name))byName.set(p.name,p)}const dependsOn=new Map;for(const p of packages){dependsOn.set(p.dir,p.deps.map(d=>byName.get(d)?.dir).filter(d=>!!d&&d!==p.dir))}return dependsOn}__name(dependencyEdges,"dependencyEdges");function dependencyClosure(dirs,packages){const dependsOn=dependencyEdges(packages);const closure=new Set;const add=__name(dir=>{if(closure.has(dir))return;closure.add(dir);for(const d of dependsOn.get(dir)??[])add(d)},"add");dirs.forEach(add);return[...closure].sort()}__name(dependencyClosure,"dependencyClosure");function reverseDependencyClosure(affected,packages){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=new Set(affected.filter(a=>byDir.has(a)));let grew=true;while(grew){grew=false;for(const p of packages){if(consumers.has(p.dir))continue;if((dependsOn.get(p.dir)??[]).some(d=>consumers.has(d))){consumers.add(p.dir);grew=true}}}return[...consumers].sort()}__name(reverseDependencyClosure,"reverseDependencyClosure");function buildSetFor(affected,packages,alsoBuild=[]){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=reverseDependencyClosure(affected,packages);const wanted=new Set;const addDeps=__name(dir=>{if(wanted.has(dir))return;wanted.add(dir);for(const d of dependsOn.get(dir)??[])addDeps(d)},"addDeps");for(const c of consumers)addDeps(c);for(const extra of alsoBuild)if(byDir.has(extra))addDeps(extra);const order=[];const seen=new Set;const visit=__name(dir=>{if(seen.has(dir))return;seen.add(dir);for(const d of dependsOn.get(dir)??[]){if(wanted.has(d))visit(d)}order.push(dir)},"visit");for(const dir of alsoBuild.filter(d=>wanted.has(d)).sort())visit(dir);for(const dir of[...wanted].sort())visit(dir);return order}__name(buildSetFor,"buildSetFor");var GIT_ENV_REDIRECTS=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_COMMON_DIR"];var GIT_ENV_CONFIG=["GIT_CONFIG_COUNT","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_PARAMETERS","GIT_DEFAULT_HASH"];var GIT_ENV_EXEC=["GIT_SSH_COMMAND","GIT_SSH","GIT_EXEC_PATH","GIT_TEMPLATE_DIR","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_EDITOR","GIT_SEQUENCE_EDITOR","GIT_EXTERNAL_DIFF","XDG_CONFIG_HOME"];function mountRootFor(cwd){return mountRootVerdict(cwd).root}__name(mountRootFor,"mountRootFor");function mountNullKind(cwd){return mountRootVerdict(cwd).nullKind??"refused"}__name(mountNullKind,"mountNullKind");function mountRootVerdict(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).lastIndexOf(marker);if(at<0)return{root:null,nullKind:"outside"};const root=resolved.slice(0,at+marker.length-1);const outermost=outermostReviewTmpRoot(root);const bound=outermost===root?resolve(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync2(root);if(unmountableRootSpelling(real)){return{root:null,nullKind:"unmountable"}}return{root:real,nullKind:null}}catch{return{root:null,nullKind:"refused"}}}__name(mountRootVerdict,"mountRootVerdict");function unmountableRootSpelling(root){return root.includes(":")||root.startsWith("\\\\")}__name(unmountableRootSpelling,"unmountableRootSpelling");function insideReviewTmpLexically(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;return(resolved+sep).lastIndexOf(marker)>=0}__name(insideReviewTmpLexically,"insideReviewTmpLexically");function resolvedGitDir(cwd){return revParse(cwd,"--absolute-git-dir")}__name(resolvedGitDir,"resolvedGitDir");function resolvedCommonDir(cwd){return revParse(cwd,"--path-format=absolute","--git-common-dir")}__name(resolvedCommonDir,"resolvedCommonDir");function revParse(cwd,...flags){const resolved=spawnSync("git",["-c","core.hooksPath=/dev/null/no-hooks","-c","core.fsmonitor=","rev-parse",...flags],{cwd,encoding:"utf8",timeout:3e4,env:{...sanitizedGitEnv(),LC_ALL:"C"}});const value=resolved.error||resolved.status!==0||!resolved.stdout?null:resolved.stdout.replace(/\n$/,"");return{value:value!==null&&value.includes("\uFFFD")?null:value,notARepository:resolved.status===128&&resolved.stderr.includes("not a git repository")}}__name(revParse,"revParse");function untrustedPointer(dir,gitDir,expectedOwner,root){if(adminEntryInsideReviewTmp(gitDir,root,dir)){return"resolves to an admin entry inside the review temp dir, where the reviewed code can rewrite it"}const common=resolvedCommonDir(dir);if(common.value===null&&!common.notARepository){return"git could not resolve its own common dir from this tree, so whether the pointer names the main repository instead of a linked worktree's admin entry is unknown"}if(common.value!==null&&common.value===gitDir){return"resolves to the repository's own common dir rather than a linked worktree's admin entry, so every command through it acts on the main repository instead of this tree"}let backpointer;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname(resolve(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync2(ownerSpelled)}catch{ownerTree=null}const writableRoot=outermostReviewTmpRoot(root);if(ownerSpelled===writableRoot||isSubpath(writableRoot,ownerSpelled)){const redirect=redirectedAncestor(ownerSpelled,writableRoot);if(redirect!==null){return`resolves to a different tree's admin entry \u2014 the owner its gitdir backpointer names resolves through a symlink inside the review temp dir (${redirect}), so the round trip would agree with whatever the link points at`}}let expectedReal;try{expectedReal=realpathSync2(expectedOwner)}catch{return"could not resolve the tree the entry must belong to"}if(ownerTree===null){return"resolves to an admin entry that does not point back at this tree \u2014 the owner its backpointer names cannot be resolved, so the commands this gates would measure whichever repository it does name"}if(ownerTree!==expectedReal){return"resolves to a different tree's admin entry \u2014 its gitdir backpointer names that tree, not this one, so every command through it would measure and mutate the tree it actually belongs to"}return null}__name(untrustedPointer,"untrustedPointer");function untrustedRepositoryFrom(cwd,mountRoot=mountRootFor){const root=mountRoot(cwd);if(root===null){if(mountNullKind(cwd)!=="refused")return null;return`${cwd}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command run from here would land is unmeasured`}if(!existsSync2(cwd)){if(!insideReviewTmpLexically(cwd))return null;return`${cwd}: no directory exists at this spelling inside the review temp dir \u2014 an ancestor was renamed out from under it, so where a command run from here would land is unmeasured`}const target=resolvedGitDir(cwd);if(target.value===null){return target.notARepository?null:`${cwd}: git could not resolve its own git dir, so where a command run from here would land is unmeasured`}const toplevel=revParse(cwd,"--show-toplevel");if(toplevel.value===null){return`${cwd}: git could not resolve its own top-level directory, so where a command run from here would land is unmeasured`}const why=untrustedPointer(cwd,target.value,toplevel.value,root);return why===null?null:`${cwd} ${why}`}__name(untrustedRepositoryFrom,"untrustedRepositoryFrom");function untrustedGitfile(tree,mountRoot=mountRootFor){if(!existsSync2(tree))return null;const root=mountRoot(tree);if(root===null){if(mountNullKind(tree)!=="refused")return null;return`${tree}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command through its .git would land is unmeasured`}const dotGit=join2(tree,".git");let stat;try{stat=lstatSync(dotGit)}catch{return`${tree} has no .git to resolve`}if(!stat.isFile()){return`${tree}'s .git is not the gitfile the pipeline created, and the tree is inside the review temp dir`}const target=resolvedGitDir(tree);if(target.value===null){return`${tree}: git could not resolve its own git dir`}const why=untrustedPointer(tree,target.value,tree,root);return why===null?null:`${tree} ${why}`}__name(untrustedGitfile,"untrustedGitfile");function adminEntryInsideReviewTmp(gitDir,root,tree){if(root===null)return mountNullKind(tree)==="refused";let real;let realRoot;try{const canonical=realpathSync2.native??realpathSync2;real=canonical(resolve(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=root.indexOf(marker);return at<0?root:root.slice(0,at+marker.length-1)}__name(outermostReviewTmpRoot,"outermostReviewTmpRoot");function redirectedAncestor(dir,stopAt=process.cwd()){try{const stop=resolve(stopAt);let stopReal=stop;try{stopReal=realpathSync2(stopAt)}catch{}for(let cur=resolve(dir);;cur=dirname(cur)){let isLink;try{isLink=lstatSync(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync2(cur)===stopReal)return null}catch{}if(dirname(cur)===cur)return null}}catch{return null}}__name(redirectedAncestor,"redirectedAncestor");function sanitizedGitEnv(){const env={...process.env};const drop=new Set([...GIT_ENV_REDIRECTS,...GIT_ENV_CONFIG,...GIT_ENV_EXEC].map(k=>k.toLowerCase()));for(const key of Object.keys(env)){const lower=key.toLowerCase();if(drop.has(lower)||/^git_config_(key|value)_\d+$/.test(lower)){delete env[key]}}env["GIT_NO_REPLACE_OBJECTS"]="1";env["GIT_GRAFT_FILE"]="/dev/null/grafts";return env}__name(sanitizedGitEnv,"sanitizedGitEnv");var MAX_INCLUDE_DEPTH=10;var MAX_INCLUDE_FILES=64;var FILTER_SCREEN_NAMED=12;var SCREEN_KEYS="^filter\\..*\\.(smudge|clean|process)$|^include\\.path$|^includeif\\..*\\.path$";function filterCommandsIn(commonDir,gitDir){const candidates=[join2(commonDir,"config"),join2(gitDir,"config.worktree")];try{for(const entry of readdirSync2(join2(commonDir,"worktrees"))){candidates.push(join2(commonDir,"worktrees",entry,"config.worktree"))}}catch{}const filters=new Set;const unread=new Set;const dangling=new Set;const visited=new Set;const read=__name(file=>{const r=spawnSync("git",["config","--file",file,"-z","--get-regexp",SCREEN_KEYS],{cwd:commonDir,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error){return{unreadable:r.error.code??r.error.message}}if(r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return{unreadable:`git config exited ${r.status}`}}const records=[];for(const rec of r.stdout.split("\0")){if(!rec)continue;const nl=rec.indexOf("\n");records.push(nl===-1?[rec,""]:[rec.slice(0,nl),rec.slice(nl+1)])}return{records}},"read");const visit=__name((file,depth,via)=>{let real;try{real=realpathSync2.native(file)}catch(e){if(via!==null){const code=e?.code;if(code==="ENOENT"){dangling.add(`${via} -> ${file} (missing \u2014 git ignores it)`)}else{unread.add(`${via} -> ${file} (could not be resolved: ${code??"unknown"} \u2014 not screened)`)}}return}if(visited.has(real))return;if(visited.size>=MAX_INCLUDE_FILES){unread.add(`${via??file} -> ${file} (include fan-out past ${MAX_INCLUDE_FILES} files \u2014 not screened)`);return}visited.add(real);try{if(!statSync2(real).isFile()){unread.add(`${via??file} -> ${file} (not a regular file \u2014 not screened)`);return}accessSync(real,constants.R_OK)}catch{unread.add(`${via??file} -> ${file} (could not be read)`);return}if(depth>MAX_INCLUDE_DEPTH){unread.add(`${via} -> ${file} (nested past git's include limit \u2014 not screened)`);return}const r=read(file);if("unreadable"in r){unread.add(`${file} (could not be read: ${r.unreadable})`);return}for(const[key,value]of r.records){if(key.startsWith("filter.")){filters.add(key);continue}let target;if(value.startsWith("~/")){target=`${process.env["HOME"]||homedir()}${sep}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute2(value)?value:`${dirname(file)}${sep}${value}`}visit(target,depth+1,`${key} (in ${file})`)}},"visit");for(const candidate of candidates)visit(candidate,0,null);return{filters:[...filters],unread:[...unread],dangling:[...dangling]}}__name(filterCommandsIn,"filterCommandsIn");function describeFilterScreen(hits){const named=hits.slice(0,FILTER_SCREEN_NAMED);const rest=hits.length-named.length;return rest>0?`${named.join(", ")}, and ${rest} more`:named.join(", ")}__name(describeFilterScreen,"describeFilterScreen");function filterBlankEnv(filterKeys){const names=new Set;for(const key of filterKeys){const m=/^filter\.(.+)\.(?:smudge|clean|process)$/.exec(key);if(m)names.add(m[1])}const env={};let n=0;for(const name of names){for(const[key,value]of[["clean",""],["smudge",""],["process",""],["required","false"]]){env[`GIT_CONFIG_KEY_${n}`]=`filter.${name}.${key}`;env[`GIT_CONFIG_VALUE_${n}`]=value;n++}}if(n>0)env["GIT_CONFIG_COUNT"]=String(n);return env}__name(filterBlankEnv,"filterBlankEnv");var UNRESOLVED_REPO="the repository's git directories could not be resolved (git rev-parse failed) \u2014 not screened";function screenForTree(worktree){const discover=__name(flag=>{const r=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return null}return r.stdout.endsWith("\n")?r.stdout.slice(0,-1):r.stdout},"discover");const commonDir=discover("--git-common-dir");const gitDir=discover("--git-dir");if(commonDir===null||gitDir===null)return null;return filterCommandsIn(commonDir,gitDir)}__name(screenForTree,"screenForTree");function localFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread,...screen.dangling]}__name(localFilterCommands,"localFilterCommands");function filterScreenForTree(worktree){return screenForTree(worktree)}__name(filterScreenForTree,"filterScreenForTree");function resolvedContentTransformForTree(worktree){const r=spawnSync("git",["config","--get-regexp","^filter\\..*\\.(smudge|clean|process)$|^core\\.(autocrlf|eol)$"],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.status!==0||typeof r.stdout!=="string")return false;for(const line of r.stdout.split("\n")){const space=line.indexOf(" ");const key=(space===-1?line:line.slice(0,space)).toLowerCase();const value=space===-1?"true":line.slice(space+1).trim().toLowerCase();if(key.startsWith("filter."))return true;if(key==="core.autocrlf"&&(value==="true"||value==="input")){return true}if(key==="core.eol"&&(value==="crlf"||value==="native"&&process.platform==="win32")){return true}}return false}__name(resolvedContentTransformForTree,"resolvedContentTransformForTree");function checkoutFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread]}__name(checkoutFilterCommands,"checkoutFilterCommands");function discardWorktree(cwd,tree){let symlink=false;try{symlink=lstatSync(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync(tree,{recursive:true,force:true});dropWorktreeRegistration(cwd,tree,ownAdminDir);if(sweep!==void 0&&sweep.status!==0){dropWorktreeRegistration(cwd,tree,null)}return sweep}__name(discardWorktree,"discardWorktree");function dropWorktreeRegistration(cwd,tree,adminDir){if(adminDir!==null){try{rmSync(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(common.status!==0||typeof common.stdout!=="string")return;const dir=join2(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync2(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join2(dir,id,"gitdir"),"utf8").trim();const named=dirname(gitdir);if(samePath(named)!==wanted)continue;if(existsSync2(named))continue;rmSync(join2(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join2(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve(dirname(resolve(tree)),match[1].trim());const back=readFileSync2(join2(dir,"gitdir"),"utf8").trim();return samePath(dirname(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve(p);try{return join2(realpathSync2(dirname(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join2(mkdtempSync(join2(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep).join("/");writeFileSync(file,"node_modules/\ndist/\n",{flag:"wx",mode:384});pipelineExcludesFile=file}catch{pipelineExcludesFile=""}}return pipelineExcludesFile===""?[]:["-c",`core.excludesFile=${pipelineExcludesFile}`]}__name(pipelineExcludeArgs,"pipelineExcludeArgs");function inPipelineFootprint(rec){const parts=rec.split("/");for(let i=0;i<parts.length-1;i++){if(parts[i]==="node_modules"||parts[i]==="dist")return true;if(parts[i]===".husky"&&parts[i+1]==="_"&&i+1<parts.length-1)return true}return false}__name(inPipelineFootprint,"inPipelineFootprint");function ignoreSourcesOf(cwd,paths,anchor=[]){const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"check-ignore","-z","-v","--stdin"],{cwd,input:`${paths.join("\0")}\0`,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return null}const fields=r.stdout.split("\0");const rules=new Map;for(let i=0;i+3<fields.length;i+=4){rules.set(fields[i+3],{source:fields[i],pattern:fields[i+2]})}return rules}__name(ignoreSourcesOf,"ignoreSourcesOf");function hidesEverything(pattern){const core=pattern.replace(/^\//,"").replace(/\/$/,"");if(core.length===0)return false;const segments=core.split("/");return core.includes("*")&&segments.every(seg=>/^[*?]+$/.test(seg))}__name(hidesEverything,"hidesEverything");function trackedIgnoreSources(cwd,sources,anchor=[]){const inside=[...sources].filter(s=>s.length>0&&!isAbsolute2(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync("git",[...anchor,"ls-files","-z","--",...inside],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return new Set}return new Set(r.stdout.split("\0").filter(p=>p.length>0))}__name(trackedIgnoreSources,"trackedIgnoreSources");var RESIDUE_PATH_CAP=12;function worktreeResidue(cwd,cap=RESIDUE_PATH_CAP,expectedHeadSha){try{if(!lstatSync(join2(cwd,".git")).isFile()){return{paths:[],total:0,unmeasured:".git is not a gitfile (a planted repository?) \u2014 a repo stood up at this path answers a clean status for a dirty tree, and the probe cannot tell the two apart"}}}catch{}const root=mountRootFor(cwd);if(root===null){if(mountNullKind(cwd)==="refused"){return{paths:[],total:0,unmeasured:"the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, and the status below would measure whichever repository the pointer here names"}}}else{const target=resolvedGitDir(cwd);let why;if(target.value!==null){why=untrustedPointer(cwd,target.value,cwd,root)}else{why=target.notARepository?null:"git could not resolve its own git dir"}if(why!==null){return{paths:[],total:0,unmeasured:`the .git gitfile ${why} \u2014 the status below would measure whichever repository it names, and refresh that index through whatever filters it configures`}}}const discover=__name(flag=>{const r2=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(r2.error||r2.status!==0||typeof r2.stdout!=="string"){return null}return r2.stdout.endsWith("\n")?r2.stdout.slice(0,-1):r2.stdout},"discover");const toplevel=discover("--show-toplevel");const gitDir=discover("--git-dir");const commonDir=discover("--git-common-dir");let isWorktree=false;let anchor=[];let filterBlanks={};try{if(toplevel!==null&&gitDir!==null&&commonDir!==null&&realpathSync2(toplevel)===realpathSync2(cwd)){isWorktree=true;if(lstatSync(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve(cwd);const bound=dirname(commonDir);const redirected=redirectedAncestor(dirname(spelled),bound);if(redirected!==null){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${redirected}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}let backpointer=null;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").trim()}catch{}if(backpointer===null){return{paths:[],total:0,unmeasured:"the .git gitfile names a repository with no admin entry for this tree \u2014 a standalone repository answering for this path, whose index the commands below would measure"}}let pointsBack=false;try{pointsBack=realpathSync2(dirname(resolve(gitDir,backpointer)))===realpathSync2(cwd)}catch{}if(!pointsBack){return{paths:[],total:0,unmeasured:"the .git gitfile names an admin entry that does not point back at this tree \u2014 the commands below would measure whichever repository it does name"}}anchor=[`--git-dir=${realpathSync2(gitDir)}`,`--work-tree=${realpathSync2(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync("git",[...anchor,"rev-parse","HEAD"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});const got=head.error||head.status!==0||typeof head.stdout!=="string"?null:head.stdout.trim();if(got===null||got.toLowerCase()!==expectedHeadSha.toLowerCase()){return{paths:[],total:0,unmeasured:got===null?"the pinned identity could not read its own HEAD \u2014 the commands below would have measured a repository git cannot read":`the pinned identity is checked out at ${got}, not the fetched PR head ${expectedHeadSha} \u2014 the gitfile names a repository answering for this path, and its index is what the commands below would measure`}}}const screen=filterCommandsIn(commonDir,realpathSync2(gitDir));const notReadToTheBottom=[...screen.unread,...screen.dangling];if(notReadToTheBottom.length>0){return{paths:[],total:0,unmeasured:`the residue measurement would run under repo-local config this screen could not read to the bottom: ${describeFilterScreen(notReadToTheBottom)} \u2014 a content filter reached that way would execute on the index refresh, and a filter the screen cannot see it cannot blank; remove the include, or the file it names, if it is not yours`}}filterBlanks=filterBlankEnv(screen.filters)}}catch{isWorktree=false}if(!isWorktree){return{paths:[],total:0,unmeasured:"the path is not a git worktree (repository discovery walks up into the enclosing checkout)"}}const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"-c","core.fsmonitor=","-c","core.hooksPath=/dev/null/no-hooks","status","--porcelain","--untracked-files=all","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:{...sanitizedGitEnv(),...filterBlanks}});if(r.error||r.status!==0||typeof r.stdout!=="string"){const why=r.error?r.error.code??r.error.message:`git status exited ${r.status}`;return{paths:[],total:0,unmeasured:why}}const records=r.stdout.split("\0").filter(rec=>rec.length>0);const paths=[];for(let i=0;i<records.length;i++){const rec=records[i];const status=rec.slice(0,2);paths.push(rec.slice(3));if((status.includes("R")||status.includes("C"))&&i+1<records.length){paths.push(records[++i])}}const others=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","--others","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(others.error||others.status!==0||typeof others.stdout!=="string"){const why=others.error?others.error.code??others.error.message:`git ls-files exited ${others.status}`;return{paths:[],total:0,unmeasured:why}}const seen=new Set(paths);const editedFromHead=new Set(paths);const extras=[];for(const rec of others.stdout.split("\0")){if(rec.length===0||seen.has(rec))continue;if(inPipelineFootprint(rec))continue;seen.add(rec);extras.push(rec)}if(extras.length>0){const hiddenBy=ignoreSourcesOf(cwd,extras,anchor);if(hiddenBy===null){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the ignore rules hiding this tree's untracked files could not be attributed, so `git status` cannot be trusted to have seen them"}}const fromTheCommit=trackedIgnoreSources(cwd,new Set([...hiddenBy.values()].map(rule=>rule.source)),anchor);for(const rec of extras){const rule=hiddenBy.get(rec);if(rule!==void 0&&fromTheCommit.has(rule.source)&&!editedFromHead.has(rule.source)&&!hidesEverything(rule.pattern)){continue}paths.push(rec)}}const stage=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-s","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(stage.error||stage.status!==0||typeof stage.stdout!=="string"){const why=stage.error?stage.error.code??stage.error.message:`git ls-files exited ${stage.status}`;return{paths:[],total:0,unmeasured:why}}const blind=stage.stdout.split("\0").filter(rec=>rec.startsWith("160000 ")).map(rec=>rec.slice(rec.indexOf(" ")+1)).filter(gitlink=>{if(gitlink.includes("\uFFFD"))return true;try{return readdirSync2(join2(cwd,gitlink)).length>0}catch(err){return err.code!=="ENOENT"}});if(blind.length>0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"git status cannot see inside the committed submodule path(s) "+blind.join(", ")}}const bits=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-v","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(bits.error||bits.status!==0||typeof bits.stdout!=="string"){const why=bits.error?bits.error.code??bits.error.message:`git ls-files exited ${bits.status}`;return{paths:paths.slice(0,cap),total:paths.length,unmeasured:why}}if(bits.stdout.split("\0").some(rec=>/^[a-zS]/.test(rec))){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the index carries skip-worktree or assume-unchanged bits, so `git status` cannot see edits to the tracked files they cover"}}if(expectedHeadSha===void 0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the caller brought no record of the commit this tree must hold, and a status measured through an unanchored identity would certify whichever index the .git gitfile names \u2014 a forged pair answers clean \u2014 so the measurement is refused rather than certified"}}return{paths:paths.slice(0,cap),total:paths.length}}__name(worktreeResidue,"worktreeResidue");function exposeDependencies(probeTree,dependencyRoot,opts={}){const done={linked:0,failed:0,alreadyPresent:false,selfLinked:0};if(probeTree===dependencyRoot)return done;let members=[];try{const graph=readWorkspacePackages(dependencyRoot);members=[...graph.packages.map(p=>p.dir),...graph.skipped]}catch{}const memberSources=members.map(dir=>({dir,source:containedIn(dependencyRoot,dir)})).filter(m=>{if(m.source===null)return true;try{return realpathSync2(m.source)!==realpathSync2(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join2(dependencyRoot,"node_modules");if(lstatSync(nm).isDirectory())rootNm=realpathSync2(nm)}catch{}const containment={rootNm,selfLinks:new Set(memberSources.flatMap(m=>m.source===null?[]:[m.source]))};farmNodeModules(dependencyRoot,probeTree,done,containment,opts.rebuild===true);const owned=new Set([join2(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync2(join2(dependencyRoot,dir)))done.failed++;continue}if(!existsSync2(target))continue;owned.add(join2(target,"node_modules"));try{farmNodeModules(source,target,done,containment,opts.rebuild===true)}catch{done.failed++}}if(opts.rebuild===true){for(const path of[...owned]){try{owned.add(realpathSync2(path))}catch{}}removeUnownedNodeModules(probeTree,owned,done)}return done}__name(exposeDependencies,"exposeDependencies");function removeUnownedNodeModules(tree,owned,done){const inTreeLinks=[];const walk=__name(dir=>{let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync2(full);const root=realpathSync2(tree);if(!statSync2(full).isDirectory()){}else if(real===root||real.startsWith(root+sep)){inTreeLinks.push(real)}else{done.failed++}}catch{}continue}if(!entry.isDirectory())continue;walk(full)}},"walk");walk(tree);for(const real of inTreeLinks){if(isOwned(owned,real))continue;if(holdsNodeModules(real,owned))done.failed++}}__name(removeUnownedNodeModules,"removeUnownedNodeModules");function isOwned(owned,path){if(owned.has(path))return true;try{return owned.has(realpathSync2(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full))return true;continue}if(entry.isSymbolicLink()||!entry.isDirectory())continue;if(entry.name===".git")continue;if(holdsNodeModules(full,owned))return true}return false}__name(holdsNodeModules,"holdsNodeModules");function containedIn(root,dir){try{const base=realpathSync2(resolve(root));const full=resolve(base,dir);const real=existsSync2(full)?realpathSync2(full):full;return real===base||real.startsWith(base+sep)?real:null}catch{return null}}__name(containedIn,"containedIn");var FARM_MARKER=".qwen-review-farm";function farmLinkVerdict(real,sourceNm,containment){if(insideDir(sourceNm,real))return"internal";if(containment.rootNm!==null&&insideDir(containment.rootNm,real)){return"internal"}for(const member of containment.selfLinks){if(insideDir(member,real))return"self"}return null}__name(farmLinkVerdict,"farmLinkVerdict");function insideDir(base,real){return real===base||real.startsWith(base+sep)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join2(target,FARM_MARKER),"utf8").trim()===resolve(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join2(sourceDir,"node_modules");const target=join2(targetDir,"node_modules");if(!existsSync2(source)){if(rebuild){try{lstatSync(target);rmSync(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync2(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync2(source,{withFileTypes:true})}catch{done.failed++;return}const before=done.linked;for(const entry of entries){if(entry.name===".vite"||entry.name===".vite-temp")continue;const sourceEntry=join2(source,entry.name);const targetEntry=join2(target,entry.name);let sourceStats;try{sourceStats=lstatSync(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync2(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync(targetEntry);pkgs=readdirSync2(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join2(sourceEntry,pkg);let real;try{real=realpathSync2(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join2(targetEntry,pkg),linkType);done.linked++}catch{done.failed++}}}else{try{symlinkSync(sourceEntry,targetEntry,linkType);done.linked++}catch{done.failed++}}}if(done.linked>before){try{writeFileSync(join2(target,FARM_MARKER),`${resolve(sourceDir)}
3
+ import{sanitizeFilenameComponent}from"./chunk-PFKTTUGS.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getProjectHash,isSubpath}from"./chunk-2ZK2FGZQ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function safeTarget(target){if(/^[A-Za-z0-9._-]{55}~[0-9a-f]{8}$/.test(target))return target;const flat=target.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_");const stem=flat.replace(/^[._]+/,"")||"target";if(stem.length<=SAFE_TARGET_MAX)return stem;return`${stem.slice(0,SAFE_TARGET_MAX-9)}~${createHash("sha256").update(stem).digest("hex").slice(0,8)}`}__name(safeTarget,"safeTarget");var SAFE_TARGET_MAX=64;init_esbuild_shims();var CONTROL=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;var NEEDS_PRE_ESCAPE=/[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;function inertText(value,maxChars=200){const clipped=value.length>maxChars?value.slice(0,maxChars):value;const rendered=CONTROL.test(clipped)?JSON.stringify(clipped.replace(NEEDS_PRE_ESCAPE,c=>{const hex=c.codePointAt(0).toString(16).padStart(4,"0");return`\\u${hex}`})):clipped;return clipped.length<value.length?`${rendered}\u2026`:rendered}__name(inertText,"inertText");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,readdirSync as readdirSync3,realpathSync as realpathSync4,statSync as statSync3}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute3,join as join3,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";init_esbuild_shims();import{execFileSync,spawnSync as spawnSync2}from"node:child_process";init_esbuild_shims();import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,lstatSync,mkdirSync,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,rmSync,statSync as statSync2,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname,isAbsolute as isAbsolute2,join as join2,resolve,sep}from"node:path";init_esbuild_shims();import{existsSync,readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";init_esbuild_shims();var MAX_OLD_SPACE_FLAG="--max[-_]old[-_]space[-_]size";var HEAP_TOKEN_RE=new RegExp(`(?:^|\\s)${MAX_OLD_SPACE_FLAG}(?:=(\\d*)|\\s+(\\d+))?(?=\\s|$)`,"g");function heapFlagMb(options){let mb;for(const m of options.matchAll(HEAP_TOKEN_RE)){const value=m[1]||m[2];if(value)mb=Number(value)}return mb}__name(heapFlagMb,"heapFlagMb");function withoutHeapFlag(options){return options.replace(HEAP_TOKEN_RE,"").trim()}__name(withoutHeapFlag,"withoutHeapFlag");function raiseHeap(options,mb){if((heapFlagMb(options)??0)>=mb)return void 0;return`${withoutHeapFlag(options)} --max-old-space-size=${mb}`.trim()}__name(raiseHeap,"raiseHeap");var NPM_ENV_REF_RE=/(?<!\\)(\\*)\$\{([^${}]+)\}/g;function raiseNpmHeap(options,mb){return raiseHeap(options,mb)?.replace(NPM_ENV_REF_RE,(_,esc,name)=>`${esc}${esc}\\\${${name}}`)}__name(raiseNpmHeap,"raiseNpmHeap");var HEAP_BANNER_RE=/^FATAL ERROR: [^\n]*JavaScript heap out of memory/m;function heapBannerIn(raw){return HEAP_BANNER_RE.test(raw)}__name(heapBannerIn,"heapBannerIn");function ranOutOfHeap(r){return r.exitCode!==0&&(r.heapExhausted??heapBannerIn(r.output))}__name(ranOutOfHeap,"ranOutOfHeap");function killedFromOutside(r){return!r.timedOut&&r.spawnError===void 0&&(r.exitCode===137||r.exitCode===null&&r.signal==="SIGKILL")}__name(killedFromOutside,"killedFromOutside");init_esbuild_shims();function stripComments(src){return src.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,m=>m.startsWith("/")?" ":m)}__name(stripComments,"stripComments");function isWorkspaceMember(filePath,workspaceGlobs){return workspaceDirFor(filePath,workspaceGlobs)!==null}__name(isWorkspaceMember,"isWorkspaceMember");function workspaceDirFor(filePath,workspaceGlobs){const norm=filePath.replace(/^\.\//,"");let owner=null;const previous=[];for(const glob of workspaceGlobs){const negated=glob.startsWith("!");const g=glob.replace(/^!/,"").replace(/^\.\//,"").replace(/\/$/,"");let dir=null;if(g.endsWith("/*")){const base=g.slice(0,-2);if(norm.startsWith(`${base}/`)){const seg=norm.slice(base.length+1).split("/")[0];if(seg)dir=`${base}/${seg}`}}else if(norm===g||norm.startsWith(`${g}/`)){dir=g}if(dir===null)continue;if(!negated){if(dir!==owner){previous.push(owner);owner=dir}}else if(dir===owner){owner=previous.pop()??null}}return owner}__name(workspaceDirFor,"workspaceDirFor");function isNegationExcluded(filePath,workspaceGlobs){if(workspaceDirFor(filePath,workspaceGlobs)!==null)return false;const positives=workspaceGlobs.filter(g=>!g.startsWith("!"));return workspaceDirFor(filePath,positives)!==null}__name(isNegationExcluded,"isNegationExcluded");function hasUnmodeledWorkspaceGlob(globs){return globs.some(glob=>{const g=glob.replace(/^!/,"").replace(/^\.\//,"");if(!g.includes("*"))return false;return!/^[^*]+\/\*$/.test(g)})}__name(hasUnmodeledWorkspaceGlob,"hasUnmodeledWorkspaceGlob");function readWorkspaceGlobs(root){try{const pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const ws=pkg.workspaces;const globs=Array.isArray(ws)?ws:Array.isArray(ws?.packages)?ws.packages:[];return globs.filter(g=>typeof g==="string")}catch{return[]}}__name(readWorkspaceGlobs,"readWorkspaceGlobs");function readRootPackage(root){let pkg;try{pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"))}catch{return null}if(pkg===null)return null;const scripts=Object.keys(pkg.scripts??{});if(!scripts.includes("build")&&!scripts.includes("test"))return null;const scriptsText={};for(const[k,v]of Object.entries(pkg.scripts??{})){if(typeof v==="string")scriptsText[k]=v}return{dir:".",name:typeof pkg.name==="string"&&pkg.name?pkg.name:"root",scripts,deps:declaredDeps(pkg),scriptsText}}__name(readRootPackage,"readRootPackage");function scriptFansOut(text){return typeof text==="string"&&(/(^|\s)(--workspaces|--?ws)(?=[\s'"`]|$)/.test(text)||/\bpnpm\s+(-r|--recursive)(?=[\s'"`]|$)/.test(text))}__name(scriptFansOut,"scriptFansOut");var COMMAND_SEPARATOR_RE=/[;&|\n]+/;function chainsCommands(text){return text.split(COMMAND_SEPARATOR_RE).filter(c=>c.trim()!=="").length>1}__name(chainsCommands,"chainsCommands");var NODE_VALUE_FLAGS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--env-file-if-exists","--input-type","--title","--redirect-warnings","--watch-path","--diagnostic-dir","--report-dir","--cpu-prof-dir","--heap-prof-dir","--icu-data-dir","--openssl-config"]);var SCRIPT_RUNNERS=new Set(["node","tsx"]);var NODE_INLINE_FLAGS=new Set(["-e","--eval","-p","--print","-"]);function nodeScripts(text){const files=[];for(const command of text.split(COMMAND_SEPARATOR_RE)){const words=command.trim().split(/\s+/);const runner=words.findIndex(w=>SCRIPT_RUNNERS.has(w));for(let i=runner+1;i>0&&i<words.length;i++){const word=words[i];if(NODE_INLINE_FLAGS.has(word))break;if(word.startsWith("-")){if(NODE_VALUE_FLAGS.has(word))i++;continue}if(/^[\w@./-]+\.[cm]?[jt]s$/.test(word))files.push(word);break}}return files}__name(nodeScripts,"nodeScripts");function childProcessCommands(src){const commands=[];for(const m of stripComments(src).matchAll(/\b(?:exec|execSync|execFile|execFileSync|spawn|spawnSync)\s*\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g)){commands.push(m[1].slice(1,-1))}return commands}__name(childProcessCommands,"childProcessCommands");var MAX_HAND_OFF_SCRIPT_BYTES=1024*1024;function rootBuildFanOutScript(root,text){if(typeof text!=="string")return void 0;for(const file of nodeScripts(text)){try{const path=realpathSync(join(root,file));const inRoot=relative(realpathSync(root),path);if(inRoot.startsWith("..")||isAbsolute(inRoot))continue;const stat=statSync(path);if(!stat.isFile()||stat.size>MAX_HAND_OFF_SCRIPT_BYTES)continue;if(childProcessCommands(readFileSync(path,"utf8")).some(scriptFansOut))return file}catch{}}return void 0}__name(rootBuildFanOutScript,"rootBuildFanOutScript");function declaredBuildHeapMb(root){const text=readRootPackage(root)?.scriptsText["build"];if(typeof text!=="string")return void 0;let declared;for(const m of text.matchAll(/\bNODE_OPTIONS=(?:"([^"]*)"|'([^']*)'|(\S*))/g)){const mb=heapFlagMb(m[1]??m[2]??m[3]??"");if(mb!==void 0)declared=Math.max(declared??0,mb)}return declared}__name(declaredBuildHeapMb,"declaredBuildHeapMb");function declaredDeps(pkg){return[...Object.keys(pkg.dependencies??{}),...Object.keys(pkg.devDependencies??{}),...Object.keys(pkg.peerDependencies??{}),...Object.keys(pkg.optionalDependencies??{})]}__name(declaredDeps,"declaredDeps");function workspaceDirCandidates(root,globs){const dirs=new Set;for(const glob of globs){if(glob.startsWith("!"))continue;const g=glob.replace(/^\.\//,"").replace(/\/$/,"");if(g.endsWith("/*")){const base=g.slice(0,-2);let entries;try{entries=readdirSync(join(root,base),{withFileTypes:true}).filter(e=>e.isDirectory()||e.isSymbolicLink()&&existsSync(join(root,base,e.name,"package.json"))).map(e=>e.name)}catch{continue}for(const e of entries)dirs.add(`${base}/${e}`)}else{dirs.add(g)}}return[...dirs].sort()}__name(workspaceDirCandidates,"workspaceDirCandidates");function readWorkspacePackages(root){const globs=readWorkspaceGlobs(root);const packages=[];const skipped=[];for(const dir of workspaceDirCandidates(root,globs)){const manifest=join(root,dir,"package.json");if(!existsSync(manifest))continue;if(workspaceDirFor(`${dir}/package.json`,globs)!==dir){const positives=globs.filter(g=>!g.startsWith("!"));if(workspaceDirFor(`${dir}/package.json`,positives)===dir)continue;skipped.push(dir);continue}let pkg;try{pkg=JSON.parse(readFileSync(manifest,"utf8"))}catch{skipped.push(dir);continue}if(pkg===null||typeof pkg.name!=="string"||!pkg.name){skipped.push(dir);continue}packages.push({dir,name:pkg.name,scripts:Object.keys(pkg.scripts??{}),deps:declaredDeps(pkg)})}packages.sort((a,b)=>a.dir.localeCompare(b.dir));skipped.sort();return{packages,skipped}}__name(readWorkspacePackages,"readWorkspacePackages");function affectedWorkspaces(changedFiles,workspaceGlobs){const dirs=new Set;for(const f of changedFiles){const d=workspaceDirFor(f,workspaceGlobs);if(d)dirs.add(d)}return[...dirs].sort()}__name(affectedWorkspaces,"affectedWorkspaces");function dependencyEdges(packages){const byName=new Map;for(const p of packages){if(p.dir!=="."||!byName.has(p.name))byName.set(p.name,p)}const dependsOn=new Map;for(const p of packages){dependsOn.set(p.dir,p.deps.map(d=>byName.get(d)?.dir).filter(d=>!!d&&d!==p.dir))}return dependsOn}__name(dependencyEdges,"dependencyEdges");function dependencyClosure(dirs,packages){const dependsOn=dependencyEdges(packages);const closure=new Set;const add=__name(dir=>{if(closure.has(dir))return;closure.add(dir);for(const d of dependsOn.get(dir)??[])add(d)},"add");dirs.forEach(add);return[...closure].sort()}__name(dependencyClosure,"dependencyClosure");function reverseDependencyClosure(affected,packages){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=new Set(affected.filter(a=>byDir.has(a)));let grew=true;while(grew){grew=false;for(const p of packages){if(consumers.has(p.dir))continue;if((dependsOn.get(p.dir)??[]).some(d=>consumers.has(d))){consumers.add(p.dir);grew=true}}}return[...consumers].sort()}__name(reverseDependencyClosure,"reverseDependencyClosure");function buildSetFor(affected,packages,alsoBuild=[]){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=reverseDependencyClosure(affected,packages);const wanted=new Set;const addDeps=__name(dir=>{if(wanted.has(dir))return;wanted.add(dir);for(const d of dependsOn.get(dir)??[])addDeps(d)},"addDeps");for(const c of consumers)addDeps(c);for(const extra of alsoBuild)if(byDir.has(extra))addDeps(extra);const order=[];const seen=new Set;const visit=__name(dir=>{if(seen.has(dir))return;seen.add(dir);for(const d of dependsOn.get(dir)??[]){if(wanted.has(d))visit(d)}order.push(dir)},"visit");for(const dir of alsoBuild.filter(d=>wanted.has(d)).sort())visit(dir);for(const dir of[...wanted].sort())visit(dir);return order}__name(buildSetFor,"buildSetFor");var GIT_ENV_REDIRECTS=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_COMMON_DIR"];var GIT_ENV_CONFIG=["GIT_CONFIG_COUNT","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_PARAMETERS","GIT_DEFAULT_HASH"];var GIT_ENV_EXEC=["GIT_SSH_COMMAND","GIT_SSH","GIT_EXEC_PATH","GIT_TEMPLATE_DIR","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_EDITOR","GIT_SEQUENCE_EDITOR","GIT_EXTERNAL_DIFF","XDG_CONFIG_HOME"];function mountRootFor(cwd){return mountRootVerdict(cwd).root}__name(mountRootFor,"mountRootFor");function mountNullKind(cwd){return mountRootVerdict(cwd).nullKind??"refused"}__name(mountNullKind,"mountNullKind");function mountRootVerdict(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).lastIndexOf(marker);if(at<0)return{root:null,nullKind:"outside"};const root=resolved.slice(0,at+marker.length-1);const outermost=outermostReviewTmpRoot(root);const bound=outermost===root?resolve(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync2(root);if(unmountableRootSpelling(real)){return{root:null,nullKind:"unmountable"}}return{root:real,nullKind:null}}catch{return{root:null,nullKind:"refused"}}}__name(mountRootVerdict,"mountRootVerdict");function unmountableRootSpelling(root){return root.includes(":")||root.startsWith("\\\\")}__name(unmountableRootSpelling,"unmountableRootSpelling");function insideReviewTmpLexically(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;return(resolved+sep).lastIndexOf(marker)>=0}__name(insideReviewTmpLexically,"insideReviewTmpLexically");function resolvedGitDir(cwd){return revParse(cwd,"--absolute-git-dir")}__name(resolvedGitDir,"resolvedGitDir");function resolvedCommonDir(cwd){return revParse(cwd,"--path-format=absolute","--git-common-dir")}__name(resolvedCommonDir,"resolvedCommonDir");function revParse(cwd,...flags){const resolved=spawnSync("git",["-c","core.hooksPath=/dev/null/no-hooks","-c","core.fsmonitor=","rev-parse",...flags],{cwd,encoding:"utf8",timeout:3e4,env:{...sanitizedGitEnv(),LC_ALL:"C"}});const value=resolved.error||resolved.status!==0||!resolved.stdout?null:resolved.stdout.replace(/\n$/,"");return{value:value!==null&&value.includes("\uFFFD")?null:value,notARepository:resolved.status===128&&resolved.stderr.includes("not a git repository")}}__name(revParse,"revParse");function untrustedPointer(dir,gitDir,expectedOwner,root){if(adminEntryInsideReviewTmp(gitDir,root,dir)){return"resolves to an admin entry inside the review temp dir, where the reviewed code can rewrite it"}const common=resolvedCommonDir(dir);if(common.value===null&&!common.notARepository){return"git could not resolve its own common dir from this tree, so whether the pointer names the main repository instead of a linked worktree's admin entry is unknown"}if(common.value!==null&&common.value===gitDir){return"resolves to the repository's own common dir rather than a linked worktree's admin entry, so every command through it acts on the main repository instead of this tree"}let backpointer;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname(resolve(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync2(ownerSpelled)}catch{ownerTree=null}const writableRoot=outermostReviewTmpRoot(root);if(ownerSpelled===writableRoot||isSubpath(writableRoot,ownerSpelled)){const redirect=redirectedAncestor(ownerSpelled,writableRoot);if(redirect!==null){return`resolves to a different tree's admin entry \u2014 the owner its gitdir backpointer names resolves through a symlink inside the review temp dir (${redirect}), so the round trip would agree with whatever the link points at`}}let expectedReal;try{expectedReal=realpathSync2(expectedOwner)}catch{return"could not resolve the tree the entry must belong to"}if(ownerTree===null){return"resolves to an admin entry that does not point back at this tree \u2014 the owner its backpointer names cannot be resolved, so the commands this gates would measure whichever repository it does name"}if(ownerTree!==expectedReal){return"resolves to a different tree's admin entry \u2014 its gitdir backpointer names that tree, not this one, so every command through it would measure and mutate the tree it actually belongs to"}return null}__name(untrustedPointer,"untrustedPointer");function untrustedRepositoryFrom(cwd,mountRoot=mountRootFor){const root=mountRoot(cwd);if(root===null){if(mountNullKind(cwd)!=="refused")return null;return`${cwd}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command run from here would land is unmeasured`}if(!existsSync2(cwd)){if(!insideReviewTmpLexically(cwd))return null;return`${cwd}: no directory exists at this spelling inside the review temp dir \u2014 an ancestor was renamed out from under it, so where a command run from here would land is unmeasured`}const target=resolvedGitDir(cwd);if(target.value===null){return target.notARepository?null:`${cwd}: git could not resolve its own git dir, so where a command run from here would land is unmeasured`}const toplevel=revParse(cwd,"--show-toplevel");if(toplevel.value===null){return`${cwd}: git could not resolve its own top-level directory, so where a command run from here would land is unmeasured`}const why=untrustedPointer(cwd,target.value,toplevel.value,root);return why===null?null:`${cwd} ${why}`}__name(untrustedRepositoryFrom,"untrustedRepositoryFrom");function untrustedGitfile(tree,mountRoot=mountRootFor){if(!existsSync2(tree))return null;const root=mountRoot(tree);if(root===null){if(mountNullKind(tree)!=="refused")return null;return`${tree}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command through its .git would land is unmeasured`}const dotGit=join2(tree,".git");let stat;try{stat=lstatSync(dotGit)}catch{return`${tree} has no .git to resolve`}if(!stat.isFile()){return`${tree}'s .git is not the gitfile the pipeline created, and the tree is inside the review temp dir`}const target=resolvedGitDir(tree);if(target.value===null){return`${tree}: git could not resolve its own git dir`}const why=untrustedPointer(tree,target.value,tree,root);return why===null?null:`${tree} ${why}`}__name(untrustedGitfile,"untrustedGitfile");function adminEntryInsideReviewTmp(gitDir,root,tree){if(root===null)return mountNullKind(tree)==="refused";let real;let realRoot;try{const canonical=realpathSync2.native??realpathSync2;real=canonical(resolve(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=root.indexOf(marker);return at<0?root:root.slice(0,at+marker.length-1)}__name(outermostReviewTmpRoot,"outermostReviewTmpRoot");function redirectedAncestor(dir,stopAt=process.cwd()){try{const stop=resolve(stopAt);let stopReal=stop;try{stopReal=realpathSync2(stopAt)}catch{}for(let cur=resolve(dir);;cur=dirname(cur)){let isLink;try{isLink=lstatSync(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync2(cur)===stopReal)return null}catch{}if(dirname(cur)===cur)return null}}catch{return null}}__name(redirectedAncestor,"redirectedAncestor");function sanitizedGitEnv(){const env={...process.env};const drop=new Set([...GIT_ENV_REDIRECTS,...GIT_ENV_CONFIG,...GIT_ENV_EXEC].map(k=>k.toLowerCase()));for(const key of Object.keys(env)){const lower=key.toLowerCase();if(drop.has(lower)||/^git_config_(key|value)_\d+$/.test(lower)){delete env[key]}}env["GIT_NO_REPLACE_OBJECTS"]="1";env["GIT_GRAFT_FILE"]="/dev/null/grafts";return env}__name(sanitizedGitEnv,"sanitizedGitEnv");var MAX_INCLUDE_DEPTH=10;var MAX_INCLUDE_FILES=64;var FILTER_SCREEN_NAMED=12;var SCREEN_KEYS="^filter\\..*\\.(smudge|clean|process)$|^include\\.path$|^includeif\\..*\\.path$";function filterCommandsIn(commonDir,gitDir){const candidates=[join2(commonDir,"config"),join2(gitDir,"config.worktree")];try{for(const entry of readdirSync2(join2(commonDir,"worktrees"))){candidates.push(join2(commonDir,"worktrees",entry,"config.worktree"))}}catch{}const filters=new Set;const unread=new Set;const dangling=new Set;const visited=new Set;const read=__name(file=>{const r=spawnSync("git",["config","--file",file,"-z","--get-regexp",SCREEN_KEYS],{cwd:commonDir,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error){return{unreadable:r.error.code??r.error.message}}if(r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return{unreadable:`git config exited ${r.status}`}}const records=[];for(const rec of r.stdout.split("\0")){if(!rec)continue;const nl=rec.indexOf("\n");records.push(nl===-1?[rec,""]:[rec.slice(0,nl),rec.slice(nl+1)])}return{records}},"read");const visit=__name((file,depth,via)=>{let real;try{real=realpathSync2.native(file)}catch(e){if(via!==null){const code=e?.code;if(code==="ENOENT"){dangling.add(`${via} -> ${file} (missing \u2014 git ignores it)`)}else{unread.add(`${via} -> ${file} (could not be resolved: ${code??"unknown"} \u2014 not screened)`)}}return}if(visited.has(real))return;if(visited.size>=MAX_INCLUDE_FILES){unread.add(`${via??file} -> ${file} (include fan-out past ${MAX_INCLUDE_FILES} files \u2014 not screened)`);return}visited.add(real);try{if(!statSync2(real).isFile()){unread.add(`${via??file} -> ${file} (not a regular file \u2014 not screened)`);return}accessSync(real,constants.R_OK)}catch{unread.add(`${via??file} -> ${file} (could not be read)`);return}if(depth>MAX_INCLUDE_DEPTH){unread.add(`${via} -> ${file} (nested past git's include limit \u2014 not screened)`);return}const r=read(file);if("unreadable"in r){unread.add(`${file} (could not be read: ${r.unreadable})`);return}for(const[key,value]of r.records){if(key.startsWith("filter.")){filters.add(key);continue}let target;if(value.startsWith("~/")){target=`${process.env["HOME"]||homedir()}${sep}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute2(value)?value:`${dirname(file)}${sep}${value}`}visit(target,depth+1,`${key} (in ${file})`)}},"visit");for(const candidate of candidates)visit(candidate,0,null);return{filters:[...filters],unread:[...unread],dangling:[...dangling]}}__name(filterCommandsIn,"filterCommandsIn");function describeFilterScreen(hits){const named=hits.slice(0,FILTER_SCREEN_NAMED);const rest=hits.length-named.length;return rest>0?`${named.join(", ")}, and ${rest} more`:named.join(", ")}__name(describeFilterScreen,"describeFilterScreen");function filterBlankEnv(filterKeys){const names=new Set;for(const key of filterKeys){const m=/^filter\.(.+)\.(?:smudge|clean|process)$/.exec(key);if(m)names.add(m[1])}const env={};let n=0;for(const name of names){for(const[key,value]of[["clean",""],["smudge",""],["process",""],["required","false"]]){env[`GIT_CONFIG_KEY_${n}`]=`filter.${name}.${key}`;env[`GIT_CONFIG_VALUE_${n}`]=value;n++}}if(n>0)env["GIT_CONFIG_COUNT"]=String(n);return env}__name(filterBlankEnv,"filterBlankEnv");var UNRESOLVED_REPO="the repository's git directories could not be resolved (git rev-parse failed) \u2014 not screened";function screenForTree(worktree){const discover=__name(flag=>{const r=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return null}return r.stdout.endsWith("\n")?r.stdout.slice(0,-1):r.stdout},"discover");const commonDir=discover("--git-common-dir");const gitDir=discover("--git-dir");if(commonDir===null||gitDir===null)return null;return filterCommandsIn(commonDir,gitDir)}__name(screenForTree,"screenForTree");function localFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread,...screen.dangling]}__name(localFilterCommands,"localFilterCommands");function filterScreenForTree(worktree){return screenForTree(worktree)}__name(filterScreenForTree,"filterScreenForTree");function resolvedContentTransformForTree(worktree){const r=spawnSync("git",["config","--get-regexp","^filter\\..*\\.(smudge|clean|process)$|^core\\.(autocrlf|eol)$"],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.status!==0||typeof r.stdout!=="string")return false;for(const line of r.stdout.split("\n")){const space=line.indexOf(" ");const key=(space===-1?line:line.slice(0,space)).toLowerCase();const value=space===-1?"true":line.slice(space+1).trim().toLowerCase();if(key.startsWith("filter."))return true;if(key==="core.autocrlf"&&(value==="true"||value==="input")){return true}if(key==="core.eol"&&(value==="crlf"||value==="native"&&process.platform==="win32")){return true}}return false}__name(resolvedContentTransformForTree,"resolvedContentTransformForTree");function checkoutFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread]}__name(checkoutFilterCommands,"checkoutFilterCommands");function discardWorktree(cwd,tree){let symlink=false;try{symlink=lstatSync(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync(tree,{recursive:true,force:true});dropWorktreeRegistration(cwd,tree,ownAdminDir);if(sweep!==void 0&&sweep.status!==0){dropWorktreeRegistration(cwd,tree,null)}return sweep}__name(discardWorktree,"discardWorktree");function dropWorktreeRegistration(cwd,tree,adminDir){if(adminDir!==null){try{rmSync(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(common.status!==0||typeof common.stdout!=="string")return;const dir=join2(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync2(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join2(dir,id,"gitdir"),"utf8").trim();const named=dirname(gitdir);if(samePath(named)!==wanted)continue;if(existsSync2(named))continue;rmSync(join2(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join2(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve(dirname(resolve(tree)),match[1].trim());const back=readFileSync2(join2(dir,"gitdir"),"utf8").trim();return samePath(dirname(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve(p);try{return join2(realpathSync2(dirname(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join2(mkdtempSync(join2(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep).join("/");writeFileSync(file,"node_modules/\ndist/\n",{flag:"wx",mode:384});pipelineExcludesFile=file}catch{pipelineExcludesFile=""}}return pipelineExcludesFile===""?[]:["-c",`core.excludesFile=${pipelineExcludesFile}`]}__name(pipelineExcludeArgs,"pipelineExcludeArgs");function inPipelineFootprint(rec){const parts=rec.split("/");for(let i=0;i<parts.length-1;i++){if(parts[i]==="node_modules"||parts[i]==="dist")return true;if(parts[i]===".husky"&&parts[i+1]==="_"&&i+1<parts.length-1)return true}return false}__name(inPipelineFootprint,"inPipelineFootprint");function ignoreSourcesOf(cwd,paths,anchor=[]){const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"check-ignore","-z","-v","--stdin"],{cwd,input:`${paths.join("\0")}\0`,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return null}const fields=r.stdout.split("\0");const rules=new Map;for(let i=0;i+3<fields.length;i+=4){rules.set(fields[i+3],{source:fields[i],pattern:fields[i+2]})}return rules}__name(ignoreSourcesOf,"ignoreSourcesOf");function hidesEverything(pattern){const core=pattern.replace(/^\//,"").replace(/\/$/,"");if(core.length===0)return false;const segments=core.split("/");return core.includes("*")&&segments.every(seg=>/^[*?]+$/.test(seg))}__name(hidesEverything,"hidesEverything");function trackedIgnoreSources(cwd,sources,anchor=[]){const inside=[...sources].filter(s=>s.length>0&&!isAbsolute2(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync("git",[...anchor,"ls-files","-z","--",...inside],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return new Set}return new Set(r.stdout.split("\0").filter(p=>p.length>0))}__name(trackedIgnoreSources,"trackedIgnoreSources");var RESIDUE_PATH_CAP=12;function worktreeResidue(cwd,cap=RESIDUE_PATH_CAP,expectedHeadSha){try{if(!lstatSync(join2(cwd,".git")).isFile()){return{paths:[],total:0,unmeasured:".git is not a gitfile (a planted repository?) \u2014 a repo stood up at this path answers a clean status for a dirty tree, and the probe cannot tell the two apart"}}}catch{}const root=mountRootFor(cwd);if(root===null){if(mountNullKind(cwd)==="refused"){return{paths:[],total:0,unmeasured:"the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, and the status below would measure whichever repository the pointer here names"}}}else{const target=resolvedGitDir(cwd);let why;if(target.value!==null){why=untrustedPointer(cwd,target.value,cwd,root)}else{why=target.notARepository?null:"git could not resolve its own git dir"}if(why!==null){return{paths:[],total:0,unmeasured:`the .git gitfile ${why} \u2014 the status below would measure whichever repository it names, and refresh that index through whatever filters it configures`}}}const discover=__name(flag=>{const r2=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(r2.error||r2.status!==0||typeof r2.stdout!=="string"){return null}return r2.stdout.endsWith("\n")?r2.stdout.slice(0,-1):r2.stdout},"discover");const toplevel=discover("--show-toplevel");const gitDir=discover("--git-dir");const commonDir=discover("--git-common-dir");let isWorktree=false;let anchor=[];let filterBlanks={};try{if(toplevel!==null&&gitDir!==null&&commonDir!==null&&realpathSync2(toplevel)===realpathSync2(cwd)){isWorktree=true;if(lstatSync(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve(cwd);const bound=dirname(commonDir);const redirected=redirectedAncestor(dirname(spelled),bound);if(redirected!==null){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${redirected}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}let backpointer=null;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").trim()}catch{}if(backpointer===null){return{paths:[],total:0,unmeasured:"the .git gitfile names a repository with no admin entry for this tree \u2014 a standalone repository answering for this path, whose index the commands below would measure"}}let pointsBack=false;try{pointsBack=realpathSync2(dirname(resolve(gitDir,backpointer)))===realpathSync2(cwd)}catch{}if(!pointsBack){return{paths:[],total:0,unmeasured:"the .git gitfile names an admin entry that does not point back at this tree \u2014 the commands below would measure whichever repository it does name"}}anchor=[`--git-dir=${realpathSync2(gitDir)}`,`--work-tree=${realpathSync2(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync("git",[...anchor,"rev-parse","HEAD"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});const got=head.error||head.status!==0||typeof head.stdout!=="string"?null:head.stdout.trim();if(got===null||got.toLowerCase()!==expectedHeadSha.toLowerCase()){return{paths:[],total:0,unmeasured:got===null?"the pinned identity could not read its own HEAD \u2014 the commands below would have measured a repository git cannot read":`the pinned identity is checked out at ${got}, not the fetched PR head ${expectedHeadSha} \u2014 the gitfile names a repository answering for this path, and its index is what the commands below would measure`}}}const screen=filterCommandsIn(commonDir,realpathSync2(gitDir));const notReadToTheBottom=[...screen.unread,...screen.dangling];if(notReadToTheBottom.length>0){return{paths:[],total:0,unmeasured:`the residue measurement would run under repo-local config this screen could not read to the bottom: ${describeFilterScreen(notReadToTheBottom)} \u2014 a content filter reached that way would execute on the index refresh, and a filter the screen cannot see it cannot blank; remove the include, or the file it names, if it is not yours`}}filterBlanks=filterBlankEnv(screen.filters)}}catch{isWorktree=false}if(!isWorktree){return{paths:[],total:0,unmeasured:"the path is not a git worktree (repository discovery walks up into the enclosing checkout)"}}const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"-c","core.fsmonitor=","-c","core.hooksPath=/dev/null/no-hooks","status","--porcelain","--untracked-files=all","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:{...sanitizedGitEnv(),...filterBlanks}});if(r.error||r.status!==0||typeof r.stdout!=="string"){const why=r.error?r.error.code??r.error.message:`git status exited ${r.status}`;return{paths:[],total:0,unmeasured:why}}const records=r.stdout.split("\0").filter(rec=>rec.length>0);const paths=[];for(let i=0;i<records.length;i++){const rec=records[i];const status=rec.slice(0,2);paths.push(rec.slice(3));if((status.includes("R")||status.includes("C"))&&i+1<records.length){paths.push(records[++i])}}const others=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","--others","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(others.error||others.status!==0||typeof others.stdout!=="string"){const why=others.error?others.error.code??others.error.message:`git ls-files exited ${others.status}`;return{paths:[],total:0,unmeasured:why}}const seen=new Set(paths);const editedFromHead=new Set(paths);const extras=[];for(const rec of others.stdout.split("\0")){if(rec.length===0||seen.has(rec))continue;if(inPipelineFootprint(rec))continue;seen.add(rec);extras.push(rec)}if(extras.length>0){const hiddenBy=ignoreSourcesOf(cwd,extras,anchor);if(hiddenBy===null){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the ignore rules hiding this tree's untracked files could not be attributed, so `git status` cannot be trusted to have seen them"}}const fromTheCommit=trackedIgnoreSources(cwd,new Set([...hiddenBy.values()].map(rule=>rule.source)),anchor);for(const rec of extras){const rule=hiddenBy.get(rec);if(rule!==void 0&&fromTheCommit.has(rule.source)&&!editedFromHead.has(rule.source)&&!hidesEverything(rule.pattern)){continue}paths.push(rec)}}const stage=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-s","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(stage.error||stage.status!==0||typeof stage.stdout!=="string"){const why=stage.error?stage.error.code??stage.error.message:`git ls-files exited ${stage.status}`;return{paths:[],total:0,unmeasured:why}}const blind=stage.stdout.split("\0").filter(rec=>rec.startsWith("160000 ")).map(rec=>rec.slice(rec.indexOf(" ")+1)).filter(gitlink=>{if(gitlink.includes("\uFFFD"))return true;try{return readdirSync2(join2(cwd,gitlink)).length>0}catch(err){return err.code!=="ENOENT"}});if(blind.length>0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"git status cannot see inside the committed submodule path(s) "+blind.join(", ")}}const bits=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-v","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(bits.error||bits.status!==0||typeof bits.stdout!=="string"){const why=bits.error?bits.error.code??bits.error.message:`git ls-files exited ${bits.status}`;return{paths:paths.slice(0,cap),total:paths.length,unmeasured:why}}if(bits.stdout.split("\0").some(rec=>/^[a-zS]/.test(rec))){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the index carries skip-worktree or assume-unchanged bits, so `git status` cannot see edits to the tracked files they cover"}}if(expectedHeadSha===void 0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the caller brought no record of the commit this tree must hold, and a status measured through an unanchored identity would certify whichever index the .git gitfile names \u2014 a forged pair answers clean \u2014 so the measurement is refused rather than certified"}}return{paths:paths.slice(0,cap),total:paths.length}}__name(worktreeResidue,"worktreeResidue");function exposeDependencies(probeTree,dependencyRoot,opts={}){const done={linked:0,failed:0,alreadyPresent:false,selfLinked:0};if(probeTree===dependencyRoot)return done;let members=[];try{const graph=readWorkspacePackages(dependencyRoot);members=[...graph.packages.map(p=>p.dir),...graph.skipped]}catch{}const memberSources=members.map(dir=>({dir,source:containedIn(dependencyRoot,dir)})).filter(m=>{if(m.source===null)return true;try{return realpathSync2(m.source)!==realpathSync2(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join2(dependencyRoot,"node_modules");if(lstatSync(nm).isDirectory())rootNm=realpathSync2(nm)}catch{}const containment={rootNm,selfLinks:new Set(memberSources.flatMap(m=>m.source===null?[]:[m.source]))};farmNodeModules(dependencyRoot,probeTree,done,containment,opts.rebuild===true);const owned=new Set([join2(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync2(join2(dependencyRoot,dir)))done.failed++;continue}if(!existsSync2(target))continue;owned.add(join2(target,"node_modules"));try{farmNodeModules(source,target,done,containment,opts.rebuild===true)}catch{done.failed++}}if(opts.rebuild===true){for(const path of[...owned]){try{owned.add(realpathSync2(path))}catch{}}removeUnownedNodeModules(probeTree,owned,done)}return done}__name(exposeDependencies,"exposeDependencies");function removeUnownedNodeModules(tree,owned,done){const inTreeLinks=[];const walk=__name(dir=>{let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync2(full);const root=realpathSync2(tree);if(!statSync2(full).isDirectory()){}else if(real===root||real.startsWith(root+sep)){inTreeLinks.push(real)}else{done.failed++}}catch{}continue}if(!entry.isDirectory())continue;walk(full)}},"walk");walk(tree);for(const real of inTreeLinks){if(isOwned(owned,real))continue;if(holdsNodeModules(real,owned))done.failed++}}__name(removeUnownedNodeModules,"removeUnownedNodeModules");function isOwned(owned,path){if(owned.has(path))return true;try{return owned.has(realpathSync2(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full))return true;continue}if(entry.isSymbolicLink()||!entry.isDirectory())continue;if(entry.name===".git")continue;if(holdsNodeModules(full,owned))return true}return false}__name(holdsNodeModules,"holdsNodeModules");function containedIn(root,dir){try{const base=realpathSync2(resolve(root));const full=resolve(base,dir);const real=existsSync2(full)?realpathSync2(full):full;return real===base||real.startsWith(base+sep)?real:null}catch{return null}}__name(containedIn,"containedIn");var FARM_MARKER=".qwen-review-farm";function farmLinkVerdict(real,sourceNm,containment){if(insideDir(sourceNm,real))return"internal";if(containment.rootNm!==null&&insideDir(containment.rootNm,real)){return"internal"}for(const member of containment.selfLinks){if(insideDir(member,real))return"self"}return null}__name(farmLinkVerdict,"farmLinkVerdict");function insideDir(base,real){return real===base||real.startsWith(base+sep)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join2(target,FARM_MARKER),"utf8").trim()===resolve(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join2(sourceDir,"node_modules");const target=join2(targetDir,"node_modules");if(!existsSync2(source)){if(rebuild){try{lstatSync(target);rmSync(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync2(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync2(source,{withFileTypes:true})}catch{done.failed++;return}const before=done.linked;for(const entry of entries){if(entry.name===".vite"||entry.name===".vite-temp")continue;const sourceEntry=join2(source,entry.name);const targetEntry=join2(target,entry.name);let sourceStats;try{sourceStats=lstatSync(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync2(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync(targetEntry);pkgs=readdirSync2(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join2(sourceEntry,pkg);let real;try{real=realpathSync2(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join2(targetEntry,pkg),linkType);done.linked++}catch{done.failed++}}}else{try{symlinkSync(sourceEntry,targetEntry,linkType);done.linked++}catch{done.failed++}}}if(done.linked>before){try{writeFileSync(join2(target,FARM_MARKER),`${resolve(sourceDir)}
4
4
  `)}catch{}}}__name(farmNodeModules,"farmNodeModules");function worktreeCreateFailureDetail(label,err,sweepStderr){const sweepErr=sweepStderr.trim();return`${label} worktree could not be created: ${err instanceof Error?err.message:String(err)}`+(sweepErr?` (stale-tree sweep also reported: ${sweepErr})`:"")}__name(worktreeCreateFailureDetail,"worktreeCreateFailureDetail");import{existsSync as existsSync3,lstatSync as lstatSync2,realpathSync as realpathSync3,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,resolve as resolve2}from"node:path";var GIT_TIMEOUT_MS=12e4;function gitOpts(){return{timeout:GIT_TIMEOUT_MS,env:{...sanitizedGitEnv(),GIT_TERMINAL_PROMPT:"0"}}}__name(gitOpts,"gitOpts");var trustedLaunchDir=null;function kernelCwd(){try{const r=spawnSync2("/bin/pwd",["-P"],{encoding:"utf8",timeout:5e3,env:sanitizedGitEnv()});if(r.error||r.status!==0||!r.stdout)return null;return r.stdout.replace(/\n$/,"")}catch{return null}}__name(kernelCwd,"kernelCwd");function launchDirRefusal(){const cwd=process.cwd();if(trustedLaunchDir===cwd)return null;if(!insideReviewTmpLexically(cwd)){trustedLaunchDir=cwd;return null}if(process.platform!=="win32"){const kernel=kernelCwd();if(kernel===null){return`the kernel-resolved working directory could not be determined (cwd ${cwd}), so where a command run from here would land is unmeasured`}if(!insideReviewTmpLexically(kernel)){return`the process's working directory was renamed mid-run: the spelling ${cwd} is inside the review temp dir but the kernel reports ${kernel} \u2014 where every command would actually run`}let cachedReal;try{cachedReal=realpathSync3(cwd)}catch{cachedReal=null}if(cachedReal!==kernel){return`the process's working directory spelling ${cwd} resolves to ${cachedReal??"a path that no longer exists"} while the kernel reports ${kernel}: a rename mid-run split them, and every command runs at the kernel's answer`}return untrustedRepositoryFrom(kernel)}return untrustedRepositoryFrom(cwd)}__name(launchDirRefusal,"launchDirRefusal");function assertTrustedLaunchDir(){const refusal=launchDirRefusal();if(refusal!==null){throw new Error(`refusing to run git from this directory: ${refusal}. The command would resolve through that pointer and act on whatever repository it names. Run the review from a checkout outside the review temp dir.`)}}__name(assertTrustedLaunchDir,"assertTrustedLaunchDir");function git(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(git,"git");function gitWithEnv(extraEnv,args){assertTrustedLaunchDir();const opts=gitOpts();return execFileSync("git",args,{...opts,env:{...opts.env,...extraEnv},maxBuffer:512*1024*1024,encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(gitWithEnv,"gitWithEnv");function gitWithInput(input,args){return gitWithInputRaw(input,args).replace(/\r\n/g,"\n").trim()}__name(gitWithInput,"gitWithInput");function gitWithInputRaw(input,args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8",input,maxBuffer:512*1024*1024})}__name(gitWithInputRaw,"gitWithInputRaw");function gitOpt(...args){return gitProbe(...args).out}__name(gitOpt,"gitOpt");function gitProbe(...args){try{const refusal=launchDirRefusal();if(refusal!==null)return{out:null,status:null,refusal};return{out:execFileSync("git",args,{...gitOpts(),encoding:"utf8",stdio:["ignore","pipe","pipe"]}).replace(/\r\n/g,"\n").trim(),status:0,refusal:null}}catch(err){const status=err.status;return{out:null,status:typeof status==="number"?status:null,refusal:null}}}__name(gitProbe,"gitProbe");function repoRoot(){const first=git("worktree","list","--porcelain").split("\n")[0]??"";if(!first.startsWith("worktree ")){throw new Error(`cannot find the main worktree in: ${first}`)}return first.slice("worktree ".length)}__name(repoRoot,"repoRoot");function refExists(ref){return gitOpt("rev-parse","--verify","--quiet",ref)!==null}__name(refExists,"refExists");function worktreeReleaseResult(existed,stillThere,removeError){const freed=existed&&!stillThere;if(!existed||freed){return{existed,freed,reason:void 0}}return{existed,freed,reason:removeError?removeError instanceof Error?removeError.message:String(removeError):"the path is still there after `git worktree remove --force` and `rm -rf`"}}__name(worktreeReleaseResult,"worktreeReleaseResult");function releaseWorktree(worktreePath2){let redirected;try{redirected=redirectedAncestor(dirname2(resolve2(worktreePath2)))}catch(err){return worktreeReleaseResult(true,true,err)}if(redirected!==null){return worktreeReleaseResult(true,true,new Error(`refusing to release through a symlink: ${redirected} is a symlink, so the removal would land wherever it points`))}try{if(lstatSync2(worktreePath2).isSymbolicLink()){let removeError2;try{rmSync2(worktreePath2,{force:true})}catch(e){removeError2=e}const pruned2=gitProbe("worktree","prune");let stillThere2=false;try{lstatSync2(worktreePath2);stillThere2=true}catch{}return worktreeReleaseResult(true,stillThere2||pruned2.refusal!==null||pruned2.status===null,removeError2??refusalError(pruned2.refusal)??(pruned2.status===null?couldNotRunError():void 0))}}catch{}const existed=existsSync3(worktreePath2);let removeError;const removed=existed?gitProbe("worktree","remove",worktreePath2,"--force"):null;if(existed){try{rmSync2(worktreePath2,{recursive:true,force:true})}catch(e){removeError=e}}const pruned=gitProbe("worktree","prune");const refusal=removed?.refusal??pruned.refusal;const couldNotRun=removed?.status!==0&&pruned.status===null;const stillThere=existsSync3(worktreePath2);return worktreeReleaseResult(existed,stillThere||existed&&couldNotRun,removeError??(couldNotRun?refusalError(refusal)??couldNotRunError():void 0))}__name(releaseWorktree,"releaseWorktree");function couldNotRunError(){return new Error('the `git worktree prune` that frees the registration and the branch could not be run at all (a spawn failure or the timeout kill), so both survive \u2014 the next `git worktree add` over the path will still fail with "missing but already registered". Re-run `qwen review cleanup`.')}__name(couldNotRunError,"couldNotRunError");function refusalError(refusal){if(refusal===null)return void 0;return new Error(`git could not run from this directory \u2014 ${refusal}. The directory is cleared but this worktree's registration and branch were not, so the next \`git worktree add\` over it will still fail. Run \`qwen review cleanup\` from a checkout outside the review temp dir.`)}__name(refusalError,"refusalError");function gitRaw(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),maxBuffer:512*1024*1024,stdio:["ignore","pipe","pipe"]})}__name(gitRaw,"gitRaw");function gitRawTolerateDiff(...args){try{return gitRaw(...args)}catch(err){const e=err;if(e.status===1&&e.stdout&&e.stdout.length>0)return e.stdout;throw err}}__name(gitRawTolerateDiff,"gitRawTolerateDiff");function assertWritableOutPath(out){if(typeof out!=="string"){throw new TypeError(Array.isArray(out)?"--out must be given once, as a file path":"--out must name a file path")}if(out.trim()===""){throw new TypeError("--out must name a file path")}if(/[/\\]$/.test(out.trim())){throw new TypeError(`--out names a directory, not a file: ${out}`)}const resolved=resolve3(out);if(existsSync4(resolved)&&statSync3(resolved).isDirectory()){throw new TypeError(`--out names a directory, not a file: ${out}`)}}__name(assertWritableOutPath,"assertWritableOutPath");var REVIEW_TMP_DIR=join3(".qwen","tmp");var RETIRED_REVIEW_LEASE_DIR=join3(".qwen","review-leases");var REVIEW_TRUST_STATE_DIR="review-state";var REVIEWS_DIR=join3(".qwen","reviews");var REVIEW_CACHE_DIR=join3(".qwen","review-cache");function outermostReviewRepositoryRoot(repositoryRoot){const resolved=resolve3(repositoryRoot);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=(resolved+sep2).indexOf(marker);return at<0?resolved:resolved.slice(0,at)}__name(outermostReviewRepositoryRoot,"outermostReviewRepositoryRoot");function canonicalReviewRepositoryRoot(repositoryRoot){let canonical=outermostReviewRepositoryRoot(repositoryRoot);try{canonical=realpathSync4.native(canonical)}catch(error){if(error.code!=="ENOENT")throw error}canonical=outermostReviewRepositoryRoot(canonical);return canonical}__name(canonicalReviewRepositoryRoot,"canonicalReviewRepositoryRoot");function reviewTrustStateDir(repositoryRoot){const digest=getProjectHash(canonicalReviewRepositoryRoot(repositoryRoot));return join3(Storage.getGlobalQwenDir(),REVIEW_TRUST_STATE_DIR,digest)}__name(reviewTrustStateDir,"reviewTrustStateDir");function reviewRepositoryRootForWorktree(worktree){const resolved=resolve3(worktree);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=resolved.indexOf(marker);if(at<0){throw new Error(`cannot place the base-tree trust artifact for ${worktree}: the worktree is not shaped like <root>/.qwen/tmp/<name>, so there is no host-side review directory to key it under`)}return resolved.slice(0,at)}__name(reviewRepositoryRootForWorktree,"reviewRepositoryRootForWorktree");var GENERATED_WORKFLOWS_SUBDIR=join3("workflows","generated");var REVIEW_WORKFLOWS_SUBDIR="review";var REVIEW_WORKFLOW_PREFIX="qwen-review-";var GeneratedWorkflowDirUnavailableError=class extends Error{static{__name(this,"GeneratedWorkflowDirUnavailableError")}};function projectDirFromEnv(env){const projectDir=env["QWEN_CODE_PROJECT_DIR"]?.trim();if(!projectDir){throw new GeneratedWorkflowDirUnavailableError("the CLI did not export QWEN_CODE_PROJECT_DIR, so there is no directory the Workflow tool would load a generated script from. Run this command from inside a qwen session.")}return projectDir}__name(projectDirFromEnv,"projectDirFromEnv");function reviewSessionDirName(session){const digest=createHash2("sha256").update(session).digest("hex").slice(0,8);return`${sanitizeFilenameComponent(session)}-${digest}`}__name(reviewSessionDirName,"reviewSessionDirName");function reviewWorkflowsDir(env=process.env){const session=env["QWEN_CODE_SESSION_ID"]?.trim();return join3(projectDirFromEnv(env),GENERATED_WORKFLOWS_SUBDIR,REVIEW_WORKFLOWS_SUBDIR,session?reviewSessionDirName(session):"no-session")}__name(reviewWorkflowsDir,"reviewWorkflowsDir");function ensureWritableReviewWorkflowsDir(env=process.env){const projectDir=projectDirFromEnv(env);const dir=reviewWorkflowsDir(env);const root=join3(projectDir,GENERATED_WORKFLOWS_SUBDIR);for(const component of[root,join3(root,REVIEW_WORKFLOWS_SUBDIR),dir]){let isLink=false;try{isLink=lstatSync3(component).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`refusing to write a generated review script through the symlinked directory '${component}' \u2014 it would land outside the generated-workflows root the Workflow loader trusts.`)}}mkdirSync2(dir,{recursive:true});const realDir=realpathSync4(dir);const realRoot=realpathSync4(root);if(realDir!==realRoot&&!realDir.startsWith(realRoot+sep2)){throw new Error(`refusing to write a generated review script: the canonical session directory '${realDir}' escapes the canonical generated-workflows root '${realRoot}'.`)}return dir}__name(ensureWritableReviewWorkflowsDir,"ensureWritableReviewWorkflowsDir");function reviewWorkflowScriptPath(planPath,script,env=process.env){const resolved=resolve3(planPath);let canonical=resolved;try{canonical=realpathSync4(resolved)}catch{}const digest=createHash2("sha256").update(canonical).digest("hex").slice(0,10);const contentDigest=createHash2("sha256").update(script).digest("hex");return join3(reviewWorkflowsDir(env),`${REVIEW_WORKFLOW_PREFIX}${digest}-${contentDigest}.js`)}__name(reviewWorkflowScriptPath,"reviewWorkflowScriptPath");var LEASE_PREFIX="qwen-review-lease-";var PARSE_ARGS_REPORT=join3(REVIEW_TMP_DIR,"qwen-review-parse-args.json");function lastReviewEffortPath(projectRoot,sessionProjectDir){const owner=sessionProjectDir?.trim()?resolve3(sessionProjectDir):new Storage(projectRoot).getProjectDir();return join3(owner,"review-last-effort")}__name(lastReviewEffortPath,"lastReviewEffortPath");function worktreePath(prNumber){return join3(REVIEW_TMP_DIR,`review-pr-${prNumber}`)}__name(worktreePath,"worktreePath");function probeWorktreePath(worktree){return`${resolve3(worktree)}-probe`}__name(probeWorktreePath,"probeWorktreePath");function baseWorktreePath(worktree){return`${resolve3(worktree)}-base`}__name(baseWorktreePath,"baseWorktreePath");var SCRATCH_INFIX="-scratch-";function scratchWorktreePath(worktree,label){const safe=scratchLabel(label);if(!safe){throw new TypeError(`scratch label ${JSON.stringify(label)} keeps no path-safe character (A-Za-z0-9._-); a tree cannot be named for it`)}return`${resolve3(worktree)}${SCRATCH_INFIX}${safe}`}__name(scratchWorktreePath,"scratchWorktreePath");function scratchWorktreePrefix(worktree){return`${resolve3(worktree)}${SCRATCH_INFIX}`}__name(scratchWorktreePrefix,"scratchWorktreePrefix");function scratchLabel(label){return label.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_").replace(/^[._-]+/,"").slice(0,64)}__name(scratchLabel,"scratchLabel");function reviewBranch(prNumber){return`qwen-review/pr-${prNumber}`}__name(reviewBranch,"reviewBranch");function tmpFile(target,suffix){return join3(REVIEW_TMP_DIR,`qwen-review-${safeTarget(target)}-${suffix}`)}__name(tmpFile,"tmpFile");function tmpPrefix(target){return`qwen-review-${safeTarget(target)}-`}__name(tmpPrefix,"tmpPrefix");function ensureReviewTmpDir(command){for(const dir of[dirname3(REVIEW_TMP_DIR),REVIEW_TMP_DIR]){let isLink=false;try{isLink=lstatSync3(dir).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`${command}: ${dir} is a symbolic link \u2014 every file this review writes (plan, diff, candidate, stop sidecar, worktree) would land wherever it points, and the plan would be read back from there. Refusing to run; nothing here can tell your own link from a committed one. If it is YOURS \u2014 this directory holds a full worktree per PR, so redirecting it onto other storage is a reasonable thing to have done \u2014 neither ${dirname3(REVIEW_TMP_DIR)} nor ${REVIEW_TMP_DIR} can be one: redirect the checkout itself, or a directory the review never names.`)}}let listing;try{listing=gitRaw("ls-files","-s","-z").toString("utf8")}catch(err){if(insideRepository()){throw new Error(`${command}: could not list the tracked entries under ${REVIEW_TMP_DIR} (${inertText(err.message,2e3)}) \u2014 refusing to run rather than write through a link the listing might have named. Lightweight mode (\`fetch-diff\`) is the one flow that could otherwise proceed without git; every other one needs it for the diff itself.`)}listing=""}const scratch=REVIEW_TMP_DIR.split(sep2).join("/").toLowerCase();const planted=listing.split("\0").find(entry=>{const gitlink=entry.startsWith("160000 ");if(!entry.startsWith("120000 ")&&!gitlink)return false;const path=entry.slice(entry.indexOf(" ")+1).toLowerCase();if(path===dirname3(scratch)||path===scratch)return true;if(!path.startsWith(`${scratch}/`))return false;return!gitlink||!isReviewWorktreeName(path.slice(scratch.length+1))});if(planted!==void 0){const path=planted.slice(planted.indexOf(" ")+1);const what=planted.startsWith("160000 ")?"a submodule":"a symbolic link";throw new Error(`${command}: the workspace tracks ${what} at ${inertText(path)} \u2014 on the scratch directory ${REVIEW_TMP_DIR} or a path through it \u2014 and a plain write to that name would follow it out of the tree. Refusing to run; remove it from the index AND the working tree (\`git rm -f -- <path>\`) and retry.`)}const onDisk=roundOwnedLinkOnDisk(command);if(onDisk!==null){throw new Error(`${command}: ${inertText(onDisk)} is a symbolic link on disk, at a name this review writes \u2014 a plain write to it would follow the link out of the tree. Refusing to run; delete the link and retry.`)}mkdirSync2(REVIEW_TMP_DIR,{recursive:true})}__name(ensureReviewTmpDir,"ensureReviewTmpDir");function roundOwnedLinkOnDisk(command){const list=__name(dir=>{try{return readdirSync3(dir,{withFileTypes:true})}catch(err){const code=err.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw new Error(`${command}: could not list ${inertText(dir)} (${inertText(err.message)}) \u2014 refusing to run rather than write through a link the listing might have named.`)}},"list");const walk=__name(dir=>{for(const entry of list(dir)){const path=join3(dir,entry.name);if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}return null},"walk");for(const entry of list(REVIEW_TMP_DIR)){const path=join3(REVIEW_TMP_DIR,entry.name);const name=entry.name.toLowerCase();if(name.startsWith("qwen-review-")){if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}else if(isReviewWorktreeName(name)&&entry.isSymbolicLink()){return path}}return null}__name(roundOwnedLinkOnDisk,"roundOwnedLinkOnDisk");function commandPrefixed(command,message){const prefix=`${command}: `;return message.startsWith(prefix)?message:`${prefix}${message}`}__name(commandPrefixed,"commandPrefixed");function writesIntoReviewTmp(out){const scratch=resolve3(REVIEW_TMP_DIR).toLowerCase();const target=resolve3(out).toLowerCase();return target===scratch||target.startsWith(scratch+sep2)}__name(writesIntoReviewTmp,"writesIntoReviewTmp");function isReviewWorktreeName(name){return/^review-pr-\d+(-probe|-base|-scratch-[^/]*)?$/.test(name)}__name(isReviewWorktreeName,"isReviewWorktreeName");function insideRepository(){let dir=resolve3(".");for(;;){if(existsSync4(join3(dir,".git")))return true;const parent=dirname3(dir);if(parent===dir)return false;dir=parent}}__name(insideRepository,"insideRepository");function inertPath(p){return p.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u2500`]+/gu," ")}__name(inertPath,"inertPath");function canonicalise(abs){const walked=[];let cur=abs;for(;;){try{const real=realpathSync4(cur);return walked.length===0?real:join3(real,...walked.reverse())}catch{const parent=resolve3(cur,"..");if(parent===cur)return abs;walked.push(cur.slice(parent.length).replace(sep2==="/"?/^\/+/:/^[\\/]+/,""));cur=parent}}}__name(canonicalise,"canonicalise");function repoRelativeOf(repoRoot2,file,from=process.cwd()){const abs=canonicalise(resolve3(from,file));const rel=relative2(repoRoot2,abs);const escapes=rel===".."||rel.startsWith(".."+sep2)||isAbsolute3(rel);return{rel:sep2==="/"?rel:rel.split(sep2).join("/"),abs,escapes}}__name(repoRelativeOf,"repoRelativeOf");function assertUnredirectedParent(target,what,command){const parent=resolve3(dirname3(target));let real;try{real=realpathSync4(parent)}catch(err){throw new Error(`${command}: cannot resolve the ${what} directory ${inertText(parent)}: `+inertText(err.message))}if(real!==parent){throw new Error(`${command}: the ${what} directory ${inertText(parent)} resolves to ${inertText(real)} \u2014 a symlink in the path would redirect this write outside the tree it names. Refusing.`)}}__name(assertUnredirectedParent,"assertUnredirectedParent");export{safeTarget,CONTROL,inertText,assertWritableOutPath,REVIEW_TMP_DIR,RETIRED_REVIEW_LEASE_DIR,REVIEWS_DIR,REVIEW_CACHE_DIR,reviewTrustStateDir,reviewRepositoryRootForWorktree,ensureWritableReviewWorkflowsDir,reviewWorkflowScriptPath,LEASE_PREFIX,PARSE_ARGS_REPORT,lastReviewEffortPath,worktreePath,probeWorktreePath,baseWorktreePath,scratchWorktreePath,scratchWorktreePrefix,scratchLabel,reviewBranch,tmpFile,tmpPrefix,ensureReviewTmpDir,commandPrefixed,writesIntoReviewTmp,inertPath,repoRelativeOf,assertUnredirectedParent,raiseHeap,raiseNpmHeap,heapBannerIn,ranOutOfHeap,killedFromOutside,isWorkspaceMember,workspaceDirFor,isNegationExcluded,hasUnmodeledWorkspaceGlob,readWorkspaceGlobs,readRootPackage,scriptFansOut,chainsCommands,rootBuildFanOutScript,declaredBuildHeapMb,readWorkspacePackages,affectedWorkspaces,dependencyClosure,reverseDependencyClosure,buildSetFor,mountRootFor,untrustedRepositoryFrom,untrustedGitfile,redirectedAncestor,sanitizedGitEnv,describeFilterScreen,filterBlankEnv,localFilterCommands,filterScreenForTree,resolvedContentTransformForTree,checkoutFilterCommands,discardWorktree,RESIDUE_PATH_CAP,worktreeResidue,exposeDependencies,worktreeCreateFailureDetail,GIT_TIMEOUT_MS,git,gitWithEnv,gitWithInput,gitWithInputRaw,gitOpt,gitProbe,repoRoot,refExists,releaseWorktree,gitRaw,gitRawTolerateDiff};
5
5
  /**
6
6
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-STPD3MIX.js";import{t}from"./chunk-4NQCOITC.js";import{So}from"./chunk-3SQ76U4F.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
3
+ import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-GOZ5FAUV.js";import{t}from"./chunk-FK5L2WVV.js";import{So}from"./chunk-PFKTTUGS.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
4
4
  Original error: ${promoteErr.message}
5
5
  Rollback error: ${rollbackErr.message}
6
6
  Manual recovery: mv "${oldDir}" "${standaloneDir}"`;throw new Error(detail)}throw promoteErr}return"done"}}__name(atomicReplace,"atomicReplace");function ensureBinWrapper(standaloneDir,target,runtime="node"){const binDir=path.join(path.dirname(standaloneDir),"..","bin");const artifacts={wrapperCreated:false};const{launcher,interpreter,entryPoint}=standaloneRuntimePaths(standaloneDir,target,runtime);const hasLauncher=fs.existsSync(launcher);try{fs.mkdirSync(binDir,{recursive:true});if(target.startsWith("win")){if(UNSAFE_CMD_CHARS.test(standaloneDir)){throw new Error("standaloneDir contains characters unsafe for cmd.exe wrapper")}const wrapperPath=path.join(binDir,"qwen.cmd");artifacts.wrapperPath=wrapperPath;const content=hasLauncher?`@echo off\r