@moberg_hr/work-tree 2.22.5 → 2.23.0

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 (281) hide show
  1. package/dist/{account-J55P3HXH.js → account-FKQZQP3W.js} +20 -17
  2. package/dist/{account-J55P3HXH.js.map → account-FKQZQP3W.js.map} +1 -1
  3. package/dist/{add-repo-ALVEGU25.js → add-repo-VJ2OPGRB.js} +10 -10
  4. package/dist/{answer-CI2SPQQL.js → answer-HQGVCGOF.js} +8 -8
  5. package/dist/{attach-7LBIFBLX.js → attach-M46SZYRL.js} +18 -15
  6. package/dist/{attach-7LBIFBLX.js.map → attach-M46SZYRL.js.map} +1 -1
  7. package/dist/bin.js +3 -3
  8. package/dist/{block-TVIYWRJ5.js → block-B2WNCH52.js} +10 -10
  9. package/dist/{broadcast-GZNMZFOY.js → broadcast-JD755S3I.js} +6 -6
  10. package/dist/{catchup-ZURJI6BF.js → catchup-PTV2VTWT.js} +11 -11
  11. package/dist/{child-K6YYF6MQ.js → child-XFLJLJ6I.js} +8 -8
  12. package/dist/{chunk-RTCTD5PJ.js → chunk-26BZGPFZ.js} +3 -3
  13. package/dist/{chunk-EVTMZ5IH.js → chunk-336YLJ5L.js} +60 -60
  14. package/dist/{chunk-OCUUM755.js → chunk-4FOC35LW.js} +2 -2
  15. package/dist/{chunk-B2WV5RAL.js → chunk-4GIAERRK.js} +5 -5
  16. package/dist/{chunk-BQS73CWR.js → chunk-4LZLVHZE.js} +2 -2
  17. package/dist/{chunk-DCENKA6E.js → chunk-4VTRRZWZ.js} +2 -2
  18. package/dist/{chunk-GNERWNZY.js → chunk-5IZMEAKN.js} +4 -4
  19. package/dist/{chunk-ATQB6PTV.js → chunk-5THKIWZU.js} +3 -3
  20. package/dist/{chunk-NOQA7MJ4.js → chunk-6HVDHGNE.js} +3 -3
  21. package/dist/{chunk-NYGKSOQ4.js → chunk-6ISLCEBR.js} +6 -6
  22. package/dist/chunk-6KMG4WNW.js +87 -0
  23. package/dist/chunk-6KMG4WNW.js.map +1 -0
  24. package/dist/{chunk-F4UIKOU6.js → chunk-6RFDASKQ.js} +4 -4
  25. package/dist/{chunk-5P27YL64.js → chunk-7I2UHJJF.js} +8 -8
  26. package/dist/{chunk-FV7BSQPQ.js → chunk-AEH72XTU.js} +2 -2
  27. package/dist/{chunk-3ZPVKUYD.js → chunk-ASGJ3MCL.js} +6 -1
  28. package/dist/chunk-ASGJ3MCL.js.map +1 -0
  29. package/dist/{chunk-DF4GOVDE.js → chunk-AUIHERJ7.js} +2 -2
  30. package/dist/{chunk-6Y3VLCKA.js → chunk-AZF7HIDT.js} +3 -3
  31. package/dist/chunk-BCYBF7KJ.js +207 -0
  32. package/dist/chunk-BCYBF7KJ.js.map +1 -0
  33. package/dist/{chunk-KQMHGEI2.js → chunk-BS6GTKF2.js} +51 -13
  34. package/dist/chunk-BS6GTKF2.js.map +1 -0
  35. package/dist/{chunk-AIYZJ7XD.js → chunk-BTGPUOF7.js} +5 -5
  36. package/dist/chunk-CJFAJV2K.js +9 -0
  37. package/dist/{chunk-VQDE3DRG.js → chunk-DHZ5DF6Y.js} +6 -2
  38. package/dist/{chunk-VQDE3DRG.js.map → chunk-DHZ5DF6Y.js.map} +1 -1
  39. package/dist/{chunk-LV5JRLBM.js → chunk-DP6YMZUL.js} +2 -2
  40. package/dist/{chunk-Z4FWXDJG.js → chunk-DSDPJATB.js} +3 -3
  41. package/dist/{chunk-RLPC3YKZ.js → chunk-EE744F4B.js} +2 -2
  42. package/dist/{chunk-QOLHDDM2.js → chunk-EEMPMVCP.js} +4 -4
  43. package/dist/{chunk-SDYY5MHW.js → chunk-EJZMCAM2.js} +7 -7
  44. package/dist/{chunk-EYJ42LDG.js → chunk-EOXYDFBB.js} +4 -4
  45. package/dist/{chunk-DC73NF67.js → chunk-ETO7CUIS.js} +3 -3
  46. package/dist/{chunk-ZO7TF5OL.js → chunk-ETRKZHM5.js} +4 -4
  47. package/dist/{chunk-HI674QZF.js → chunk-EVGYDJI2.js} +2 -2
  48. package/dist/{chunk-PUJSLL6R.js → chunk-FEI73IPX.js} +4 -4
  49. package/dist/{chunk-KU3TQAA7.js → chunk-FRFS6JC4.js} +8 -10
  50. package/dist/{chunk-KU3TQAA7.js.map → chunk-FRFS6JC4.js.map} +1 -1
  51. package/dist/{chunk-4QMWNAEJ.js → chunk-HCYES6U7.js} +2 -2
  52. package/dist/{chunk-WRDULHAN.js → chunk-HTV7366A.js} +117 -16
  53. package/dist/chunk-HTV7366A.js.map +1 -0
  54. package/dist/{chunk-5FIUVBUC.js → chunk-JIMD77FI.js} +7 -7
  55. package/dist/{chunk-TOMDOA4P.js → chunk-K76NOSEX.js} +2 -2
  56. package/dist/{chunk-FGBLFF4O.js → chunk-KUYEYPO4.js} +2 -2
  57. package/dist/{chunk-Z4P23XG3.js → chunk-L5U47Q63.js} +5 -5
  58. package/dist/{chunk-YO3BNAAK.js → chunk-LZJ5VDUD.js} +26 -4
  59. package/dist/chunk-LZJ5VDUD.js.map +1 -0
  60. package/dist/{chunk-USENBMUV.js → chunk-NS7WH53I.js} +1 -1
  61. package/dist/chunk-NS7WH53I.js.map +1 -0
  62. package/dist/{chunk-EA4C6TVY.js → chunk-O7BXNXU2.js} +3 -3
  63. package/dist/{chunk-ZTWZS5RK.js → chunk-OETBYJFV.js} +3 -3
  64. package/dist/chunk-PCJVBGRS.js +64 -0
  65. package/dist/chunk-PCJVBGRS.js.map +1 -0
  66. package/dist/{chunk-RNPNBGVX.js → chunk-QPQV3IU2.js} +3 -5
  67. package/dist/{chunk-RNPNBGVX.js.map → chunk-QPQV3IU2.js.map} +1 -1
  68. package/dist/chunk-R7IENU76.js +79 -0
  69. package/dist/chunk-R7IENU76.js.map +1 -0
  70. package/dist/{chunk-23QLXVH6.js → chunk-R7JIKEIL.js} +12 -14
  71. package/dist/{chunk-23QLXVH6.js.map → chunk-R7JIKEIL.js.map} +1 -1
  72. package/dist/{chunk-CA56ETYX.js → chunk-TVIM5VV5.js} +5 -5
  73. package/dist/{chunk-PTAG6WIE.js → chunk-UGDTSOPX.js} +17 -3
  74. package/dist/chunk-UGDTSOPX.js.map +1 -0
  75. package/dist/{chunk-D2SVBU7R.js → chunk-ULI54QYZ.js} +2 -2
  76. package/dist/{chunk-7Q5PBXF6.js → chunk-V56WW2LA.js} +51 -10
  77. package/dist/chunk-V56WW2LA.js.map +1 -0
  78. package/dist/{chunk-G4T2HGLJ.js → chunk-V6FD76AQ.js} +4 -4
  79. package/dist/{chunk-QNOJOZYK.js → chunk-VVJY6IKW.js} +2 -2
  80. package/dist/{chunk-Q2B3NUSM.js → chunk-WLYWO6JH.js} +4 -4
  81. package/dist/{chunk-IU6LA6EB.js → chunk-WYCGV5Z7.js} +4 -4
  82. package/dist/{chunk-AITL3JYB.js → chunk-XJQ7XJJC.js} +398 -68
  83. package/dist/chunk-XJQ7XJJC.js.map +1 -0
  84. package/dist/{chunk-CMRTNTMU.js → chunk-Z3JSYKOS.js} +6 -6
  85. package/dist/{chunk-UAF2YFLZ.js → chunk-ZBVM57LO.js} +6 -6
  86. package/dist/{chunk-GQ5WECPJ.js → chunk-ZDTFAMD2.js} +2 -2
  87. package/dist/{chunk-EEHPZMS3.js → chunk-ZIZ5ZTEN.js} +2 -2
  88. package/dist/{cleanup-G4WQACD6.js → cleanup-RVQ2PPCC.js} +30 -29
  89. package/dist/{cleanup-G4WQACD6.js.map → cleanup-RVQ2PPCC.js.map} +1 -1
  90. package/dist/{cli-OPORB5PF.js → cli-RQ7LQXRX.js} +4 -4
  91. package/dist/{color-C223W3Z6.js → color-37SJ7NPH.js} +9 -9
  92. package/dist/{config-KQYXQCQA.js → config-QMNCPBT7.js} +8 -8
  93. package/dist/{coordinate-4E5GIMC6.js → coordinate-22N2UBE4.js} +9 -9
  94. package/dist/{diff-HEOLTXO2.js → diff-VSM47DNB.js} +9 -10
  95. package/dist/{diff-HEOLTXO2.js.map → diff-VSM47DNB.js.map} +1 -1
  96. package/dist/{digest-GYF4YLUH.js → digest-H5YMEW54.js} +8 -8
  97. package/dist/{fork-B35ONP3Z.js → fork-Q2AEFG5M.js} +27 -24
  98. package/dist/{fork-B35ONP3Z.js.map → fork-Q2AEFG5M.js.map} +1 -1
  99. package/dist/{history-25DNQKKC.js → history-E34WUNZO.js} +6 -6
  100. package/dist/{hook-B4JO2X57.js → hook-IMBHXXH2.js} +17 -17
  101. package/dist/{hydrate-IJEKNZIP.js → hydrate-IPNTSEDA.js} +6 -6
  102. package/dist/{init-UJVOUDJI.js → init-V7Z3RVHQ.js} +10 -10
  103. package/dist/{install-skills-FV2L5QHE.js → install-skills-PP7WYASM.js} +6 -7
  104. package/dist/install-skills-bin.js +5 -6
  105. package/dist/install-skills-bin.js.map +1 -1
  106. package/dist/{keep-PKXGFZO2.js → keep-JZBFDYC5.js} +8 -8
  107. package/dist/{list-VYQ3QE2H.js → list-D6GWBNUI.js} +6 -6
  108. package/dist/{move-IAZY23ZX.js → move-T6IVLRRI.js} +13 -13
  109. package/dist/{note-6HQUKUYY.js → note-L4YF6DYN.js} +8 -8
  110. package/dist/{overlaps-CGP3RJOW.js → overlaps-33U2T7IV.js} +11 -11
  111. package/dist/{pin-PAWGQ4Q2.js → pin-BVNCXHQI.js} +9 -9
  112. package/dist/{pr-OJOGE3A3.js → pr-DBTWVMRE.js} +19 -18
  113. package/dist/{pr-OJOGE3A3.js.map → pr-DBTWVMRE.js.map} +1 -1
  114. package/dist/{prune-42MS36OR.js → prune-HUYBTMZM.js} +27 -27
  115. package/dist/pty-host-IJFDGRA4.js +2653 -0
  116. package/dist/pty-host-IJFDGRA4.js.map +1 -0
  117. package/dist/{read-ATNCW4KH.js → read-4OUYRSKS.js} +8 -8
  118. package/dist/{recent-MTBFQT36.js → recent-PB233FPD.js} +14 -13
  119. package/dist/{recent-MTBFQT36.js.map → recent-PB233FPD.js.map} +1 -1
  120. package/dist/{remove-GLDJOKUI.js → remove-YCQLIDTS.js} +28 -28
  121. package/dist/{report-AK7Z2Y4S.js → report-XMESBL7C.js} +8 -8
  122. package/dist/{restart-DEPDGEZB.js → restart-NQ5DJ3TN.js} +8 -8
  123. package/dist/{resume-C2QPKKFN.js → resume-KL5JCKVD.js} +14 -13
  124. package/dist/{resume-C2QPKKFN.js.map → resume-KL5JCKVD.js.map} +1 -1
  125. package/dist/{review-RYAGH3PY.js → review-MIKB545E.js} +7 -7
  126. package/dist/{review-now-K4UWD7A5.js → review-now-VF6X6M64.js} +2 -2
  127. package/dist/{run-WNP2SMNW.js → run-Y255ESUN.js} +6 -6
  128. package/dist/{screen-P746M4F2.js → screen-AZFHPOCB.js} +8 -8
  129. package/dist/{search-XQ2WMK5X.js → search-DAFKJTLY.js} +6 -6
  130. package/dist/{section-Q7TPOV7U.js → section-WCC35C44.js} +9 -9
  131. package/dist/{send-EGG23J2B.js → send-MYEMZU7Z.js} +9 -9
  132. package/dist/{sessions-2NNCWIND.js → sessions-P3D46QLP.js} +24 -22
  133. package/dist/{sessions-2NNCWIND.js.map → sessions-P3D46QLP.js.map} +1 -1
  134. package/dist/{show-KSMC7AJL.js → show-JOO5OT2F.js} +7 -7
  135. package/dist/{snooze-4LVYUQEX.js → snooze-7KLABMIG.js} +8 -8
  136. package/dist/{start-YKLLXW3L.js → start-PGVZZJQT.js} +8 -8
  137. package/dist/{state-GM22X3RN.js → state-XHTOESKK.js} +3 -3
  138. package/dist/state-XHTOESKK.js.map +1 -0
  139. package/dist/{status-4HGP4ZEF.js → status-CXIRNRMP.js} +9 -9
  140. package/dist/{statusline-QJ6CJGHB.js → statusline-HPH2ORNT.js} +3 -3
  141. package/dist/{stop-YBQL6NFF.js → stop-IJNUSRIG.js} +8 -8
  142. package/dist/{sync-DUXN2MFJ.js → sync-3HMCC55V.js} +27 -27
  143. package/dist/{time-Q42HPZZ3.js → time-DUDNSHM3.js} +9 -9
  144. package/dist/{time-actions-IXZRVKKQ.js → time-actions-M4QTTH4M.js} +3 -3
  145. package/dist/{timesheet-YJ6O3GUU.js → timesheet-BMKDX5KZ.js} +12 -12
  146. package/dist/{todo-ZBFRL2A5.js → todo-QMXJ5R3E.js} +2 -2
  147. package/dist/{tree-H2UYE6LH.js → tree-TL4GISI5.js} +28 -26
  148. package/dist/{tree-H2UYE6LH.js.map → tree-TL4GISI5.js.map} +1 -1
  149. package/dist/{update-RGNKMRUL.js → update-3TODL7J3.js} +13 -13
  150. package/dist/{usage-YZRZKJ3H.js → usage-YFTN2IS7.js} +8 -8
  151. package/dist/{usage-ask-BYPNLA2B.js → usage-ask-EZR3W3UW.js} +3 -3
  152. package/dist/{version-4IOMOIDP.js → version-LNHKXZBP.js} +4 -4
  153. package/dist/{wait-YOHPFWVJ.js → wait-B37BTCVG.js} +9 -9
  154. package/dist/wd-bin.js +3 -3
  155. package/dist/web/assets/{PtyView-CYAhB_pW.js → PtyView-C8yW4SST.js} +26 -28
  156. package/dist/web/assets/PtyView-C8yW4SST.js.map +1 -0
  157. package/dist/web/assets/index-DDZCgbD-.js +129 -0
  158. package/dist/web/assets/index-DDZCgbD-.js.map +1 -0
  159. package/dist/web/assets/index-yBTfBzDm.css +1 -0
  160. package/dist/web/index.html +2 -2
  161. package/dist/{web-Q672AIMZ.js → web-JAAXINIU.js} +468 -492
  162. package/dist/web-JAAXINIU.js.map +1 -0
  163. package/npm-shrinkwrap.json +3 -4
  164. package/package.json +2 -2
  165. package/dist/chunk-3ZPVKUYD.js.map +0 -1
  166. package/dist/chunk-7Q5PBXF6.js.map +0 -1
  167. package/dist/chunk-7ZOY2QQN.js +0 -43
  168. package/dist/chunk-7ZOY2QQN.js.map +0 -1
  169. package/dist/chunk-AITL3JYB.js.map +0 -1
  170. package/dist/chunk-EXZ4A6VJ.js +0 -9
  171. package/dist/chunk-ICEP4WAK.js +0 -256
  172. package/dist/chunk-ICEP4WAK.js.map +0 -1
  173. package/dist/chunk-KQMHGEI2.js.map +0 -1
  174. package/dist/chunk-LNHSBM4L.js +0 -26
  175. package/dist/chunk-LNHSBM4L.js.map +0 -1
  176. package/dist/chunk-PTAG6WIE.js.map +0 -1
  177. package/dist/chunk-USENBMUV.js.map +0 -1
  178. package/dist/chunk-WRDULHAN.js.map +0 -1
  179. package/dist/chunk-YO3BNAAK.js.map +0 -1
  180. package/dist/pty-host-EAWW62U4.js +0 -1235
  181. package/dist/pty-host-EAWW62U4.js.map +0 -1
  182. package/dist/state-GM22X3RN.js.map +0 -1
  183. package/dist/web/assets/PtyView-CYAhB_pW.js.map +0 -1
  184. package/dist/web/assets/index-Ca7KbCED.css +0 -1
  185. package/dist/web/assets/index-iBmmgBZv.js +0 -129
  186. package/dist/web/assets/index-iBmmgBZv.js.map +0 -1
  187. package/dist/web-Q672AIMZ.js.map +0 -1
  188. /package/dist/{add-repo-ALVEGU25.js.map → add-repo-VJ2OPGRB.js.map} +0 -0
  189. /package/dist/{answer-CI2SPQQL.js.map → answer-HQGVCGOF.js.map} +0 -0
  190. /package/dist/{block-TVIYWRJ5.js.map → block-B2WNCH52.js.map} +0 -0
  191. /package/dist/{broadcast-GZNMZFOY.js.map → broadcast-JD755S3I.js.map} +0 -0
  192. /package/dist/{catchup-ZURJI6BF.js.map → catchup-PTV2VTWT.js.map} +0 -0
  193. /package/dist/{child-K6YYF6MQ.js.map → child-XFLJLJ6I.js.map} +0 -0
  194. /package/dist/{chunk-RTCTD5PJ.js.map → chunk-26BZGPFZ.js.map} +0 -0
  195. /package/dist/{chunk-EVTMZ5IH.js.map → chunk-336YLJ5L.js.map} +0 -0
  196. /package/dist/{chunk-OCUUM755.js.map → chunk-4FOC35LW.js.map} +0 -0
  197. /package/dist/{chunk-B2WV5RAL.js.map → chunk-4GIAERRK.js.map} +0 -0
  198. /package/dist/{chunk-BQS73CWR.js.map → chunk-4LZLVHZE.js.map} +0 -0
  199. /package/dist/{chunk-DCENKA6E.js.map → chunk-4VTRRZWZ.js.map} +0 -0
  200. /package/dist/{chunk-GNERWNZY.js.map → chunk-5IZMEAKN.js.map} +0 -0
  201. /package/dist/{chunk-ATQB6PTV.js.map → chunk-5THKIWZU.js.map} +0 -0
  202. /package/dist/{chunk-NOQA7MJ4.js.map → chunk-6HVDHGNE.js.map} +0 -0
  203. /package/dist/{chunk-NYGKSOQ4.js.map → chunk-6ISLCEBR.js.map} +0 -0
  204. /package/dist/{chunk-F4UIKOU6.js.map → chunk-6RFDASKQ.js.map} +0 -0
  205. /package/dist/{chunk-5P27YL64.js.map → chunk-7I2UHJJF.js.map} +0 -0
  206. /package/dist/{chunk-FV7BSQPQ.js.map → chunk-AEH72XTU.js.map} +0 -0
  207. /package/dist/{chunk-DF4GOVDE.js.map → chunk-AUIHERJ7.js.map} +0 -0
  208. /package/dist/{chunk-6Y3VLCKA.js.map → chunk-AZF7HIDT.js.map} +0 -0
  209. /package/dist/{chunk-AIYZJ7XD.js.map → chunk-BTGPUOF7.js.map} +0 -0
  210. /package/dist/{chunk-EXZ4A6VJ.js.map → chunk-CJFAJV2K.js.map} +0 -0
  211. /package/dist/{chunk-LV5JRLBM.js.map → chunk-DP6YMZUL.js.map} +0 -0
  212. /package/dist/{chunk-Z4FWXDJG.js.map → chunk-DSDPJATB.js.map} +0 -0
  213. /package/dist/{chunk-RLPC3YKZ.js.map → chunk-EE744F4B.js.map} +0 -0
  214. /package/dist/{chunk-QOLHDDM2.js.map → chunk-EEMPMVCP.js.map} +0 -0
  215. /package/dist/{chunk-SDYY5MHW.js.map → chunk-EJZMCAM2.js.map} +0 -0
  216. /package/dist/{chunk-EYJ42LDG.js.map → chunk-EOXYDFBB.js.map} +0 -0
  217. /package/dist/{chunk-DC73NF67.js.map → chunk-ETO7CUIS.js.map} +0 -0
  218. /package/dist/{chunk-ZO7TF5OL.js.map → chunk-ETRKZHM5.js.map} +0 -0
  219. /package/dist/{chunk-HI674QZF.js.map → chunk-EVGYDJI2.js.map} +0 -0
  220. /package/dist/{chunk-PUJSLL6R.js.map → chunk-FEI73IPX.js.map} +0 -0
  221. /package/dist/{chunk-4QMWNAEJ.js.map → chunk-HCYES6U7.js.map} +0 -0
  222. /package/dist/{chunk-5FIUVBUC.js.map → chunk-JIMD77FI.js.map} +0 -0
  223. /package/dist/{chunk-TOMDOA4P.js.map → chunk-K76NOSEX.js.map} +0 -0
  224. /package/dist/{chunk-FGBLFF4O.js.map → chunk-KUYEYPO4.js.map} +0 -0
  225. /package/dist/{chunk-Z4P23XG3.js.map → chunk-L5U47Q63.js.map} +0 -0
  226. /package/dist/{chunk-EA4C6TVY.js.map → chunk-O7BXNXU2.js.map} +0 -0
  227. /package/dist/{chunk-ZTWZS5RK.js.map → chunk-OETBYJFV.js.map} +0 -0
  228. /package/dist/{chunk-CA56ETYX.js.map → chunk-TVIM5VV5.js.map} +0 -0
  229. /package/dist/{chunk-D2SVBU7R.js.map → chunk-ULI54QYZ.js.map} +0 -0
  230. /package/dist/{chunk-G4T2HGLJ.js.map → chunk-V6FD76AQ.js.map} +0 -0
  231. /package/dist/{chunk-QNOJOZYK.js.map → chunk-VVJY6IKW.js.map} +0 -0
  232. /package/dist/{chunk-Q2B3NUSM.js.map → chunk-WLYWO6JH.js.map} +0 -0
  233. /package/dist/{chunk-IU6LA6EB.js.map → chunk-WYCGV5Z7.js.map} +0 -0
  234. /package/dist/{chunk-CMRTNTMU.js.map → chunk-Z3JSYKOS.js.map} +0 -0
  235. /package/dist/{chunk-UAF2YFLZ.js.map → chunk-ZBVM57LO.js.map} +0 -0
  236. /package/dist/{chunk-GQ5WECPJ.js.map → chunk-ZDTFAMD2.js.map} +0 -0
  237. /package/dist/{chunk-EEHPZMS3.js.map → chunk-ZIZ5ZTEN.js.map} +0 -0
  238. /package/dist/{cli-OPORB5PF.js.map → cli-RQ7LQXRX.js.map} +0 -0
  239. /package/dist/{color-C223W3Z6.js.map → color-37SJ7NPH.js.map} +0 -0
  240. /package/dist/{config-KQYXQCQA.js.map → config-QMNCPBT7.js.map} +0 -0
  241. /package/dist/{coordinate-4E5GIMC6.js.map → coordinate-22N2UBE4.js.map} +0 -0
  242. /package/dist/{digest-GYF4YLUH.js.map → digest-H5YMEW54.js.map} +0 -0
  243. /package/dist/{history-25DNQKKC.js.map → history-E34WUNZO.js.map} +0 -0
  244. /package/dist/{hook-B4JO2X57.js.map → hook-IMBHXXH2.js.map} +0 -0
  245. /package/dist/{hydrate-IJEKNZIP.js.map → hydrate-IPNTSEDA.js.map} +0 -0
  246. /package/dist/{init-UJVOUDJI.js.map → init-V7Z3RVHQ.js.map} +0 -0
  247. /package/dist/{install-skills-FV2L5QHE.js.map → install-skills-PP7WYASM.js.map} +0 -0
  248. /package/dist/{keep-PKXGFZO2.js.map → keep-JZBFDYC5.js.map} +0 -0
  249. /package/dist/{list-VYQ3QE2H.js.map → list-D6GWBNUI.js.map} +0 -0
  250. /package/dist/{move-IAZY23ZX.js.map → move-T6IVLRRI.js.map} +0 -0
  251. /package/dist/{note-6HQUKUYY.js.map → note-L4YF6DYN.js.map} +0 -0
  252. /package/dist/{overlaps-CGP3RJOW.js.map → overlaps-33U2T7IV.js.map} +0 -0
  253. /package/dist/{pin-PAWGQ4Q2.js.map → pin-BVNCXHQI.js.map} +0 -0
  254. /package/dist/{prune-42MS36OR.js.map → prune-HUYBTMZM.js.map} +0 -0
  255. /package/dist/{read-ATNCW4KH.js.map → read-4OUYRSKS.js.map} +0 -0
  256. /package/dist/{remove-GLDJOKUI.js.map → remove-YCQLIDTS.js.map} +0 -0
  257. /package/dist/{report-AK7Z2Y4S.js.map → report-XMESBL7C.js.map} +0 -0
  258. /package/dist/{restart-DEPDGEZB.js.map → restart-NQ5DJ3TN.js.map} +0 -0
  259. /package/dist/{review-RYAGH3PY.js.map → review-MIKB545E.js.map} +0 -0
  260. /package/dist/{review-now-K4UWD7A5.js.map → review-now-VF6X6M64.js.map} +0 -0
  261. /package/dist/{run-WNP2SMNW.js.map → run-Y255ESUN.js.map} +0 -0
  262. /package/dist/{screen-P746M4F2.js.map → screen-AZFHPOCB.js.map} +0 -0
  263. /package/dist/{search-XQ2WMK5X.js.map → search-DAFKJTLY.js.map} +0 -0
  264. /package/dist/{section-Q7TPOV7U.js.map → section-WCC35C44.js.map} +0 -0
  265. /package/dist/{send-EGG23J2B.js.map → send-MYEMZU7Z.js.map} +0 -0
  266. /package/dist/{show-KSMC7AJL.js.map → show-JOO5OT2F.js.map} +0 -0
  267. /package/dist/{snooze-4LVYUQEX.js.map → snooze-7KLABMIG.js.map} +0 -0
  268. /package/dist/{start-YKLLXW3L.js.map → start-PGVZZJQT.js.map} +0 -0
  269. /package/dist/{status-4HGP4ZEF.js.map → status-CXIRNRMP.js.map} +0 -0
  270. /package/dist/{statusline-QJ6CJGHB.js.map → statusline-HPH2ORNT.js.map} +0 -0
  271. /package/dist/{stop-YBQL6NFF.js.map → stop-IJNUSRIG.js.map} +0 -0
  272. /package/dist/{sync-DUXN2MFJ.js.map → sync-3HMCC55V.js.map} +0 -0
  273. /package/dist/{time-Q42HPZZ3.js.map → time-DUDNSHM3.js.map} +0 -0
  274. /package/dist/{time-actions-IXZRVKKQ.js.map → time-actions-M4QTTH4M.js.map} +0 -0
  275. /package/dist/{timesheet-YJ6O3GUU.js.map → timesheet-BMKDX5KZ.js.map} +0 -0
  276. /package/dist/{todo-ZBFRL2A5.js.map → todo-QMXJ5R3E.js.map} +0 -0
  277. /package/dist/{update-RGNKMRUL.js.map → update-3TODL7J3.js.map} +0 -0
  278. /package/dist/{usage-YZRZKJ3H.js.map → usage-YFTN2IS7.js.map} +0 -0
  279. /package/dist/{usage-ask-BYPNLA2B.js.map → usage-ask-EZR3W3UW.js.map} +0 -0
  280. /package/dist/{version-4IOMOIDP.js.map → version-LNHKXZBP.js.map} +0 -0
  281. /package/dist/{wait-YOHPFWVJ.js.map → wait-B37BTCVG.js.map} +0 -0
@@ -0,0 +1,2653 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ensureAgentPath,
4
+ resumeFromParams,
5
+ stopHost
6
+ } from "./chunk-LZJ5VDUD.js";
7
+ import {
8
+ startedUnder,
9
+ stopLeftovers
10
+ } from "./chunk-PCJVBGRS.js";
11
+ import {
12
+ CATCH_UP_PARAM,
13
+ FLOW_PARAM,
14
+ HIGH_WATERMARK,
15
+ LOW_WATERMARK,
16
+ MIN_ROWS,
17
+ gridFromParams,
18
+ validGrid,
19
+ windowsPtyFor
20
+ } from "./chunk-6KMG4WNW.js";
21
+ import {
22
+ StreamStatus
23
+ } from "./chunk-BCYBF7KJ.js";
24
+ import {
25
+ PtyHostBusyError,
26
+ PtyHostClient,
27
+ PtyHostVersionError,
28
+ ensureHost,
29
+ findHost
30
+ } from "./chunk-ZDTFAMD2.js";
31
+ import {
32
+ adoptLegacyRestoreList,
33
+ dbPtySessions
34
+ } from "./chunk-HCYES6U7.js";
35
+ import {
36
+ HOST_FEATURES,
37
+ PROTOCOL_VERSION,
38
+ hostInfoPath,
39
+ hostStartLockPath,
40
+ isPersistedPty,
41
+ keepEnv
42
+ } from "./chunk-NS7WH53I.js";
43
+ import {
44
+ isAccountLoginId
45
+ } from "./chunk-SJBEIYLK.js";
46
+ import {
47
+ ASSISTANT_ID
48
+ } from "./chunk-K76NOSEX.js";
49
+ import "./chunk-7E5XPDKX.js";
50
+ import "./chunk-AEH72XTU.js";
51
+ import {
52
+ batchArgProblem,
53
+ programFor
54
+ } from "./chunk-4CXUVBOD.js";
55
+ import {
56
+ listProcessUsage,
57
+ loadHistory
58
+ } from "./chunk-XJQ7XJJC.js";
59
+ import "./chunk-NEJVK5CF.js";
60
+ import {
61
+ sessionIdFor
62
+ } from "./chunk-QGUBOOEN.js";
63
+ import {
64
+ agentById,
65
+ bestEffort,
66
+ buildAiLaunchArgs,
67
+ logSwallowed,
68
+ sessionToolFor,
69
+ swallow
70
+ } from "./chunk-BS6GTKF2.js";
71
+ import "./chunk-KGHWHAVF.js";
72
+ import "./chunk-KUYEYPO4.js";
73
+ import {
74
+ applyEnvDelta,
75
+ hasEnvDelta,
76
+ isEnvDelta
77
+ } from "./chunk-ED6YLB4S.js";
78
+ import {
79
+ VERSION
80
+ } from "./chunk-CJFAJV2K.js";
81
+ import "./chunk-Z6ACV5ZQ.js";
82
+ import "./chunk-JUGF3YE7.js";
83
+ import {
84
+ resolveWorkBinPath
85
+ } from "./chunk-HK6AZQ5Z.js";
86
+ import "./chunk-EVGYDJI2.js";
87
+ import {
88
+ loadConfig
89
+ } from "./chunk-ASGJ3MCL.js";
90
+ import "./chunk-W4GDPHIF.js";
91
+ import "./chunk-BR6OWWAA.js";
92
+ import {
93
+ killTree
94
+ } from "./chunk-VHENFC2S.js";
95
+ import {
96
+ shellEnv
97
+ } from "./chunk-QOSAWNOU.js";
98
+ import {
99
+ atomicWriteFile,
100
+ ensureFile,
101
+ withFileLock,
102
+ withFileLockSync
103
+ } from "./chunk-D2J3AD6L.js";
104
+ import {
105
+ report
106
+ } from "./chunk-5ZCCUM75.js";
107
+ import {
108
+ debug
109
+ } from "./chunk-IAKOKZYW.js";
110
+ import "./chunk-F2ECTTSY.js";
111
+
112
+ // src/commands/pty-host.ts
113
+ import chalk from "chalk";
114
+
115
+ // src/core/pty/pty-host.ts
116
+ import http from "http";
117
+ import crypto2 from "crypto";
118
+ import fs3 from "fs";
119
+ import os2 from "os";
120
+ import { WebSocketServer } from "ws";
121
+
122
+ // src/core/pty/pty-registry.ts
123
+ import fs2 from "fs";
124
+ import { randomBytes } from "crypto";
125
+
126
+ // src/core/pty/pty-session.ts
127
+ import pty from "node-pty";
128
+ import crossSpawn from "cross-spawn";
129
+ import childProcess from "child_process";
130
+ import { createRequire } from "module";
131
+ import os from "os";
132
+ import path2 from "path";
133
+
134
+ // src/core/pty/spawn-helper.ts
135
+ import fs from "fs";
136
+ import path from "path";
137
+ function makeSpawnHelperExecutable(ptyDir, platform = process.platform, arch = process.arch, f = fs) {
138
+ const out = { fixed: [], failed: [] };
139
+ if (platform === "win32") return out;
140
+ for (const file of [
141
+ path.join(ptyDir, "prebuilds", `${platform}-${arch}`, "spawn-helper"),
142
+ path.join(ptyDir, "build", "Release", "spawn-helper")
143
+ ]) {
144
+ let mode;
145
+ try {
146
+ mode = f.statSync(file).mode;
147
+ } catch {
148
+ continue;
149
+ }
150
+ if ((mode & 73) === 73) continue;
151
+ try {
152
+ f.chmodSync(file, mode & 511 | 493);
153
+ out.fixed.push(file);
154
+ } catch (err) {
155
+ out.failed.push({ file, error: err.message });
156
+ }
157
+ }
158
+ return out;
159
+ }
160
+
161
+ // src/core/pty/screen-mirror.ts
162
+ import xtermHeadless from "@xterm/headless";
163
+ import xtermSerialize from "@xterm/addon-serialize";
164
+ import xtermUnicode11 from "@xterm/addon-unicode11";
165
+
166
+ // src/core/pty/scrollback.ts
167
+ var REPLAY_SCROLLBACK = 2e3;
168
+
169
+ // src/core/pty/screen-mirror.ts
170
+ var { Terminal } = xtermHeadless;
171
+ var { SerializeAddon } = xtermSerialize;
172
+ var { Unicode11Addon } = xtermUnicode11;
173
+ var ESC = "\x1B";
174
+ var CSI = "\x1B[";
175
+ var ENTER_ALT = "\x1B[?1049h\x1B[H";
176
+ var START = "\x1B7\x1B[?1049l\x1B[H\x1B[2J\x1B[!p\x1B[0m";
177
+ var MOUSE_PROTOCOL = { x10: 9, vt200: 1e3, drag: 1002, any: 1003 };
178
+ var MOUSE_ENCODINGS = /* @__PURE__ */ new Set([1005, 1006, 1015, 1016]);
179
+ var ALT_SCREEN = /* @__PURE__ */ new Set([47, 1047, 1049]);
180
+ var CHARSET_SLOTS = ["(", ")", "*", "+"];
181
+ var CHARSET_FINALS = "0AB4C5RQKYE6ZH7=";
182
+ var KEYBOARD_STACK_MAX = 8;
183
+ var CONTROL = /[\x00-\x1f\x7f-\x9f]/g;
184
+ var freshScreen = () => ({ savedCursor: null, scrollRegion: null, keyboardFlags: [] });
185
+ var freshState = (title = null) => ({
186
+ cursorHidden: false,
187
+ cursorBlink: null,
188
+ cursorStyle: null,
189
+ title,
190
+ mouseEncoding: [],
191
+ alternateScroll: null,
192
+ colorSchemeUpdates: null,
193
+ modifyOtherKeys: null,
194
+ charsets: ["B", "B", "B", "B"],
195
+ normal: freshScreen(),
196
+ alternate: freshScreen()
197
+ });
198
+ var nums = (params) => params.filter((p) => typeof p === "number");
199
+ var decModes = (modes, final) => modes.length ? `${CSI}?${modes.join(";")}${final}` : "";
200
+ var cup = (row, col) => `${CSI}${row + 1};${col + 1}H`;
201
+ var SPECIAL_COLORS = ["10", "11", "12"];
202
+ var ScreenMirror = class {
203
+ terminal;
204
+ serializer = new SerializeAddon();
205
+ st = freshState();
206
+ /** OSC 9;4 and OSC 7501, as the agent last said them (stream-status.ts). */
207
+ stream = new StreamStatus();
208
+ answers = null;
209
+ /** The chunk being parsed is one the mirror answers the queries in (set and cleared by the write queue's callbacks). */
210
+ answering = false;
211
+ /** Writes and resizes queued and not applied yet: a resize waits behind them (`resize`). */
212
+ queued = 0;
213
+ /** The grid as last asked for: the terminal's own once every queued resize is applied. */
214
+ grid;
215
+ /** Snapshots waiting for the writes before them to be parsed (`snapshotSettled`). */
216
+ settling = /* @__PURE__ */ new Set();
217
+ /**
218
+ * The last snapshots taken, kept until the screen changes (a write, a resize): attaching again to a session that
219
+ * printed nothing since — a reload, switching back to it — is then sent the same text without serializing 2000
220
+ * lines again (~10 ms of the attach, terminal-rendering.md). Only ever kept or used with nothing queued: xterm
221
+ * parses a long write in slices, and a snapshot between two of them is of a screen that is still changing.
222
+ */
223
+ kept = {};
224
+ disposed = false;
225
+ /**
226
+ * `windowsPty`: the PTY is ConPTY's (terminal-size.ts `windowsPtyFor`), which reflows lines itself on a resize: the
227
+ * copy then resizes as the Terminal tab's xterm.js does with the same option, not reflowing them a second time.
228
+ */
229
+ constructor(cols, rows, scrollback = REPLAY_SCROLLBACK, opts = {}) {
230
+ this.terminal = new Terminal({
231
+ cols,
232
+ rows,
233
+ scrollback,
234
+ allowProposedApi: true,
235
+ ...opts.windowsPty ? { windowsPty: opts.windowsPty } : {}
236
+ });
237
+ this.grid = { cols, rows };
238
+ this.terminal.loadAddon(this.serializer);
239
+ this.terminal.loadAddon(new Unicode11Addon());
240
+ this.terminal.unicode.activeVersion = "11";
241
+ this.track();
242
+ this.terminal.onData((reply) => {
243
+ if (this.answering) this.answers?.send(reply);
244
+ });
245
+ this.answerColors();
246
+ }
247
+ /**
248
+ * From now on, the agent's queries in output written while `answers.now()` says so (no client attached) are
249
+ * answered here: what xterm answers itself, and the colour queries it leaves to a renderer (OSC 10, 11, 12 and 4).
250
+ */
251
+ answerQueries(answers) {
252
+ this.answers = answers;
253
+ }
254
+ /**
255
+ * Output, queued for parsing. Whether its queries are answered here is decided now, as it arrives: xterm parses it a
256
+ * moment later, by when a client may have attached (and been sent a screen with no query in it) or detached. A
257
+ * write's callback runs once it is parsed and before the next write is, so empty writes around it mark the chunk.
258
+ */
259
+ write(data, done) {
260
+ this.queued++;
261
+ this.kept = {};
262
+ const parsed = () => {
263
+ this.queued--;
264
+ done?.();
265
+ };
266
+ if (!this.answers?.now()) {
267
+ this.terminal.write(data, parsed);
268
+ return;
269
+ }
270
+ this.terminal.write("", () => this.answering = true);
271
+ this.terminal.write(data, () => {
272
+ this.answering = false;
273
+ parsed();
274
+ });
275
+ }
276
+ /**
277
+ * In order with the writes around it: output that arrived before the resize was drawn for the old grid and is parsed
278
+ * at it, output after it at the new one. xterm parses writes later, so a resize applied at once would lay out what is
279
+ * still queued for a grid it was never drawn for — and every snapshot after would carry it. With nothing queued it is
280
+ * applied now; else behind an empty write, whose callback runs once all before it is parsed. `snapshotSettled` waits
281
+ * the same way, so a snapshot asked for after a resize is at the new grid.
282
+ */
283
+ resize(cols, rows) {
284
+ if (cols === this.grid.cols && rows === this.grid.rows) return;
285
+ this.grid = { cols, rows };
286
+ if (!this.queued) {
287
+ this.applyResize(cols, rows);
288
+ return;
289
+ }
290
+ this.queued++;
291
+ try {
292
+ this.terminal.write("", () => {
293
+ this.queued--;
294
+ this.applyResize(cols, rows);
295
+ });
296
+ } catch {
297
+ this.queued--;
298
+ }
299
+ }
300
+ applyResize(cols, rows) {
301
+ if (cols === this.terminal.cols && rows === this.terminal.rows) return;
302
+ this.st.normal.scrollRegion = null;
303
+ this.st.alternate.scrollRegion = null;
304
+ this.kept = {};
305
+ this.terminal.resize(cols, rows);
306
+ }
307
+ /** What the agent last said about itself in its output (OSC 7501, else OSC 9;4), as far as it is parsed; null: nothing. */
308
+ streamSignal() {
309
+ return this.stream.signal();
310
+ }
311
+ /** A copy of the tracked state (tests, diagnostics). */
312
+ state() {
313
+ return structuredClone(this.st);
314
+ }
315
+ /**
316
+ * The screen and scrollback as escape sequences that redraw it, then the state that puts a fresh terminal in
317
+ * the same modes (`rehydrate`). What a client attaching is sent instead of raw output — raw bytes can start
318
+ * mid-sequence and were drawn for another client's grid. Null if it can't be taken (logged): never an empty screen
319
+ * in its place, which a client would draw over the one it has (pty-registry.ts decides what it is sent instead).
320
+ * `scrollback: false`: the screen only (SnapshotOptions). The positions written after it (the saved cursor, the
321
+ * cursor, the normal screen's under the alternate one) count from the screen's top, so they are the same either way.
322
+ */
323
+ snapshot(opts = {}) {
324
+ const which = opts.scrollback === false ? "screen" : "full";
325
+ const kept = this.queued ? void 0 : this.kept[which];
326
+ if (kept !== void 0) return kept;
327
+ const taken = this.serialize(opts);
328
+ if (taken !== null && !this.queued) this.kept[which] = taken;
329
+ return taken;
330
+ }
331
+ serialize(opts) {
332
+ let body;
333
+ try {
334
+ body = this.serializer.serialize(opts.scrollback === false ? { scrollback: 0 } : void 0);
335
+ } catch (err) {
336
+ logSwallowed("screen copy: take a snapshot", err);
337
+ return null;
338
+ }
339
+ let regionBeforeAlt = false;
340
+ if (this.terminal.buffer.active.type === "alternate") {
341
+ const at = body.indexOf(ENTER_ALT);
342
+ if (at >= 0) {
343
+ const normal = this.normalUnderAlt();
344
+ regionBeforeAlt = normal.region;
345
+ body = body.slice(0, at) + normal.text + body.slice(at);
346
+ }
347
+ }
348
+ return START + body + this.rehydrate(regionBeforeAlt);
349
+ }
350
+ /** snapshot(), once everything written so far is parsed: xterm queues writes, and a write's callback runs once it is. */
351
+ snapshotSettled(opts = {}) {
352
+ return new Promise((resolve) => {
353
+ if (this.disposed) return resolve("");
354
+ const settle = () => {
355
+ this.settling.delete(settle);
356
+ resolve(this.disposed ? "" : this.snapshot(opts));
357
+ };
358
+ this.settling.add(settle);
359
+ try {
360
+ this.terminal.write("", settle);
361
+ } catch {
362
+ settle();
363
+ }
364
+ });
365
+ }
366
+ /** The visible screen as plain text, one line per row. */
367
+ screenText() {
368
+ try {
369
+ const buf = this.terminal.buffer.active;
370
+ const lines = [];
371
+ for (let y = buf.viewportY; y < buf.viewportY + this.terminal.rows; y++) {
372
+ lines.push(buf.getLine(y)?.translateToString(true) ?? "");
373
+ }
374
+ return lines.join("\n");
375
+ } catch {
376
+ return "";
377
+ }
378
+ }
379
+ /** Disposing drops xterm's queued writes and their callbacks: a snapshot still waiting is answered '' then, never left hanging. */
380
+ dispose() {
381
+ this.disposed = true;
382
+ const waiting = [...this.settling];
383
+ this.settling.clear();
384
+ this.terminal.dispose();
385
+ for (const settle of waiting) settle();
386
+ }
387
+ get screen() {
388
+ return this.terminal.buffer.active.type;
389
+ }
390
+ /** The normal screen's own state while the alternate one is shown: its scroll region (then its cursor again,
391
+ * which DECSTBM homes and 1049 saves) and its keyboard flags. */
392
+ normalUnderAlt() {
393
+ const n = this.st.normal;
394
+ const cur = this.terminal.buffer.normal;
395
+ let text = "";
396
+ if (n.scrollRegion) text += `${CSI}${n.scrollRegion.top + 1};${n.scrollRegion.bottom + 1}r`;
397
+ if (n.scrollRegion || cur.cursorX < this.terminal.cols) text += cup(cur.cursorY, Math.min(cur.cursorX, this.terminal.cols - 1));
398
+ text += n.keyboardFlags.map((f) => `${CSI}>${f}u`).join("");
399
+ return { text, region: !!n.scrollRegion };
400
+ }
401
+ /**
402
+ * Everything after the addon's output, in an order that matters: the saved cursor first (it needs an absolute
403
+ * position), the modes, then the scroll region and origin mode — both move the cursor — and the cursor last.
404
+ * Each mode is stated whatever the addon wrote, so one it already wrote (or a later addon version writes) is
405
+ * only said twice; modes with a universal default are stated either way, so a native terminal that `work attach`
406
+ * writes into ends in them even if something left it otherwise. Never 2026 (synchronized output): a snapshot
407
+ * with it on would hold the client's screen until the app happened to turn it off.
408
+ */
409
+ rehydrate(regionBeforeAlt) {
410
+ const t = this.terminal;
411
+ const m = t.modes;
412
+ const s = this.st;
413
+ const buf = t.buffer.active;
414
+ const screen = s[this.screen];
415
+ let out = "";
416
+ let moved = false;
417
+ if (m.originMode) {
418
+ out += `${CSI}?6l`;
419
+ moved = true;
420
+ }
421
+ if (screen.savedCursor) {
422
+ out += cup(Math.max(screen.savedCursor.line - buf.baseY, 0), Math.min(screen.savedCursor.x, t.cols - 1)) + `${ESC}7`;
423
+ moved = true;
424
+ }
425
+ out += `${CSI}?9;1000;1002;1003l`;
426
+ if (m.mouseTrackingMode !== "none") out += `${CSI}?${MOUSE_PROTOCOL[m.mouseTrackingMode]}h`;
427
+ out += `${CSI}?1005;1006;1015;1016l`;
428
+ for (const e of s.mouseEncoding) out += `${CSI}?${e.mode}${e.on ? "h" : "l"}`;
429
+ const on = [];
430
+ const off = [];
431
+ const state = (mode, value) => {
432
+ if (value !== null) (value ? on : off).push(mode);
433
+ };
434
+ state(1, m.applicationCursorKeysMode);
435
+ state(7, m.wraparoundMode);
436
+ state(12, s.cursorBlink);
437
+ state(25, !s.cursorHidden);
438
+ state(45, m.reverseWraparoundMode);
439
+ state(1004, m.sendFocusMode);
440
+ state(1007, s.alternateScroll);
441
+ state(2004, m.bracketedPasteMode);
442
+ state(2031, s.colorSchemeUpdates);
443
+ out += decModes(off, "l") + decModes(on, "h");
444
+ out += m.applicationKeypadMode ? `${ESC}=` : `${ESC}>`;
445
+ out += m.insertMode ? `${CSI}4h` : `${CSI}4l`;
446
+ if (s.cursorStyle !== null) out += `${CSI}${s.cursorStyle} q`;
447
+ if (s.title !== null) out += `${ESC}]2;${s.title.replace(CONTROL, "")}\x07`;
448
+ out += screen.keyboardFlags.map((f) => `${CSI}>${f}u`).join("");
449
+ if (s.modifyOtherKeys !== null) out += `${CSI}>4;${s.modifyOtherKeys}m`;
450
+ s.charsets.forEach((f, i) => {
451
+ if (f !== "B") out += `${ESC}${CHARSET_SLOTS[i]}${f}`;
452
+ });
453
+ const region = screen.scrollRegion;
454
+ if (region || regionBeforeAlt) {
455
+ out += region ? `${CSI}${region.top + 1};${region.bottom + 1}r` : `${CSI}r`;
456
+ moved = true;
457
+ }
458
+ if (m.originMode) out += `${CSI}?6h`;
459
+ const pendingWrap = buf.cursorX >= t.cols;
460
+ if (moved || !pendingWrap) {
461
+ const top = m.originMode && region ? region.top : 0;
462
+ out += cup(buf.cursorY - top, Math.min(buf.cursorX, t.cols - 1));
463
+ }
464
+ return out;
465
+ }
466
+ track() {
467
+ const t = this.terminal;
468
+ const p = t.parser;
469
+ t.onTitleChange((title) => this.st.title = title);
470
+ p.registerCsiHandler({ prefix: "?", final: "h" }, (params) => this.decset(nums(params), true));
471
+ p.registerCsiHandler({ prefix: "?", final: "l" }, (params) => this.decset(nums(params), false));
472
+ p.registerCsiHandler({ intermediates: " ", final: "q" }, (params) => {
473
+ const n = nums(params)[0] ?? 0;
474
+ if (n >= 0 && n <= 6) this.st.cursorStyle = n === 0 ? null : n;
475
+ return false;
476
+ });
477
+ p.registerCsiHandler({ final: "r" }, (params) => {
478
+ const [first = 0, second = 0] = nums(params);
479
+ const top = first || 1;
480
+ const bottom = params.length < 2 || second > t.rows || second === 0 ? t.rows : second;
481
+ if (bottom > top) this.st[this.screen].scrollRegion = top === 1 && bottom === t.rows ? null : { top: top - 1, bottom: bottom - 1 };
482
+ return false;
483
+ });
484
+ p.registerEscHandler({ final: "7" }, () => this.saveCursor(this.screen));
485
+ p.registerCsiHandler({ final: "s" }, () => this.saveCursor(this.screen));
486
+ p.registerCsiHandler({ intermediates: "!", final: "p" }, () => {
487
+ const screen = this.st[this.screen];
488
+ screen.savedCursor = null;
489
+ screen.scrollRegion = null;
490
+ this.st.cursorHidden = false;
491
+ this.st.cursorStyle = null;
492
+ this.st.charsets = ["B", "B", "B", "B"];
493
+ return false;
494
+ });
495
+ p.registerEscHandler({ final: "c" }, () => {
496
+ this.st = { ...freshState(this.st.title), cursorBlink: this.st.cursorBlink, cursorHidden: this.st.cursorHidden };
497
+ this.stream.reset();
498
+ return false;
499
+ });
500
+ p.registerOscHandler(9, (data) => {
501
+ this.stream.osc9(data);
502
+ return false;
503
+ });
504
+ p.registerOscHandler(7501, (data) => {
505
+ this.stream.osc7501(data);
506
+ return false;
507
+ });
508
+ for (const [i, slot] of CHARSET_SLOTS.entries())
509
+ for (const final of CHARSET_FINALS)
510
+ p.registerEscHandler({ intermediates: slot, final }, () => {
511
+ this.st.charsets[i] = final;
512
+ return false;
513
+ });
514
+ p.registerCsiHandler({ prefix: ">", final: "u" }, (params) => {
515
+ const stack = this.st[this.screen].keyboardFlags;
516
+ stack.push(nums(params)[0] ?? 0);
517
+ if (stack.length > KEYBOARD_STACK_MAX) stack.shift();
518
+ return false;
519
+ });
520
+ p.registerCsiHandler({ prefix: "<", final: "u" }, (params) => {
521
+ const stack = this.st[this.screen].keyboardFlags;
522
+ stack.splice(Math.max(stack.length - (nums(params)[0] || 1), 0));
523
+ return false;
524
+ });
525
+ p.registerCsiHandler({ prefix: "=", final: "u" }, (params) => {
526
+ const stack = this.st[this.screen].keyboardFlags;
527
+ const [flags = 0, mode = 1] = nums(params);
528
+ const current = stack.at(-1) ?? 0;
529
+ const next = mode === 2 ? current | flags : mode === 3 ? current & ~flags : flags;
530
+ if (stack.length) stack[stack.length - 1] = next;
531
+ else if (next) stack.push(next);
532
+ return false;
533
+ });
534
+ p.registerCsiHandler({ prefix: ">", final: "m" }, (params) => {
535
+ const [resource = 0, value] = nums(params);
536
+ if (resource === 4 || params.length <= 1) this.st.modifyOtherKeys = resource === 4 && value ? value : null;
537
+ return false;
538
+ });
539
+ p.registerCsiHandler({ prefix: ">", final: "n" }, (params) => {
540
+ const resource = nums(params)[0] ?? 0;
541
+ if (resource === 4 || resource === 0) this.st.modifyOtherKeys = null;
542
+ return false;
543
+ });
544
+ }
545
+ /**
546
+ * OSC 10 / 11 / 12 / 4 with `?`: xterm.js leaves the answer to its renderer, so a headless one stays silent. Answered
547
+ * as the browser's xterm.js does (`_setOrReportSpecialColor`, `setOrReportIndexedColor`): OSC 10 ; ? ; ? asks for 10
548
+ * and 11, OSC 4 takes index ; ? pairs. Each handler returns false: xterm still handles a colour being set.
549
+ */
550
+ answerColors() {
551
+ const p = this.terminal.parser;
552
+ SPECIAL_COLORS.forEach(
553
+ (first, offset) => p.registerOscHandler(Number(first), (data) => {
554
+ const a = this.answering ? this.answers : null;
555
+ data.split(";").forEach((spec, i) => {
556
+ const slot = SPECIAL_COLORS[offset + i];
557
+ if (a && slot && spec === "?") a.send(a.colors.reply(slot));
558
+ });
559
+ return false;
560
+ })
561
+ );
562
+ p.registerOscHandler(4, (data) => {
563
+ const a = this.answering ? this.answers : null;
564
+ const slots = data.split(";");
565
+ for (let i = 0; a && i + 1 < slots.length; i += 2) {
566
+ const index = /^\d+$/.test(slots[i]) ? Number(slots[i]) : -1;
567
+ if (index >= 0 && index <= 255 && slots[i + 1] === "?") a.send(a.colors.reply(`4;${index}`));
568
+ }
569
+ return false;
570
+ });
571
+ }
572
+ saveCursor(screen) {
573
+ const buf = this.terminal.buffer.active;
574
+ this.st[screen].savedCursor = { x: buf.cursorX, line: buf.baseY + buf.cursorY };
575
+ return false;
576
+ }
577
+ decset(modes, on) {
578
+ const s = this.st;
579
+ let screen = this.screen;
580
+ for (const mode of modes) {
581
+ if (mode === 12) s.cursorBlink = on;
582
+ else if (mode === 25) s.cursorHidden = !on;
583
+ else if (mode === 1007) s.alternateScroll = on;
584
+ else if (mode === 2031) s.colorSchemeUpdates = on;
585
+ else if (MOUSE_ENCODINGS.has(mode)) {
586
+ s.mouseEncoding = [...s.mouseEncoding.filter((e) => e.mode !== mode), { mode, on }];
587
+ if (s.mouseEncoding.every((e) => !e.on)) s.mouseEncoding = [];
588
+ } else if (mode === 1048 && on) this.saveCursor(screen);
589
+ else if (ALT_SCREEN.has(mode)) {
590
+ if (on) screen = "alternate";
591
+ else if (screen === "alternate") {
592
+ s.alternate.scrollRegion = null;
593
+ s.alternate.keyboardFlags = [];
594
+ if (mode === 1049) s.normal.savedCursor = null;
595
+ screen = "normal";
596
+ }
597
+ }
598
+ }
599
+ return false;
600
+ }
601
+ };
602
+
603
+ // src/core/pty/sync-output.ts
604
+ var SYNC_MODE = 2026;
605
+ var MAX_PARAMS = 64;
606
+ var GROUND = 0;
607
+ var ESCAPE = 1;
608
+ var CSI2 = 2;
609
+ var PRIVATE = 3;
610
+ var SyncScanner = class {
611
+ /** A frame is open: a set was seen and no reset since. */
612
+ open = false;
613
+ state = GROUND;
614
+ params = "";
615
+ /** Follow `chunk`: the places in it where a frame opened or closed, in order. */
616
+ feed(chunk) {
617
+ const changes = [];
618
+ let i = 0;
619
+ while (i < chunk.length) {
620
+ if (this.state === GROUND) {
621
+ const esc = chunk.indexOf("\x1B", i);
622
+ if (esc < 0) break;
623
+ this.state = ESCAPE;
624
+ i = esc + 1;
625
+ continue;
626
+ }
627
+ const c = chunk[i];
628
+ if (this.state === ESCAPE) {
629
+ if (c === "[") this.state = CSI2;
630
+ else {
631
+ this.state = GROUND;
632
+ if (c === "c")
633
+ this.change(false, i + 1, changes);
634
+ else if (c === "\x1B") this.state = ESCAPE;
635
+ }
636
+ } else if (this.state === CSI2) {
637
+ if (c === "?") {
638
+ this.state = PRIVATE;
639
+ this.params = "";
640
+ } else this.state = c === "\x1B" ? ESCAPE : GROUND;
641
+ } else if (c >= "0" && c <= "9" || c === ";" || c === ":") {
642
+ this.params += c;
643
+ if (this.params.length > MAX_PARAMS) this.state = GROUND;
644
+ } else {
645
+ this.state = c === "\x1B" ? ESCAPE : GROUND;
646
+ if ((c === "h" || c === "l") && this.params.split(";").some((p) => Number(p.split(":")[0]) === SYNC_MODE))
647
+ this.change(c === "h", i + 1, changes);
648
+ }
649
+ i++;
650
+ }
651
+ return changes;
652
+ }
653
+ /** Start again with no frame open (the PTY's process changed). */
654
+ reset() {
655
+ this.open = false;
656
+ this.state = GROUND;
657
+ this.params = "";
658
+ }
659
+ change(open, at, changes) {
660
+ if (open === this.open) return;
661
+ this.open = open;
662
+ changes.push({ at, open });
663
+ }
664
+ };
665
+ function cutAtFrameEnds(scanner, chunk) {
666
+ const ends = scanner.feed(chunk).filter((c) => !c.open && c.at < chunk.length);
667
+ if (!ends.length) return [chunk];
668
+ const pieces = [];
669
+ let from = 0;
670
+ for (const { at } of ends) {
671
+ pieces.push(chunk.slice(from, at));
672
+ from = at;
673
+ }
674
+ pieces.push(chunk.slice(from));
675
+ return pieces;
676
+ }
677
+
678
+ // src/core/pty/pty-session.ts
679
+ var HIDDEN = /* @__PURE__ */ Symbol.for("work.forkHidesConsole");
680
+ function hideForkConsoles(cp) {
681
+ if (cp.fork[HIDDEN]) return;
682
+ const orig = cp.fork;
683
+ const wrapped = function(modulePath, a, b) {
684
+ const args = Array.isArray(a) ? a : [];
685
+ const options = (Array.isArray(a) || a == null ? b : a) ?? {};
686
+ return orig.call(cp, modulePath, args, { windowsHide: true, ...options });
687
+ };
688
+ wrapped[HIDDEN] = true;
689
+ cp.fork = wrapped;
690
+ }
691
+ if (process.platform === "win32") hideForkConsoles(childProcess);
692
+ var spawnHelperChecked = false;
693
+ function ensureSpawnHelper() {
694
+ if (spawnHelperChecked) return;
695
+ spawnHelperChecked = true;
696
+ try {
697
+ const dir = path2.dirname(createRequire(import.meta.url).resolve("node-pty/package.json"));
698
+ const { fixed, failed } = makeSpawnHelperExecutable(dir);
699
+ for (const file of fixed) debug("made node-pty spawn-helper executable", file);
700
+ for (const { file, error } of failed)
701
+ report(
702
+ "warn",
703
+ `node-pty's spawn-helper isn't executable and couldn't be made so (${error}): terminals can't start. Run: chmod +x "${file}"`
704
+ );
705
+ } catch (err) {
706
+ debug("spawn-helper check failed", err.message);
707
+ }
708
+ }
709
+ function startsAsBatch(cmd, env = process.env, platform = process.platform, cwd) {
710
+ return platform === "win32" && programFor(cmd, { env, cwd })?.batch === true;
711
+ }
712
+ function resolvePtyCommand(cmd, args, opts = {}) {
713
+ if (process.platform !== "win32") return { file: cmd, args };
714
+ const program = programFor(cmd, { env: opts.env ?? process.env, cwd: opts.cwd });
715
+ if (!program) throw new Error(`${cmd} not found on PATH`);
716
+ if (!program.batch) return { file: program.file, args: [...program.pre, ...args] };
717
+ const why = batchArgProblem(args);
718
+ if (why) throw new Error(`${cmd}: ${why}`);
719
+ const parse = crossSpawn._parse;
720
+ const parsed = parse(program.file, args, opts);
721
+ const env = shellEnv(opts.env ?? process.env);
722
+ if (parsed.options.windowsVerbatimArguments) {
723
+ return { file: parsed.command, args: parsed.args.join(" "), env };
724
+ }
725
+ return { file: parsed.file ?? parsed.command, args: parsed.args, env };
726
+ }
727
+ function terminalEnv(env) {
728
+ return env.COLORTERM ? env : { ...env, COLORTERM: "truecolor" };
729
+ }
730
+ var PROMPT_SETTLE_MS = 800;
731
+ var PROMPT_WAIT_MS = 2e4;
732
+ function typeWhenSettled(target, text, opts) {
733
+ let quiet;
734
+ let typed = false;
735
+ const stop = () => {
736
+ typed = true;
737
+ clearTimeout(quiet);
738
+ clearTimeout(cap);
739
+ sub.dispose();
740
+ };
741
+ const type = () => {
742
+ if (typed) return;
743
+ stop();
744
+ if (opts.exited()) return;
745
+ opts.submit(text).catch((err) => debug("PtySession: typing the first prompt failed", err.message));
746
+ };
747
+ const cap = setTimeout(type, opts.waitMs ?? PROMPT_WAIT_MS);
748
+ cap.unref?.();
749
+ const sub = target.onData(() => {
750
+ if (typed) return;
751
+ clearTimeout(quiet);
752
+ quiet = setTimeout(type, opts.settleMs ?? PROMPT_SETTLE_MS);
753
+ });
754
+ target.onExit(() => {
755
+ if (!typed) stop();
756
+ });
757
+ }
758
+ function readUseBundledConpty() {
759
+ try {
760
+ return loadConfig()?.useBundledConpty === true;
761
+ } catch {
762
+ return false;
763
+ }
764
+ }
765
+ function conptyOptions(platform, useBundled) {
766
+ return platform === "win32" && useBundled ? { useConptyDll: true } : {};
767
+ }
768
+ function conptyFor(platform, release, useBundled) {
769
+ const options = conptyOptions(platform, useBundled);
770
+ const windowsPty = windowsPtyFor(platform, release, options.useConptyDll === true);
771
+ return windowsPty ? { options, windowsPty } : { options };
772
+ }
773
+ function readAgentsLowPriority() {
774
+ try {
775
+ return loadConfig()?.agentsLowPriority === true;
776
+ } catch {
777
+ return false;
778
+ }
779
+ }
780
+ function lowerPriority(pid, set = os.setPriority) {
781
+ try {
782
+ set(pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
783
+ return null;
784
+ } catch (err) {
785
+ return err.message;
786
+ }
787
+ }
788
+ function slowStart(ms) {
789
+ return {
790
+ note: ms > 1e3 ? `(the start took ${ms} ms)` : "",
791
+ warn: ms > 5e3 ? `[pty] starting a terminal took ${Math.round(ms / 1e3)} s: the PTY host answered nothing meanwhile` : null
792
+ };
793
+ }
794
+ function canPauseOutput(platform) {
795
+ return platform !== "win32";
796
+ }
797
+ function onChildExit(pty2, exiting) {
798
+ const target = pty2;
799
+ const once = target.once;
800
+ if (typeof once !== "function") return false;
801
+ target.once = function(event, listener) {
802
+ if (event === "close") exiting();
803
+ return once.call(this, event, listener);
804
+ };
805
+ return true;
806
+ }
807
+ var PtySession = class {
808
+ pty;
809
+ /**
810
+ * Stop reading the agent's output, and start again (flow control, output-pacer.ts): paused, its writes block once
811
+ * the PTY's buffer is full. Undefined where that isn't safe (`canPauseOutput`).
812
+ */
813
+ pause;
814
+ resume;
815
+ paused = false;
816
+ /** The PTY host's copy of the screen (screen-mirror.ts): what a client attaching is sent first. */
817
+ mirror;
818
+ /** The ConPTY it runs on, as xterm.js's `windowsPty` (its screens say it, pty-registry.ts); undefined off Windows. */
819
+ windowsPty;
820
+ /** Where its output is in synchronized frames (sync-output.ts): it is cut at each frame's end. */
821
+ frames = new SyncScanner();
822
+ cwd;
823
+ outputHandler;
824
+ _exited = false;
825
+ _outputBuffer = "";
826
+ _loggedOutput = false;
827
+ onExit;
828
+ constructor(cwd, cols, rows, command, aiOptions) {
829
+ this.cwd = cwd;
830
+ const conpty = conptyFor(process.platform, os.release(), readUseBundledConpty());
831
+ if (conpty.windowsPty) this.windowsPty = conpty.windowsPty;
832
+ this.mirror = new ScreenMirror(cols, rows, void 0, { windowsPty: conpty.windowsPty });
833
+ let rawCmd;
834
+ let rawArgs;
835
+ let typeLater;
836
+ if (command) {
837
+ rawCmd = command.cmd;
838
+ rawArgs = command.args;
839
+ } else if (aiOptions) {
840
+ const launchOpts = { resume: aiOptions.resume, promptFile: aiOptions.promptFile };
841
+ ({ cmd: rawCmd, args: rawArgs } = buildAiLaunchArgs(aiOptions.tool, { ...launchOpts, initialPrompt: aiOptions.initialPrompt }));
842
+ if (aiOptions.initialPrompt && batchArgProblem([aiOptions.initialPrompt]) && startsAsBatch(aiOptions.tool.cmd, aiOptions.env, process.platform, cwd)) {
843
+ ({ cmd: rawCmd, args: rawArgs } = buildAiLaunchArgs(aiOptions.tool, launchOpts));
844
+ typeLater = aiOptions.initialPrompt;
845
+ }
846
+ } else {
847
+ throw new Error("PtySession requires either a custom command or aiOptions");
848
+ }
849
+ const env = terminalEnv(
850
+ Object.fromEntries(
851
+ Object.entries(agentById(aiOptions?.tool.cmd ?? "claude").launch.cleanEnv(aiOptions?.env ?? process.env)).filter(
852
+ (e) => e[1] != null
853
+ )
854
+ )
855
+ );
856
+ if (aiOptions?.port !== void 0) {
857
+ env.PORT = String(aiOptions.port);
858
+ }
859
+ const { file: spawnCmd, args: spawnArgs, env: batchEnv } = resolvePtyCommand(rawCmd, rawArgs, { env, cwd });
860
+ debug("PtySession spawn", { spawnCmd, spawnArgs, cwd, cols, rows });
861
+ ensureSpawnHelper();
862
+ const started = Date.now();
863
+ this.pty = pty.spawn(spawnCmd, spawnArgs, {
864
+ name: "xterm-256color",
865
+ cwd,
866
+ cols,
867
+ rows,
868
+ env: batchEnv ?? env,
869
+ ...conpty.options
870
+ });
871
+ const slow = slowStart(Date.now() - started);
872
+ debug("PtySession spawned pid=", this.pty.pid, slow.note);
873
+ if (slow.warn) report("warn", slow.warn);
874
+ if (aiOptions && readAgentsLowPriority()) {
875
+ const why = lowerPriority(this.pty.pid);
876
+ debug(why ? `PtySession: couldn't lower the agent's priority (${why})` : "PtySession: agent started below normal priority");
877
+ }
878
+ if (canPauseOutput(process.platform)) {
879
+ let ending = false;
880
+ onChildExit(this.pty, () => {
881
+ ending = true;
882
+ this.resume?.();
883
+ });
884
+ this.pause = () => {
885
+ if (this._exited || ending || this.paused) return;
886
+ this.paused = true;
887
+ try {
888
+ this.pty.pause();
889
+ } catch {
890
+ }
891
+ };
892
+ this.resume = () => {
893
+ if (!this.paused) return;
894
+ this.paused = false;
895
+ try {
896
+ this.pty.resume();
897
+ } catch {
898
+ }
899
+ };
900
+ }
901
+ this.pty.onData((data) => {
902
+ for (const piece of cutAtFrameEnds(this.frames, data)) {
903
+ this.mirror.write(piece);
904
+ this.outputHandler?.(piece);
905
+ }
906
+ if (!this._loggedOutput) {
907
+ this._outputBuffer = (this._outputBuffer || "") + data;
908
+ if (this._outputBuffer.length > 500) {
909
+ debug("PtySession first output", { cwd, output: this._outputBuffer.slice(0, 500) });
910
+ this._loggedOutput = true;
911
+ this._outputBuffer = "";
912
+ }
913
+ }
914
+ });
915
+ if (typeLater !== void 0) {
916
+ const agent = agentById(aiOptions?.tool.cmd ?? "claude");
917
+ typeWhenSettled(this.pty, typeLater, {
918
+ exited: () => this._exited,
919
+ submit: (text) => agent.input.submit((d) => {
920
+ this.write(d);
921
+ return Promise.resolve(!this._exited);
922
+ }, text)
923
+ });
924
+ }
925
+ this.pty.onExit(({ exitCode }) => {
926
+ if (!this._loggedOutput && this._outputBuffer) {
927
+ debug("PtySession output before exit", { cwd, output: this._outputBuffer.slice(0, 500) });
928
+ }
929
+ this._outputBuffer = "";
930
+ debug("PtySession exited", { cwd, exitCode });
931
+ this._exited = true;
932
+ this.onExit?.(exitCode);
933
+ });
934
+ }
935
+ get exited() {
936
+ return this._exited;
937
+ }
938
+ write(data) {
939
+ if (!this._exited) {
940
+ try {
941
+ this.pty.write(data);
942
+ } catch {
943
+ }
944
+ }
945
+ }
946
+ resize(cols, rows) {
947
+ if (!this._exited) {
948
+ try {
949
+ this.pty.resize(cols, rows);
950
+ } catch {
951
+ }
952
+ this.mirror.resize(cols, rows);
953
+ }
954
+ }
955
+ /**
956
+ * The agent's queries in output that arrives while `now()` says so (no client attached: pty-registry.ts) are answered
957
+ * by the screen's copy, colour queries from `colors` (ScreenMirror.answerQueries).
958
+ */
959
+ answerQueries(now, colors) {
960
+ this.mirror.answerQueries({ now, colors, send: (reply) => this.write(reply) });
961
+ }
962
+ /** The headless terminal the screen is kept in. */
963
+ get terminal() {
964
+ return this.mirror.terminal;
965
+ }
966
+ /**
967
+ * The current screen + scrollback as escape sequences that redraw it
968
+ * exactly (colors, cursor, modes, alt screen — ScreenMirror.snapshot). What a late attacher is
969
+ * sent instead of raw output history — raw bytes can start mid-sequence
970
+ * and were drawn for another client's grid (VS Code does the same).
971
+ */
972
+ serialize(opts) {
973
+ return this.mirror.snapshot(opts);
974
+ }
975
+ /**
976
+ * serialize(), once the screen has parsed everything written to it so far:
977
+ * xterm queues writes, and a write's callback runs right after that write
978
+ * is parsed — before any written later. What a new client is sent first.
979
+ */
980
+ serializeSettled(opts) {
981
+ return this.mirror.snapshotSettled(opts);
982
+ }
983
+ /** The visible screen as plain text, one line per row (no colors).
984
+ * What the dashboard checks before answering a prompt by keystroke. */
985
+ screenText() {
986
+ return this.mirror.screenText();
987
+ }
988
+ /** What the agent last said about itself in its output: OSC 7501 program status, else OSC 9;4 progress (stream-status.ts). */
989
+ streamSignal() {
990
+ return this.mirror.streamSignal();
991
+ }
992
+ setOutputHandler(handler) {
993
+ this.outputHandler = handler;
994
+ }
995
+ dispose() {
996
+ this.setOutputHandler(void 0);
997
+ this.resume?.();
998
+ if (!this._exited) {
999
+ try {
1000
+ this.pty.kill();
1001
+ } catch {
1002
+ }
1003
+ }
1004
+ this.mirror.dispose();
1005
+ }
1006
+ };
1007
+
1008
+ // src/core/pty/terminal-colors.ts
1009
+ var TERMINAL_THEME = { background: "#1e1e1e", foreground: "#d4d4d4", cursor: "#ffffff" };
1010
+ var ANSI_16 = [
1011
+ "#2e3436",
1012
+ "#cc0000",
1013
+ "#4e9a06",
1014
+ "#c4a000",
1015
+ "#3465a4",
1016
+ "#75507b",
1017
+ "#06989a",
1018
+ "#d3d7cf",
1019
+ "#555753",
1020
+ "#ef2929",
1021
+ "#8ae234",
1022
+ "#fce94f",
1023
+ "#729fcf",
1024
+ "#ad7fa8",
1025
+ "#34e2e2",
1026
+ "#eeeeec"
1027
+ ];
1028
+ var CUBE = [0, 95, 135, 175, 215, 255];
1029
+ function paletteRgb(index) {
1030
+ if (index < 16) return hexRgb(ANSI_16[index]);
1031
+ if (index < 232) {
1032
+ const i = index - 16;
1033
+ return [CUBE[Math.floor(i / 36) % 6], CUBE[Math.floor(i / 6) % 6], CUBE[i % 6]];
1034
+ }
1035
+ const c = 8 + (index - 232) * 10;
1036
+ return [c, c, c];
1037
+ }
1038
+ function hexRgb(hex) {
1039
+ return [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16));
1040
+ }
1041
+ function rgbSpec([r, g, b]) {
1042
+ const two = (n) => n.toString(16).padStart(2, "0").repeat(2);
1043
+ return `rgb:${two(r)}/${two(g)}/${two(b)}`;
1044
+ }
1045
+ var SPEC = /^(?:rgb:[\da-f]{1,4}\/[\da-f]{1,4}\/[\da-f]{1,4}|#(?:[\da-f]{3}){1,4})$/i;
1046
+ var COLOR_REPLY = /^\x1b\]((?:1[0-2])|4;\d{1,3});([^\x07\x1b]*)(?:\x07|\x1b\\)$/;
1047
+ var TerminalColors = class {
1048
+ seen = /* @__PURE__ */ new Map();
1049
+ /** A colour reply a terminal sent (`ESC ] 11 ; rgb:… ST`): remembered for its slot. Anything else is ignored. */
1050
+ remember(reply) {
1051
+ const m = COLOR_REPLY.exec(reply);
1052
+ if (!m || !SPEC.test(m[2])) return;
1053
+ const slot = m[1].startsWith("4;") ? `4;${Number(m[1].slice(2))}` : m[1];
1054
+ if (slot.startsWith("4;") && Number(slot.slice(2)) > 255) return;
1055
+ this.seen.set(slot, m[2]);
1056
+ }
1057
+ /** The value to answer a query for `slot` with: `10`, `11`, `12`, or `4;<index>` (0–255). */
1058
+ value(slot) {
1059
+ const seen = this.seen.get(slot);
1060
+ if (seen) return seen;
1061
+ if (slot === "10") return rgbSpec(hexRgb(TERMINAL_THEME.foreground));
1062
+ if (slot === "11") return rgbSpec(hexRgb(TERMINAL_THEME.background));
1063
+ if (slot === "12") return rgbSpec(hexRgb(TERMINAL_THEME.cursor));
1064
+ return rgbSpec(paletteRgb(Number(slot.slice(2))));
1065
+ }
1066
+ /** The whole reply for `slot`, as xterm.js says it (ST-terminated). */
1067
+ reply(slot) {
1068
+ return `\x1B]${slot};${this.value(slot)}\x1B\\`;
1069
+ }
1070
+ };
1071
+
1072
+ // src/core/pty/output-tail.ts
1073
+ var RESUME_TAIL_CHARS = 256 * 1024;
1074
+ var OutputTail = class {
1075
+ constructor(max = RESUME_TAIL_CHARS) {
1076
+ this.max = max;
1077
+ }
1078
+ chunks = [];
1079
+ /** The first chunk still held (`chunks` is compacted now and then, not shifted each time). */
1080
+ head = 0;
1081
+ held = 0;
1082
+ total = 0;
1083
+ /** The offset of the first character held. */
1084
+ get start() {
1085
+ return this.total - this.held;
1086
+ }
1087
+ /** The offset after the last character: everything up to here has arrived. */
1088
+ get end() {
1089
+ return this.total;
1090
+ }
1091
+ push(text) {
1092
+ if (!text) return;
1093
+ this.total += text.length;
1094
+ this.chunks.push(text);
1095
+ this.held += text.length;
1096
+ while (this.held > this.max) {
1097
+ const first = this.chunks[this.head];
1098
+ const over = this.held - this.max;
1099
+ if (first.length <= over) {
1100
+ this.head++;
1101
+ this.held -= first.length;
1102
+ } else {
1103
+ this.chunks[this.head] = first.slice(over);
1104
+ this.held -= over;
1105
+ }
1106
+ }
1107
+ if (this.head > 1024 && this.head * 2 > this.chunks.length) {
1108
+ this.chunks = this.chunks.slice(this.head);
1109
+ this.head = 0;
1110
+ }
1111
+ }
1112
+ /** Everything from `offset` to the end; null when it isn't all held (too old, or ahead of the stream). */
1113
+ since(offset) {
1114
+ if (!Number.isSafeInteger(offset) || offset < this.start || offset > this.total) return null;
1115
+ let skip = offset - this.start;
1116
+ const out = [];
1117
+ for (let i = this.head; i < this.chunks.length; i++) {
1118
+ const c = this.chunks[i];
1119
+ if (skip >= c.length) {
1120
+ skip -= c.length;
1121
+ continue;
1122
+ }
1123
+ out.push(skip ? c.slice(skip) : c);
1124
+ skip = 0;
1125
+ }
1126
+ return out.join("");
1127
+ }
1128
+ /** Hold nothing more (the entry is gone); the count stays. */
1129
+ clear() {
1130
+ this.chunks = [];
1131
+ this.head = 0;
1132
+ this.held = 0;
1133
+ }
1134
+ };
1135
+ function resumeFrom(at, target, tail, stated) {
1136
+ if (at.stream !== target.stream) return { refused: "stream" };
1137
+ if (target.busy) return { refused: "busy" };
1138
+ const same = (g) => g.cols === at.cols && g.rows === at.rows;
1139
+ if (!same(target.grid) || !same(target.gridBefore) || stated && !same(stated)) return { refused: "grid" };
1140
+ return continueFrom(at.offset, target, tail);
1141
+ }
1142
+ function continueFrom(offset, target, tail) {
1143
+ if (target.busy) return { refused: "busy" };
1144
+ if (offset > tail.end) return { refused: "ahead" };
1145
+ if (target.gridAt > offset) return { refused: "resized" };
1146
+ const missed = tail.since(offset);
1147
+ if (missed === null) return { refused: "too-old" };
1148
+ const first = missed.charCodeAt(0);
1149
+ if (first >= 56320 && first <= 57343) return { refused: "split" };
1150
+ return { missed };
1151
+ }
1152
+
1153
+ // src/core/pty/output-pacer.ts
1154
+ var COALESCE_MS = 5;
1155
+ var MAX_FRAME_CHARS = 64 * 1024;
1156
+ var PAUSE_TIMEOUT_MS = 500;
1157
+ var CATCH_UP_MIN_MS = 500;
1158
+ var FRAME_HOLD_MS = 200;
1159
+ var FRAME_HOLD_MAX_CHARS = 1024 * 1024;
1160
+ var realTimers = {
1161
+ now: () => Date.now(),
1162
+ set: (fn, ms) => setTimeout(fn, ms),
1163
+ clear: (handle) => clearTimeout(handle)
1164
+ };
1165
+ var OutputPacer = class {
1166
+ pending = [];
1167
+ pendingLength = 0;
1168
+ /** The coalescing window, open from the first output of a quiet moment until one passes with nothing. */
1169
+ window = null;
1170
+ clients = /* @__PURE__ */ new Map();
1171
+ paused = null;
1172
+ flow;
1173
+ timers;
1174
+ holder;
1175
+ /** Where the output is in synchronized frames, as it arrives. */
1176
+ sync = new SyncScanner();
1177
+ /** A synchronized frame being held (its output is in `pending`): until it ends, or its time or size cap. */
1178
+ frame = null;
1179
+ /** The frame open now was let go at its cap: the rest of it flows as any output does, until it ends. */
1180
+ letGo = false;
1181
+ /** What waits for no frame to be held (a client joining, a catch-up): `gone` once the PTY's entry is disposed. */
1182
+ waiting = [];
1183
+ /** The last of the output as it arrived: what a reconnecting client missed, when it is still all here. Ends at `offset`. */
1184
+ tail;
1185
+ constructor(deps) {
1186
+ this.flow = deps.flow;
1187
+ this.holder = deps.holder;
1188
+ this.timers = deps.timers ?? realTimers;
1189
+ this.tail = deps.tail ?? new OutputTail();
1190
+ }
1191
+ /**
1192
+ * Characters of output so far: where the next frame starts, and where a snapshot taken now stands. The tail's end, one
1193
+ * count for both: each piece is pushed to the tail as the pacer takes it in, so a client joining between two pieces of
1194
+ * one chunk (at a frame's end) is never sent from the tail what it will be sent live.
1195
+ */
1196
+ get offset() {
1197
+ return this.tail.end;
1198
+ }
1199
+ /** Whether the PTY is paused for a client now. */
1200
+ get isPaused() {
1201
+ return this.paused !== null;
1202
+ }
1203
+ /** Whether a synchronized frame is being held now. */
1204
+ get inFrame() {
1205
+ return this.frame !== null;
1206
+ }
1207
+ /**
1208
+ * Output arrived: sent at once if it is the first of a quiet moment, else with what follows within COALESCE_MS — or,
1209
+ * inside a synchronized frame, held until the frame ends.
1210
+ */
1211
+ output(data) {
1212
+ if (!data) return;
1213
+ let from = 0;
1214
+ for (const change of this.sync.feed(data)) {
1215
+ this.piece(data.slice(from, change.at), change.open);
1216
+ from = change.at;
1217
+ }
1218
+ if (from < data.length) this.piece(data.slice(from), this.sync.open);
1219
+ }
1220
+ /**
1221
+ * `fn` once no frame is held: now if none is, else at the end of the one being held (or its cap), right after it went
1222
+ * to the clients. `gone`: the entry was disposed first. A client joining then is sent nothing of that frame — its
1223
+ * screen, taken then, has all of it.
1224
+ */
1225
+ whenNoFrame(fn) {
1226
+ if (this.frame) this.waiting.push(fn);
1227
+ else fn(false);
1228
+ }
1229
+ /** Send what is pending now, a frame being held included (the process is stopping). */
1230
+ flush() {
1231
+ this.letFrameGo(false);
1232
+ this.flushPending();
1233
+ }
1234
+ /**
1235
+ * A client joins at the current offset: what arrived before it is in its snapshot and is not sent to it. (The registry
1236
+ * joins clients between frames, `whenNoFrame`; one joining mid-frame has what is held sent to the others first.)
1237
+ */
1238
+ add(key, client) {
1239
+ this.letFrameGo(this.sync.open);
1240
+ this.flushPending();
1241
+ this.clients.set(key, {
1242
+ client,
1243
+ sent: 0,
1244
+ acked: 0,
1245
+ at: this.offset,
1246
+ continuedAt: null,
1247
+ screenNext: false,
1248
+ behind: false,
1249
+ mayPause: true,
1250
+ snapshotAt: this.timers.now(),
1251
+ catchUp: null,
1252
+ catchUpAfterFrame: false
1253
+ });
1254
+ this.evaluate();
1255
+ }
1256
+ remove(key) {
1257
+ const c = this.clients.get(key);
1258
+ if (!c) return;
1259
+ if (c.catchUp !== null) this.timers.clear(c.catchUp);
1260
+ this.clients.delete(key);
1261
+ if (this.paused?.by === c) this.release();
1262
+ this.evaluate();
1263
+ }
1264
+ /** It finished drawing `chars` more characters. */
1265
+ ack(key, chars) {
1266
+ const c = this.clients.get(key);
1267
+ if (!c || !c.client.metered || !(chars > 0)) return;
1268
+ c.acked = Math.min(c.sent, c.acked + chars);
1269
+ if (c.behind) this.scheduleCatchUp(c);
1270
+ this.evaluate();
1271
+ }
1272
+ /** It was used (typed in, resized): it may pause the PTY again, and it may hold it now. */
1273
+ used(key) {
1274
+ const c = this.clients.get(key);
1275
+ if (c) c.mayPause = true;
1276
+ this.evaluate();
1277
+ }
1278
+ /** Whether it is sent live output (not behind). */
1279
+ live(key) {
1280
+ const c = this.clients.get(key);
1281
+ return !!c && !c.behind;
1282
+ }
1283
+ stats(key) {
1284
+ const c = this.clients.get(key);
1285
+ return c ? { sent: c.sent, acked: c.acked, unacked: c.sent - c.acked, behind: c.behind } : null;
1286
+ }
1287
+ /** The PTY's process changed (a restart) or ended (null): a pause of the old one is over, and so is any frame it had open. */
1288
+ setFlow(flow) {
1289
+ this.letFrameGo(false);
1290
+ this.sync.reset();
1291
+ this.release();
1292
+ this.flow = flow;
1293
+ this.evaluate();
1294
+ }
1295
+ /**
1296
+ * The process ended: its last output goes out, no pause is left, and a client that is behind is sent the final
1297
+ * screen now, whatever CATCH_UP_MIN_MS says, instead of being left on a stale one (the registry tells it the PTY
1298
+ * ended once that screen is sent).
1299
+ */
1300
+ end() {
1301
+ this.letFrameGo(false);
1302
+ this.flushPending();
1303
+ this.setFlow(null);
1304
+ for (const c of [...this.clients.values()]) {
1305
+ if (!c.behind) continue;
1306
+ if (c.catchUp !== null) this.timers.clear(c.catchUp);
1307
+ c.catchUp = null;
1308
+ this.catchUp(c);
1309
+ }
1310
+ }
1311
+ /** The entry is gone: no pause left, no timer, no client. */
1312
+ dispose() {
1313
+ this.release();
1314
+ this.flow = null;
1315
+ if (this.window !== null) this.timers.clear(this.window);
1316
+ this.window = null;
1317
+ if (this.frame) this.timers.clear(this.frame.timer);
1318
+ this.frame = null;
1319
+ for (const c of this.clients.values()) if (c.catchUp !== null) this.timers.clear(c.catchUp);
1320
+ this.clients.clear();
1321
+ this.pending = [];
1322
+ this.pendingLength = 0;
1323
+ this.tail.clear();
1324
+ for (const fn of this.waiting.splice(0)) fn(true);
1325
+ }
1326
+ /** A piece of output after which a synchronized frame is `open` (or not): held while one is, else coalesced. */
1327
+ piece(text, open) {
1328
+ this.tail.push(text);
1329
+ if (this.frame) {
1330
+ this.hold(text);
1331
+ if (!open) this.frameEnded();
1332
+ else if (this.pendingLength > FRAME_HOLD_MAX_CHARS) this.letFrameGo(true);
1333
+ return;
1334
+ }
1335
+ if (open && !this.letGo) {
1336
+ this.frame = { timer: this.timers.set(() => this.letFrameGo(this.sync.open), FRAME_HOLD_MS) };
1337
+ this.hold(text);
1338
+ return;
1339
+ }
1340
+ if (!open) this.letGo = false;
1341
+ if (this.pendingLength && this.pendingLength + text.length > MAX_FRAME_CHARS) this.flushPending(this.offset - text.length);
1342
+ if (this.window === null) {
1343
+ this.window = this.timers.set(() => this.windowEnd(), COALESCE_MS);
1344
+ this.deliver(text);
1345
+ return;
1346
+ }
1347
+ this.hold(text);
1348
+ }
1349
+ hold(text) {
1350
+ this.pending.push(text);
1351
+ this.pendingLength += text.length;
1352
+ }
1353
+ /** The frame being held ended: it goes out now, whole, and then what waited for its end. */
1354
+ frameEnded() {
1355
+ if (!this.frame) return;
1356
+ this.timers.clear(this.frame.timer);
1357
+ this.frame = null;
1358
+ this.flushPending();
1359
+ this.afterFrame();
1360
+ }
1361
+ /**
1362
+ * Stop holding the frame (its cap, a client joining mid-frame, the process stopping): what is held goes out with
1363
+ * what is pending, and what waited for its end goes on. `stillOpen`: the rest of it flows as any output does.
1364
+ */
1365
+ letFrameGo(stillOpen) {
1366
+ if (!this.frame) return;
1367
+ this.timers.clear(this.frame.timer);
1368
+ this.frame = null;
1369
+ this.letGo = stillOpen;
1370
+ this.flushPending();
1371
+ this.afterFrame();
1372
+ }
1373
+ afterFrame() {
1374
+ for (const fn of this.waiting.splice(0)) fn(false);
1375
+ this.evaluate();
1376
+ }
1377
+ windowEnd() {
1378
+ this.window = null;
1379
+ if (!this.pendingLength || this.frame) return;
1380
+ this.window = this.timers.set(() => this.windowEnd(), COALESCE_MS);
1381
+ this.flushPending();
1382
+ }
1383
+ /** What is pending goes out as one frame, ending at `end` (the tail's end unless a piece it doesn't hold was pushed since). */
1384
+ flushPending(end = this.offset) {
1385
+ if (!this.pendingLength) return;
1386
+ const frame = this.pending.length === 1 ? this.pending[0] : this.pending.join("");
1387
+ this.pending = [];
1388
+ this.pendingLength = 0;
1389
+ this.deliver(frame, end);
1390
+ }
1391
+ deliver(frame, end = this.offset) {
1392
+ for (const c of this.clients.values()) {
1393
+ if (c.behind) continue;
1394
+ c.sent += frame.length;
1395
+ c.at = end;
1396
+ try {
1397
+ c.client.send(frame, end);
1398
+ } catch {
1399
+ }
1400
+ }
1401
+ const holder = this.holder();
1402
+ for (const [key, c] of this.clients) {
1403
+ if (c.behind || !c.client.metered || c.sent - c.acked <= HIGH_WATERMARK) continue;
1404
+ if (key === holder && this.flow && c.mayPause) continue;
1405
+ this.fallBehind(c);
1406
+ }
1407
+ this.evaluate();
1408
+ }
1409
+ /**
1410
+ * It is sent no more live output until it catches up. Caught up from the tail last time, and fallen behind again before
1411
+ * it acked anything sent after (so before it drew past what it missed): it is slower than the output, and sending it all
1412
+ * again would only keep it behind — its next catch-up is a screen, which skips to where the output stands.
1413
+ */
1414
+ fallBehind(c) {
1415
+ c.behind = true;
1416
+ c.screenNext = c.continuedAt !== null && c.acked <= c.continuedAt;
1417
+ }
1418
+ /**
1419
+ * Pause the PTY for its holder above HIGH_WATERMARK, resume it below LOW_WATERMARK — or when nobody holds it any more.
1420
+ * Never paused mid-frame: the rest of the frame could not be read, nor the frame sent, until the pause timed out.
1421
+ */
1422
+ evaluate() {
1423
+ const key = this.holder();
1424
+ const h = key === null ? void 0 : this.clients.get(key);
1425
+ const holds = !!h && !!this.flow && h.client.metered && !h.behind && h.mayPause;
1426
+ if (this.paused) {
1427
+ if (holds && this.paused.by === h && h.sent - h.acked >= LOW_WATERMARK) return;
1428
+ this.release();
1429
+ }
1430
+ if (holds && !this.frame && h.sent - h.acked > HIGH_WATERMARK) this.pause(h);
1431
+ }
1432
+ pause(h) {
1433
+ try {
1434
+ this.flow?.pause();
1435
+ } catch {
1436
+ return;
1437
+ }
1438
+ this.paused = { by: h, timer: this.timers.set(() => this.timedOut(h), PAUSE_TIMEOUT_MS) };
1439
+ }
1440
+ release() {
1441
+ if (!this.paused) return;
1442
+ this.timers.clear(this.paused.timer);
1443
+ this.paused = null;
1444
+ try {
1445
+ this.flow?.resume();
1446
+ } catch {
1447
+ }
1448
+ }
1449
+ /** The PTY waited for its holder long enough: it goes on, and the holder is behind (what was pending went to it first). */
1450
+ timedOut(h) {
1451
+ if (this.paused?.by !== h) return;
1452
+ this.letFrameGo(this.sync.open);
1453
+ this.flushPending();
1454
+ this.fallBehind(h);
1455
+ h.mayPause = false;
1456
+ this.release();
1457
+ this.evaluate();
1458
+ }
1459
+ scheduleCatchUp(c) {
1460
+ if (c.catchUp !== null || c.sent - c.acked >= LOW_WATERMARK) return;
1461
+ const wait = c.snapshotAt + CATCH_UP_MIN_MS - this.timers.now();
1462
+ if (wait > 0) {
1463
+ c.catchUp = this.timers.set(() => {
1464
+ c.catchUp = null;
1465
+ this.catchUp(c);
1466
+ }, wait);
1467
+ return;
1468
+ }
1469
+ this.catchUp(c);
1470
+ }
1471
+ /**
1472
+ * It caught up: what arrived meanwhile goes to the others (what it is sent now has it), then it is sent what it missed
1473
+ * from the tail, or a screen, and live output — between frames: its screen is never one drawn halfway, and what it
1474
+ * missed never ends inside one.
1475
+ */
1476
+ catchUp(c) {
1477
+ if (!c.behind || ![...this.clients.values()].includes(c)) return;
1478
+ if (this.frame) {
1479
+ if (!c.catchUpAfterFrame) {
1480
+ c.catchUpAfterFrame = true;
1481
+ this.waiting.push(() => {
1482
+ c.catchUpAfterFrame = false;
1483
+ this.catchUp(c);
1484
+ });
1485
+ }
1486
+ return;
1487
+ }
1488
+ this.flushPending();
1489
+ const from = c.screenNext ? null : c.at;
1490
+ c.behind = false;
1491
+ c.screenNext = false;
1492
+ c.snapshotAt = this.timers.now();
1493
+ c.at = this.offset;
1494
+ let continued = false;
1495
+ try {
1496
+ continued = c.client.resync(from) === true;
1497
+ } catch {
1498
+ }
1499
+ c.continuedAt = continued ? c.sent : null;
1500
+ this.evaluate();
1501
+ }
1502
+ };
1503
+
1504
+ // src/core/pty/pty-registry.ts
1505
+ var REPLAY_MAX = 256 * 1024;
1506
+ var HALT_RESUME_MS = 5 * 6e4;
1507
+ var FORGET_EXITED_MS = 5e3;
1508
+ var DEFAULT_GRID = { cols: 120, rows: 32 };
1509
+ var REDRAW_JIGGLE_MS = 100;
1510
+ var GRID_PERSIST_MS = 1e3;
1511
+ var definedEnv = (env) => Object.fromEntries(Object.entries(env).filter((e) => typeof e[1] === "string"));
1512
+ var defaultSpawner = (spec) => new PtySession(spec.cwd, spec.cols ?? DEFAULT_GRID.cols, spec.rows ?? DEFAULT_GRID.rows, void 0, {
1513
+ tool: spec.tool,
1514
+ resume: spec.resume,
1515
+ port: spec.port,
1516
+ initialPrompt: spec.initialPrompt,
1517
+ env: spec.env
1518
+ });
1519
+ function mostCommonGrid(grids) {
1520
+ const counts = /* @__PURE__ */ new Map();
1521
+ for (const g of grids) {
1522
+ if (!g) continue;
1523
+ const key = `${g.cols}x${g.rows}`;
1524
+ const c = counts.get(key) ?? { grid: g, n: 0 };
1525
+ c.n++;
1526
+ counts.set(key, c);
1527
+ }
1528
+ let best = null;
1529
+ for (const c of counts.values()) if (!best || c.n > best.n) best = c;
1530
+ return best?.grid ?? null;
1531
+ }
1532
+ var flowOf = (pty2) => pty2.pause && pty2.resume ? { pause: () => pty2.pause?.(), resume: () => pty2.resume?.() } : null;
1533
+ var realLeftoverWork = {
1534
+ under: async (pid) => startedUnder(pid, await listProcessUsage(), process.pid),
1535
+ stop: (found) => stopLeftovers(found)
1536
+ };
1537
+ function fileSessionsStore(file) {
1538
+ return {
1539
+ read() {
1540
+ const out = {};
1541
+ try {
1542
+ const raw = JSON.parse(fs2.readFileSync(file, "utf-8"));
1543
+ if (raw && typeof raw === "object") {
1544
+ for (const [id, entry] of Object.entries(raw)) if (isPersistedPty(entry)) out[id] = entry;
1545
+ }
1546
+ } catch {
1547
+ }
1548
+ return out;
1549
+ },
1550
+ write(all) {
1551
+ ensureFile(file, "{}");
1552
+ withFileLockSync(file, () => atomicWriteFile(file, JSON.stringify(all, null, 2)));
1553
+ }
1554
+ };
1555
+ }
1556
+ var PtyRegistry = class {
1557
+ entries = /* @__PURE__ */ new Map();
1558
+ spawner;
1559
+ hasConversation;
1560
+ store;
1561
+ cwdExists;
1562
+ keepEnvNames;
1563
+ sessionTool;
1564
+ timers;
1565
+ windowsPty;
1566
+ /**
1567
+ * The last grid a client set (a resize, an attach or a start that stated one): what a PTY started with no grid of its
1568
+ * own (a background start, a session's Start) starts at. After a host restart, before any client: the restored
1569
+ * sessions' most common grid. In memory; each session's own grid is in the restore list.
1570
+ */
1571
+ lastGrid = null;
1572
+ /** The restore-list write a grid change is waiting for (GRID_PERSIST_MS). */
1573
+ gridPersist = null;
1574
+ leftovers;
1575
+ /** Serializes persistence writes inside this process. */
1576
+ writeChain = Promise.resolve();
1577
+ /** The colours the host answers a colour query with itself: the last a terminal attached to any PTY answered with. */
1578
+ colors = new TerminalColors();
1579
+ constructor(deps = {}) {
1580
+ this.spawner = deps.spawner ?? defaultSpawner;
1581
+ this.hasConversation = deps.hasConversation ?? ((cwd, tool, env) => agentById(tool).launch.canResume(cwd, { env }));
1582
+ this.store = deps.sessions ?? (deps.sessionsPath ? fileSessionsStore(deps.sessionsPath) : dbPtySessions);
1583
+ this.cwdExists = deps.cwdExists ?? ((p) => fs2.existsSync(p));
1584
+ this.keepEnvNames = deps.keepEnvNames ?? (() => loadConfig()?.hostEnv ?? []);
1585
+ this.sessionTool = deps.sessionTool ?? sessionToolFor;
1586
+ this.timers = deps.timers;
1587
+ if (deps.windowsPty) this.windowsPty = deps.windowsPty;
1588
+ this.leftovers = deps.leftovers !== void 0 ? deps.leftovers : deps.spawner ? null : realLeftoverWork;
1589
+ }
1590
+ /** What runs under the entry's agent now (nothing known: none). */
1591
+ async startedBy(e) {
1592
+ if (!this.leftovers || e.pty.exited) return [];
1593
+ try {
1594
+ return await this.leftovers.under(e.pty.pty.pid);
1595
+ } catch (err) {
1596
+ logSwallowed(`list what ${e.id}'s agent started`, err);
1597
+ return [];
1598
+ }
1599
+ }
1600
+ /** Once its agent is gone: what it started and left running, stopped (said in the host's log). */
1601
+ stopLeftBehind(id, found) {
1602
+ if (!this.leftovers || !found.length) return Promise.resolve();
1603
+ return this.leftovers.stop(found).then(
1604
+ (stopped) => {
1605
+ if (stopped.length)
1606
+ report(
1607
+ "info",
1608
+ `${id}: stopped ${stopped.length} process(es) its agent had left running: ${stopped.map((p) => p.pid).join(", ")}`
1609
+ );
1610
+ },
1611
+ (err) => logSwallowed(`stop what ${id}'s agent left running`, err)
1612
+ );
1613
+ }
1614
+ list() {
1615
+ return [...this.entries.values()].map((e) => this.info(e));
1616
+ }
1617
+ get(id) {
1618
+ const e = this.entries.get(id);
1619
+ return e ? this.info(e) : null;
1620
+ }
1621
+ /** Spawn unless a live PTY already exists for `id` (idempotent). */
1622
+ spawn(id, spec, restored = false) {
1623
+ const existing = this.entries.get(id);
1624
+ if (existing && (!existing.pty.exited || existing.restarting || existing.halted)) return this.info(existing);
1625
+ const { unsafeFlag: _retired, ...tool } = spec.tool;
1626
+ spec = { ...spec, tool: this.sessionTool(tool) };
1627
+ const agentEnv = hasEnvDelta(spec.agentEnv) ? spec.agentEnv : void 0;
1628
+ const kept = spec.env ? keepEnv(definedEnv(applyEnvDelta(spec.env, agentEnv)), this.keepEnvNames()) : spec.keptEnv ?? existing?.spec.keptEnv;
1629
+ const env = this.launchEnv({ env: spec.env, keptEnv: kept, agentEnv });
1630
+ if (env) spec = { ...spec, env };
1631
+ const stated = validGrid(spec.cols, spec.rows);
1632
+ const { cols, rows } = stated ?? this.lastGrid ?? DEFAULT_GRID;
1633
+ if (stated && !restored) this.lastGrid = stated;
1634
+ const pty2 = this.spawner({
1635
+ ...spec,
1636
+ cols,
1637
+ rows,
1638
+ // `--continue` hard-errors in a directory Claude never ran in;
1639
+ // `--fresh` opts out even when one exists.
1640
+ resume: !spec.fresh && this.hasConversation(spec.cwd, spec.tool.cmd, spec.env ?? process.env)
1641
+ });
1642
+ const pacer = new OutputPacer({ flow: null, holder: () => this.pick(entry), timers: this.timers });
1643
+ const entry = {
1644
+ id,
1645
+ // Only what a restore may reuse: env/prompt/fresh are one-shot (and
1646
+ // env can hold secrets), so they never reach pty-sessions.json — but
1647
+ // the variables config `hostEnv` names do (keepEnv), so a restore after
1648
+ // a reboot gets the JAVA_HOME / PATH it was started with.
1649
+ spec: {
1650
+ cwd: spec.cwd,
1651
+ tool: spec.tool,
1652
+ port: spec.port,
1653
+ ...kept ? { keptEnv: kept } : {},
1654
+ ...agentEnv ? { agentEnv } : {}
1655
+ },
1656
+ env: spec.env,
1657
+ pty: pty2,
1658
+ cols,
1659
+ rows,
1660
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1661
+ restored,
1662
+ replay: "",
1663
+ subscribers: /* @__PURE__ */ new Set(),
1664
+ exitSubscribers: /* @__PURE__ */ new Set(),
1665
+ leader: null,
1666
+ answerer: null,
1667
+ pacer,
1668
+ exitCode: null,
1669
+ lastOutputAt: Date.now(),
1670
+ stream: randomBytes(8).toString("hex"),
1671
+ gridAt: 0
1672
+ };
1673
+ this.wire(entry, pty2);
1674
+ this.entries.set(id, entry);
1675
+ void this.persist();
1676
+ return this.info(entry);
1677
+ }
1678
+ /**
1679
+ * The env a spawn runs with: the shell's when it came from one; else the host's plus what its session kept; then the
1680
+ * session's account change (`agentEnv`) over it — on the host's own environment when there is nothing else, so a
1681
+ * default session never inherits a CLAUDE_CONFIG_DIR the host was started with. Undefined: no change, the host's own env.
1682
+ */
1683
+ launchEnv(spec) {
1684
+ const base = spec.env ?? (spec.keptEnv ? { ...process.env, ...spec.keptEnv } : void 0);
1685
+ return hasEnvDelta(spec.agentEnv) ? definedEnv(applyEnvDelta(base ?? process.env, spec.agentEnv)) : base;
1686
+ }
1687
+ /** `pty` becomes the entry's process: its output to the entry's clients, its exit told to them (then forgotten). */
1688
+ wire(entry, pty2) {
1689
+ const id = entry.id;
1690
+ entry.pty = pty2;
1691
+ const keepRaw = !pty2.serialize;
1692
+ entry.pacer.setFlow(flowOf(pty2));
1693
+ pty2.answerQueries?.(() => this.designate(entry) === null, this.colors);
1694
+ pty2.setOutputHandler((data) => {
1695
+ this.designate(entry);
1696
+ entry.lastOutputAt = Date.now();
1697
+ if (keepRaw) {
1698
+ entry.replay += data;
1699
+ if (entry.replay.length > REPLAY_MAX) {
1700
+ entry.replay = entry.replay.slice(entry.replay.length - REPLAY_MAX);
1701
+ }
1702
+ }
1703
+ entry.pacer.output(data);
1704
+ });
1705
+ pty2.onExit = (code) => {
1706
+ entry.pacer.end();
1707
+ entry.exitCode = code;
1708
+ for (const cb of entry.exitSubscribers) {
1709
+ try {
1710
+ cb(code);
1711
+ } catch {
1712
+ }
1713
+ }
1714
+ setTimeout(() => {
1715
+ if (this.entries.get(id) === entry) {
1716
+ this.entries.delete(id);
1717
+ void this.persist();
1718
+ }
1719
+ }, FORGET_EXITED_MS).unref?.();
1720
+ };
1721
+ }
1722
+ /**
1723
+ * Who answers the agent's queries in the output arriving now: exactly one, decided as it arrives (terminal-rendering.md,
1724
+ * "Who answers a query"). The client used last (it typed or resized: it has the PTY's size), else the first attached;
1725
+ * null when none is attached — then the PTY's screen copy answers. Kept until the next output, so the answers to it
1726
+ * that come back from that client go through.
1727
+ */
1728
+ designate(e) {
1729
+ const who = this.pick(e);
1730
+ e.answerer = who;
1731
+ return who;
1732
+ }
1733
+ /**
1734
+ * `designate`'s choice, without making it: among the clients sent live output (one behind is sent none, so it would
1735
+ * never see the query: output-pacer.ts), the one used last, else the first attached. Also the one that holds the
1736
+ * PTY (may pause it until it has drawn what it was sent).
1737
+ */
1738
+ pick(e) {
1739
+ if (e.leader && e.subscribers.has(e.leader) && e.pacer.live(e.leader)) return e.leader;
1740
+ for (const c of e.subscribers) if (e.pacer.live(c)) return c;
1741
+ return null;
1742
+ }
1743
+ /** The live PTY's visible screen as text; null when there is none (or
1744
+ * it can't render one — test fakes). */
1745
+ screen(id) {
1746
+ const e = this.entries.get(id);
1747
+ if (!e || e.pty.exited || !e.pty.screenText) return null;
1748
+ return e.pty.screenText();
1749
+ }
1750
+ write(id, data) {
1751
+ const e = this.entries.get(id);
1752
+ if (!e || e.pty.exited) return false;
1753
+ e.pty.write(data);
1754
+ return true;
1755
+ }
1756
+ /** Last writer wins — with several clients attached (browser + a real
1757
+ * terminal) the host calls this when one resizes AND when one is typed in
1758
+ * (its own grid again), so the client used last sets the grid, like
1759
+ * tmux's `window-size latest` (pty-host.ts). */
1760
+ resize(id, cols, rows) {
1761
+ const e = this.entries.get(id);
1762
+ if (!e || e.pty.exited) return;
1763
+ const grid = validGrid(cols, rows);
1764
+ if (!grid || cols === e.cols && rows === e.rows) return;
1765
+ e.cols = cols;
1766
+ e.rows = rows;
1767
+ e.pty.resize(cols, rows);
1768
+ e.gridAt = e.pacer.offset;
1769
+ this.remember(grid);
1770
+ }
1771
+ /** `grid` is the last a client set: what a start with none takes, and — soon — the session's grid in the restore list. */
1772
+ remember(grid) {
1773
+ this.lastGrid = grid;
1774
+ if (this.gridPersist !== null) return;
1775
+ const timers = this.timers ?? realTimers;
1776
+ const handle = timers.set(() => {
1777
+ this.gridPersist = null;
1778
+ void this.persist();
1779
+ }, GRID_PERSIST_MS);
1780
+ handle?.unref?.();
1781
+ this.gridPersist = handle;
1782
+ }
1783
+ /**
1784
+ * Ask its agent to draw its screen again (⋯ → Reconnect terminal: the screen looks wrong). The PTY is made one row
1785
+ * smaller and, REDRAW_JIGGLE_MS later, put back to the grid it has then: two real size changes, so the agent sees one
1786
+ * whatever it runs on. A same-size SIGWINCH (zmx's way) repaints nothing in a Node or Bun agent (REDRAW_JIGGLE_MS); on
1787
+ * Windows ConPTY sends no resize for an unchanged size at all. The clients aren't resized: the agent's repaint at the
1788
+ * smaller grid is drawn over by the one at theirs. False when nothing runs.
1789
+ */
1790
+ redraw(id) {
1791
+ const e = this.entries.get(id);
1792
+ if (!e || e.pty.exited || e.restarting || e.halted) return false;
1793
+ if (e.redrawing !== void 0) return true;
1794
+ e.pty.resize(e.cols, e.rows > MIN_ROWS ? e.rows - 1 : e.rows + 1);
1795
+ e.gridAt = e.pacer.offset;
1796
+ e.redrawing = (this.timers ?? realTimers).set(() => {
1797
+ e.redrawing = void 0;
1798
+ if (this.entries.get(id) === e && !e.pty.exited && !e.restarting && !e.halted) {
1799
+ e.pty.resize(e.cols, e.rows);
1800
+ e.gridAt = e.pacer.offset;
1801
+ }
1802
+ }, REDRAW_JIGGLE_MS);
1803
+ return true;
1804
+ }
1805
+ /**
1806
+ * Attach a client: the screen snapshot, a disposer, and — for a real
1807
+ * session — `ready`, the snapshot once the screen has parsed everything
1808
+ * that arrived before this attach, then `start()` once it was sent.
1809
+ *
1810
+ * Output reaches clients the moment it arrives, but the screen parses it a
1811
+ * moment later (xterm's write is queued). A client attaching in between got
1812
+ * a snapshot without that output and subscribed too late to be sent it: it
1813
+ * was lost (a Linux PTY answers fast enough to land there). So output
1814
+ * arriving from the attach on is held for this client until `start()`, and
1815
+ * `ready` is the screen exactly as of the attach — nothing lost, nothing
1816
+ * twice. `replay` (taken at once) is for screens with no parsing step.
1817
+ *
1818
+ * `lead()`: this client was used (typed in, resized), so it answers the agent's queries from the next output on.
1819
+ * `replies(parts)`: what of what this client sent on its own goes to the agent — its focus and mouse-motion reports
1820
+ * always, its answers only if it answers the queries in the output that arrived last (`designate`).
1821
+ *
1822
+ * Output reaches it in frames (output-pacer.ts). `opts.metered`: it acks what it draws (`ack(chars)`); if it falls
1823
+ * behind, it is sent nothing until it catches up, then what it missed from the tail when that is provably enough, else
1824
+ * the screen as it stands then (`opts.onReplay`; a screen taken and held as the attach's is: nothing lost, nothing
1825
+ * twice), and live output again. `offset`: the output offset its snapshot stands at (where its first frame starts).
1826
+ */
1827
+ attach(id, onData, onExit, opts = {}) {
1828
+ const e = this.entries.get(id);
1829
+ if (!e) return null;
1830
+ const exitedWith = e.pty.exited && !e.restarting && !e.halted ? e.exitCode ?? 0 : null;
1831
+ const restarting = !!e.restarting || !!e.halted;
1832
+ const settled = restarting ? void 0 : e.pty.serializeSettled;
1833
+ let held = settled ? [] : null;
1834
+ let started = !settled;
1835
+ let gone = false;
1836
+ const sub = (d, end) => held ? held.push([d, end]) : onData(d, end);
1837
+ const windowsPty = this.windowsPty ? e.pty.windowsPty ?? this.windowsPty : void 0;
1838
+ const snapshot = (data, offset2 = e.pacer.offset) => ({
1839
+ data,
1840
+ cols: e.cols,
1841
+ rows: e.rows,
1842
+ stream: e.stream,
1843
+ offset: offset2,
1844
+ ...windowsPty ? { windowsPty } : {}
1845
+ });
1846
+ let catchingUp = false;
1847
+ let endedWith = null;
1848
+ const exitSub = (code) => {
1849
+ if (catchingUp || !started) endedWith = code;
1850
+ else onExit(code);
1851
+ };
1852
+ const sendCatchUp = (data, at) => {
1853
+ if (data !== null) return opts.onReplay?.(snapshot(data, at));
1854
+ report("warn", `${id}: a terminal's catch-up screen couldn't be taken; it keeps the screen it has`);
1855
+ if (!opts.screenOnlyCatchUp) opts.onReplay?.({ ...snapshot("", at), stream: "", resumed: true });
1856
+ };
1857
+ const busy = () => e.pty.exited || !!e.restarting || !!e.halted || e.redrawing !== void 0;
1858
+ const resync = (from) => {
1859
+ if (gone || !started) return false;
1860
+ if (from !== null && !opts.screenOnlyCatchUp && held === null) {
1861
+ const r = continueFrom(from, { gridAt: e.gridAt, busy: busy() }, e.pacer.tail);
1862
+ if ("missed" in r) {
1863
+ opts.onReplay?.({ ...snapshot(r.missed), resumed: true });
1864
+ return true;
1865
+ }
1866
+ }
1867
+ const shot = opts.screenOnlyCatchUp ? { scrollback: false } : void 0;
1868
+ const between = !!e.restarting || !!e.halted;
1869
+ const settle = between ? void 0 : e.pty.serializeSettled;
1870
+ const at = e.pacer.offset;
1871
+ if (!settle) {
1872
+ const data = between ? "" : e.pty.serialize?.(shot);
1873
+ sendCatchUp(data === null ? null : data || e.replay, at);
1874
+ return false;
1875
+ }
1876
+ const mine = [];
1877
+ held = mine;
1878
+ catchingUp = true;
1879
+ void settle.call(e.pty, shot).catch((err) => {
1880
+ logSwallowed(`${id}: take a catch-up screen`, err);
1881
+ return null;
1882
+ }).then((data) => {
1883
+ if (gone || held !== mine) return;
1884
+ sendCatchUp(data === null ? null : data || e.replay, at);
1885
+ held = null;
1886
+ catchingUp = false;
1887
+ for (const [d, end] of mine) onData(d, end);
1888
+ if (endedWith !== null) onExit(endedWith);
1889
+ });
1890
+ return false;
1891
+ };
1892
+ let resolveReady = () => {
1893
+ };
1894
+ const ready = new Promise((resolve) => resolveReady = resolve);
1895
+ let offset = e.pacer.offset;
1896
+ const join = (entryGone) => {
1897
+ if (gone || entryGone || this.entries.get(id) !== e) {
1898
+ resolveReady(snapshot(""));
1899
+ return;
1900
+ }
1901
+ e.pacer.add(sub, { metered: !!opts.metered, send: sub, resync });
1902
+ offset = e.pacer.offset;
1903
+ if (opts.resume) {
1904
+ const r = resumeFrom(
1905
+ opts.resume,
1906
+ {
1907
+ stream: e.stream,
1908
+ grid: { cols: e.cols, rows: e.rows },
1909
+ gridBefore,
1910
+ gridAt: e.gridAt,
1911
+ busy: busy()
1912
+ },
1913
+ e.pacer.tail,
1914
+ opts.grid
1915
+ );
1916
+ if ("missed" in r) {
1917
+ resolveReady({ ...snapshot(r.missed, offset), resumed: true });
1918
+ return;
1919
+ }
1920
+ opts.onResumeRefused?.(r.refused);
1921
+ }
1922
+ if (settled)
1923
+ void settled.call(e.pty).catch((err) => {
1924
+ logSwallowed(`${id}: take a screen for an attach`, err);
1925
+ return null;
1926
+ }).then((d) => resolveReady(snapshot(firstScreen(d), offset)));
1927
+ else resolveReady(snapshot(restarting ? "" : firstScreen(e.pty.serialize?.()), offset));
1928
+ };
1929
+ const firstScreen = (d) => {
1930
+ if (d === null) report("warn", `${id}: a terminal's screen couldn't be taken; it attached with an empty one`);
1931
+ return d || e.replay;
1932
+ };
1933
+ const gridBefore = { cols: e.cols, rows: e.rows };
1934
+ if (exitedWith === null) {
1935
+ e.subscribers.add(sub);
1936
+ e.exitSubscribers.add(exitSub);
1937
+ const grid = opts.grid ? validGrid(opts.grid.cols, opts.grid.rows) : null;
1938
+ if (grid) {
1939
+ e.leader = sub;
1940
+ e.pacer.used(sub);
1941
+ if (!restarting) this.resize(id, grid.cols, grid.rows);
1942
+ else {
1943
+ e.cols = grid.cols;
1944
+ e.rows = grid.rows;
1945
+ this.remember(grid);
1946
+ }
1947
+ }
1948
+ }
1949
+ const replay = snapshot(restarting ? "" : e.pty.serialize?.() || e.replay);
1950
+ if (exitedWith !== null) resolveReady(replay);
1951
+ else e.pacer.whenNoFrame(join);
1952
+ return {
1953
+ exitedWith,
1954
+ replay,
1955
+ get offset() {
1956
+ return offset;
1957
+ },
1958
+ ready,
1959
+ start: () => {
1960
+ const q = held;
1961
+ held = null;
1962
+ started = true;
1963
+ for (const [d, end] of q ?? []) onData(d, end);
1964
+ if (endedWith !== null && !catchingUp) {
1965
+ const code = endedWith;
1966
+ endedWith = null;
1967
+ onExit(code);
1968
+ }
1969
+ },
1970
+ detach: () => {
1971
+ gone = true;
1972
+ e.subscribers.delete(sub);
1973
+ e.exitSubscribers.delete(exitSub);
1974
+ if (e.leader === sub) e.leader = null;
1975
+ if (e.answerer === sub) this.designate(e);
1976
+ e.pacer.remove(sub);
1977
+ },
1978
+ lead: () => {
1979
+ e.leader = sub;
1980
+ e.pacer.used(sub);
1981
+ },
1982
+ ack: (chars) => e.pacer.ack(sub, chars),
1983
+ replies: (parts) => {
1984
+ const answers = e.answerer === sub;
1985
+ let out = "";
1986
+ for (const part of parts) {
1987
+ if (!part.answer) out += part.text;
1988
+ else if (answers) {
1989
+ out += part.text;
1990
+ this.colors.remember(part.text);
1991
+ }
1992
+ }
1993
+ return out;
1994
+ }
1995
+ };
1996
+ }
1997
+ /**
1998
+ * Explicit kill (worktree removal, user closed the session). Removed
1999
+ * from the persisted list so it is NOT restored.
2000
+ *
2001
+ * Resolves once the process has actually exited (or after `timeoutMs`):
2002
+ * on Windows a just-killed process still holds its cwd for a moment, and
2003
+ * the caller's next step is usually deleting that very directory.
2004
+ */
2005
+ async kill(id, timeoutMs = 3e3) {
2006
+ const e = this.entries.get(id);
2007
+ if (!e) return;
2008
+ const started = this.leftovers ? await this.startedBy(e) : [];
2009
+ if (this.entries.get(id) !== e) return;
2010
+ this.entries.delete(id);
2011
+ if (e.halted) clearTimeout(e.halted.timer);
2012
+ const attached = [...e.exitSubscribers];
2013
+ e.subscribers.clear();
2014
+ e.exitSubscribers.clear();
2015
+ e.pacer.dispose();
2016
+ const exited = e.pty.exited ? Promise.resolve(e.exitCode ?? 0) : new Promise((resolve) => {
2017
+ const timer = setTimeout(() => resolve(0), timeoutMs);
2018
+ e.pty.onExit = (code2) => {
2019
+ clearTimeout(timer);
2020
+ resolve(code2);
2021
+ };
2022
+ });
2023
+ e.pty.dispose();
2024
+ const [code] = await Promise.all([exited, this.persist()]);
2025
+ await this.stopLeftBehind(id, started);
2026
+ for (const cb of attached) {
2027
+ try {
2028
+ cb(code);
2029
+ } catch {
2030
+ }
2031
+ }
2032
+ }
2033
+ /**
2034
+ * Its agent stopped and started again in place, resuming its conversation (a
2035
+ * tool that updated runs its new version). The new process goes into the same
2036
+ * entry, so the terminals attached stay attached (and a detach still finds them),
2037
+ * see the new one draw, and one that attaches meanwhile joins it; the restore
2038
+ * list keeps it. Null when there's no live PTY of that id.
2039
+ *
2040
+ * Never two agents on one conversation: an old one that hasn't exited within
2041
+ * `timeoutMs` is left running and tracked, and the restart fails. A new one that
2042
+ * can't start (its tool gone mid-update) ends the session as a kill does, its
2043
+ * terminals told so.
2044
+ *
2045
+ * `agentEnv`: the agent's environment for the new process differs from the old one's by this (a session moved to
2046
+ * another account): it replaces the entry's own, in the restore list too — the process is started on what the
2047
+ * session is now, not on what it was.
2048
+ */
2049
+ restart(id, timeoutMs = 3e3, agentEnv) {
2050
+ const e = this.entries.get(id);
2051
+ if (!e) return Promise.resolve(null);
2052
+ if (e.restarting) return e.restarting;
2053
+ if (e.halted) return Promise.reject(new Error("its agent is halted: resume it first"));
2054
+ if (e.pty.exited) return Promise.resolve(null);
2055
+ const running = this.haltEntry(e, timeoutMs).then((ok) => ok ? this.resumeEntry(e, agentEnv) : this.get(e.id)).finally(() => {
2056
+ e.restarting = void 0;
2057
+ });
2058
+ e.restarting = running;
2059
+ return running;
2060
+ }
2061
+ /**
2062
+ * Its agent stopped, and kept stopped until `resume` (a switch of account moves its conversation files in between,
2063
+ * which a running — or just exiting — agent would write into again). The entry, its restore-list record and the
2064
+ * attached clients stay, and none is told it ended. Refused while it is being restarted or already halted; an agent that
2065
+ * doesn't stop within `timeoutMs` ends the session as `restart` does. A `resume` that never comes (work web died)
2066
+ * can't leave the session dead: after `resumeAfterMs` it is started again on its old spec. Null: nothing runs.
2067
+ */
2068
+ halt(id, timeoutMs = 3e3, resumeAfterMs = HALT_RESUME_MS) {
2069
+ const e = this.entries.get(id);
2070
+ if (!e) return Promise.resolve(null);
2071
+ if (e.restarting || e.halted) return Promise.reject(new Error("its agent is already being restarted or halted"));
2072
+ if (e.pty.exited) return Promise.resolve(null);
2073
+ const running = this.haltEntry(e, timeoutMs).then((ok) => {
2074
+ if (!ok) return this.get(id);
2075
+ const timer = setTimeout(() => {
2076
+ report("warn", `${id}: halted, and no resume within ${Math.round(resumeAfterMs / 1e3)} s: starting it again on its old spec`);
2077
+ this.resume(id).catch(swallow(`resume halted ${id}`));
2078
+ }, resumeAfterMs);
2079
+ timer.unref?.();
2080
+ e.halted = { timer };
2081
+ return this.info(e);
2082
+ }).finally(() => {
2083
+ e.restarting = void 0;
2084
+ });
2085
+ e.restarting = running;
2086
+ return running;
2087
+ }
2088
+ /**
2089
+ * Start a halted agent again in place, resuming its conversation, on `agentEnv` when given (as `restart` takes it): the
2090
+ * clients carry on. Null when it isn't halted.
2091
+ */
2092
+ resume(id, agentEnv) {
2093
+ const e = this.entries.get(id);
2094
+ if (!e?.halted) return Promise.resolve(null);
2095
+ clearTimeout(e.halted.timer);
2096
+ e.halted = void 0;
2097
+ const running = this.resumeEntry(e, agentEnv).finally(() => {
2098
+ e.restarting = void 0;
2099
+ });
2100
+ e.restarting = running;
2101
+ return running;
2102
+ }
2103
+ /** Stop the entry's process and wait for it to exit (timeoutMs); one that won't ends the session and throws. False: it was killed meanwhile. */
2104
+ async haltEntry(e, timeoutMs) {
2105
+ const id = e.id;
2106
+ const old = e.pty;
2107
+ e.pacer.flush();
2108
+ e.pacer.setFlow(null);
2109
+ let exited;
2110
+ const gone = new Promise((resolve) => exited = resolve);
2111
+ old.onExit = () => exited();
2112
+ const started = this.leftovers ? await this.startedBy(e) : [];
2113
+ const stopped = old.exited ? true : await new Promise((resolve) => {
2114
+ const timer = setTimeout(() => resolve(false), timeoutMs);
2115
+ void gone.then(() => {
2116
+ clearTimeout(timer);
2117
+ resolve(true);
2118
+ });
2119
+ old.dispose();
2120
+ });
2121
+ if (stopped) await this.stopLeftBehind(id, started);
2122
+ if (this.entries.get(id) !== e) return false;
2123
+ if (!stopped) {
2124
+ await this.endEntry(e);
2125
+ throw new Error(
2126
+ `its agent didn't stop within ${Math.round(timeoutMs / 1e3)} s; its session was stopped (open it to start it again)`
2127
+ );
2128
+ }
2129
+ return true;
2130
+ }
2131
+ /** Start the entry's agent again in place (its process is gone): `--continue`, on `agentEnv` when given. */
2132
+ async resumeEntry(e, agentEnv) {
2133
+ if (this.entries.get(e.id) !== e) return this.get(e.id);
2134
+ if (agentEnv) this.useAgentEnv(e, agentEnv);
2135
+ e.spec = { ...e.spec, tool: this.sessionTool(e.spec.tool) };
2136
+ let pty2;
2137
+ try {
2138
+ const env = e.env ?? this.launchEnv(e.spec);
2139
+ pty2 = this.spawner({
2140
+ ...e.spec,
2141
+ env,
2142
+ cols: e.cols,
2143
+ rows: e.rows,
2144
+ resume: this.hasConversation(e.spec.cwd, e.spec.tool.cmd, env ?? process.env)
2145
+ });
2146
+ } catch (err) {
2147
+ await this.endEntry(e);
2148
+ throw err;
2149
+ }
2150
+ e.exitCode = null;
2151
+ e.replay = "";
2152
+ e.startedAt = (/* @__PURE__ */ new Date()).toISOString();
2153
+ e.restored = false;
2154
+ e.lastOutputAt = Date.now();
2155
+ this.wire(e, pty2);
2156
+ void this.persist();
2157
+ return this.info(e);
2158
+ }
2159
+ /** The entry's agent environment becomes `delta`: in its spec (the restore list), the variables it kept, and the environment it started with. */
2160
+ useAgentEnv(e, delta) {
2161
+ const { agentEnv: _old, keptEnv, ...rest } = e.spec;
2162
+ const kept = keptEnv ? definedEnv(applyEnvDelta(keptEnv, delta)) : void 0;
2163
+ e.spec = {
2164
+ ...rest,
2165
+ ...kept && Object.keys(kept).length ? { keptEnv: kept } : {},
2166
+ ...hasEnvDelta(delta) ? { agentEnv: delta } : {}
2167
+ };
2168
+ if (e.env) e.env = definedEnv(applyEnvDelta(e.env, delta));
2169
+ }
2170
+ /** A restart that can't go on ends the session as a kill does: its terminals told (they offer Enter to start it again), forgotten. */
2171
+ async endEntry(e) {
2172
+ if (e.halted) clearTimeout(e.halted.timer);
2173
+ if (this.entries.get(e.id) === e) this.entries.delete(e.id);
2174
+ const attached = [...e.exitSubscribers];
2175
+ e.subscribers.clear();
2176
+ e.exitSubscribers.clear();
2177
+ e.pacer.dispose();
2178
+ await this.persist();
2179
+ for (const cb of attached) {
2180
+ try {
2181
+ cb(1);
2182
+ } catch {
2183
+ }
2184
+ }
2185
+ }
2186
+ /**
2187
+ * Respawn everything in the persisted list. Called once at host startup.
2188
+ * Worktrees that no longer exist are dropped, and so is the Ctrl+K
2189
+ * assistant: it starts when you open it (its conversation resumes then) —
2190
+ * restored, one opened once ran for good, a Claude nobody used. Nor is an
2191
+ * account's login terminal (account-login.ts): it is the Accounts page's,
2192
+ * for as long as its panel is open.
2193
+ */
2194
+ async restore() {
2195
+ const saved = this.readPersisted();
2196
+ const restored = [];
2197
+ for (const [id, entry] of Object.entries(saved)) {
2198
+ if (id === ASSISTANT_ID || isAccountLoginId(id) || !this.cwdExists(entry.cwd)) continue;
2199
+ try {
2200
+ this.spawn(id, entry, true);
2201
+ restored.push(id);
2202
+ } catch (err) {
2203
+ logSwallowed(`restore session ${id} in ${entry.cwd}`, err);
2204
+ }
2205
+ }
2206
+ this.lastGrid ??= mostCommonGrid(restored.map((id) => validGrid(saved[id].cols, saved[id].rows)));
2207
+ await this.persist();
2208
+ return restored;
2209
+ }
2210
+ /** Host shutdown: kill every PTY but KEEP the persisted list, so the next
2211
+ * host start restores them. */
2212
+ disposeAllKeepingState() {
2213
+ if (this.gridPersist !== null) (this.timers ?? realTimers).clear(this.gridPersist);
2214
+ this.gridPersist = null;
2215
+ for (const e of this.entries.values()) {
2216
+ e.pty.onExit = void 0;
2217
+ e.subscribers.clear();
2218
+ e.exitSubscribers.clear();
2219
+ e.pacer.dispose();
2220
+ e.pty.dispose();
2221
+ }
2222
+ this.entries.clear();
2223
+ }
2224
+ /** Resolves once every queued persistence write has landed. */
2225
+ flush() {
2226
+ return this.writeChain;
2227
+ }
2228
+ info(e) {
2229
+ const signal = e.pty.exited ? null : e.pty.streamSignal?.() ?? null;
2230
+ return {
2231
+ id: e.id,
2232
+ cwd: e.spec.cwd,
2233
+ pid: e.pty.pty.pid,
2234
+ exited: e.pty.exited,
2235
+ cols: e.cols,
2236
+ rows: e.rows,
2237
+ startedAt: e.startedAt,
2238
+ restored: e.restored,
2239
+ clients: e.subscribers.size,
2240
+ lastOutputAt: new Date(e.lastOutputAt).toISOString(),
2241
+ tool: e.spec.tool.cmd,
2242
+ ...signal ? { signal } : {}
2243
+ };
2244
+ }
2245
+ readPersisted() {
2246
+ try {
2247
+ return this.store.read();
2248
+ } catch (err) {
2249
+ logSwallowed("read the PTY restore list", err);
2250
+ return {};
2251
+ }
2252
+ }
2253
+ persist() {
2254
+ const snapshot = {};
2255
+ for (const e of this.entries.values()) {
2256
+ snapshot[e.id] = { ...e.spec, cols: e.cols, rows: e.rows, startedAt: e.startedAt };
2257
+ }
2258
+ this.writeChain = this.writeChain.then(() => this.store.write(snapshot)).catch(swallow("persist the PTY restore list (next change retries)"));
2259
+ return this.writeChain;
2260
+ }
2261
+ };
2262
+
2263
+ // src/core/pty/terminal-tickets.ts
2264
+ import crypto from "crypto";
2265
+ var TICKET_TTL_MS = 3e4;
2266
+ var LOOPBACK_ORIGIN = /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d{1,5})?$/;
2267
+ var isLoopbackOrigin = (origin) => LOOPBACK_ORIGIN.test(origin);
2268
+ function createTicketBook(now = Date.now) {
2269
+ const book = /* @__PURE__ */ new Map();
2270
+ const sweep = () => {
2271
+ const t = now();
2272
+ for (const [k, v] of book) if (v.expires <= t) book.delete(k);
2273
+ };
2274
+ return {
2275
+ issue(id, origin) {
2276
+ if (!id || !isLoopbackOrigin(origin)) return null;
2277
+ sweep();
2278
+ const ticket = crypto.randomBytes(24).toString("hex");
2279
+ book.set(ticket, { id, origin, expires: now() + TICKET_TTL_MS });
2280
+ return ticket;
2281
+ },
2282
+ redeem(ticket, id, origin) {
2283
+ const t = book.get(ticket);
2284
+ if (!t) return false;
2285
+ book.delete(ticket);
2286
+ return t.expires > now() && t.id === id && t.origin === origin;
2287
+ }
2288
+ };
2289
+ }
2290
+
2291
+ // src/core/pty/terminal-replies.ts
2292
+ var REPORT = String.raw`\x1b\[[IO]|\x1b\[<(?:35|39|43|47|51|55|59|63);\d+;\d+M`;
2293
+ var ANSWER = String.raw`\x1b\[[?>=][\d;]*c|\x1b\[(?!1;[2-8]R)\d+;\d+R|\x1b\[\?\d+;\d+(?:;\d+)?R|\x1b\[\??\d*n|\x1b\[\?\d*u|\x1b\[\??[\d;]*\$y|\x1b\[\d+(?:;\d+)*t|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[P_][\s\S]*?\x1b\\`;
2294
+ var PART = new RegExp(`(${REPORT})|(?:${ANSWER})`, "y");
2295
+ function replyParts(data) {
2296
+ if (!data) return null;
2297
+ const parts = [];
2298
+ PART.lastIndex = 0;
2299
+ while (PART.lastIndex < data.length) {
2300
+ const at = PART.lastIndex;
2301
+ const m = PART.exec(data);
2302
+ if (!m || m.index !== at || !m[0]) return null;
2303
+ parts.push({ text: m[0], answer: m[1] === void 0 });
2304
+ }
2305
+ return parts;
2306
+ }
2307
+
2308
+ // src/core/pty/pty-host.ts
2309
+ var ATTACH_PATH = /^\/ptys\/([^/?]+)\/attach(?:\?|$)/;
2310
+ var PTY_PATH = /^\/ptys\/([^/?]+)(\/write|\/screen|\/restart|\/halt|\/resume)?$/;
2311
+ var MAX_BODY = 1024 * 1024;
2312
+ function readBody(req) {
2313
+ return new Promise((resolve, reject) => {
2314
+ let size = 0;
2315
+ const chunks = [];
2316
+ req.on("data", (c) => {
2317
+ size += c.length;
2318
+ if (size > MAX_BODY) {
2319
+ reject(new Error("body too large"));
2320
+ req.destroy();
2321
+ return;
2322
+ }
2323
+ chunks.push(c);
2324
+ });
2325
+ req.on("end", () => {
2326
+ try {
2327
+ const text = Buffer.concat(chunks).toString("utf-8");
2328
+ resolve(text ? JSON.parse(text) : {});
2329
+ } catch (err) {
2330
+ reject(err);
2331
+ }
2332
+ });
2333
+ req.on("error", reject);
2334
+ });
2335
+ }
2336
+ function send(res, status, body) {
2337
+ res.writeHead(status, { "Content-Type": "application/json" });
2338
+ res.end(JSON.stringify(body));
2339
+ }
2340
+ function isSpawnSpec(v) {
2341
+ if (!v || typeof v !== "object") return false;
2342
+ const s = v;
2343
+ return typeof s.cwd === "string" && s.cwd.length > 0 && !!s.tool && typeof s.tool.cmd === "string" && Array.isArray(s.tool.baseArgs);
2344
+ }
2345
+ async function startPtyHost(opts = {}) {
2346
+ const registry = opts.registry ?? new PtyRegistry({ windowsPty: windowsPtyFor(process.platform, os2.release()) });
2347
+ const token = crypto2.randomBytes(24).toString("hex");
2348
+ let allowedHosts = /* @__PURE__ */ new Set();
2349
+ const tickets = createTicketBook();
2350
+ const authorized = (req, url) => {
2351
+ if (!req.headers.host || !allowedHosts.has(req.headers.host)) return false;
2352
+ const given = req.headers["x-work-token"] ?? url.searchParams.get("token") ?? "";
2353
+ const a = Buffer.from(given);
2354
+ const b = Buffer.from(token);
2355
+ return a.length === b.length && crypto2.timingSafeEqual(a, b);
2356
+ };
2357
+ const server = http.createServer(async (req, res) => {
2358
+ const url = new URL(req.url ?? "/", "http://localhost");
2359
+ if (!authorized(req, url)) return send(res, 403, { error: "forbidden" });
2360
+ try {
2361
+ if (req.method === "GET" && url.pathname === "/health") {
2362
+ return send(res, 200, { version: PROTOCOL_VERSION, pid: process.pid, features: HOST_FEATURES, work: VERSION });
2363
+ }
2364
+ if (req.method === "GET" && url.pathname === "/ptys") {
2365
+ return send(res, 200, registry.list());
2366
+ }
2367
+ if (req.method === "POST" && url.pathname === "/tickets") {
2368
+ const body = await readBody(req).catch(() => ({}));
2369
+ const ticket = typeof body.id === "string" && typeof body.origin === "string" ? tickets.issue(body.id, body.origin) : null;
2370
+ return ticket ? send(res, 200, { ticket }) : send(res, 400, { error: "a terminal id and a page origin on this machine" });
2371
+ }
2372
+ const m = url.pathname.match(PTY_PATH);
2373
+ if (m) {
2374
+ const id = decodeURIComponent(m[1]);
2375
+ if (m[2] === "/screen" && req.method === "GET") {
2376
+ const text = registry.screen(id);
2377
+ return text === null ? send(res, 404, { error: "not found" }) : send(res, 200, { text });
2378
+ }
2379
+ if (m[2] === "/restart" && req.method === "POST") {
2380
+ const body = await readBody(req).catch(() => ({}));
2381
+ const agentEnv = isEnvDelta(body.agentEnv) ? body.agentEnv : void 0;
2382
+ const info3 = await registry.restart(id, void 0, agentEnv);
2383
+ return info3 ? send(res, 200, agentEnv ? { ...info3, agentEnvApplied: true } : info3) : send(res, 409, { error: "not running" });
2384
+ }
2385
+ if (m[2] === "/halt" && req.method === "POST") {
2386
+ const info3 = await registry.halt(id);
2387
+ return info3 ? send(res, 200, info3) : send(res, 409, { error: "not running" });
2388
+ }
2389
+ if (m[2] === "/resume" && req.method === "POST") {
2390
+ const body = await readBody(req).catch(() => ({}));
2391
+ const info3 = await registry.resume(id, isEnvDelta(body.agentEnv) ? body.agentEnv : void 0);
2392
+ return info3 ? send(res, 200, info3) : send(res, 409, { error: "not halted" });
2393
+ }
2394
+ if (m[2] === "/write" && req.method === "POST") {
2395
+ const body = await readBody(req);
2396
+ if (typeof body.data !== "string") return send(res, 400, { error: "data required" });
2397
+ return send(res, registry.write(id, body.data) ? 200 : 404, {});
2398
+ }
2399
+ if (!m[2] && req.method === "POST") {
2400
+ const spec = await readBody(req);
2401
+ if (!isSpawnSpec(spec)) return send(res, 400, { error: "invalid spawn spec" });
2402
+ if (!fs3.existsSync(spec.cwd)) return send(res, 400, { error: "cwd does not exist" });
2403
+ return send(res, 200, registry.spawn(id, spec));
2404
+ }
2405
+ if (!m[2] && req.method === "GET") {
2406
+ const info3 = registry.get(id);
2407
+ return info3 ? send(res, 200, info3) : send(res, 404, { error: "not found" });
2408
+ }
2409
+ if (!m[2] && req.method === "DELETE") {
2410
+ await registry.kill(id);
2411
+ return send(res, 200, {});
2412
+ }
2413
+ }
2414
+ return send(res, 404, { error: "not found" });
2415
+ } catch (err) {
2416
+ return send(res, 500, { error: err.message });
2417
+ }
2418
+ });
2419
+ const wss = new WebSocketServer({ noServer: true });
2420
+ server.on("upgrade", (req, socket, head) => {
2421
+ const url = new URL(req.url ?? "/", "http://localhost");
2422
+ const m = (req.url ?? "").match(ATTACH_PATH);
2423
+ const id = m ? decodeURIComponent(m[1]) : "";
2424
+ const ticket = url.searchParams.get("ticket");
2425
+ const ok = !!m && (ticket ? !!req.headers.host && allowedHosts.has(req.headers.host) && tickets.redeem(ticket, id, req.headers.origin) : authorized(req, url));
2426
+ if (!ok) {
2427
+ socket.destroy();
2428
+ return;
2429
+ }
2430
+ const metered = url.searchParams.get(FLOW_PARAM) === "1";
2431
+ const screenOnlyCatchUp = url.searchParams.get(CATCH_UP_PARAM) === "screen";
2432
+ const grid = gridFromParams(url.searchParams) ?? void 0;
2433
+ const resume = resumeFromParams(url.searchParams) ?? void 0;
2434
+ wss.handleUpgrade(req, socket, head, (ws) => {
2435
+ const attached = registry.attach(
2436
+ id,
2437
+ (data) => {
2438
+ try {
2439
+ ws.send(Buffer.from(data, "utf-8"), { binary: true });
2440
+ } catch {
2441
+ }
2442
+ },
2443
+ (code) => {
2444
+ try {
2445
+ ws.send(JSON.stringify({ type: "exit", code }));
2446
+ ws.close(1e3);
2447
+ } catch {
2448
+ }
2449
+ },
2450
+ {
2451
+ metered,
2452
+ screenOnlyCatchUp,
2453
+ grid,
2454
+ resume,
2455
+ onReplay: (replay) => {
2456
+ try {
2457
+ ws.send(JSON.stringify({ type: "replay", ...replay }));
2458
+ } catch {
2459
+ }
2460
+ }
2461
+ }
2462
+ );
2463
+ if (!attached) {
2464
+ try {
2465
+ ws.send(JSON.stringify({ type: "error", message: "no such pty" }));
2466
+ ws.close(1011);
2467
+ } catch {
2468
+ }
2469
+ return;
2470
+ }
2471
+ void attached.ready.then((replay) => {
2472
+ try {
2473
+ ws.send(JSON.stringify({ type: "replay", ...replay }));
2474
+ } catch {
2475
+ }
2476
+ if (attached.exitedWith !== null) {
2477
+ try {
2478
+ ws.send(JSON.stringify({ type: "exit", code: attached.exitedWith }));
2479
+ ws.close(1e3);
2480
+ } catch {
2481
+ }
2482
+ return;
2483
+ }
2484
+ attached.start();
2485
+ });
2486
+ if (attached.exitedWith !== null) return;
2487
+ let size = grid ?? null;
2488
+ ws.on("message", (raw, isBinary) => {
2489
+ if (isBinary) return;
2490
+ let msg;
2491
+ try {
2492
+ msg = JSON.parse(raw.toString("utf-8"));
2493
+ } catch {
2494
+ return;
2495
+ }
2496
+ if (msg.type === "input" && typeof msg.data === "string") {
2497
+ const parts = replyParts(msg.data);
2498
+ if (parts) {
2499
+ const out = attached.replies(parts);
2500
+ if (out) registry.write(id, out);
2501
+ return;
2502
+ }
2503
+ attached.lead();
2504
+ if (size) registry.resize(id, size.cols, size.rows);
2505
+ registry.write(id, msg.data);
2506
+ } else if (msg.type === "resize") {
2507
+ const asked = validGrid(msg.cols, msg.rows);
2508
+ if (!asked) return;
2509
+ size = asked;
2510
+ attached.lead();
2511
+ registry.resize(id, asked.cols, asked.rows);
2512
+ } else if (msg.type === "ack" && Number.isSafeInteger(msg.chars) && msg.chars > 0) {
2513
+ attached.ack(msg.chars);
2514
+ } else if (msg.type === "redraw") {
2515
+ registry.redraw(id);
2516
+ }
2517
+ });
2518
+ ws.on("close", () => attached.detach());
2519
+ ws.on("error", () => attached.detach());
2520
+ });
2521
+ });
2522
+ await new Promise((resolve, reject) => {
2523
+ server.once("error", reject);
2524
+ server.listen(0, "127.0.0.1", () => resolve());
2525
+ });
2526
+ const port = server.address().port;
2527
+ allowedHosts = /* @__PURE__ */ new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
2528
+ const info2 = { pid: process.pid, port, token, version: PROTOCOL_VERSION };
2529
+ if (opts.writeInfo !== false) {
2530
+ atomicWriteFile(hostInfoPath(), JSON.stringify(info2));
2531
+ }
2532
+ if (opts.restore !== false) {
2533
+ if (!opts.registry) {
2534
+ const adopted = bestEffort("adopt the old pty-sessions.json", () => adoptLegacyRestoreList(), null);
2535
+ if (adopted !== null && adopted !== void 0)
2536
+ report("info", `[pty-host] adopted ${adopted} session(s) from an older host's pty-sessions.json`);
2537
+ }
2538
+ await registry.restore();
2539
+ }
2540
+ return {
2541
+ info: info2,
2542
+ registry,
2543
+ async stop() {
2544
+ registry.disposeAllKeepingState();
2545
+ for (const c of wss.clients) c.terminate();
2546
+ wss.close();
2547
+ server.closeAllConnections();
2548
+ await new Promise((r) => server.close(() => r()));
2549
+ if (opts.writeInfo !== false) {
2550
+ try {
2551
+ const cur = JSON.parse(fs3.readFileSync(hostInfoPath(), "utf-8"));
2552
+ if (cur.pid === process.pid) fs3.unlinkSync(hostInfoPath());
2553
+ } catch {
2554
+ }
2555
+ }
2556
+ }
2557
+ };
2558
+ }
2559
+
2560
+ // src/commands/pty-host.ts
2561
+ function info(message) {
2562
+ process.stderr.write(message + "\n");
2563
+ }
2564
+ async function printStatus() {
2565
+ let host;
2566
+ try {
2567
+ host = await findHost();
2568
+ } catch (err) {
2569
+ if (err instanceof PtyHostVersionError || err instanceof PtyHostBusyError) {
2570
+ info(chalk.yellow(err.message));
2571
+ return;
2572
+ }
2573
+ throw err;
2574
+ }
2575
+ if (!host) {
2576
+ info(chalk.gray("No PTY host running."));
2577
+ return;
2578
+ }
2579
+ const ptys = await new PtyHostClient(host).list();
2580
+ const names = new Map(loadHistory().map((s) => [sessionIdFor(s), `${s.target} \xB7 ${s.branch}`]));
2581
+ info(chalk.gray(`PTY host PID ${host.pid}, port ${host.port} \u2014 ${ptys.length} session(s)`));
2582
+ for (const p of ptys) {
2583
+ const state = p.exited ? chalk.red("exited") : chalk.green("live");
2584
+ const tag = p.restored ? chalk.gray(" (restored)") : "";
2585
+ info(` ${state} ${names.get(p.id) ?? p.id}${tag} ${chalk.gray(p.cwd)}`);
2586
+ }
2587
+ }
2588
+ var ptyHostCommand = {
2589
+ command: "pty-host",
2590
+ describe: false,
2591
+ // internal — started on demand by `work web` / `work attach`
2592
+ builder: (yargs) => yargs.option("stop", { type: "boolean", default: false, describe: "Stop the PTY host (sessions restore on next start)." }).option("restart", { type: "boolean", default: false, describe: "Restart the PTY host, e.g. after upgrading work." }).option("status", { type: "boolean", default: false, describe: "List the sessions the PTY host owns." }).option("force", {
2593
+ type: "boolean",
2594
+ default: false,
2595
+ describe: "With --stop/--restart: also stop a host that doesn't answer (hung), once it proves to be work's PTY host."
2596
+ }),
2597
+ handler: async (argv) => {
2598
+ if (argv.status) {
2599
+ await printStatus();
2600
+ return;
2601
+ }
2602
+ if (argv.stop || argv.restart) {
2603
+ const outcome = await stopHost(killTree, 5e3, { force: argv.force });
2604
+ info(
2605
+ chalk.gray(
2606
+ {
2607
+ stopped: "Stopped the PTY host.",
2608
+ "not-running": "No PTY host running.",
2609
+ "stale-file": "No PTY host running (removed a stale discovery file; nothing was killed).",
2610
+ unresponsive: argv.force ? "The PTY host is not responding, and its process doesn't look like work's PTY host: nothing was stopped." : "The PTY host is not responding (busy, or hung). Nothing was stopped \u2014 try again in a moment, or add --force to stop a hung one.",
2611
+ failed: "Could not stop the PTY host."
2612
+ }[outcome]
2613
+ )
2614
+ );
2615
+ if (outcome === "failed" || outcome === "unresponsive") {
2616
+ process.exitCode = 1;
2617
+ return;
2618
+ }
2619
+ if (argv.stop) return;
2620
+ await new Promise((r) => setTimeout(r, 500));
2621
+ const host = await ensureHost(resolveWorkBinPath(process.argv[1]));
2622
+ info(chalk.gray(`PTY host restarted (PID ${host.pid}); sessions are being restored.`));
2623
+ return;
2624
+ }
2625
+ const lock = hostStartLockPath();
2626
+ ensureFile(lock, "");
2627
+ const handle = await withFileLock(lock, async () => {
2628
+ const running = await findHost().catch(
2629
+ (err) => err instanceof PtyHostVersionError || err instanceof PtyHostBusyError ? true : null
2630
+ );
2631
+ if (running) return null;
2632
+ ensureAgentPath();
2633
+ return startPtyHost();
2634
+ });
2635
+ if (!handle) {
2636
+ info(chalk.gray("PTY host already running."));
2637
+ return;
2638
+ }
2639
+ info(chalk.gray(`PTY host listening on 127.0.0.1:${handle.info.port} (PID ${process.pid})`));
2640
+ const shutdown = () => {
2641
+ void handle.stop().finally(() => process.exit(0));
2642
+ };
2643
+ process.on("SIGINT", shutdown);
2644
+ process.on("SIGTERM", shutdown);
2645
+ await new Promise(() => {
2646
+ });
2647
+ }
2648
+ };
2649
+ export {
2650
+ ptyHostCommand,
2651
+ stopHost
2652
+ };
2653
+ //# sourceMappingURL=pty-host-IJFDGRA4.js.map