@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 @@
1
+ {"version":3,"sources":["../src/commands/pty-host.ts","../src/core/pty/pty-host.ts","../src/core/pty/pty-registry.ts","../src/core/pty/pty-session.ts","../src/core/pty/spawn-helper.ts","../src/core/pty/screen-mirror.ts","../src/core/pty/scrollback.ts","../src/core/pty/sync-output.ts","../src/core/pty/terminal-colors.ts","../src/core/pty/output-tail.ts","../src/core/pty/output-pacer.ts","../src/core/pty/terminal-tickets.ts","../src/core/pty/terminal-replies.ts"],"sourcesContent":["import chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { startPtyHost } from '../core/pty/pty-host.js';\nimport { ensureHost, findHost, PtyHostBusyError, PtyHostClient, PtyHostVersionError } from '../core/pty/pty-host-client.js';\nimport { ensureFile, withFileLock } from '../core/platform/fs-safe.js';\nimport { hostStartLockPath } from '../core/pty/pty-host-protocol.js';\nimport { stopHost } from '../core/pty/host-control.js';\nimport { killTree } from '../core/platform/process.js';\nimport { loadHistory } from '../core/sessions/history.js';\nimport { sessionIdFor } from '../core/sessions/session-id.js';\nimport { resolveWorkBinPath } from '../core/platform/work-bin.js';\nimport { ensureAgentPath } from '../core/agents/agent-path.js';\n\nfunction info(message: string): void {\n process.stderr.write(message + '\\n');\n}\n\n// Moved to core (host-control.ts): the dashboard's Restart uses it too. Re-exported for the tests.\nexport { stopHost, type StopOutcome } from '../core/pty/host-control.js';\n\nasync function printStatus(): Promise<void> {\n let host;\n try {\n host = await findHost();\n } catch (err) {\n if (err instanceof PtyHostVersionError || err instanceof PtyHostBusyError) {\n info(chalk.yellow(err.message));\n return;\n }\n throw err;\n }\n if (!host) {\n info(chalk.gray('No PTY host running.'));\n return;\n }\n const ptys = await new PtyHostClient(host).list();\n const names = new Map(loadHistory().map((s) => [sessionIdFor(s), `${s.target} · ${s.branch}`]));\n info(chalk.gray(`PTY host PID ${host.pid}, port ${host.port} — ${ptys.length} session(s)`));\n for (const p of ptys) {\n const state = p.exited ? chalk.red('exited') : chalk.green('live');\n const tag = p.restored ? chalk.gray(' (restored)') : '';\n info(` ${state} ${names.get(p.id) ?? p.id}${tag} ${chalk.gray(p.cwd)}`);\n }\n}\n\nexport const ptyHostCommand: CommandModule = {\n command: 'pty-host',\n describe: false, // internal — started on demand by `work web` / `work attach`\n builder: (yargs) =>\n yargs\n .option('stop', { type: 'boolean', default: false, describe: 'Stop the PTY host (sessions restore on next start).' })\n .option('restart', { type: 'boolean', default: false, describe: 'Restart the PTY host, e.g. after upgrading work.' })\n .option('status', { type: 'boolean', default: false, describe: 'List the sessions the PTY host owns.' })\n .option('force', {\n type: 'boolean',\n default: false,\n describe: \"With --stop/--restart: also stop a host that doesn't answer (hung), once it proves to be work's PTY host.\",\n }),\n handler: async (argv) => {\n if (argv.status) {\n await printStatus();\n return;\n }\n if (argv.stop || argv.restart) {\n const outcome = await stopHost(killTree, 5000, { force: argv.force as boolean });\n info(\n chalk.gray(\n {\n stopped: 'Stopped the PTY host.',\n 'not-running': 'No PTY host running.',\n 'stale-file': 'No PTY host running (removed a stale discovery file; nothing was killed).',\n unresponsive: argv.force\n ? \"The PTY host is not responding, and its process doesn't look like work's PTY host: nothing was stopped.\"\n : 'The PTY host is not responding (busy, or hung). Nothing was stopped — try again in a moment, or add --force to stop a hung one.',\n failed: 'Could not stop the PTY host.',\n }[outcome],\n ),\n );\n if (outcome === 'failed' || outcome === 'unresponsive') {\n process.exitCode = 1;\n return; // never --restart on top of a host we couldn't stop\n }\n if (argv.stop) return;\n await new Promise((r) => setTimeout(r, 500));\n const host = await ensureHost(resolveWorkBinPath(process.argv[1]));\n info(chalk.gray(`PTY host restarted (PID ${host.pid}); sessions are being restored.`));\n return;\n }\n\n // Singleton: a second host would restore every saved session a second\n // time (two Claudes per conversation). Check-and-start under a lock; a\n // version-mismatched or busy (not answering in time) host still counts\n // as running.\n const lock = hostStartLockPath();\n ensureFile(lock, '');\n const handle = await withFileLock(lock, async () => {\n const running = await findHost().catch((err) =>\n err instanceof PtyHostVersionError || err instanceof PtyHostBusyError ? true : null,\n );\n if (running) return null;\n // Started by the Mac app from the Dock, the PATH is the system's: `claude` wouldn't be found and\n // every session would end at once (\"exited with code 1\"). The login shell's, before the restore\n // below starts any (shell-path.ts); only once we know we're the host.\n ensureAgentPath();\n // Restore INSIDE the lock, as part of starting: startPtyHost writes\n // the discovery file and reads the saved list in the same tick,\n // before any request is served — so a client spawning a session\n // can't overwrite the list first (which lost every other saved\n // session), and a racing `work remove` waits for the restore.\n return startPtyHost();\n });\n if (!handle) {\n info(chalk.gray('PTY host already running.'));\n return;\n }\n info(chalk.gray(`PTY host listening on 127.0.0.1:${handle.info.port} (PID ${process.pid})`));\n const shutdown = () => {\n void handle.stop().finally(() => process.exit(0));\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n await new Promise(() => {});\n },\n};\n","import http from 'node:http';\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport { WebSocketServer } from 'ws';\nimport { atomicWriteFile } from '../platform/fs-safe.js';\nimport { PtyRegistry } from './pty-registry.js';\nimport { adoptLegacyRestoreList } from './pty-sessions-file.js';\nimport { bestEffort } from '../platform/best-effort.js';\nimport { VERSION } from '../../version.js';\nimport { HOST_FEATURES, PROTOCOL_VERSION, hostInfoPath, type ClientFrame, type HostInfo, type SpawnSpec } from './pty-host-protocol.js';\nimport { report } from '../platform/report.js';\nimport { isEnvDelta } from '../platform/env-delta.js';\nimport { createTicketBook } from './terminal-tickets.js';\nimport { replyParts } from './terminal-replies.js';\nimport { CATCH_UP_PARAM, FLOW_PARAM } from './flow-control.js';\nimport { gridFromParams, validGrid, windowsPtyFor } from './terminal-size.js';\nimport { resumeFromParams } from './resume.js';\n\nconst ATTACH_PATH = /^\\/ptys\\/([^/?]+)\\/attach(?:\\?|$)/;\nconst PTY_PATH = /^\\/ptys\\/([^/?]+)(\\/write|\\/screen|\\/restart|\\/halt|\\/resume)?$/;\nconst MAX_BODY = 1024 * 1024;\n\nexport interface PtyHostHandle {\n info: HostInfo;\n registry: PtyRegistry;\n /** Kill every PTY (state file kept for the next restore) and stop. */\n stop(): Promise<void>;\n}\n\nfunction readBody(req: http.IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0;\n const chunks: Buffer[] = [];\n req.on('data', (c: Buffer) => {\n size += c.length;\n if (size > MAX_BODY) {\n reject(new Error('body too large'));\n req.destroy();\n return;\n }\n chunks.push(c);\n });\n req.on('end', () => {\n try {\n const text = Buffer.concat(chunks).toString('utf-8');\n resolve(text ? JSON.parse(text) : {});\n } catch (err) {\n reject(err);\n }\n });\n req.on('error', reject);\n });\n}\n\nfunction send(res: http.ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(body));\n}\n\nfunction isSpawnSpec(v: unknown): v is SpawnSpec {\n if (!v || typeof v !== 'object') return false;\n const s = v as Partial<SpawnSpec>;\n return typeof s.cwd === 'string' && s.cwd.length > 0 && !!s.tool && typeof s.tool.cmd === 'string' && Array.isArray(s.tool.baseArgs);\n}\n\n/**\n * The PTY host: a small localhost-only server that owns every Claude PTY\n * so they survive `work web` restarts and rebuilds, and so any number of\n * clients (browser terminal via `work web`, a real terminal via\n * `work attach`) can attach to the same session.\n *\n * Auth: a random token written to `~/.work/pty-host.json` (user-only\n * readable location) must accompany every request — `x-work-token` header\n * for HTTP, `?token=` for the WebSocket upgrade. Plus a Host-header check\n * against DNS rebinding, same as the other local servers (§1.3).\n */\nexport async function startPtyHost(opts: { registry?: PtyRegistry; restore?: boolean; writeInfo?: boolean } = {}): Promise<PtyHostHandle> {\n // On Windows its PTYs are ConPTY's: every screen it sends says so (windowsPty, terminal-size.ts).\n const registry = opts.registry ?? new PtyRegistry({ windowsPty: windowsPtyFor(process.platform, os.release()) });\n const token = crypto.randomBytes(24).toString('hex');\n let allowedHosts = new Set<string>();\n // A dashboard page's Terminal tab connects here directly with one of these (terminal-tickets.ts), never the token.\n const tickets = createTicketBook();\n\n const authorized = (req: http.IncomingMessage, url: URL): boolean => {\n if (!req.headers.host || !allowedHosts.has(req.headers.host)) return false;\n const given = (req.headers['x-work-token'] as string | undefined) ?? url.searchParams.get('token') ?? '';\n const a = Buffer.from(given);\n const b = Buffer.from(token);\n return a.length === b.length && crypto.timingSafeEqual(a, b);\n };\n\n const server = http.createServer(async (req, res) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (!authorized(req, url)) return send(res, 403, { error: 'forbidden' });\n\n try {\n if (req.method === 'GET' && url.pathname === '/health') {\n // `work`: the release it runs (additive) — it outlives updates, so the dashboard can say when it's older.\n return send(res, 200, { version: PROTOCOL_VERSION, pid: process.pid, features: HOST_FEATURES, work: VERSION });\n }\n if (req.method === 'GET' && url.pathname === '/ptys') {\n return send(res, 200, registry.list());\n }\n // work web, for a page it checked: a one-time ticket to attach that terminal from that page's origin.\n if (req.method === 'POST' && url.pathname === '/tickets') {\n const body = (await readBody(req).catch(() => ({}))) as { id?: unknown; origin?: unknown };\n const ticket = typeof body.id === 'string' && typeof body.origin === 'string' ? tickets.issue(body.id, body.origin) : null;\n return ticket ? send(res, 200, { ticket }) : send(res, 400, { error: 'a terminal id and a page origin on this machine' });\n }\n const m = url.pathname.match(PTY_PATH);\n if (m) {\n const id = decodeURIComponent(m[1]);\n if (m[2] === '/screen' && req.method === 'GET') {\n const text = registry.screen(id);\n return text === null ? send(res, 404, { error: 'not found' }) : send(res, 200, { text });\n }\n // Additive (no protocol bump): an older host answers 404 \"not found\", and the pool stops and starts it instead.\n if (m[2] === '/restart' && req.method === 'POST') {\n // The body is optional (a restart for an updated tool has none): `agentEnv`, a session moved to another account.\n const body = (await readBody(req).catch(() => ({}))) as { agentEnv?: unknown };\n const agentEnv = isEnvDelta(body.agentEnv) ? body.agentEnv : undefined;\n const info = await registry.restart(id, undefined, agentEnv);\n // `agentEnvApplied` tells the caller this host took the environment (one from before ignores it).\n return info ? send(res, 200, agentEnv ? { ...info, agentEnvApplied: true } : info) : send(res, 409, { error: 'not running' });\n }\n // Additive too: halt stops the agent and keeps the session (entry, record, attached terminals) until resume starts it\n // again — a switch of account moves its conversation files in between. An older host answers 404 to both.\n if (m[2] === '/halt' && req.method === 'POST') {\n const info = await registry.halt(id);\n return info ? send(res, 200, info) : send(res, 409, { error: 'not running' });\n }\n if (m[2] === '/resume' && req.method === 'POST') {\n const body = (await readBody(req).catch(() => ({}))) as { agentEnv?: unknown };\n const info = await registry.resume(id, isEnvDelta(body.agentEnv) ? body.agentEnv : undefined);\n return info ? send(res, 200, info) : send(res, 409, { error: 'not halted' });\n }\n if (m[2] === '/write' && req.method === 'POST') {\n const body = (await readBody(req)) as { data?: unknown };\n if (typeof body.data !== 'string') return send(res, 400, { error: 'data required' });\n return send(res, registry.write(id, body.data) ? 200 : 404, {});\n }\n if (!m[2] && req.method === 'POST') {\n const spec = await readBody(req);\n if (!isSpawnSpec(spec)) return send(res, 400, { error: 'invalid spawn spec' });\n if (!fs.existsSync(spec.cwd)) return send(res, 400, { error: 'cwd does not exist' });\n return send(res, 200, registry.spawn(id, spec));\n }\n if (!m[2] && req.method === 'GET') {\n const info = registry.get(id);\n return info ? send(res, 200, info) : send(res, 404, { error: 'not found' });\n }\n if (!m[2] && req.method === 'DELETE') {\n await registry.kill(id);\n return send(res, 200, {});\n }\n }\n return send(res, 404, { error: 'not found' });\n } catch (err) {\n return send(res, 500, { error: (err as Error).message });\n }\n });\n\n const wss = new WebSocketServer({ noServer: true });\n server.on('upgrade', (req, socket, head) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n const m = (req.url ?? '').match(ATTACH_PATH);\n const id = m ? decodeURIComponent(m[1]) : '';\n // work web's relay and `work attach` bring the token; a dashboard page brings a ticket work web got for it.\n const ticket = url.searchParams.get('ticket');\n const ok =\n !!m &&\n (ticket\n ? !!req.headers.host && allowedHosts.has(req.headers.host) && tickets.redeem(ticket, id, req.headers.origin)\n : authorized(req, url));\n if (!ok) {\n socket.destroy();\n return;\n }\n // A client that acks what it draws (flow-control.ts) is paced: one too far behind is sent the screen once it caught up.\n const metered = url.searchParams.get(FLOW_PARAM) === '1';\n // `work attach`: that screen without the scrollback (its native terminal keeps your history).\n const screenOnlyCatchUp = url.searchParams.get(CATCH_UP_PARAM) === 'screen';\n // Its grid, when it takes the size as it attaches (`?cols=…&rows=…`, terminal-size.ts): the PTY is resized to it\n // before the snapshot. A hidden terminal states none, and changes nothing.\n const grid = gridFromParams(url.searchParams) ?? undefined;\n // A client reconnecting with its screen kept (`?resume=…`, resume.ts): sent only what it missed when that is enough.\n const resume = resumeFromParams(url.searchParams) ?? undefined;\n wss.handleUpgrade(req, socket, head, (ws) => {\n const attached = registry.attach(\n id,\n (data) => {\n try {\n ws.send(Buffer.from(data, 'utf-8'), { binary: true });\n } catch {\n /* */\n }\n },\n (code) => {\n try {\n ws.send(JSON.stringify({ type: 'exit', code }));\n ws.close(1000);\n } catch {\n /* */\n }\n },\n {\n metered,\n screenOnlyCatchUp,\n grid,\n resume,\n onReplay: (replay) => {\n try {\n ws.send(JSON.stringify({ type: 'replay', ...replay }));\n } catch {\n /* the socket closed meanwhile: its close detaches it */\n }\n },\n },\n );\n if (!attached) {\n try {\n ws.send(JSON.stringify({ type: 'error', message: 'no such pty' }));\n ws.close(1011);\n } catch {\n /* */\n }\n return;\n }\n // Always first, even when empty: clients hold input and their own\n // resize until they've drawn it (see HostControlFrame 'replay'). The\n // screen as of the attach, then what came since (registry.attach).\n void attached.ready.then((replay) => {\n try {\n ws.send(JSON.stringify({ type: 'replay', ...replay }));\n } catch {\n /* */\n }\n if (attached.exitedWith !== null) {\n try {\n ws.send(JSON.stringify({ type: 'exit', code: attached.exitedWith }));\n ws.close(1000);\n } catch {\n /* */\n }\n return;\n }\n attached.start();\n });\n if (attached.exitedWith !== null) return;\n // This client's own grid. The PTY has one size for all its clients: the one used last sets it — resized OR typed\n // in (tmux's `window-size latest` counts both). With \"last resize\" alone, opening the session in the app shrank\n // the PTY to the app's grid, and a terminal attached to it stayed drawn for that size while you typed in it.\n let size: { cols: number; rows: number } | null = grid ?? null;\n ws.on('message', (raw, isBinary) => {\n if (isBinary) return;\n let msg: ClientFrame;\n try {\n msg = JSON.parse(raw.toString('utf-8')) as ClientFrame;\n } catch {\n return;\n }\n if (msg.type === 'input' && typeof msg.data === 'string') {\n const parts = replyParts(msg.data);\n if (parts) {\n // What it sent on its own (terminal-replies.ts): not someone using it, and only one client answers the\n // agent's queries (terminal-rendering.md, \"Who answers a query\").\n const out = attached.replies(parts);\n if (out) registry.write(id, out);\n return;\n }\n // Someone typed in it (a frame with typing in it goes through whole, any replies in it too): back to this\n // client's grid first (a no-op when it is), and it answers the agent from now on.\n attached.lead();\n if (size) registry.resize(id, size.cols, size.rows);\n registry.write(id, msg.data);\n } else if (msg.type === 'resize') {\n // Only a grid the PTY would take is this client's size, and makes it the one used last.\n const asked = validGrid(msg.cols, msg.rows);\n if (!asked) return;\n size = asked;\n attached.lead();\n registry.resize(id, asked.cols, asked.rows);\n } else if (msg.type === 'ack' && Number.isSafeInteger(msg.chars) && msg.chars > 0) {\n attached.ack(msg.chars);\n } else if (msg.type === 'redraw') {\n // ⋯ → Reconnect terminal: the agent draws its screen again (registry.redraw). Not someone using it: no size taken.\n registry.redraw(id);\n }\n });\n ws.on('close', () => attached.detach());\n ws.on('error', () => attached.detach());\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', () => resolve());\n });\n const port = (server.address() as { port: number }).port;\n allowedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);\n\n const info: HostInfo = { pid: process.pid, port, token, version: PROTOCOL_VERSION };\n if (opts.writeInfo !== false) {\n atomicWriteFile(hostInfoPath(), JSON.stringify(info));\n }\n if (opts.restore !== false) {\n // An older host that outlived the upgrade kept its list in the old\n // file: take it over before restoring (see adoptLegacyRestoreList).\n if (!opts.registry) {\n const adopted = bestEffort('adopt the old pty-sessions.json', () => adoptLegacyRestoreList(), null);\n if (adopted !== null && adopted !== undefined)\n report('info', `[pty-host] adopted ${adopted} session(s) from an older host's pty-sessions.json`);\n }\n await registry.restore();\n }\n\n return {\n info,\n registry,\n async stop() {\n registry.disposeAllKeepingState();\n // Every attached terminal's connection ends now: server.close() waits for open connections, and a dashboard\n // page connected straight here (a ticket) keeps its WebSocket for as long as the tab is open — the host\n // never stopped (`work pty-host --stop` / `--restart` hung while a Terminal tab was open).\n for (const c of wss.clients) c.terminate();\n wss.close();\n server.closeAllConnections();\n await new Promise<void>((r) => server.close(() => r()));\n if (opts.writeInfo !== false) {\n try {\n const cur = JSON.parse(fs.readFileSync(hostInfoPath(), 'utf-8')) as HostInfo;\n if (cur.pid === process.pid) fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n }\n },\n };\n}\n","import fs from 'node:fs';\nimport { randomBytes } from 'node:crypto';\nimport { agentById, sessionToolFor } from '../agents/index.js';\nimport type { AiToolSpec } from '../platform/ai-launcher.js';\nimport { ASSISTANT_ID } from '../agents/assistant.js';\nimport { isAccountLoginId } from './account-login-id.js';\nimport { loadConfig } from '../platform/config.js';\nimport { PtySession } from './pty-session.js';\nimport { atomicWriteFile, ensureFile, withFileLockSync } from '../platform/fs-safe.js';\nimport { dbPtySessions, type PtySessionsStore } from './pty-sessions-file.js';\nimport { applyEnvDelta, hasEnvDelta, type EnvDelta } from '../platform/env-delta.js';\nimport { isPersistedPty, keepEnv, type PersistedPty, type PersistedPtys, type PtyInfo, type SpawnSpec } from './pty-host-protocol.js';\nimport { logSwallowed, swallow } from '../platform/best-effort.js';\nimport { report } from '../platform/report.js';\nimport { TerminalColors } from './terminal-colors.js';\nimport type { ReplyPart } from './terminal-replies.js';\nimport { OutputPacer, realTimers, type PacerTimers, type PtyFlow } from './output-pacer.js';\nimport type { SnapshotOptions } from './screen-mirror.js';\nimport type { StreamSignal } from './stream-status.js';\nimport { MIN_ROWS, validGrid, type Grid, type WindowsPty } from './terminal-size.js';\nimport { continueFrom, resumeFrom, type ResumeRefusal } from './output-tail.js';\nimport type { ResumePoint } from './resume.js';\nimport { startedUnder, stopLeftovers, type ProcessRow } from '../platform/process-tree.js';\nimport { listProcessUsage } from '../platform/process-usage.js';\n\nconst REPLAY_MAX = 256 * 1024;\n\n/**\n * A halted agent that no `resume` reaches in this long is started again on its old spec (work web died between the two).\n * Minutes, not seconds: a switch of account moves its conversation folders in between, and a big one across volumes takes\n * a while; the switch then restarts it in place on the new account (`not-halted` → restart, pty-pool.ts).\n */\nexport const HALT_RESUME_MS = 5 * 60_000;\n\n/** How long an exited PTY lingers before it's dropped from the persisted\n * list. During a Windows shutdown/logoff the child Claudes are often killed\n * a moment BEFORE the host; dropping them immediately would erase exactly\n * the list we need to restore after the reboot. A host that's itself about\n * to die never reaches the timer. */\nconst FORGET_EXITED_MS = 5_000;\n\n/** The grid a PTY starts at when nothing says another: no client stated one, and none has set one since the host started. */\nexport const DEFAULT_GRID: Grid = { cols: 120, rows: 32 };\n\n/**\n * How long `redraw` holds the PTY one row smaller before it puts it back. A same-size SIGWINCH repaints nothing in a\n * Node or Bun agent (Claude Code is a Bun binary): their `'resize'` event fires only when the size they read changed,\n * and they read it when they get to the signal. Measured (node-pty 1.1, Node 24 and Bun 1.3): the two resizes back to\n * back gave two SIGWINCHes and no `'resize'`; 30 ms apart gave both. 100 ms leaves a busy agent's event loop time.\n */\nexport const REDRAW_JIGGLE_MS = 100;\n\n/** A grid a client set is written to the restore list this long after the last change (a drag resizes many times). */\nconst GRID_PERSIST_MS = 1000;\n\n/** Minimal PTY surface the registry needs — `PtySession` in production, a\n * fake in tests. */\nexport interface PtyLike {\n readonly pty: { pid: number };\n readonly exited: boolean;\n onExit?: (code: number) => void;\n setOutputHandler(h?: (data: string) => void): void;\n write(data: string): void;\n resize(cols: number, rows: number): void;\n dispose(): void;\n /** Serialized screen state (see PtySession.serialize); null when it couldn't be taken. Optional so test\n * fakes can fall back to the raw replay buffer. */\n serialize?(opts?: SnapshotOptions): string | null;\n /** The serialized screen once everything written so far is parsed (see\n * PtySession.serializeSettled); null when it couldn't be taken. Optional: a fake's screen is its raw buffer. */\n serializeSettled?(opts?: SnapshotOptions): Promise<string | null>;\n /** Visible screen as plain text (PtySession.screenText). */\n screenText?(): string;\n /** What its agent says about itself in its output (PtySession.streamSignal). Optional: a fake says nothing. */\n streamSignal?(): StreamSignal | null;\n /** Its screen's copy answers the agent's queries in output arriving while `now()` says so (PtySession.answerQueries).\n * Optional: a fake has no screen to answer from. */\n answerQueries?(now: () => boolean, colors: Pick<TerminalColors, 'reply'>): void;\n /** Stop and start reading its output, for a client to catch up (PtySession.pause). Optional: where it can't, nothing waits. */\n pause?(): void;\n resume?(): void;\n /** The ConPTY it runs on (PtySession.windowsPty: the bundled one reflows as a newer Windows). Optional: the host's is said. */\n readonly windowsPty?: WindowsPty;\n}\n\n/** How a client attaches (`attach`). */\nexport interface AttachOptions {\n /** It acks what it draws (`?flow=1`, flow-control.ts): it is paced. Else it is sent everything, as before. */\n metered?: boolean;\n /**\n * It fell behind and caught up: what it missed (`resumed`), or the screen as it stands now, before live output again\n * (the host's `replay` frame).\n */\n onReplay?: (replay: ReplaySnapshot) => void;\n /**\n * Its catch-up screens are the screen only, without the scrollback (`?catchup=screen`: `work attach`, whose native\n * terminal keeps its own history). Its first screen still has the scrollback.\n */\n screenOnlyCatchUp?: boolean;\n /**\n * Its grid, stated as it attaches (`?cols=…&rows=…`, terminal-size.ts): it takes the PTY's size, as its first resize\n * would have — the terminal shown or `work attach`, never a hidden one. The PTY and its screen are resized to it\n * BEFORE the snapshot is taken, so the snapshot is drawn for its grid and it needs no second reflow; the agent's\n * repaint for it follows as live output.\n */\n grid?: Grid;\n /**\n * It reconnects with its screen kept, and has drawn this PTY's output up to here (`?resume=…`, resume.ts): it is sent\n * what it missed instead of a screen when that is provably all it needs (`resumeFrom`, output-tail.ts), else a screen.\n */\n resume?: ResumePoint;\n /** Why it was sent a screen though it asked to resume (tests, the debug log). */\n onResumeRefused?: (why: ResumeRefusal) => void;\n}\n\n/** What a newly attached client is sent first: the screen as it stands,\n * plus the grid it was drawn for. */\nexport interface ReplaySnapshot {\n data: string;\n cols: number;\n rows: number;\n /** The PTY's output stream (one per entry: resume.ts) and the offset this screen stands at — where its live output starts. */\n stream: string;\n offset: number;\n /**\n * `data` is not a screen but the output the client missed, from where it said it stood (a reconnect) or was sent output\n * up to (a catch-up) up to `offset`: drawn on its screen as it is. Also a catch-up whose screen couldn't be taken:\n * `data` '' and `stream` '' (where it stands is unknown now: it never resumes from here), its screen kept.\n */\n resumed?: true;\n /** The PTY is ConPTY's (a host on Windows): the client's xterm.js sets this, so it doesn't reflow lines ConPTY reflows. */\n windowsPty?: WindowsPty;\n}\n\n/** An environment without its unset names, typed as the spawn takes it. */\nconst definedEnv = (env: Record<string, string | undefined>): Record<string, string> =>\n Object.fromEntries(Object.entries(env).filter((e): e is [string, string] => typeof e[1] === 'string'));\n\nexport type PtySpawner = (spec: SpawnSpec & { resume: boolean }) => PtyLike;\n\nexport const defaultSpawner: PtySpawner = (spec) =>\n new PtySession(spec.cwd, spec.cols ?? DEFAULT_GRID.cols, spec.rows ?? DEFAULT_GRID.rows, undefined, {\n tool: spec.tool,\n resume: spec.resume,\n port: spec.port,\n initialPrompt: spec.initialPrompt,\n env: spec.env,\n });\n\n/** The grid most of `grids` are (the first of those tied), or null when none is a grid. */\nfunction mostCommonGrid(grids: Array<Grid | null>): Grid | null {\n const counts = new Map<string, { grid: Grid; n: number }>();\n for (const g of grids) {\n if (!g) continue;\n const key = `${g.cols}x${g.rows}`;\n const c = counts.get(key) ?? { grid: g, n: 0 };\n c.n++;\n counts.set(key, c);\n }\n let best: { grid: Grid; n: number } | null = null;\n for (const c of counts.values()) if (!best || c.n > best.n) best = c;\n return best?.grid ?? null;\n}\n\n/** An attached client, as its subscription to the output. */\ntype Client = (data: string) => void;\n\n/** What pauses the PTY's output, if it can be paused. */\nconst flowOf = (pty: PtyLike): PtyFlow | null =>\n pty.pause && pty.resume ? { pause: () => pty.pause?.(), resume: () => pty.resume?.() } : null;\n\ninterface Entry {\n id: string;\n spec: Omit<PersistedPty, 'startedAt'>;\n pty: PtyLike;\n cols: number;\n rows: number;\n startedAt: string;\n restored: boolean;\n replay: string;\n /** The attached clients, the first attached first. */\n subscribers: Set<Client>;\n exitSubscribers: Set<(code: number) => void>;\n /** The client used last — typed in or resized (`lead`); the PTY has its size. Null: none since, or it left. */\n leader: Client | null;\n /** Who answers the queries in the output that arrived last (`designate`): its answers go through, the others' don't. */\n answerer: Client | null;\n /** Its output on its way to the clients: coalesced into frames, paced by their acks (output-pacer.ts). */\n pacer: OutputPacer<Client>;\n /** Set once the process exited (the entry lingers FORGET_EXITED_MS). */\n exitCode: number | null;\n /** When it last printed anything (ms): an idle Claude at its prompt prints nothing. */\n lastOutputAt: number;\n /** Its agent is being restarted (restart): the old process's end isn't the session's, a spawn starts no\n * second one, and a second restart gets this one's outcome. */\n restarting?: Promise<PtyInfo | null>;\n /** Its agent was stopped by `halt` and isn't started again yet: the entry, its record and its clients stay; `timer` starts it\n * again on its old spec if no `resume` comes. */\n halted?: { timer: ReturnType<typeof setTimeout> };\n /** The environment it was started with, in memory only (never in the restore list: it can hold secrets), so a\n * restart runs as the session did; a restore after the host restarts has only what `hostEnv` kept. */\n env?: Record<string, string>;\n /** A `redraw` under way: the timer that puts the grid back. */\n redrawing?: unknown;\n /** Its output stream's id (resume.ts): a new one for every entry, so an offset of another process or host is never taken for one of this. */\n stream: string;\n /** The output offset its PTY's grid last changed at: output after it may be drawn for another grid than output before. */\n gridAt: number;\n}\n\nexport interface RegistryDeps {\n /** The env variable names to keep for a restore (default: config `hostEnv`). */\n keepEnvNames?: () => string[];\n spawner?: PtySpawner;\n /** Its agent can resume a conversation in this folder, with the environment it will start with (default: the agent's own check, agents/). */\n hasConversation?: (cwd: string, tool: string, env?: Readonly<Record<string, string | undefined>>) => boolean;\n /** Where the restore list lives. Default: state.db. */\n sessions?: PtySessionsStore;\n /** Keep the restore list in this JSON file instead (tests, which must\n * never touch the user's state.db). */\n sessionsPath?: string;\n cwdExists?: (cwd: string) => boolean;\n /** The tool as it is started (default: its agent's `sessionTool`, which gives a Claude work's hooks). */\n sessionTool?: (tool: AiToolSpec) => AiToolSpec;\n /** The output pacer's clock (tests). */\n timers?: PacerTimers;\n /** The `windowsPty` its clients are told with each screen (terminal-size.ts). None by default: the PTY host sets it\n * from its platform and Windows build (pty-host.ts), so a registry in a test says the same on every platform. */\n windowsPty?: WindowsPty | null;\n /**\n * What an agent started, found before it is stopped and stopped after it (`LeftoverWork`). Default: the real process\n * tree, only with the real spawner — a test's fake pid may be a real process of yours.\n */\n leftovers?: LeftoverWork | null;\n}\n\n/**\n * The processes an agent started (its background commands, a dev server, what those started), found before work stops\n * it and stopped once it is gone (reported: `dotnet run` a Claude had started kept running for days after it — stopping\n * a process on macOS and Linux leaves its children running, handed to launchd / init). Only ones still the same process\n * (same command line) are stopped.\n */\nexport interface LeftoverWork {\n /** Everything under this pid now. */\n under(pid: number): Promise<ProcessRow[]>;\n /** Those still running: stopped. Returns the ones it stopped. */\n stop(found: readonly ProcessRow[]): Promise<ProcessRow[]>;\n}\n\nexport const realLeftoverWork: LeftoverWork = {\n under: async (pid) => startedUnder(pid, await listProcessUsage(), process.pid),\n stop: (found) => stopLeftovers(found),\n};\n\n/** A restore list in a plain JSON file, written under the file lock. */\nexport function fileSessionsStore(file: string): PtySessionsStore {\n return {\n read() {\n const out: PersistedPtys = {};\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown;\n if (raw && typeof raw === 'object') {\n for (const [id, entry] of Object.entries(raw)) if (isPersistedPty(entry)) out[id] = entry;\n }\n } catch {\n /* missing or unreadable: nothing to restore */\n }\n return out;\n },\n write(all) {\n ensureFile(file, '{}');\n withFileLockSync(file, () => atomicWriteFile(file, JSON.stringify(all, null, 2)));\n },\n };\n}\n\n/**\n * Owns every live PTY in the host process and mirrors the set to the\n * restore list (state.db `pty_sessions`, see pty-sessions-file.ts) so a\n * host restart (crash, `--restart`, reboot) can respawn them with\n * `--continue`. Writes replace the list in one transaction, so two hosts\n * racing at startup can't interleave.\n */\nexport class PtyRegistry {\n private readonly entries = new Map<string, Entry>();\n private readonly spawner: PtySpawner;\n private readonly hasConversation: (cwd: string, tool: string, env?: Readonly<Record<string, string | undefined>>) => boolean;\n private readonly store: PtySessionsStore;\n private readonly cwdExists: (cwd: string) => boolean;\n private readonly keepEnvNames: () => string[];\n private readonly sessionTool: (tool: AiToolSpec) => AiToolSpec;\n private readonly timers?: PacerTimers;\n private readonly windowsPty?: WindowsPty;\n /**\n * 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\n * own (a background start, a session's Start) starts at. After a host restart, before any client: the restored\n * sessions' most common grid. In memory; each session's own grid is in the restore list.\n */\n private lastGrid: Grid | null = null;\n /** The restore-list write a grid change is waiting for (GRID_PERSIST_MS). */\n private gridPersist: unknown = null;\n private readonly leftovers: LeftoverWork | null;\n /** Serializes persistence writes inside this process. */\n private writeChain: Promise<void> = Promise.resolve();\n /** The colours the host answers a colour query with itself: the last a terminal attached to any PTY answered with. */\n readonly colors = new TerminalColors();\n\n constructor(deps: RegistryDeps = {}) {\n this.spawner = deps.spawner ?? defaultSpawner;\n this.hasConversation = deps.hasConversation ?? ((cwd, tool, env) => agentById(tool).launch.canResume(cwd, { env }));\n this.store = deps.sessions ?? (deps.sessionsPath ? fileSessionsStore(deps.sessionsPath) : dbPtySessions);\n this.cwdExists = deps.cwdExists ?? ((p) => fs.existsSync(p));\n this.keepEnvNames = deps.keepEnvNames ?? (() => loadConfig()?.hostEnv ?? []);\n this.sessionTool = deps.sessionTool ?? sessionToolFor;\n this.timers = deps.timers;\n if (deps.windowsPty) this.windowsPty = deps.windowsPty;\n this.leftovers = deps.leftovers !== undefined ? deps.leftovers : deps.spawner ? null : realLeftoverWork;\n }\n\n /** What runs under the entry's agent now (nothing known: none). */\n private async startedBy(e: Entry): Promise<ProcessRow[]> {\n if (!this.leftovers || e.pty.exited) return [];\n try {\n return await this.leftovers.under(e.pty.pty.pid);\n } catch (err) {\n logSwallowed(`list what ${e.id}'s agent started`, err);\n return [];\n }\n }\n\n /** Once its agent is gone: what it started and left running, stopped (said in the host's log). */\n private stopLeftBehind(id: string, found: readonly ProcessRow[]): Promise<void> {\n if (!this.leftovers || !found.length) return Promise.resolve();\n return this.leftovers.stop(found).then(\n (stopped) => {\n if (stopped.length)\n report(\n 'info',\n `${id}: stopped ${stopped.length} process(es) its agent had left running: ${stopped.map((p) => p.pid).join(', ')}`,\n );\n },\n (err) => logSwallowed(`stop what ${id}'s agent left running`, err),\n );\n }\n\n list(): PtyInfo[] {\n return [...this.entries.values()].map((e) => this.info(e));\n }\n\n get(id: string): PtyInfo | null {\n const e = this.entries.get(id);\n return e ? this.info(e) : null;\n }\n\n /** Spawn unless a live PTY already exists for `id` (idempotent). */\n spawn(id: string, spec: SpawnSpec & { keptEnv?: Record<string, string> }, restored = false): PtyInfo {\n const existing = this.entries.get(id);\n if (existing && (!existing.pty.exited || existing.restarting || existing.halted)) return this.info(existing);\n // A restore entry (or an older client) from before --unsafe was retired may carry `unsafe: true` and its tool an\n // `unsafeFlag`: neither is started with, nor written back — the entry this host records says it starts normally,\n // which is what lifts the one-release guards (sessions/legacy-unsafe.ts). REMOVE the strip with them next release.\n const { unsafeFlag: _retired, ...tool } = spec.tool as typeof spec.tool & { unsafeFlag?: unknown };\n // Started — and recorded for a restore — with work's hooks for this process (`--settings`, a restore entry from\n // before gets it too), never the user's settings' (agents/session-hooks.ts).\n spec = { ...spec, tool: this.sessionTool(tool) };\n\n // A spawn from a shell keeps the variables config `hostEnv` names; a\n // restore — or a respawn without a shell (the Terminal tab) — runs with\n // the host's environment plus what its session kept.\n // What is kept is the environment as the agent will see it: the session's account (`agentEnv`) applied first, so a\n // default session never keeps the launching shell's CLAUDE_CONFIG_DIR, and a named one always keeps its own.\n const agentEnv = hasEnvDelta(spec.agentEnv) ? spec.agentEnv : undefined;\n const kept = spec.env\n ? keepEnv(definedEnv(applyEnvDelta(spec.env, agentEnv)), this.keepEnvNames())\n : (spec.keptEnv ?? existing?.spec.keptEnv);\n const env = this.launchEnv({ env: spec.env, keptEnv: kept, agentEnv });\n if (env) spec = { ...spec, env };\n\n // The grid it starts at: the one stated (a tab's, `work attach`'s terminal's, a restore's own), else the last one a\n // client set, else the default. Started at one and resized a moment later, an agent paints twice.\n const stated = validGrid(spec.cols, spec.rows);\n const { cols, rows } = stated ?? this.lastGrid ?? DEFAULT_GRID;\n if (stated && !restored) this.lastGrid = stated;\n const pty = this.spawner({\n ...spec,\n cols,\n rows,\n // `--continue` hard-errors in a directory Claude never ran in;\n // `--fresh` opts out even when one exists.\n resume: !spec.fresh && this.hasConversation(spec.cwd, spec.tool.cmd, spec.env ?? process.env),\n });\n // The one that holds the PTY (may pause it) is the one that answers the agent: the client used last, else the first attached.\n const pacer = new OutputPacer<Client>({ flow: null, holder: () => this.pick(entry), timers: this.timers });\n const entry: Entry = {\n id,\n // Only what a restore may reuse: env/prompt/fresh are one-shot (and\n // env can hold secrets), so they never reach pty-sessions.json — but\n // the variables config `hostEnv` names do (keepEnv), so a restore after\n // a reboot gets the JAVA_HOME / PATH it was started with.\n spec: {\n cwd: spec.cwd,\n tool: spec.tool,\n port: spec.port,\n ...(kept ? { keptEnv: kept } : {}),\n ...(agentEnv ? { agentEnv } : {}),\n },\n env: spec.env as Record<string, string> | undefined,\n pty,\n cols,\n rows,\n startedAt: new Date().toISOString(),\n restored,\n replay: '',\n subscribers: new Set(),\n exitSubscribers: new Set(),\n leader: null,\n answerer: null,\n pacer,\n exitCode: null,\n lastOutputAt: Date.now(),\n stream: randomBytes(8).toString('hex'),\n gridAt: 0,\n };\n this.wire(entry, pty);\n this.entries.set(id, entry);\n void this.persist();\n return this.info(entry);\n }\n\n /**\n * 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\n * session's account change (`agentEnv`) over it — on the host's own environment when there is nothing else, so a\n * default session never inherits a CLAUDE_CONFIG_DIR the host was started with. Undefined: no change, the host's own env.\n */\n private launchEnv(spec: {\n env?: Record<string, string>;\n keptEnv?: Record<string, string>;\n agentEnv?: EnvDelta;\n }): Record<string, string> | undefined {\n const base = spec.env ?? (spec.keptEnv ? { ...(process.env as Record<string, string>), ...spec.keptEnv } : undefined);\n return hasEnvDelta(spec.agentEnv) ? definedEnv(applyEnvDelta(base ?? process.env, spec.agentEnv)) : base;\n }\n\n /** `pty` becomes the entry's process: its output to the entry's clients, its exit told to them (then forgotten). */\n private wire(entry: Entry, pty: PtyLike): void {\n const id = entry.id;\n entry.pty = pty;\n // Raw history is only a fallback for PTYs that can't serialize their\n // screen (test fakes) — real sessions replay PtySession.serialize().\n const keepRaw = !pty.serialize;\n entry.pacer.setFlow(flowOf(pty));\n // Asked as the output arrives (before its screen parses it): with no client attached, the screen's copy answers.\n pty.answerQueries?.(() => this.designate(entry) === null, this.colors);\n pty.setOutputHandler((data) => {\n this.designate(entry);\n entry.lastOutputAt = Date.now();\n if (keepRaw) {\n entry.replay += data;\n if (entry.replay.length > REPLAY_MAX) {\n entry.replay = entry.replay.slice(entry.replay.length - REPLAY_MAX);\n }\n }\n // To the clients now, or with what follows within a few ms (output-pacer.ts): who answers it is decided above, as it arrives.\n entry.pacer.output(data);\n });\n pty.onExit = (code) => {\n // Its last output before its end, and the final screen to a client that is behind (each told it ended after it).\n entry.pacer.end();\n entry.exitCode = code;\n for (const cb of entry.exitSubscribers) {\n try {\n cb(code);\n } catch {\n /* */\n }\n }\n setTimeout(() => {\n // Only forget it if nothing respawned under the same id meanwhile.\n if (this.entries.get(id) === entry) {\n this.entries.delete(id);\n void this.persist();\n }\n }, FORGET_EXITED_MS).unref?.();\n };\n }\n\n /**\n * Who answers the agent's queries in the output arriving now: exactly one, decided as it arrives (terminal-rendering.md,\n * \"Who answers a query\"). The client used last (it typed or resized: it has the PTY's size), else the first attached;\n * null when none is attached — then the PTY's screen copy answers. Kept until the next output, so the answers to it\n * that come back from that client go through.\n */\n private designate(e: Entry): Client | null {\n const who = this.pick(e);\n e.answerer = who;\n return who;\n }\n\n /**\n * `designate`'s choice, without making it: among the clients sent live output (one behind is sent none, so it would\n * never see the query: output-pacer.ts), the one used last, else the first attached. Also the one that holds the\n * PTY (may pause it until it has drawn what it was sent).\n */\n private pick(e: Entry): Client | null {\n if (e.leader && e.subscribers.has(e.leader) && e.pacer.live(e.leader)) return e.leader;\n for (const c of e.subscribers) if (e.pacer.live(c)) return c;\n return null;\n }\n\n /** The live PTY's visible screen as text; null when there is none (or\n * it can't render one — test fakes). */\n screen(id: string): string | null {\n const e = this.entries.get(id);\n if (!e || e.pty.exited || !e.pty.screenText) return null;\n return e.pty.screenText();\n }\n\n write(id: string, data: string): boolean {\n const e = this.entries.get(id);\n if (!e || e.pty.exited) return false;\n e.pty.write(data);\n return true;\n }\n\n /** Last writer wins — with several clients attached (browser + a real\n * terminal) the host calls this when one resizes AND when one is typed in\n * (its own grid again), so the client used last sets the grid, like\n * tmux's `window-size latest` (pty-host.ts). */\n resize(id: string, cols: number, rows: number): void {\n const e = this.entries.get(id);\n if (!e || e.pty.exited) return;\n const grid = validGrid(cols, rows);\n if (!grid || (cols === e.cols && rows === e.rows)) return;\n e.cols = cols;\n e.rows = rows;\n e.pty.resize(cols, rows);\n e.gridAt = e.pacer.offset;\n this.remember(grid);\n }\n\n /** `grid` is the last a client set: what a start with none takes, and — soon — the session's grid in the restore list. */\n private remember(grid: Grid): void {\n this.lastGrid = grid;\n if (this.gridPersist !== null) return;\n const timers = this.timers ?? realTimers;\n const handle = timers.set(() => {\n this.gridPersist = null;\n void this.persist();\n }, GRID_PERSIST_MS);\n (handle as { unref?: () => void } | null)?.unref?.();\n this.gridPersist = handle;\n }\n\n /**\n * Ask its agent to draw its screen again (⋯ → Reconnect terminal: the screen looks wrong). The PTY is made one row\n * smaller and, REDRAW_JIGGLE_MS later, put back to the grid it has then: two real size changes, so the agent sees one\n * whatever it runs on. A same-size SIGWINCH (zmx's way) repaints nothing in a Node or Bun agent (REDRAW_JIGGLE_MS); on\n * Windows ConPTY sends no resize for an unchanged size at all. The clients aren't resized: the agent's repaint at the\n * smaller grid is drawn over by the one at theirs. False when nothing runs.\n */\n redraw(id: string): boolean {\n const e = this.entries.get(id);\n if (!e || e.pty.exited || e.restarting || e.halted) return false;\n if (e.redrawing !== undefined) return true;\n e.pty.resize(e.cols, e.rows > MIN_ROWS ? e.rows - 1 : e.rows + 1);\n e.gridAt = e.pacer.offset;\n e.redrawing = (this.timers ?? realTimers).set(() => {\n e.redrawing = undefined;\n // Back to the grid it has now (a client may have set another meanwhile), unless it was killed or restarted.\n if (this.entries.get(id) === e && !e.pty.exited && !e.restarting && !e.halted) {\n e.pty.resize(e.cols, e.rows);\n e.gridAt = e.pacer.offset;\n }\n }, REDRAW_JIGGLE_MS);\n return true;\n }\n\n /**\n * Attach a client: the screen snapshot, a disposer, and — for a real\n * session — `ready`, the snapshot once the screen has parsed everything\n * that arrived before this attach, then `start()` once it was sent.\n *\n * Output reaches clients the moment it arrives, but the screen parses it a\n * moment later (xterm's write is queued). A client attaching in between got\n * a snapshot without that output and subscribed too late to be sent it: it\n * was lost (a Linux PTY answers fast enough to land there). So output\n * arriving from the attach on is held for this client until `start()`, and\n * `ready` is the screen exactly as of the attach — nothing lost, nothing\n * twice. `replay` (taken at once) is for screens with no parsing step.\n *\n * `lead()`: this client was used (typed in, resized), so it answers the agent's queries from the next output on.\n * `replies(parts)`: what of what this client sent on its own goes to the agent — its focus and mouse-motion reports\n * always, its answers only if it answers the queries in the output that arrived last (`designate`).\n *\n * Output reaches it in frames (output-pacer.ts). `opts.metered`: it acks what it draws (`ack(chars)`); if it falls\n * behind, it is sent nothing until it catches up, then what it missed from the tail when that is provably enough, else\n * the screen as it stands then (`opts.onReplay`; a screen taken and held as the attach's is: nothing lost, nothing\n * twice), and live output again. `offset`: the output offset its snapshot stands at (where its first frame starts).\n */\n attach(\n id: string,\n onData: (data: string, end?: number) => void,\n onExit: (code: number) => void,\n opts: AttachOptions = {},\n ): {\n replay: ReplaySnapshot;\n ready: Promise<ReplaySnapshot>;\n start: () => void;\n detach: () => void;\n lead: () => void;\n replies: (parts: ReplyPart[]) => string;\n ack: (chars: number) => void;\n offset: number;\n exitedWith: number | null;\n } | null {\n const e = this.entries.get(id);\n if (!e) return null;\n // Attaching to one that already exited (inside the linger window): its\n // exit subscribers have fired, so tell this client now — otherwise it\n // would sit on a dead screen, its input silently dropped.\n const exitedWith = e.pty.exited && !e.restarting && !e.halted ? (e.exitCode ?? 0) : null;\n // Mid-restart the process in the entry is the old one, already disposed (its screen with it): nothing of it to\n // send or wait on — the new one draws from scratch, straight to this client.\n const restarting = !!e.restarting || !!e.halted;\n const settled = restarting ? undefined : e.pty.serializeSettled;\n // Held output while the settled snapshot is taken; null = passed straight on.\n let held: Array<[string, number | undefined]> | null = settled ? [] : null;\n let started = !settled;\n let gone = false;\n const sub = (d: string, end?: number) => (held ? held.push([d, end]) : onData(d, end));\n // On Windows (the host says so), the ConPTY this PTY runs on: the bundled one reflows as a newer build than the OS's.\n const windowsPty = this.windowsPty ? (e.pty.windowsPty ?? this.windowsPty) : undefined;\n // A screen (or, resumed, what was missed) and where it stands in the output: where its live output starts.\n const snapshot = (data: string, offset = e.pacer.offset): ReplaySnapshot => ({\n data,\n cols: e.cols,\n rows: e.rows,\n stream: e.stream,\n offset,\n ...(windowsPty ? { windowsPty } : {}),\n });\n // A screen being taken (its first, a catch-up): output held meanwhile, and the PTY's end, told after the screen.\n let catchingUp = false;\n let endedWith: number | null = null;\n const exitSub = (code: number) => {\n if (catchingUp || !started) endedWith = code;\n else onExit(code);\n };\n // A catch-up's screen, sent. One that couldn't be taken (null) is not sent as an empty screen, which the client would\n // draw over the one it has, blank: it keeps its screen, said in the debug log. It missed what came meanwhile, so a\n // client that resumes (a tab) is told it no longer knows where it stands — no stream (it never resumes from here),\n // nothing to draw, drawn as missed output is (`resumed`: never over a reset terminal); `work attach`, which draws\n // every screen over a cleared one and never resumes, is sent nothing.\n const sendCatchUp = (data: string | null, at: number) => {\n if (data !== null) return opts.onReplay?.(snapshot(data, at));\n report('warn', `${id}: a terminal's catch-up screen couldn't be taken; it keeps the screen it has`);\n if (!opts.screenOnlyCatchUp) opts.onReplay?.({ ...snapshot('', at), stream: '', resumed: true });\n };\n // Whether the agent is between processes or its grid is moving: nothing is sent from the tail then.\n const busy = () => e.pty.exited || !!e.restarting || !!e.halted || e.redrawing !== undefined;\n // It fell behind and caught up (output-pacer.ts). Sent output up to `from`, in order on its socket, so its screen will\n // stand there: what it missed since, from the tail, when that is provably all it needs (`continueFrom`, the checks a\n // reconnect's resume makes but the grid: it draws it where it would have drawn it live) — a `replay` marked resumed,\n // drawn on the screen it has (its scrollback kept), not counted or acked, as a screen isn't. Else (`from` null: the\n // pacer wants a screen; `work attach`, which draws every screen over a cleared one; output held for it) the screen as\n // it stands now, the output from now on held until it is sent.\n const resync = (from: number | null): boolean => {\n // Before its first screen nothing could have been acked; after it left, nobody to send it to.\n if (gone || !started) return false;\n if (from !== null && !opts.screenOnlyCatchUp && held === null) {\n const r = continueFrom(from, { gridAt: e.gridAt, busy: busy() }, e.pacer.tail);\n if ('missed' in r) {\n opts.onReplay?.({ ...snapshot(r.missed), resumed: true });\n return true;\n }\n }\n const shot: SnapshotOptions | undefined = opts.screenOnlyCatchUp ? { scrollback: false } : undefined;\n // Mid-restart the old process's screen is gone with it: an empty screen, the new one draws from scratch.\n const between = !!e.restarting || !!e.halted;\n const settle = between ? undefined : e.pty.serializeSettled;\n // The pacer sent what was pending to the others first: the screen is everything up to here, the output held from here.\n const at = e.pacer.offset;\n if (!settle) {\n const data = between ? '' : e.pty.serialize?.(shot);\n sendCatchUp(data === null ? null : data || e.replay, at);\n return false;\n }\n const mine: Array<[string, number | undefined]> = [];\n held = mine;\n catchingUp = true;\n void settle\n .call(e.pty, shot)\n .catch((err: unknown) => {\n logSwallowed(`${id}: take a catch-up screen`, err);\n return null;\n })\n .then((data) => {\n if (gone || held !== mine) return;\n sendCatchUp(data === null ? null : data || e.replay, at);\n held = null;\n catchingUp = false;\n for (const [d, end] of mine) onData(d, end);\n if (endedWith !== null) onExit(endedWith);\n });\n return false;\n };\n // Its first screen: taken where it joins the output (`join`), as a promise of it.\n let resolveReady: (r: ReplaySnapshot) => void = () => {};\n const ready = new Promise<ReplaySnapshot>((resolve) => (resolveReady = resolve));\n let offset = e.pacer.offset;\n /**\n * It joins the output here, and its first screen is taken here: what came before is on that screen, what comes after\n * is sent to it (the pacer sends what was pending to the others first). Between synchronized frames (whenNoFrame):\n * mid-frame, at the frame's end (or its cap) — the PTY's output is cut there (PtySession), so the screen is exactly\n * what came before, never one drawn halfway (a screen has no 2026 in it to hold the client's drawing).\n */\n const join = (entryGone: boolean) => {\n if (gone || entryGone || this.entries.get(id) !== e) {\n resolveReady(snapshot(''));\n return;\n }\n e.pacer.add(sub, { metered: !!opts.metered, send: sub, resync });\n offset = e.pacer.offset;\n // Reconnecting with its screen kept: what it missed, from exactly where it stands, when that is provably enough\n // (output-tail.ts); not a screen, not counted or acked (as a screen isn't), and the output from here held as for a screen.\n if (opts.resume) {\n const r = resumeFrom(\n opts.resume,\n {\n stream: e.stream,\n grid: { cols: e.cols, rows: e.rows },\n gridBefore,\n gridAt: e.gridAt,\n busy: busy(),\n },\n e.pacer.tail,\n opts.grid,\n );\n if ('missed' in r) {\n resolveReady({ ...snapshot(r.missed, offset), resumed: true });\n return;\n }\n opts.onResumeRefused?.(r.refused);\n }\n if (settled)\n void settled\n .call(e.pty)\n .catch((err: unknown) => {\n logSwallowed(`${id}: take a screen for an attach`, err);\n return null;\n })\n .then((d) => resolveReady(snapshot(firstScreen(d), offset)));\n else resolveReady(snapshot(restarting ? '' : firstScreen(e.pty.serialize?.()), offset));\n };\n // Its first screen; one that couldn't be taken (null): it attaches all the same, on an empty screen the agent's next\n // repaint fills, and that is said. Never left waiting: a terminal that gets no first frame takes no input.\n const firstScreen = (d: string | null | undefined): string => {\n if (d === null) report('warn', `${id}: a terminal's screen couldn't be taken; it attached with an empty one`);\n return d || e.replay;\n };\n // The PTY's grid before this attach resizes it to the one it states: a resume needs its own grid to have been the PTY's.\n const gridBefore: Grid = { cols: e.cols, rows: e.rows };\n if (exitedWith === null) {\n e.subscribers.add(sub);\n e.exitSubscribers.add(exitSub);\n // It stated its grid: it takes the size now, as its first resize would have (it is the one used last), and the\n // snapshot below is taken at that grid: the screen copy reflowed now, the agent's repaint for it (SIGWINCH)\n // following as live output, held for it like any other until `start()`.\n const grid = opts.grid ? validGrid(opts.grid.cols, opts.grid.rows) : null;\n if (grid) {\n e.leader = sub;\n e.pacer.used(sub);\n if (!restarting) this.resize(id, grid.cols, grid.rows);\n else {\n // Nothing runs to resize: the agent being started again starts at it (resumeEntry).\n e.cols = grid.cols;\n e.rows = grid.rows;\n this.remember(grid);\n }\n }\n }\n const replay = snapshot(restarting ? '' : e.pty.serialize?.() || e.replay);\n if (exitedWith !== null) resolveReady(replay);\n // After the resize: the screen copy applies it in order with the output before it (ScreenMirror.resize), and the\n // screen is taken behind both.\n else e.pacer.whenNoFrame(join);\n return {\n exitedWith,\n replay,\n get offset() {\n return offset;\n },\n ready,\n start: () => {\n const q = held;\n held = null;\n started = true;\n for (const [d, end] of q ?? []) onData(d, end);\n // It ended while its first screen was being taken: told after that screen and the output before its end.\n if (endedWith !== null && !catchingUp) {\n const code = endedWith;\n endedWith = null;\n onExit(code);\n }\n },\n detach: () => {\n gone = true;\n e.subscribers.delete(sub);\n e.exitSubscribers.delete(exitSub);\n if (e.leader === sub) e.leader = null;\n // It left before answering, maybe: the next in line answers what it was sent (it was sent the same).\n if (e.answerer === sub) this.designate(e);\n // Holding the PTY paused, maybe: the next in line holds it, or nobody does and it reads on.\n e.pacer.remove(sub);\n },\n lead: () => {\n e.leader = sub;\n e.pacer.used(sub);\n },\n ack: (chars) => e.pacer.ack(sub, chars),\n replies: (parts) => {\n const answers = e.answerer === sub;\n let out = '';\n for (const part of parts) {\n if (!part.answer) out += part.text;\n else if (answers) {\n out += part.text;\n this.colors.remember(part.text);\n }\n }\n return out;\n },\n };\n }\n\n /**\n * Explicit kill (worktree removal, user closed the session). Removed\n * from the persisted list so it is NOT restored.\n *\n * Resolves once the process has actually exited (or after `timeoutMs`):\n * on Windows a just-killed process still holds its cwd for a moment, and\n * the caller's next step is usually deleting that very directory.\n */\n async kill(id: string, timeoutMs = 3000): Promise<void> {\n const e = this.entries.get(id);\n if (!e) return;\n // What its agent started, while they are still its: once it's gone they belong to launchd / init.\n const started = this.leftovers ? await this.startedBy(e) : [];\n if (this.entries.get(id) !== e) return; // killed meanwhile\n this.entries.delete(id);\n if (e.halted) clearTimeout(e.halted.timer);\n // The terminals attached to it are told it ended (and so offer Enter to start it again):\n // dropped silently, a dashboard tab kept a connection to nothing and took no input.\n const attached = [...e.exitSubscribers];\n e.subscribers.clear();\n e.exitSubscribers.clear();\n e.pacer.dispose();\n const exited = e.pty.exited\n ? Promise.resolve(e.exitCode ?? 0)\n : new Promise<number>((resolve) => {\n const timer = setTimeout(() => resolve(0), timeoutMs);\n e.pty.onExit = (code) => {\n clearTimeout(timer);\n resolve(code);\n };\n });\n e.pty.dispose();\n const [code] = await Promise.all([exited, this.persist()]);\n await this.stopLeftBehind(id, started);\n for (const cb of attached) {\n try {\n cb(code);\n } catch {\n /* that client is gone */\n }\n }\n }\n\n /**\n * Its agent stopped and started again in place, resuming its conversation (a\n * tool that updated runs its new version). The new process goes into the same\n * entry, so the terminals attached stay attached (and a detach still finds them),\n * see the new one draw, and one that attaches meanwhile joins it; the restore\n * list keeps it. Null when there's no live PTY of that id.\n *\n * Never two agents on one conversation: an old one that hasn't exited within\n * `timeoutMs` is left running and tracked, and the restart fails. A new one that\n * can't start (its tool gone mid-update) ends the session as a kill does, its\n * terminals told so.\n *\n * `agentEnv`: the agent's environment for the new process differs from the old one's by this (a session moved to\n * another account): it replaces the entry's own, in the restore list too — the process is started on what the\n * session is now, not on what it was.\n */\n restart(id: string, timeoutMs = 3000, agentEnv?: EnvDelta): Promise<PtyInfo | null> {\n const e = this.entries.get(id);\n if (!e) return Promise.resolve(null);\n // Asked twice (two windows, the CLI): both get the one restart's outcome, failure included.\n if (e.restarting) return e.restarting;\n if (e.halted) return Promise.reject(new Error('its agent is halted: resume it first'));\n if (e.pty.exited) return Promise.resolve(null);\n const running = this.haltEntry(e, timeoutMs)\n .then((ok) => (ok ? this.resumeEntry(e, agentEnv) : this.get(e.id)))\n .finally(() => {\n e.restarting = undefined;\n });\n e.restarting = running;\n return running;\n }\n\n /**\n * Its agent stopped, and kept stopped until `resume` (a switch of account moves its conversation files in between,\n * which a running — or just exiting — agent would write into again). The entry, its restore-list record and the\n * attached clients stay, and none is told it ended. Refused while it is being restarted or already halted; an agent that\n * doesn't stop within `timeoutMs` ends the session as `restart` does. A `resume` that never comes (work web died)\n * can't leave the session dead: after `resumeAfterMs` it is started again on its old spec. Null: nothing runs.\n */\n halt(id: string, timeoutMs = 3000, resumeAfterMs = HALT_RESUME_MS): Promise<PtyInfo | null> {\n const e = this.entries.get(id);\n if (!e) return Promise.resolve(null);\n if (e.restarting || e.halted) return Promise.reject(new Error('its agent is already being restarted or halted'));\n if (e.pty.exited) return Promise.resolve(null);\n const running = this.haltEntry(e, timeoutMs)\n .then((ok) => {\n if (!ok) return this.get(id); // killed meanwhile\n const timer = setTimeout(() => {\n report('warn', `${id}: halted, and no resume within ${Math.round(resumeAfterMs / 1000)} s: starting it again on its old spec`);\n this.resume(id).catch(swallow(`resume halted ${id}`));\n }, resumeAfterMs);\n timer.unref?.();\n e.halted = { timer };\n return this.info(e);\n })\n .finally(() => {\n e.restarting = undefined;\n });\n e.restarting = running;\n return running;\n }\n\n /**\n * Start a halted agent again in place, resuming its conversation, on `agentEnv` when given (as `restart` takes it): the\n * clients carry on. Null when it isn't halted.\n */\n resume(id: string, agentEnv?: EnvDelta): Promise<PtyInfo | null> {\n const e = this.entries.get(id);\n if (!e?.halted) return Promise.resolve(null);\n clearTimeout(e.halted.timer);\n e.halted = undefined;\n const running = this.resumeEntry(e, agentEnv).finally(() => {\n e.restarting = undefined;\n });\n e.restarting = running;\n return running;\n }\n\n /** 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. */\n private async haltEntry(e: Entry, timeoutMs: number): Promise<boolean> {\n const id = e.id;\n const old = e.pty;\n // Its last output to the clients, and no pause left on a process that is going.\n e.pacer.flush();\n e.pacer.setFlow(null);\n let exited!: () => void;\n const gone = new Promise<void>((resolve) => (exited = resolve));\n // Listening first: an agent that exits while what it started is listed is still seen to.\n old.onExit = () => exited();\n // A restart or an account switch ends what it started too: the new agent knows nothing of those commands.\n const started = this.leftovers ? await this.startedBy(e) : [];\n const stopped = old.exited\n ? true\n : await new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), timeoutMs);\n void gone.then(() => {\n clearTimeout(timer);\n resolve(true);\n });\n old.dispose();\n });\n if (stopped) await this.stopLeftBehind(id, started);\n if (this.entries.get(id) !== e) return false; // killed meanwhile\n if (!stopped) {\n // Its screen is gone with the dispose and the kill is on its way: not a session to keep showing (frozen\n // terminals, input into a dying process). Ended as a stop is, and no second agent is started on its\n // conversation while the old one may still be going.\n await this.endEntry(e);\n throw new Error(\n `its agent didn't stop within ${Math.round(timeoutMs / 1000)} s; its session was stopped (open it to start it again)`,\n );\n }\n return true;\n }\n\n /** Start the entry's agent again in place (its process is gone): `--continue`, on `agentEnv` when given. */\n private async resumeEntry(e: Entry, agentEnv?: EnvDelta): Promise<PtyInfo | null> {\n if (this.entries.get(e.id) !== e) return this.get(e.id); // killed meanwhile\n if (agentEnv) this.useAgentEnv(e, agentEnv);\n // Its hooks as this build gives them (an entry started by an older host had none of its own).\n e.spec = { ...e.spec, tool: this.sessionTool(e.spec.tool) };\n let pty: PtyLike;\n try {\n const env = e.env ?? this.launchEnv(e.spec);\n pty = this.spawner({\n ...e.spec,\n env,\n cols: e.cols,\n rows: e.rows,\n resume: this.hasConversation(e.spec.cwd, e.spec.tool.cmd, env ?? process.env),\n });\n } catch (err) {\n await this.endEntry(e); // nothing runs now\n throw err;\n }\n e.exitCode = null;\n e.replay = '';\n e.startedAt = new Date().toISOString();\n e.restored = false;\n e.lastOutputAt = Date.now();\n this.wire(e, pty);\n void this.persist();\n return this.info(e);\n }\n\n /** The entry's agent environment becomes `delta`: in its spec (the restore list), the variables it kept, and the environment it started with. */\n private useAgentEnv(e: Entry, delta: EnvDelta): void {\n const { agentEnv: _old, keptEnv, ...rest } = e.spec;\n const kept = keptEnv ? definedEnv(applyEnvDelta(keptEnv, delta)) : undefined;\n e.spec = {\n ...rest,\n ...(kept && Object.keys(kept).length ? { keptEnv: kept } : {}),\n ...(hasEnvDelta(delta) ? { agentEnv: delta } : {}),\n };\n if (e.env) e.env = definedEnv(applyEnvDelta(e.env, delta));\n }\n\n /** 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. */\n private async endEntry(e: Entry): Promise<void> {\n if (e.halted) clearTimeout(e.halted.timer);\n if (this.entries.get(e.id) === e) this.entries.delete(e.id);\n const attached = [...e.exitSubscribers];\n e.subscribers.clear();\n e.exitSubscribers.clear();\n e.pacer.dispose();\n await this.persist();\n for (const cb of attached) {\n try {\n cb(1);\n } catch {\n /* that client is gone */\n }\n }\n }\n\n /**\n * Respawn everything in the persisted list. Called once at host startup.\n * Worktrees that no longer exist are dropped, and so is the Ctrl+K\n * assistant: it starts when you open it (its conversation resumes then) —\n * restored, one opened once ran for good, a Claude nobody used. Nor is an\n * account's login terminal (account-login.ts): it is the Accounts page's,\n * for as long as its panel is open.\n */\n async restore(): Promise<string[]> {\n const saved = this.readPersisted();\n const restored: string[] = [];\n for (const [id, entry] of Object.entries(saved)) {\n if (id === ASSISTANT_ID || isAccountLoginId(id) || !this.cwdExists(entry.cwd)) continue;\n try {\n this.spawn(id, entry, true);\n restored.push(id);\n } catch (err) {\n // One bad entry (tool missing, cwd unreadable) mustn't block the rest.\n logSwallowed(`restore session ${id} in ${entry.cwd}`, err);\n }\n }\n // No client has set a grid yet: a start with none takes the one most of the restored sessions had.\n this.lastGrid ??= mostCommonGrid(restored.map((id) => validGrid(saved[id].cols, saved[id].rows)));\n await this.persist();\n return restored;\n }\n\n /** Host shutdown: kill every PTY but KEEP the persisted list, so the next\n * host start restores them. */\n disposeAllKeepingState(): void {\n // A grid write still to come would write the list with nothing in it.\n if (this.gridPersist !== null) (this.timers ?? realTimers).clear(this.gridPersist);\n this.gridPersist = null;\n for (const e of this.entries.values()) {\n e.pty.onExit = undefined;\n e.subscribers.clear();\n e.exitSubscribers.clear();\n e.pacer.dispose();\n e.pty.dispose();\n }\n this.entries.clear();\n }\n\n /** Resolves once every queued persistence write has landed. */\n flush(): Promise<void> {\n return this.writeChain;\n }\n\n private info(e: Entry): PtyInfo {\n const signal = e.pty.exited ? null : (e.pty.streamSignal?.() ?? null);\n return {\n id: e.id,\n cwd: e.spec.cwd,\n pid: e.pty.pty.pid,\n exited: e.pty.exited,\n cols: e.cols,\n rows: e.rows,\n startedAt: e.startedAt,\n restored: e.restored,\n clients: e.subscribers.size,\n lastOutputAt: new Date(e.lastOutputAt).toISOString(),\n tool: e.spec.tool.cmd,\n ...(signal ? { signal } : {}),\n };\n }\n\n private readPersisted(): PersistedPtys {\n try {\n return this.store.read();\n } catch (err) {\n logSwallowed('read the PTY restore list', err);\n return {};\n }\n }\n\n private persist(): Promise<void> {\n const snapshot: PersistedPtys = {};\n // Exited entries still lingering (see FORGET_EXITED_MS) are kept on\n // purpose — dropping them on an unrelated write would defeat the delay.\n for (const e of this.entries.values()) {\n // Its grid too: a restore after a reboot starts it at the size it was used at last.\n snapshot[e.id] = { ...e.spec, cols: e.cols, rows: e.rows, startedAt: e.startedAt };\n }\n this.writeChain = this.writeChain\n .then(() => this.store.write(snapshot))\n .catch(swallow('persist the PTY restore list (next change retries)'));\n return this.writeChain;\n }\n}\n","import pty, { type IPty } from 'node-pty';\nimport { agentById } from '../agents/index.js';\nimport crossSpawn from 'cross-spawn';\nimport { debug } from '../platform/logger.js';\nimport { buildAiLaunchArgs, type AiToolSpec } from '../platform/ai-launcher.js';\nimport { batchArgProblem, programFor } from '../platform/batch-launch.js';\nimport { shellEnv } from '../platform/shell-env.js';\nimport childProcess from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { makeSpawnHelperExecutable } from './spawn-helper.js';\nimport { report } from '../platform/report.js';\nimport { loadConfig } from '../platform/config.js';\nimport { ScreenMirror, type HeadlessTerminal, type SnapshotOptions } from './screen-mirror.js';\nimport type { StreamSignal } from './stream-status.js';\nimport { windowsPtyFor, type WindowsPty } from './terminal-size.js';\nimport { SyncScanner, cutAtFrameEnds } from './sync-output.js';\nimport type { TerminalColors } from './terminal-colors.js';\n\ntype Fork = typeof childProcess.fork;\nconst HIDDEN = Symbol.for('work.forkHidesConsole');\n\n/**\n * Make `fork()` hide the child's console window unless the caller says\n * otherwise. node-pty kills a Windows PTY by forking a helper\n * (conpty_console_list_agent) without `windowsHide`; from the PTY host —\n * detached, so it has no console of its own — Windows gave every such helper\n * a new, visible console: a window flashed on each Archive or stop.\n */\nexport function hideForkConsoles(cp: { fork: Fork }): void {\n if ((cp.fork as { [HIDDEN]?: true })[HIDDEN]) return;\n // windowsHide isn't in @types/node's ForkOptions, but fork passes its\n // options on to spawn, which honours it.\n const orig = cp.fork as unknown as (modulePath: string | URL, args: readonly string[], options: object) => ReturnType<Fork>;\n const wrapped = function (modulePath: string | URL, a?: unknown, b?: unknown) {\n const args = Array.isArray(a) ? (a as readonly string[]) : [];\n const options = (Array.isArray(a) || a == null ? b : a) ?? {};\n return orig.call(cp, modulePath, args, { windowsHide: true, ...(options as object) });\n } as unknown as Fork & { [HIDDEN]?: true };\n wrapped[HIDDEN] = true;\n cp.fork = wrapped;\n}\nif (process.platform === 'win32') hideForkConsoles(childProcess);\n\nlet spawnHelperChecked = false;\n/**\n * Once per process, before the first terminal: node-pty's spawn-helper must\n * be executable on macOS and Linux, or every terminal fails with\n * \"posix_spawnp failed\" (spawn-helper.ts). Fixes an install that has it\n * wrong; says so when it can't.\n */\nfunction ensureSpawnHelper(): void {\n if (spawnHelperChecked) return;\n spawnHelperChecked = true;\n try {\n const dir = path.dirname(createRequire(import.meta.url).resolve('node-pty/package.json'));\n const { fixed, failed } = makeSpawnHelperExecutable(dir);\n for (const file of fixed) debug('made node-pty spawn-helper executable', file);\n for (const { file, error } of failed)\n report(\n 'warn',\n `node-pty's spawn-helper isn't executable and couldn't be made so (${error}): terminals can't start. Run: chmod +x \"${file}\"`,\n );\n } catch (err) {\n debug('spawn-helper check failed', (err as Error).message);\n }\n}\n\nexport interface PtyAiOptions {\n /** Resolved AI tool spec (from `getAiTool(config)`). */\n tool: AiToolSpec;\n resume?: boolean;\n promptFile?: string;\n /** Initial prompt: on the command line as an argument of its own; for a batch-file agent on Windows that cmd.exe\n * would parse (its `&`, `%`, quotes, line breaks), typed in once the agent is up instead (resolvePtyCommand). */\n initialPrompt?: string;\n /** Dev-server port exposed to the launched process as $PORT. */\n port?: number;\n /** Environment for the process instead of this process's own — the PTY\n * host passes the launching shell's env so PATH, AWS_PROFILE, venvs,\n * WT_SESSION etc. match where the user ran `work tree`. */\n env?: Record<string, string>;\n}\n\ntype CrossSpawnParse = (\n command: string,\n args: string[],\n options: { env?: NodeJS.ProcessEnv; cwd?: string },\n) => { command: string; args: string[]; file?: string; options: { windowsVerbatimArguments?: boolean } };\n\n/** Whether `cmd` starts as a batch file on Windows — cmd.exe would parse its arguments (a Node or Python shim doesn't: it's skipped). */\nexport function startsAsBatch(\n cmd: string,\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n cwd?: string,\n): boolean {\n return platform === 'win32' && programFor(cmd, { env, cwd })?.batch === true;\n}\n\n/**\n * Turn `cmd args` into what node-pty should spawn, safely.\n *\n * Windows: the program is the absolute file PATH gives it, never one in the working folder (`programFor`,\n * batch-launch.ts: a worktree's own `claude.cmd` doesn't run); a missing one throws. A path is the file Windows\n * would start for it (`C:\\npm\\claude` is `claude.cmd` beside it: that is what's started, and judged). A real .exe is spawned\n * directly with normal argv quoting. A batch file that starts a Node script — npm's `claude.cmd` — or a Python\n * module is skipped: its interpreter is spawned on the script, the arguments as argv, no cmd.exe. Any other batch\n * file goes through `cmd.exe /d /s /c \"…\"` (cross-spawn's escaping, a verbatim command line), and only with\n * arguments free of cmd's special characters: cmd.exe parses them twice, so `\"&echo X&\"` would run and a line break\n * cut the rest; such arguments throw (the caller types a prompt in after the start instead). Never a bare\n * `cmd.exe /c cmd args` (§1.1). Elsewhere: as given.\n */\nexport function resolvePtyCommand(\n cmd: string,\n args: string[],\n opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {},\n): { file: string; args: string[] | string; env?: NodeJS.ProcessEnv } {\n if (process.platform !== 'win32') return { file: cmd, args };\n const program = programFor(cmd, { env: opts.env ?? process.env, cwd: opts.cwd });\n if (!program) throw new Error(`${cmd} not found on PATH`);\n if (!program.batch) return { file: program.file, args: [...program.pre, ...args] };\n const why = batchArgProblem(args);\n if (why) throw new Error(`${cmd}: ${why}`);\n const parse = (crossSpawn as unknown as { _parse: CrossSpawnParse })._parse;\n const parsed = parse(program.file, args, opts);\n // cmd.exe runs the batch file in the worktree: a bare name inside it must not find a file of the branch (shellEnv).\n const env = shellEnv(opts.env ?? process.env);\n if (parsed.options.windowsVerbatimArguments) {\n return { file: parsed.command, args: parsed.args.join(' '), env };\n }\n return { file: parsed.file ?? parsed.command, args: parsed.args, env };\n}\n\n/**\n * The environment as the terminal the agent draws into says it: xterm.js (the Terminal tab, and the PTY host's own copy\n * of the screen) shows 24-bit colour, so `COLORTERM=truecolor` unless the environment says something itself. Without\n * it Claude Code, under `TERM=xterm-256color`, draws its truecolor theme in 256 colours (and suggests setting it).\n * The launching terminal's identity (TERM_PROGRAM, WT_SESSION …) is kept: terminal-rendering.md, \"Terminal identity\".\n */\nexport function terminalEnv(env: Record<string, string>): Record<string, string> {\n return env.COLORTERM ? env : { ...env, COLORTERM: 'truecolor' };\n}\n\n/** How long a terminal must have been quiet after its first output before a prompt is typed into it. */\nexport const PROMPT_SETTLE_MS = 800;\n/** The longest a prompt waits for that quiet before it is typed anyway. */\nexport const PROMPT_WAIT_MS = 20_000;\n\n/** What `typeWhenSettled` watches: a terminal's output and its end (node-pty's `IPty`, or a stand-in in tests). */\nexport interface SettleTarget {\n onData(listener: (data: string) => void): { dispose(): void };\n onExit(listener: () => void): unknown;\n}\n\n/**\n * Type `text` into the agent's prompt once it is up: after its first output and `settleMs` of quiet (at most\n * `waitMs` in all), through `submit` (the agent's own, agents/: the whole text, line breaks and all, then Enter).\n * Once only; never after the terminal ended. For a prompt that can't go on its command line (a batch-file agent).\n */\nexport function typeWhenSettled(\n target: SettleTarget,\n text: string,\n opts: { exited: () => boolean; submit: (text: string) => Promise<unknown>; settleMs?: number; waitMs?: number },\n): void {\n let quiet: ReturnType<typeof setTimeout> | undefined;\n let typed = false;\n const stop = () => {\n typed = true;\n clearTimeout(quiet);\n clearTimeout(cap);\n sub.dispose();\n };\n const type = () => {\n if (typed) return;\n stop();\n if (opts.exited()) return;\n opts.submit(text).catch((err: unknown) => debug('PtySession: typing the first prompt failed', (err as Error).message));\n };\n const cap = setTimeout(type, opts.waitMs ?? PROMPT_WAIT_MS);\n cap.unref?.();\n const sub = target.onData(() => {\n if (typed) return;\n clearTimeout(quiet);\n quiet = setTimeout(type, opts.settleMs ?? PROMPT_SETTLE_MS);\n });\n target.onExit(() => {\n if (!typed) stop();\n });\n}\n\n/** Config `useBundledConpty`, read at each start (off when config can't be read). */\nfunction readUseBundledConpty(): boolean {\n try {\n return loadConfig()?.useBundledConpty === true;\n } catch {\n return false;\n }\n}\n\n/** node-pty's ConPTY choice: on Windows, the bundled one when asked for; nothing elsewhere (it's Windows-only). Pure. */\nexport function conptyOptions(platform: NodeJS.Platform, useBundled: boolean): { useConptyDll?: boolean } {\n return platform === 'win32' && useBundled ? { useConptyDll: true } : {};\n}\n\n/**\n * The ConPTY a PTY starts on (`options`, node-pty's) and the `windowsPty` its screens say (terminal-size.ts), decided\n * together so they can't disagree: the bundled one behaves as a newer Windows than `release` says. Pure.\n */\nexport function conptyFor(\n platform: NodeJS.Platform,\n release: string,\n useBundled: boolean,\n): { options: { useConptyDll?: boolean }; windowsPty?: WindowsPty } {\n const options = conptyOptions(platform, useBundled);\n const windowsPty = windowsPtyFor(platform, release, options.useConptyDll === true);\n return windowsPty ? { options, windowsPty } : { options };\n}\n\n/** Config `agentsLowPriority`, read at each start (off when config can't be read). */\nfunction readAgentsLowPriority(): boolean {\n try {\n return loadConfig()?.agentsLowPriority === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Put a just-started agent below normal priority (config `agentsLowPriority`; reported: two sessions' test runs and a\n * compile filled a 15-watt CPU, and the window you type in froze). What it starts inherits it — Windows hands a\n * below-normal parent's class to its children, POSIX the nice value — so its builds and tests take the idle cores and\n * give way to what you look at. Null when done, else why not (the agent runs on at normal priority).\n */\nexport function lowerPriority(pid: number, set: (pid: number, priority: number) => void = os.setPriority): string | null {\n try {\n set(pid, os.constants.priority.PRIORITY_BELOW_NORMAL);\n return null;\n } catch (err) {\n return (err as Error).message;\n }\n}\n\n/**\n * What a terminal start that took `ms` is worth saying (node-pty's start is synchronous, so the host answered nothing\n * meanwhile): a note in the debug line from 1 s, a warning from 5 s. Pure.\n */\nexport function slowStart(ms: number): { note: string; warn: string | null } {\n return {\n note: ms > 1000 ? `(the start took ${ms} ms)` : '',\n warn: ms > 5000 ? `[pty] starting a terminal took ${Math.round(ms / 1000)} s: the PTY host answered nothing meanwhile` : null,\n };\n}\n\n/**\n * Whether a PTY's output may be paused for a client to catch up (output-pacer.ts). Not on Windows: node-pty reads\n * ConPTY's output through a worker thread so that ClosePseudoConsole, which before Windows 11 24H2 waits for that\n * output to be drained, can't block the host; paused, nothing drains it, and killing the agent could hang the whole\n * host. There a client too far behind is sent a fresh screen instead (as any other is). Pure.\n */\nexport function canPauseOutput(platform: NodeJS.Platform): boolean {\n return platform !== 'win32';\n}\n\n/**\n * Calls `exiting` the moment node-pty learns its child exited, before it waits for its socket to close. node-pty 1.1.0\n * (lib/unixTerminal.js, `onexit`) arms `setTimeout(() => socket.destroy(), DESTROY_SOCKET_TIMEOUT_MS = 200)` and then\n * registers `this.once('close', …)`. What was not read from the PTY by the time that timer fires is lost: a paused PTY\n * (flow control) must read again before then. That `once('close')` is the only one it makes on itself (its other\n * waits are on its socket), so it marks the exit. A test pins that against node-pty's source, so an upgrade that\n * changes it fails there. False when there is nothing to hook (no `once`).\n */\nexport function onChildExit(pty: object, exiting: () => void): boolean {\n const target = pty as { once?: (event: string, listener: (...args: unknown[]) => void) => unknown };\n const once = target.once;\n if (typeof once !== 'function') return false;\n target.once = function (this: unknown, event, listener) {\n if (event === 'close') exiting();\n return once.call(this, event, listener);\n };\n return true;\n}\n\nexport class PtySession {\n readonly pty: IPty;\n /**\n * Stop reading the agent's output, and start again (flow control, output-pacer.ts): paused, its writes block once\n * the PTY's buffer is full. Undefined where that isn't safe (`canPauseOutput`).\n */\n readonly pause?: () => void;\n readonly resume?: () => void;\n private paused = false;\n /** The PTY host's copy of the screen (screen-mirror.ts): what a client attaching is sent first. */\n private readonly mirror: ScreenMirror;\n /** The ConPTY it runs on, as xterm.js's `windowsPty` (its screens say it, pty-registry.ts); undefined off Windows. */\n readonly windowsPty?: WindowsPty;\n /** Where its output is in synchronized frames (sync-output.ts): it is cut at each frame's end. */\n private readonly frames = new SyncScanner();\n readonly cwd: string;\n private outputHandler?: (data: string) => void;\n private _exited = false;\n private _outputBuffer = '';\n private _loggedOutput = false;\n onExit?: (code: number) => void;\n\n constructor(cwd: string, cols: number, rows: number, command?: { cmd: string; args: string[] }, aiOptions?: PtyAiOptions) {\n this.cwd = cwd;\n // Which ConPTY, read once: node-pty starts on it, and the screens say how it reflows (config useBundledConpty).\n const conpty = conptyFor(process.platform, os.release(), readUseBundledConpty());\n if (conpty.windowsPty) this.windowsPty = conpty.windowsPty;\n // ConPTY reflows lines itself on a resize: the copy is told so, as the Terminal tab is (the replay frame).\n this.mirror = new ScreenMirror(cols, rows, undefined, { windowsPty: conpty.windowsPty });\n\n let rawCmd: string;\n let rawArgs: string[];\n let typeLater: string | undefined;\n\n if (command) {\n // Custom command (e.g. work tree)\n rawCmd = command.cmd;\n rawArgs = command.args;\n } else if (aiOptions) {\n // Launch configured AI tool (default: claude)\n const launchOpts = { resume: aiOptions.resume, promptFile: aiOptions.promptFile };\n ({ cmd: rawCmd, args: rawArgs } = buildAiLaunchArgs(aiOptions.tool, { ...launchOpts, initialPrompt: aiOptions.initialPrompt }));\n // A batch-file agent (not a Node or Python shim) on Windows: cmd.exe would parse the prompt — its `&` runs,\n // a line break cuts it. Never on its command line: typed in once it's up, as any note to a session is.\n if (\n aiOptions.initialPrompt &&\n batchArgProblem([aiOptions.initialPrompt]) &&\n startsAsBatch(aiOptions.tool.cmd, aiOptions.env, process.platform, cwd)\n ) {\n ({ cmd: rawCmd, args: rawArgs } = buildAiLaunchArgs(aiOptions.tool, launchOpts));\n typeLater = aiOptions.initialPrompt;\n }\n } else {\n throw new Error('PtySession requires either a custom command or aiOptions');\n }\n\n // A session of its own: never another agent's child (its adapter knows what a parent sets).\n const env: Record<string, string> = terminalEnv(\n Object.fromEntries(\n Object.entries(agentById(aiOptions?.tool.cmd ?? 'claude').launch.cleanEnv(aiOptions?.env ?? process.env)).filter(\n (e): e is [string, string] => e[1] != null,\n ),\n ),\n );\n if (aiOptions?.port !== undefined) {\n env.PORT = String(aiOptions.port);\n }\n const { file: spawnCmd, args: spawnArgs, env: batchEnv } = resolvePtyCommand(rawCmd, rawArgs, { env, cwd });\n\n debug('PtySession spawn', { spawnCmd, spawnArgs, cwd, cols, rows });\n ensureSpawnHelper();\n const started = Date.now();\n this.pty = pty.spawn(spawnCmd, spawnArgs, {\n name: 'xterm-256color',\n cwd,\n cols,\n rows,\n env: (batchEnv as Record<string, string> | undefined) ?? env,\n ...conpty.options,\n });\n // node-pty's start is synchronous (Windows: creating the pseudo-console): a slow one holds up the whole host.\n const slow = slowStart(Date.now() - started);\n debug('PtySession spawned pid=', this.pty.pid, slow.note);\n if (slow.warn) report('warn', slow.warn);\n // An agent only: a login terminal or another custom command is yours to type in.\n if (aiOptions && readAgentsLowPriority()) {\n const why = lowerPriority(this.pty.pid);\n debug(why ? `PtySession: couldn't lower the agent's priority (${why})` : 'PtySession: agent started below normal priority');\n }\n\n if (canPauseOutput(process.platform)) {\n // Its child exited: what it wrote last is read now (node-pty drops it 200 ms later), and nothing pauses it again.\n // On Linux the child exits with its output unread; on macOS its exit waits for that output to be read.\n let ending = false;\n onChildExit(this.pty, () => {\n ending = true;\n this.resume?.();\n });\n this.pause = () => {\n if (this._exited || ending || this.paused) return;\n this.paused = true;\n try {\n this.pty.pause();\n } catch {\n /* PTY already exited */\n }\n };\n this.resume = () => {\n if (!this.paused) return;\n this.paused = false;\n try {\n this.pty.resume();\n } catch {\n /* PTY already exited */\n }\n };\n }\n\n this.pty.onData((data) => {\n // Cut at each synchronized frame's end, the screen copy written and the output passed on piece by piece: a client\n // joining (or caught up) at a frame's end is sent a screen of exactly what came before it (pty-registry.ts).\n for (const piece of cutAtFrameEnds(this.frames, data)) {\n this.mirror.write(piece);\n this.outputHandler?.(piece);\n }\n // Log first 500 chars of PTY output for debugging early exits\n if (!this._loggedOutput) {\n this._outputBuffer = (this._outputBuffer || '') + data;\n if (this._outputBuffer.length > 500) {\n debug('PtySession first output', { cwd, output: this._outputBuffer.slice(0, 500) });\n this._loggedOutput = true;\n this._outputBuffer = '';\n }\n }\n });\n\n if (typeLater !== undefined) {\n const agent = agentById(aiOptions?.tool.cmd ?? 'claude');\n typeWhenSettled(this.pty, typeLater, {\n exited: () => this._exited,\n submit: (text) =>\n agent.input.submit((d) => {\n this.write(d);\n return Promise.resolve(!this._exited);\n }, text),\n });\n }\n\n this.pty.onExit(({ exitCode }) => {\n if (!this._loggedOutput && this._outputBuffer) {\n debug('PtySession output before exit', { cwd, output: this._outputBuffer.slice(0, 500) });\n }\n this._outputBuffer = '';\n debug('PtySession exited', { cwd, exitCode });\n this._exited = true;\n this.onExit?.(exitCode);\n });\n }\n\n get exited() {\n return this._exited;\n }\n\n write(data: string) {\n if (!this._exited) {\n try {\n this.pty.write(data);\n } catch {\n /* PTY already exited */\n }\n }\n }\n\n resize(cols: number, rows: number) {\n if (!this._exited) {\n try {\n this.pty.resize(cols, rows);\n } catch {\n // PTY already exited natively before our flag was set — ignore\n }\n this.mirror.resize(cols, rows);\n }\n }\n\n /**\n * The agent's queries in output that arrives while `now()` says so (no client attached: pty-registry.ts) are answered\n * by the screen's copy, colour queries from `colors` (ScreenMirror.answerQueries).\n */\n answerQueries(now: () => boolean, colors: Pick<TerminalColors, 'reply'>): void {\n this.mirror.answerQueries({ now, colors, send: (reply) => this.write(reply) });\n }\n\n /** The headless terminal the screen is kept in. */\n get terminal(): HeadlessTerminal {\n return this.mirror.terminal;\n }\n\n /**\n * The current screen + scrollback as escape sequences that redraw it\n * exactly (colors, cursor, modes, alt screen — ScreenMirror.snapshot). What a late attacher is\n * sent instead of raw output history — raw bytes can start mid-sequence\n * and were drawn for another client's grid (VS Code does the same).\n */\n serialize(opts?: SnapshotOptions): string | null {\n return this.mirror.snapshot(opts);\n }\n\n /**\n * serialize(), once the screen has parsed everything written to it so far:\n * xterm queues writes, and a write's callback runs right after that write\n * is parsed — before any written later. What a new client is sent first.\n */\n serializeSettled(opts?: SnapshotOptions): Promise<string | null> {\n return this.mirror.snapshotSettled(opts);\n }\n\n /** The visible screen as plain text, one line per row (no colors).\n * What the dashboard checks before answering a prompt by keystroke. */\n screenText(): string {\n return this.mirror.screenText();\n }\n\n /** What the agent last said about itself in its output: OSC 7501 program status, else OSC 9;4 progress (stream-status.ts). */\n streamSignal(): StreamSignal | null {\n return this.mirror.streamSignal();\n }\n\n setOutputHandler(handler?: (data: string) => void) {\n this.outputHandler = handler;\n }\n\n dispose() {\n this.setOutputHandler(undefined);\n // Reading again first: a paused PTY's end waits for its output to be read (node-pty emits exit once it is).\n this.resume?.();\n if (!this._exited) {\n try {\n this.pty.kill();\n } catch {\n /* PTY already exited */\n }\n }\n this.mirror.dispose();\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** The file system calls this needs (tests pass a fake one). */\nexport interface ModeFs {\n statSync(p: string): { mode: number };\n chmodSync(p: string, mode: number): void;\n}\n\nexport interface SpawnHelperCheck {\n /** Made executable. */\n fixed: string[];\n /** Not executable, and chmod failed (a root-owned global install): terminals can't start. */\n failed: Array<{ file: string; error: string }>;\n}\n\n/**\n * node-pty starts every terminal on macOS and Linux through its\n * `spawn-helper`. Its npm package ships the prebuilt one without the\n * executable bit, and its install script — which would fix that — doesn't\n * always run (npm skipping dependency install scripts; the desktop app's\n * 2.0.2 shipped it 0644): every terminal then fails with \"posix_spawnp\n * failed\". Make it executable where it lies: the prebuild for this\n * platform, and a locally built one. Nothing on Windows.\n */\nexport function makeSpawnHelperExecutable(\n ptyDir: string,\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n f: ModeFs = fs,\n): SpawnHelperCheck {\n const out: SpawnHelperCheck = { fixed: [], failed: [] };\n if (platform === 'win32') return out;\n for (const file of [\n path.join(ptyDir, 'prebuilds', `${platform}-${arch}`, 'spawn-helper'),\n path.join(ptyDir, 'build', 'Release', 'spawn-helper'),\n ]) {\n let mode: number;\n try {\n mode = f.statSync(file).mode;\n } catch {\n continue; // not there: the other one is used\n }\n if ((mode & 0o111) === 0o111) continue;\n try {\n f.chmodSync(file, (mode & 0o777) | 0o755);\n out.fixed.push(file);\n } catch (err) {\n out.failed.push({ file, error: (err as Error).message });\n }\n }\n return out;\n}\n","import xtermHeadless from '@xterm/headless';\nimport xtermSerialize from '@xterm/addon-serialize';\nimport xtermUnicode11 from '@xterm/addon-unicode11';\nimport { REPLAY_SCROLLBACK } from './scrollback.js';\nimport type { TerminalColors } from './terminal-colors.js';\nimport type { WindowsPty } from './terminal-size.js';\nimport { StreamStatus, type StreamSignal } from './stream-status.js';\nimport { logSwallowed } from '../platform/best-effort.js';\n\nconst { Terminal } = xtermHeadless;\nconst { SerializeAddon } = xtermSerialize;\nconst { Unicode11Addon } = xtermUnicode11;\n\nexport type HeadlessTerminal = InstanceType<typeof Terminal>;\ntype Screen = 'normal' | 'alternate';\n/** A CSI sequence's parameters as xterm passes them: a number, or the sub-parameters of the one before it. */\ntype Params = (number | number[])[];\n\nconst ESC = '\\x1b';\nconst CSI = '\\x1b[';\n/** What the serialize addon writes before the alternate screen's content (0.14.0 and master alike). */\nconst ENTER_ALT = '\\x1b[?1049h\\x1b[H';\n/**\n * Before the screen: the state the addon's output assumes — the normal screen (ESC 7 first, so the cursor 1049l\n * restores is where it is), cleared, with DECSTR's defaults (character sets, scroll region, origin mode, pen). A\n * fresh terminal is there already; a terminal that was written a snapshot before (or `work attach`'s real one,\n * left in the line-drawing set by something) would draw this one through what the last one left.\n */\nconst START = '\\x1b7\\x1b[?1049l\\x1b[H\\x1b[2J\\x1b[!p\\x1b[0m';\nconst MOUSE_PROTOCOL = { x10: 9, vt200: 1000, drag: 1002, any: 1003 } as const;\nconst MOUSE_ENCODINGS = new Set([1005, 1006, 1015, 1016]);\nconst ALT_SCREEN = new Set([47, 1047, 1049]);\n/** G0..G3, by the intermediate that designates each. */\nconst CHARSET_SLOTS = ['(', ')', '*', '+'] as const;\n/** The character sets xterm.js knows (an unknown one is plain ASCII to it, and kept as written for a native terminal). */\nconst CHARSET_FINALS = '0AB4C5RQKYE6ZH7=';\n/** kitty keeps 8 entries per screen; a push past that drops the oldest. */\nconst KEYBOARD_STACK_MAX = 8;\n/** C0, DEL and C1: never let a remembered title end or start a sequence when it is written back. */\nconst CONTROL = /[\\x00-\\x1f\\x7f-\\x9f]/g;\n\n/** Which snapshot: with the scrollback (the default), or the screen only (`scrollback: false`). */\nexport interface SnapshotOptions {\n /**\n * False: the screen only, no lines above it — a catch-up screen for a native terminal (`work attach`), whose own\n * scrollback holds your shell's history and, already, the agent's. The state after it is the same either way.\n */\n scrollback?: boolean;\n}\n\n/** What the mirror keeps per screen: xterm.js keeps these per buffer, kitty keeps its key flags per screen. */\nexport interface ScreenState {\n /** DECSC (ESC 7, CSI s, 1048): the column, and the line counted from the top of the scrollback. */\n savedCursor: { x: number; line: number } | null;\n /** DECSTBM, 0-based and inclusive; null = the whole screen. */\n scrollRegion: { top: number; bottom: number } | null;\n /** kitty keyboard protocol flags, bottom of the stack first. */\n keyboardFlags: number[];\n}\n\n/** The state an attaching terminal needs that the serialize addon doesn't write (terminal-rendering.md). */\nexport interface MirrorState {\n /** DECTCEM (25) reset. */\n cursorHidden: boolean;\n /** DECSET 12 as the app last set it; null = never. */\n cursorBlink: boolean | null;\n /** DECSCUSR 1..6; null = the terminal's default (never set, or 0). */\n cursorStyle: number | null;\n /** OSC 0 / 2; null = never set. */\n title: string | null;\n /** DECSET / DECRST of 1005, 1006, 1015, 1016 in the order the app wrote them (one entry per mode, its last). */\n mouseEncoding: { mode: number; on: boolean }[];\n /** 1007; null = never set (terminals differ on the default). */\n alternateScroll: boolean | null;\n /** 2031 (colour-scheme change reports); null = never set. */\n colorSchemeUpdates: boolean | null;\n /** XTMODKEYS modifyOtherKeys (CSI > 4 ; n m); null = the default. */\n modifyOtherKeys: number | null;\n /** G0..G3 designations (final characters; B = ASCII). */\n charsets: string[];\n normal: ScreenState;\n alternate: ScreenState;\n}\n\nconst freshScreen = (): ScreenState => ({ savedCursor: null, scrollRegion: null, keyboardFlags: [] });\nconst freshState = (title: string | null = null): MirrorState => ({\n cursorHidden: false,\n cursorBlink: null,\n cursorStyle: null,\n title,\n mouseEncoding: [],\n alternateScroll: null,\n colorSchemeUpdates: null,\n modifyOtherKeys: null,\n charsets: ['B', 'B', 'B', 'B'],\n normal: freshScreen(),\n alternate: freshScreen(),\n});\n\n/** The main parameters (sub-parameters dropped: none of the sequences tracked here has any). */\nconst nums = (params: Params): number[] => params.filter((p): p is number => typeof p === 'number');\nconst decModes = (modes: number[], final: 'h' | 'l'): string => (modes.length ? `${CSI}?${modes.join(';')}${final}` : '');\nconst cup = (row: number, col: number): string => `${CSI}${row + 1};${col + 1}H`;\n\n/** The OSC colour queries xterm.js leaves to its renderer (CoreBrowserTerminal), which a headless one never answers. */\nconst SPECIAL_COLORS = ['10', '11', '12'] as const;\n\n/** How the mirror answers the agent's queries in the output it is written while no client is attached (`answerQueries`). */\nexport interface MirrorAnswers {\n /** Whether the mirror answers the queries in output written now: decided as it arrives, not when it is parsed. */\n now(): boolean;\n /** Where the answers go: the PTY. */\n send(reply: string): void;\n /** The colours colour queries are answered with. */\n colors: Pick<TerminalColors, 'reply'>;\n}\n\n/**\n * The PTY host's copy of a terminal's screen: an @xterm/headless terminal fed everything the PTY prints, and the\n * snapshot a newly attached client is sent first (`replay`). The serialize addon draws the screen and scrollback\n * but leaves out state a full-screen agent depends on — the mouse encoding, a hidden cursor, the cursor's shape,\n * the title, the scroll region, the kitty keyboard flags — and places the cursor wrong after origin mode or a\n * full row. That state is followed here with xterm's own parser hooks (each returns false, so xterm still handles\n * the sequence; a sequence split across writes reaches them whole) and written after the addon's output, so a\n * fresh terminal written the snapshot ends in the same state. Uses Unicode 11 widths, as the browser does. In output\n * that arrived with no client attached, it answers the agent's queries too (`answerQueries`, terminal-rendering.md).\n * It also keeps what the agent says about itself in-band — OSC 9;4 progress, OSC 7501 program status (`streamSignal`,\n * stream-status.ts) — for a status where no hook reports one.\n */\nexport class ScreenMirror {\n readonly terminal: HeadlessTerminal;\n private readonly serializer = new SerializeAddon();\n private st: MirrorState = freshState();\n /** OSC 9;4 and OSC 7501, as the agent last said them (stream-status.ts). */\n private readonly stream = new StreamStatus();\n private answers: MirrorAnswers | null = null;\n /** The chunk being parsed is one the mirror answers the queries in (set and cleared by the write queue's callbacks). */\n private answering = false;\n /** Writes and resizes queued and not applied yet: a resize waits behind them (`resize`). */\n private queued = 0;\n /** The grid as last asked for: the terminal's own once every queued resize is applied. */\n private grid: { cols: number; rows: number };\n /** Snapshots waiting for the writes before them to be parsed (`snapshotSettled`). */\n private readonly settling = new Set<() => void>();\n /**\n * The last snapshots taken, kept until the screen changes (a write, a resize): attaching again to a session that\n * printed nothing since — a reload, switching back to it — is then sent the same text without serializing 2000\n * lines again (~10 ms of the attach, terminal-rendering.md). Only ever kept or used with nothing queued: xterm\n * parses a long write in slices, and a snapshot between two of them is of a screen that is still changing.\n */\n private kept: { full?: string; screen?: string } = {};\n private disposed = false;\n\n /**\n * `windowsPty`: the PTY is ConPTY's (terminal-size.ts `windowsPtyFor`), which reflows lines itself on a resize: the\n * copy then resizes as the Terminal tab's xterm.js does with the same option, not reflowing them a second time.\n */\n constructor(cols: number, rows: number, scrollback: number = REPLAY_SCROLLBACK, opts: { windowsPty?: WindowsPty } = {}) {\n this.terminal = new Terminal({\n cols,\n rows,\n scrollback,\n allowProposedApi: true,\n ...(opts.windowsPty ? { windowsPty: opts.windowsPty } : {}),\n });\n this.grid = { cols, rows };\n this.terminal.loadAddon(this.serializer);\n // Emoji and symbols (👍 ⭐ ✅ ⏳ 🚀) are 2 columns in the browser, which uses Unicode 11 (PtyView): 1 here\n // laid every replayed line out for the wrong columns.\n this.terminal.loadAddon(new Unicode11Addon());\n this.terminal.unicode.activeVersion = '11';\n this.track();\n // xterm answers DA, DSR / CPR, DECRQM and DECRQSS itself, through onData, while it parses the query.\n this.terminal.onData((reply) => {\n if (this.answering) this.answers?.send(reply);\n });\n this.answerColors();\n }\n\n /**\n * From now on, the agent's queries in output written while `answers.now()` says so (no client attached) are\n * answered here: what xterm answers itself, and the colour queries it leaves to a renderer (OSC 10, 11, 12 and 4).\n */\n answerQueries(answers: MirrorAnswers): void {\n this.answers = answers;\n }\n\n /**\n * Output, queued for parsing. Whether its queries are answered here is decided now, as it arrives: xterm parses it a\n * moment later, by when a client may have attached (and been sent a screen with no query in it) or detached. A\n * write's callback runs once it is parsed and before the next write is, so empty writes around it mark the chunk.\n */\n write(data: string, done?: () => void): void {\n this.queued++;\n this.kept = {};\n const parsed = () => {\n this.queued--;\n done?.();\n };\n if (!this.answers?.now()) {\n this.terminal.write(data, parsed);\n return;\n }\n this.terminal.write('', () => (this.answering = true));\n this.terminal.write(data, () => {\n this.answering = false;\n parsed();\n });\n }\n\n /**\n * In order with the writes around it: output that arrived before the resize was drawn for the old grid and is parsed\n * at it, output after it at the new one. xterm parses writes later, so a resize applied at once would lay out what is\n * still queued for a grid it was never drawn for — and every snapshot after would carry it. With nothing queued it is\n * applied now; else behind an empty write, whose callback runs once all before it is parsed. `snapshotSettled` waits\n * the same way, so a snapshot asked for after a resize is at the new grid.\n */\n resize(cols: number, rows: number): void {\n if (cols === this.grid.cols && rows === this.grid.rows) return;\n this.grid = { cols, rows };\n if (!this.queued) {\n this.applyResize(cols, rows);\n return;\n }\n this.queued++;\n try {\n this.terminal.write('', () => {\n this.queued--;\n this.applyResize(cols, rows);\n });\n } catch {\n this.queued--; // disposed: nothing to resize\n }\n }\n\n private applyResize(cols: number, rows: number): void {\n if (cols === this.terminal.cols && rows === this.terminal.rows) return;\n // xterm.js sets both buffers' scroll regions back to the whole screen on a resize.\n this.st.normal.scrollRegion = null;\n this.st.alternate.scrollRegion = null;\n this.kept = {};\n this.terminal.resize(cols, rows);\n }\n\n /** What the agent last said about itself in its output (OSC 7501, else OSC 9;4), as far as it is parsed; null: nothing. */\n streamSignal(): StreamSignal | null {\n return this.stream.signal();\n }\n\n /** A copy of the tracked state (tests, diagnostics). */\n state(): MirrorState {\n return structuredClone(this.st);\n }\n\n /**\n * The screen and scrollback as escape sequences that redraw it, then the state that puts a fresh terminal in\n * the same modes (`rehydrate`). What a client attaching is sent instead of raw output — raw bytes can start\n * mid-sequence and were drawn for another client's grid. Null if it can't be taken (logged): never an empty screen\n * in its place, which a client would draw over the one it has (pty-registry.ts decides what it is sent instead).\n * `scrollback: false`: the screen only (SnapshotOptions). The positions written after it (the saved cursor, the\n * cursor, the normal screen's under the alternate one) count from the screen's top, so they are the same either way.\n */\n snapshot(opts: SnapshotOptions = {}): string | null {\n const which = opts.scrollback === false ? 'screen' : 'full';\n const kept = this.queued ? undefined : this.kept[which];\n if (kept !== undefined) return kept;\n const taken = this.serialize(opts);\n if (taken !== null && !this.queued) this.kept[which] = taken;\n return taken;\n }\n\n private serialize(opts: SnapshotOptions): string | null {\n let body: string;\n try {\n body = this.serializer.serialize(opts.scrollback === false ? { scrollback: 0 } : undefined);\n } catch (err) {\n logSwallowed('screen copy: take a snapshot', err);\n return null;\n }\n let regionBeforeAlt = false;\n if (this.terminal.buffer.active.type === 'alternate') {\n // What belongs to the normal screen goes before the addon switches to the alternate one.\n const at = body.indexOf(ENTER_ALT);\n if (at >= 0) {\n const normal = this.normalUnderAlt();\n regionBeforeAlt = normal.region;\n body = body.slice(0, at) + normal.text + body.slice(at);\n }\n }\n return START + body + this.rehydrate(regionBeforeAlt);\n }\n\n /** snapshot(), once everything written so far is parsed: xterm queues writes, and a write's callback runs once it is. */\n snapshotSettled(opts: SnapshotOptions = {}): Promise<string | null> {\n return new Promise((resolve) => {\n if (this.disposed) return resolve('');\n const settle = () => {\n this.settling.delete(settle);\n resolve(this.disposed ? '' : this.snapshot(opts));\n };\n this.settling.add(settle);\n try {\n this.terminal.write('', settle);\n } catch {\n settle();\n }\n });\n }\n\n /** The visible screen as plain text, one line per row. */\n screenText(): string {\n try {\n const buf = this.terminal.buffer.active;\n const lines: string[] = [];\n for (let y = buf.viewportY; y < buf.viewportY + this.terminal.rows; y++) {\n lines.push(buf.getLine(y)?.translateToString(true) ?? '');\n }\n return lines.join('\\n');\n } catch {\n return '';\n }\n }\n\n /** Disposing drops xterm's queued writes and their callbacks: a snapshot still waiting is answered '' then, never left hanging. */\n dispose(): void {\n this.disposed = true;\n const waiting = [...this.settling];\n this.settling.clear();\n this.terminal.dispose();\n for (const settle of waiting) settle();\n }\n\n private get screen(): Screen {\n return this.terminal.buffer.active.type;\n }\n\n /** The normal screen's own state while the alternate one is shown: its scroll region (then its cursor again,\n * which DECSTBM homes and 1049 saves) and its keyboard flags. */\n private normalUnderAlt(): { text: string; region: boolean } {\n const n = this.st.normal;\n const cur = this.terminal.buffer.normal;\n let text = '';\n if (n.scrollRegion) text += `${CSI}${n.scrollRegion.top + 1};${n.scrollRegion.bottom + 1}r`;\n // Where leaving the alternate screen puts the cursor back: the same rule as the cursor at the end (rehydrate).\n if (n.scrollRegion || cur.cursorX < this.terminal.cols) text += cup(cur.cursorY, Math.min(cur.cursorX, this.terminal.cols - 1));\n text += n.keyboardFlags.map((f) => `${CSI}>${f}u`).join('');\n return { text, region: !!n.scrollRegion };\n }\n\n /**\n * Everything after the addon's output, in an order that matters: the saved cursor first (it needs an absolute\n * position), the modes, then the scroll region and origin mode — both move the cursor — and the cursor last.\n * Each mode is stated whatever the addon wrote, so one it already wrote (or a later addon version writes) is\n * only said twice; modes with a universal default are stated either way, so a native terminal that `work attach`\n * writes into ends in them even if something left it otherwise. Never 2026 (synchronized output): a snapshot\n * with it on would hold the client's screen until the app happened to turn it off.\n */\n private rehydrate(regionBeforeAlt: boolean): string {\n const t = this.terminal;\n const m = t.modes;\n const s = this.st;\n const buf = t.buffer.active;\n const screen = s[this.screen];\n let out = '';\n let moved = false;\n\n if (m.originMode) {\n out += `${CSI}?6l`; // positions below are absolute; set again before the cursor\n moved = true;\n }\n if (screen.savedCursor) {\n out += cup(Math.max(screen.savedCursor.line - buf.baseY, 0), Math.min(screen.savedCursor.x, t.cols - 1)) + `${ESC}7`;\n moved = true;\n }\n\n // Mouse: off, then on as the app has it — xterm.js turns any protocol off with any reset, and an encoding\n // with 1006l / 1016l alike, so resets must come first. The encodings are replayed in the app's order: a\n // terminal that supports only some of them ends where it would have.\n out += `${CSI}?9;1000;1002;1003l`;\n if (m.mouseTrackingMode !== 'none') out += `${CSI}?${MOUSE_PROTOCOL[m.mouseTrackingMode]}h`;\n out += `${CSI}?1005;1006;1015;1016l`;\n for (const e of s.mouseEncoding) out += `${CSI}?${e.mode}${e.on ? 'h' : 'l'}`;\n\n const on: number[] = [];\n const off: number[] = [];\n const state = (mode: number, value: boolean | null) => {\n if (value !== null) (value ? on : off).push(mode);\n };\n state(1, m.applicationCursorKeysMode);\n state(7, m.wraparoundMode);\n state(12, s.cursorBlink);\n state(25, !s.cursorHidden);\n state(45, m.reverseWraparoundMode);\n state(1004, m.sendFocusMode);\n state(1007, s.alternateScroll);\n state(2004, m.bracketedPasteMode);\n state(2031, s.colorSchemeUpdates);\n out += decModes(off, 'l') + decModes(on, 'h');\n out += m.applicationKeypadMode ? `${ESC}=` : `${ESC}>`;\n out += m.insertMode ? `${CSI}4h` : `${CSI}4l`;\n\n if (s.cursorStyle !== null) out += `${CSI}${s.cursorStyle} q`;\n if (s.title !== null) out += `${ESC}]2;${s.title.replace(CONTROL, '')}\\x07`;\n out += screen.keyboardFlags.map((f) => `${CSI}>${f}u`).join('');\n if (s.modifyOtherKeys !== null) out += `${CSI}>4;${s.modifyOtherKeys}m`;\n s.charsets.forEach((f, i) => {\n if (f !== 'B') out += `${ESC}${CHARSET_SLOTS[i]}${f}`;\n });\n\n const region = screen.scrollRegion;\n // A region stated for the normal screen first would carry into this one on a terminal that keeps one region.\n if (region || regionBeforeAlt) {\n out += region ? `${CSI}${region.top + 1};${region.bottom + 1}r` : `${CSI}r`;\n moved = true;\n }\n if (m.originMode) out += `${CSI}?6h`;\n // The cursor last, absolute: the addon's relative moves land one column short from a full row (xterm.js\n // #6165), and origin mode / DECSTBM home it. Except a cursor waiting to wrap after the last column, which\n // no position can say: there the addon's output already leaves it, unless something above moved it.\n const pendingWrap = buf.cursorX >= t.cols;\n if (moved || !pendingWrap) {\n const top = m.originMode && region ? region.top : 0;\n out += cup(buf.cursorY - top, Math.min(buf.cursorX, t.cols - 1));\n }\n return out;\n }\n\n private track(): void {\n const t = this.terminal;\n const p = t.parser;\n t.onTitleChange((title) => (this.st.title = title));\n p.registerCsiHandler({ prefix: '?', final: 'h' }, (params) => this.decset(nums(params), true));\n p.registerCsiHandler({ prefix: '?', final: 'l' }, (params) => this.decset(nums(params), false));\n p.registerCsiHandler({ intermediates: ' ', final: 'q' }, (params) => {\n const n = nums(params)[0] ?? 0;\n if (n >= 0 && n <= 6) this.st.cursorStyle = n === 0 ? null : n;\n return false;\n });\n p.registerCsiHandler({ final: 'r' }, (params) => {\n // xterm.js's setScrollRegion: a bottom past the screen (or 0) is the last row; a region of one row is ignored.\n const [first = 0, second = 0] = nums(params);\n const top = first || 1;\n const bottom = params.length < 2 || second > t.rows || second === 0 ? t.rows : second;\n if (bottom > top) this.st[this.screen].scrollRegion = top === 1 && bottom === t.rows ? null : { top: top - 1, bottom: bottom - 1 };\n return false;\n });\n p.registerEscHandler({ final: '7' }, () => this.saveCursor(this.screen));\n p.registerCsiHandler({ final: 's' }, () => this.saveCursor(this.screen));\n // DECSTR: what xterm.js's soft reset puts back that is followed here.\n p.registerCsiHandler({ intermediates: '!', final: 'p' }, () => {\n const screen = this.st[this.screen];\n screen.savedCursor = null;\n screen.scrollRegion = null;\n this.st.cursorHidden = false;\n this.st.cursorStyle = null;\n this.st.charsets = ['B', 'B', 'B', 'B'];\n return false;\n });\n // RIS: everything, but what xterm.js 6 keeps through it: the title, DECSET 12 (an option to it) and a hidden cursor.\n p.registerEscHandler({ final: 'c' }, () => {\n this.st = { ...freshState(this.st.title), cursorBlink: this.st.cursorBlink, cursorHidden: this.st.cursorHidden };\n this.stream.reset(); // the spec: a full reset removes every record\n return false;\n });\n // In-band status (stream-status.ts). xterm itself does nothing with either; false leaves them to any other handler.\n p.registerOscHandler(9, (data) => {\n this.stream.osc9(data);\n return false;\n });\n p.registerOscHandler(7501, (data) => {\n this.stream.osc7501(data);\n return false;\n });\n for (const [i, slot] of CHARSET_SLOTS.entries())\n for (const final of CHARSET_FINALS)\n p.registerEscHandler({ intermediates: slot, final }, () => {\n this.st.charsets[i] = final;\n return false;\n });\n // kitty keyboard protocol: push, pop, set (CSI > f u, CSI < n u, CSI = f ; mode u), per screen.\n p.registerCsiHandler({ prefix: '>', final: 'u' }, (params) => {\n const stack = this.st[this.screen].keyboardFlags;\n stack.push(nums(params)[0] ?? 0);\n if (stack.length > KEYBOARD_STACK_MAX) stack.shift();\n return false;\n });\n p.registerCsiHandler({ prefix: '<', final: 'u' }, (params) => {\n const stack = this.st[this.screen].keyboardFlags;\n stack.splice(Math.max(stack.length - (nums(params)[0] || 1), 0));\n return false;\n });\n p.registerCsiHandler({ prefix: '=', final: 'u' }, (params) => {\n const stack = this.st[this.screen].keyboardFlags;\n const [flags = 0, mode = 1] = nums(params);\n const current = stack.at(-1) ?? 0;\n const next = mode === 2 ? current | flags : mode === 3 ? current & ~flags : flags;\n if (stack.length) stack[stack.length - 1] = next;\n else if (next) stack.push(next); // flags 0 on an empty stack is where it already is\n return false;\n });\n // XTMODKEYS: CSI > 4 ; n m sets modifyOtherKeys, CSI > 4 m and CSI > 4 n put it back.\n p.registerCsiHandler({ prefix: '>', final: 'm' }, (params) => {\n const [resource = 0, value] = nums(params);\n if (resource === 4 || params.length <= 1) this.st.modifyOtherKeys = resource === 4 && value ? value : null;\n return false;\n });\n p.registerCsiHandler({ prefix: '>', final: 'n' }, (params) => {\n const resource = nums(params)[0] ?? 0;\n if (resource === 4 || resource === 0) this.st.modifyOtherKeys = null;\n return false;\n });\n }\n\n /**\n * OSC 10 / 11 / 12 / 4 with `?`: xterm.js leaves the answer to its renderer, so a headless one stays silent. Answered\n * as the browser's xterm.js does (`_setOrReportSpecialColor`, `setOrReportIndexedColor`): OSC 10 ; ? ; ? asks for 10\n * and 11, OSC 4 takes index ; ? pairs. Each handler returns false: xterm still handles a colour being set.\n */\n private answerColors(): void {\n const p = this.terminal.parser;\n SPECIAL_COLORS.forEach((first, offset) =>\n p.registerOscHandler(Number(first), (data) => {\n const a = this.answering ? this.answers : null;\n data.split(';').forEach((spec, i) => {\n const slot = SPECIAL_COLORS[offset + i];\n if (a && slot && spec === '?') a.send(a.colors.reply(slot));\n });\n return false;\n }),\n );\n p.registerOscHandler(4, (data) => {\n const a = this.answering ? this.answers : null;\n const slots = data.split(';');\n for (let i = 0; a && i + 1 < slots.length; i += 2) {\n const index = /^\\d+$/.test(slots[i]) ? Number(slots[i]) : -1;\n if (index >= 0 && index <= 255 && slots[i + 1] === '?') a.send(a.colors.reply(`4;${index}`));\n }\n return false;\n });\n }\n\n private saveCursor(screen: Screen): boolean {\n const buf = this.terminal.buffer.active;\n this.st[screen].savedCursor = { x: buf.cursorX, line: buf.baseY + buf.cursorY };\n return false;\n }\n\n private decset(modes: number[], on: boolean): boolean {\n const s = this.st;\n // A sequence may switch screens part-way (CSI ? 1049 ; 1000 h): follow it.\n let screen = this.screen;\n for (const mode of modes) {\n if (mode === 12) s.cursorBlink = on;\n else if (mode === 25) s.cursorHidden = !on;\n else if (mode === 1007) s.alternateScroll = on;\n else if (mode === 2031) s.colorSchemeUpdates = on;\n else if (MOUSE_ENCODINGS.has(mode)) {\n s.mouseEncoding = [...s.mouseEncoding.filter((e) => e.mode !== mode), { mode, on }];\n // Only resets left: every terminal is back at its default encoding.\n if (s.mouseEncoding.every((e) => !e.on)) s.mouseEncoding = [];\n } else if (mode === 1048 && on) this.saveCursor(screen);\n else if (ALT_SCREEN.has(mode)) {\n // 1049 saves the normal screen's cursor on the way in (the snapshot's own 1049h does that again) and puts\n // it back on the way out: what ESC 7 saved before is gone, and the one restored is where the cursor is.\n if (on) screen = 'alternate';\n else if (screen === 'alternate') {\n // Leaving it clears the alternate buffer (its region with it); its saved cursor stays, as in xterm.js.\n s.alternate.scrollRegion = null;\n s.alternate.keyboardFlags = [];\n if (mode === 1049) s.normal.savedCursor = null;\n screen = 'normal';\n }\n }\n }\n return false;\n }\n}\n","/**\n * How much of a terminal's history is kept, in one place for the PTY host's screen mirror and the browser's\n * terminal (the SPA imports this file: it stays pure and import-free).\n *\n * REPLAY_SCROLLBACK is what a client gets back when it attaches: the mirror keeps that many lines above the\n * screen, and all of them are serialized into the `replay` frame. Measured on a 200-column screen of coloured\n * agent output (terminal-rendering.md): 200 lines serialize in ~3 ms to a 50 KiB frame, 2000 in ~17 ms to\n * 410 KiB, 5000 in ~33 ms to 1 MiB — past what an attach can spend without being felt, and each mirror holds\n * its lines for as long as the session runs (~12 MiB at 2000 lines and 200 columns, ~21 MiB at 5000).\n *\n * VIEW_SCROLLBACK is what an open Terminal tab keeps while it stays connected: it costs that tab's memory only\n * and nothing at an attach, so it may keep more than a reattach brings back.\n */\nexport const REPLAY_SCROLLBACK = 2000;\nexport const VIEW_SCROLLBACK = 5000;\n","/**\n * Synchronized output (DEC private mode 2026, terminal-rendering.md \"Synchronized output\"): an agent wraps each repaint\n * in `CSI ? 2026 h` … `CSI ? 2026 l` so the terminal shows whole frames. The PTY host follows those marks AS THE OUTPUT\n * ARRIVES — before its screen copy has parsed it (that parse is asynchronous) — to keep each frame whole on its way to\n * the clients (output-pacer.ts) and to take a snapshot only between frames (pty-session.ts cuts its output at each\n * frame's end for that).\n *\n * Only the set and reset of 2026 are recognised, alone or among other modes (`CSI ? 2026 ; 25 h`), wherever a chunk\n * cuts them: the scanner keeps its place in a sequence across chunks. A second set inside a frame changes nothing, a\n * reset with no frame open is nothing, and RIS (`ESC c`) ends a frame, as each does in xterm.js 6. A query\n * (`CSI ? 2026 $ p`) is not a set. Pure and import-free.\n */\n\n/** Begin and end of a synchronized update (BSU / ESU), as agents write them. */\nexport const BSU = '\\x1b[?2026h';\nexport const ESU = '\\x1b[?2026l';\n\n/** DEC private mode 2026: synchronized output (the Terminal tab's repaint-scroll.ts follows it too). */\nexport const SYNC_MODE = 2026;\n/** Longer parameters than this are no mode list an agent writes: the sequence is dropped (bounded state). */\nconst MAX_PARAMS = 64;\n\n/** Where a sequence that opened or closed a frame ends in a chunk (`at`: just past its final character), and the state after it. */\nexport interface SyncChange {\n at: number;\n open: boolean;\n}\n\n/** Where the scanner is in a sequence: outside one, after ESC, after ESC [, among a private mode's parameters. */\nconst GROUND = 0;\nconst ESCAPE = 1;\nconst CSI = 2;\nconst PRIVATE = 3;\n\nexport class SyncScanner {\n /** A frame is open: a set was seen and no reset since. */\n open = false;\n private state = GROUND;\n private params = '';\n\n /** Follow `chunk`: the places in it where a frame opened or closed, in order. */\n feed(chunk: string): SyncChange[] {\n const changes: SyncChange[] = [];\n let i = 0;\n while (i < chunk.length) {\n if (this.state === GROUND) {\n const esc = chunk.indexOf('\\x1b', i);\n if (esc < 0) break;\n this.state = ESCAPE;\n i = esc + 1;\n continue;\n }\n const c = chunk[i];\n if (this.state === ESCAPE) {\n if (c === '[') this.state = CSI;\n else {\n this.state = GROUND;\n if (c === 'c')\n this.change(false, i + 1, changes); // RIS\n else if (c === '\\x1b') this.state = ESCAPE;\n }\n } else if (this.state === CSI) {\n if (c === '?') {\n this.state = PRIVATE;\n this.params = '';\n } else this.state = c === '\\x1b' ? ESCAPE : GROUND;\n } else if ((c >= '0' && c <= '9') || c === ';' || c === ':') {\n this.params += c;\n if (this.params.length > MAX_PARAMS) this.state = GROUND;\n } else {\n this.state = c === '\\x1b' ? ESCAPE : GROUND;\n if ((c === 'h' || c === 'l') && this.params.split(';').some((p) => Number(p.split(':')[0]) === SYNC_MODE))\n this.change(c === 'h', i + 1, changes);\n }\n i++;\n }\n return changes;\n }\n\n /** Start again with no frame open (the PTY's process changed). */\n reset(): void {\n this.open = false;\n this.state = GROUND;\n this.params = '';\n }\n\n private change(open: boolean, at: number, changes: SyncChange[]): void {\n if (open === this.open) return;\n this.open = open;\n changes.push({ at, open });\n }\n}\n\n/** `chunk` cut just past each place a frame CLOSES (so a snapshot can be taken between two frames); `[chunk]` when none does. */\nexport function cutAtFrameEnds(scanner: SyncScanner, chunk: string): string[] {\n const ends = scanner.feed(chunk).filter((c) => !c.open && c.at < chunk.length);\n if (!ends.length) return [chunk];\n const pieces: string[] = [];\n let from = 0;\n for (const { at } of ends) {\n pieces.push(chunk.slice(from, at));\n from = at;\n }\n pieces.push(chunk.slice(from));\n return pieces;\n}\n","/**\n * The Terminal tab's colours, and what the PTY host answers an agent's colour query with when no terminal is attached\n * to answer it (terminal-rendering.md, \"Who answers a query\"). Pure and import-free: the SPA imports it (PtyView's theme).\n */\n\n/** The Terminal tab's theme (PtyView). The cursor is xterm.js's default, stated so the host answers OSC 12 as the tab does. */\nexport const TERMINAL_THEME = { background: '#1e1e1e', foreground: '#d4d4d4', cursor: '#ffffff' } as const;\n\n/** xterm.js's default 16 colours (`DEFAULT_ANSI_COLORS`): what the tab answers OSC 4 with, the theme setting none. */\nconst ANSI_16 = [\n '#2e3436',\n '#cc0000',\n '#4e9a06',\n '#c4a000',\n '#3465a4',\n '#75507b',\n '#06989a',\n '#d3d7cf',\n '#555753',\n '#ef2929',\n '#8ae234',\n '#fce94f',\n '#729fcf',\n '#ad7fa8',\n '#34e2e2',\n '#eeeeec',\n];\nconst CUBE = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];\n\n/** Colour `index` (0–255) of xterm.js's default palette as `[r, g, b]`: the 16 above, the 6×6×6 cube, 24 greys. */\nfunction paletteRgb(index: number): [number, number, number] {\n if (index < 16) return hexRgb(ANSI_16[index]);\n if (index < 232) {\n const i = index - 16;\n return [CUBE[Math.floor(i / 36) % 6], CUBE[Math.floor(i / 6) % 6], CUBE[i % 6]];\n }\n const c = 8 + (index - 232) * 10;\n return [c, c, c];\n}\n\nfunction hexRgb(hex: string): [number, number, number] {\n return [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16)) as [number, number, number];\n}\n\n/** As xterm.js says a colour in a reply (`toRgbString`): 16 bits a channel, `rgb:1e1e/1e1e/1e1e`. */\nfunction rgbSpec([r, g, b]: [number, number, number]): string {\n const two = (n: number) => n.toString(16).padStart(2, '0').repeat(2);\n return `rgb:${two(r)}/${two(g)}/${two(b)}`;\n}\n\n/** A colour reply's value we repeat: `rgb:` with 1–4 hex digits a channel, or `#` and hex. Nothing else is said back. */\nconst SPEC = /^(?:rgb:[\\da-f]{1,4}\\/[\\da-f]{1,4}\\/[\\da-f]{1,4}|#(?:[\\da-f]{3}){1,4})$/i;\n/** A colour reply: OSC 10, 11 or 12, or OSC 4 with its index; then the value, then BEL or ST. */\nconst COLOR_REPLY = /^\\x1b\\]((?:1[0-2])|4;\\d{1,3});([^\\x07\\x1b]*)(?:\\x07|\\x1b\\\\)$/;\n\n/**\n * The colours an agent's colour queries are answered with when the PTY host answers them itself: the last a terminal\n * attached to any of its PTYs answered with (`remember`, given each answer the host lets through), else the Terminal\n * tab's. One per host process: a terminal's colours don't depend on the session it shows.\n */\nexport class TerminalColors {\n private readonly seen = new Map<string, string>();\n\n /** A colour reply a terminal sent (`ESC ] 11 ; rgb:… ST`): remembered for its slot. Anything else is ignored. */\n remember(reply: string): void {\n const m = COLOR_REPLY.exec(reply);\n if (!m || !SPEC.test(m[2])) return;\n const slot = m[1].startsWith('4;') ? `4;${Number(m[1].slice(2))}` : m[1];\n if (slot.startsWith('4;') && Number(slot.slice(2)) > 255) return;\n this.seen.set(slot, m[2]);\n }\n\n /** The value to answer a query for `slot` with: `10`, `11`, `12`, or `4;<index>` (0–255). */\n value(slot: string): string {\n const seen = this.seen.get(slot);\n if (seen) return seen;\n if (slot === '10') return rgbSpec(hexRgb(TERMINAL_THEME.foreground));\n if (slot === '11') return rgbSpec(hexRgb(TERMINAL_THEME.background));\n if (slot === '12') return rgbSpec(hexRgb(TERMINAL_THEME.cursor));\n return rgbSpec(paletteRgb(Number(slot.slice(2))));\n }\n\n /** The whole reply for `slot`, as xterm.js says it (ST-terminated). */\n reply(slot: string): string {\n return `\\x1b]${slot};${this.value(slot)}\\x1b\\\\`;\n }\n}\n","import type { Grid } from './terminal-size.js';\nimport type { ResumePoint } from './resume.js';\n\n/**\n * The last of a PTY's raw output, kept so a client that reconnects, or that fell behind and caught up, is sent only what\n * it missed (terminal-rendering.md, \"Reattach where you left off\" and \"Flow control and coalescing\"). Pure.\n *\n * 256 Ki characters. A client falls behind only once it has more than HIGH_WATERMARK (100 000) outstanding, so what it\n * misses of a burst is the burst less that: 256 Ki covers a burst of ~360 000 characters, about the 5 000 lines a tab\n * keeps (VIEW_SCROLLBACK) of ~72-character coloured lines (a 3 000-line burst of them is 218 000 characters, 230 KB) —\n * past that, the tab would push most of it out of its own scrollback anyway. What a resume or a catch-up sends from here is never\n * counted against a client's flow (as a screen isn't): it is at most this, about a catch-up screen of REPLAY_SCROLLBACK\n * (~410 KiB at 200 columns), and costs the host no copy it doesn't already hold but the one string sent. At most\n * 512 KiB per PTY (two bytes a character in the worst case), against the mirror's ~6–11.5 MiB: 10 MiB for 20 PTYs.\n * Longer than that, a client gets a screen.\n */\nexport const RESUME_TAIL_CHARS = 256 * 1024;\n\n/**\n * The last `max` characters of a stream, and where they stand in it. The cut at its start may fall anywhere (inside an\n * escape sequence, a surrogate pair, a synchronized frame): nothing is ever sent from there, only from a client's own\n * offset, which is where its terminal's parser stands.\n */\nexport class OutputTail {\n private chunks: string[] = [];\n /** The first chunk still held (`chunks` is compacted now and then, not shifted each time). */\n private head = 0;\n private held = 0;\n private total = 0;\n\n constructor(private readonly max = RESUME_TAIL_CHARS) {}\n\n /** The offset of the first character held. */\n get start(): number {\n return this.total - this.held;\n }\n\n /** The offset after the last character: everything up to here has arrived. */\n get end(): number {\n return this.total;\n }\n\n push(text: string): void {\n if (!text) return;\n this.total += text.length;\n this.chunks.push(text);\n this.held += text.length;\n while (this.held > this.max) {\n const first = this.chunks[this.head];\n const over = this.held - this.max;\n if (first.length <= over) {\n this.head++;\n this.held -= first.length;\n } else {\n this.chunks[this.head] = first.slice(over);\n this.held -= over;\n }\n }\n if (this.head > 1024 && this.head * 2 > this.chunks.length) {\n this.chunks = this.chunks.slice(this.head);\n this.head = 0;\n }\n }\n\n /** Everything from `offset` to the end; null when it isn't all held (too old, or ahead of the stream). */\n since(offset: number): string | null {\n if (!Number.isSafeInteger(offset) || offset < this.start || offset > this.total) return null;\n let skip = offset - this.start;\n const out: string[] = [];\n for (let i = this.head; i < this.chunks.length; i++) {\n const c = this.chunks[i];\n if (skip >= c.length) {\n skip -= c.length;\n continue;\n }\n out.push(skip ? c.slice(skip) : c);\n skip = 0;\n }\n return out.join('');\n }\n\n /** Hold nothing more (the entry is gone); the count stays. */\n clear(): void {\n this.chunks = [];\n this.head = 0;\n this.held = 0;\n }\n}\n\n/** Why a client is sent a screen rather than what it missed. */\nexport type ResumeRefusal =\n /** Another stream: another process under this id, a host started again, or not this host's at all. */\n | 'stream'\n /** Its terminal's grid isn't the PTY's (or the grid it states to take isn't its own): drawn there, the output would be laid out for another grid. */\n | 'grid'\n /** The PTY's grid changed after its offset: the mirror and the agent reflowed and repainted for another grid meanwhile. */\n | 'resized'\n /** What it missed is no longer all held. */\n | 'too-old'\n /** It says it has more than there is. */\n | 'ahead'\n /** Its offset falls between the two halves of a surrogate pair: not where any frame ends. */\n | 'split'\n /** The PTY is exiting, restarting, halted or being redrawn. */\n | 'busy';\n\n/** What the registry knows of a PTY when a client joins it. */\nexport interface ResumeTarget {\n stream: string;\n /** Its grid now, and before this attach resized it (a client that states a grid takes it as it attaches). */\n grid: Grid;\n gridBefore: Grid;\n /** The offset its grid last changed at (a client's resize, a redraw's jiggle). */\n gridAt: number;\n busy: boolean;\n}\n\n/**\n * What a reconnecting client at `at` is sent instead of a screen: the output it missed, or why it gets a screen. Any\n * doubt is a screen. `stated`: the grid it asked to take as it attached, if any.\n */\nexport function resumeFrom(\n at: ResumePoint,\n target: ResumeTarget,\n tail: OutputTail,\n stated?: Grid | null,\n): { missed: string } | { refused: ResumeRefusal } {\n if (at.stream !== target.stream) return { refused: 'stream' };\n if (target.busy) return { refused: 'busy' };\n const same = (g: Grid) => g.cols === at.cols && g.rows === at.rows;\n if (!same(target.grid) || !same(target.gridBefore) || (stated && !same(stated))) return { refused: 'grid' };\n return continueFrom(at.offset, target, tail);\n}\n\n/**\n * What a client that has drawn this stream up to `offset` is sent to go on from there: the output since, when it is all\n * held and nothing since makes it unsafe (an agent busy, a resize after it, an offset inside a surrogate pair), else why\n * not. A reconnecting client after its stream and grid are checked (`resumeFrom`); a client that fell behind as it\n * catches up, at the offset it was sent output up to (pty-registry.ts `resync`): that output is in order on its socket,\n * so its screen will stand there, drawn at the grid it draws live output at.\n */\nexport function continueFrom(\n offset: number,\n target: Pick<ResumeTarget, 'gridAt' | 'busy'>,\n tail: OutputTail,\n): { missed: string } | { refused: ResumeRefusal } {\n if (target.busy) return { refused: 'busy' };\n if (offset > tail.end) return { refused: 'ahead' };\n if (target.gridAt > offset) return { refused: 'resized' };\n const missed = tail.since(offset);\n if (missed === null) return { refused: 'too-old' };\n const first = missed.charCodeAt(0);\n if (first >= 0xdc00 && first <= 0xdfff) return { refused: 'split' };\n return { missed };\n}\n","import { HIGH_WATERMARK, LOW_WATERMARK } from './flow-control.js';\nimport { SyncScanner } from './sync-output.js';\nimport { OutputTail } from './output-tail.js';\n\n/**\n * The output path of one PTY, between its arriving and its clients (terminal-rendering.md, \"Flow control and\n * coalescing\"): what goes out as one frame, and to whom.\n *\n * - **Coalescing.** The first output after a quiet moment goes out at once (a keystroke's echo waits for nothing);\n * what arrives in the next `COALESCE_MS` goes out as one frame (VS Code's TerminalDataBufferer, `throttleBy` 5),\n * at most `MAX_FRAME_CHARS` of it.\n * - **Flow control.** A client that acks (flow-control.ts) has its unacknowledged characters counted. The one that\n * holds the PTY (the registry's `holder`: the one that answers the agent) pauses it above HIGH_WATERMARK and resumes\n * it below LOW_WATERMARK, as VS Code does with its one client, but for `PAUSE_TIMEOUT_MS` at most. Any other above\n * HIGH_WATERMARK (and the holder past its time) is **behind**: it is sent no output, and once its acks bring it under\n * LOW_WATERMARK it is caught up (`resync`) and goes live again: sent what it missed from the tail when it may be (its\n * screen will stand where its output stopped), else the screen as it stands. An agent never waits long for a view\n * nobody may be looking at (a background tab draws once a second).\n *\n * The set of clients a frame goes to is fixed when it goes: a client that joins, falls behind or catches up has\n * what was pending sent first, so a frame is never sent twice, nor to a client whose snapshot already has it. A\n * client falls behind only right after a whole frame went to it (or, the holder, at its time-out after what was\n * pending went to it): whatever query it was chosen to answer as the output arrived reached it.\n *\n * - **Synchronized frames.** Output between an agent's `CSI ? 2026 h` and `CSI ? 2026 l` (sync-output.ts, followed as it\n * arrives) is held and goes out as one frame when it ends, whatever COALESCE_MS and MAX_FRAME_CHARS say — or once it\n * was held FRAME_HOLD_MS or grew past FRAME_HOLD_MAX_CHARS, when what is held goes out and the rest of it flows as any\n * output does. Nothing is decided in the middle of a frame: a pause, a catch-up screen and a client joining\n * (`whenNoFrame`) wait for its end, so no client is ever sent half a frame, or a screen of one.\n *\n * Every frame ends at an offset: the characters of output since the PTY's entry was spawned (a restart keeps\n * counting). The last RESUME_TAIL_CHARS of it are kept (`tail`, output-tail.ts), so a client that reconnects, or that\n * fell behind and caught up, can be sent only what it missed from where it stands (pty-registry.ts `attach`, resume.ts).\n */\n\n/** After the first output of a quiet moment, what arrives within this many ms goes out as one frame (VS Code's `throttleBy`). */\nexport const COALESCE_MS = 5;\n/** A frame grows by coalescing to at most this many characters; a chunk bigger than that (node-pty reads ≤ 64 KiB) goes alone. */\nexport const MAX_FRAME_CHARS = 64 * 1024;\n/**\n * The longest the PTY waits for the client that holds it. A tab in front, or `work attach` in a native terminal,\n * draws 100 000 characters in a few ms to a few tens. A background tab parses in timer slices that run once a second\n * (once a minute after five): it would release each pause at its next tick, never time out, and hold the agent to\n * ~100 000 characters a second (measured: 20 MB took 159 s with a 2 s limit). Under a second, it times out on its first\n * pause or two. A client that hasn't come back by then is behind, and doesn't pause the PTY again until it is used.\n */\nexport const PAUSE_TIMEOUT_MS = 500;\n/**\n * A client that fell behind is caught up at most this often: each snapshot runs on the host's event loop (~17 ms at the\n * mirror's full 2000 lines), and a client slower than a flood would otherwise ask for one every few ms. What it missed,\n * sent from the tail instead, is not counted against its flow (as a screen isn't): this bounds that too.\n */\nexport const CATCH_UP_MIN_MS = 500;\n/**\n * The longest a synchronized frame is held whole: past it, what came of it goes out (and the rest of it as it comes), so\n * an agent that stops mid-frame never freezes its views for longer — nor a client attaching, whose screen waits for the\n * frame's end. A frame an agent writes at once arrives in a few ms (terminal-rendering.md, \"Synchronized output\").\n */\nexport const FRAME_HOLD_MS = 200;\n/** The most of one synchronized frame held: more than an inline agent's full reprint of the mirror's 2000 lines (~410 KiB). */\nexport const FRAME_HOLD_MAX_CHARS = 1024 * 1024;\n\nexport interface PacerTimers {\n now(): number;\n set(fn: () => void, ms: number): unknown;\n clear(handle: unknown): void;\n}\n\nexport const realTimers: PacerTimers = {\n now: () => Date.now(),\n set: (fn, ms) => setTimeout(fn, ms),\n clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n};\n\n/** What pauses the PTY's output: its reading stops, so the agent's writes block once the PTY's buffer is full. */\nexport interface PtyFlow {\n pause(): void;\n resume(): void;\n}\n\nexport interface PacedClient {\n /** A frame of live output, and the offset it ends at. */\n send(frame: string, end: number): void;\n /**\n * It was behind and has caught up: `from` is the offset it was sent output up to (where its screen will stand once it\n * has drawn it), or null when it must be sent a screen. Send it what it missed since `from` when that may be (true),\n * else the screen as it stands now (false); then live output again.\n */\n resync(from: number | null): boolean;\n /** It acks what it draws. One that doesn't is sent everything, as before, and never pauses the PTY. */\n metered: boolean;\n}\n\ninterface ClientState {\n readonly client: PacedClient;\n /** Characters sent to it, and acked by it. */\n sent: number;\n acked: number;\n /** The offset it was sent output up to (its attach's, a catch-up's, each frame's end). */\n at: number;\n /** Its `sent` when it was last caught up from the tail (what it missed is drawn before anything sent after); else null. */\n continuedAt: number | null;\n /** It fell behind again before it drew past what it missed: its next catch-up is a screen. */\n screenNext: boolean;\n /** Sent no live output until it catches up. */\n behind: boolean;\n /** It may pause the PTY: false once it timed out holding it, until it is used (typed in, resized) again. */\n mayPause: boolean;\n /** When it was last sent a screen or what it missed (its attach, a catch-up). */\n snapshotAt: number;\n catchUp: unknown;\n /** Its catch-up waits for the frame being held to end. */\n catchUpAfterFrame: boolean;\n}\n\nexport interface PacerStats {\n sent: number;\n acked: number;\n unacked: number;\n behind: boolean;\n}\n\nexport class OutputPacer<K> {\n private pending: string[] = [];\n private pendingLength = 0;\n /** The coalescing window, open from the first output of a quiet moment until one passes with nothing. */\n private window: unknown = null;\n private readonly clients = new Map<K, ClientState>();\n private paused: { by: ClientState; timer: unknown } | null = null;\n private flow: PtyFlow | null;\n private readonly timers: PacerTimers;\n private readonly holder: () => K | null;\n /** Where the output is in synchronized frames, as it arrives. */\n private readonly sync = new SyncScanner();\n /** A synchronized frame being held (its output is in `pending`): until it ends, or its time or size cap. */\n private frame: { timer: unknown } | null = null;\n /** The frame open now was let go at its cap: the rest of it flows as any output does, until it ends. */\n private letGo = false;\n /** What waits for no frame to be held (a client joining, a catch-up): `gone` once the PTY's entry is disposed. */\n private waiting: Array<(gone: boolean) => void> = [];\n /** The last of the output as it arrived: what a reconnecting client missed, when it is still all here. Ends at `offset`. */\n readonly tail: OutputTail;\n\n constructor(deps: { flow: PtyFlow | null; holder: () => K | null; timers?: PacerTimers; tail?: OutputTail }) {\n this.flow = deps.flow;\n this.holder = deps.holder;\n this.timers = deps.timers ?? realTimers;\n this.tail = deps.tail ?? new OutputTail();\n }\n\n /**\n * Characters of output so far: where the next frame starts, and where a snapshot taken now stands. The tail's end, one\n * count for both: each piece is pushed to the tail as the pacer takes it in, so a client joining between two pieces of\n * one chunk (at a frame's end) is never sent from the tail what it will be sent live.\n */\n get offset(): number {\n return this.tail.end;\n }\n\n /** Whether the PTY is paused for a client now. */\n get isPaused(): boolean {\n return this.paused !== null;\n }\n\n /** Whether a synchronized frame is being held now. */\n get inFrame(): boolean {\n return this.frame !== null;\n }\n\n /**\n * Output arrived: sent at once if it is the first of a quiet moment, else with what follows within COALESCE_MS — or,\n * inside a synchronized frame, held until the frame ends.\n */\n output(data: string): void {\n if (!data) return;\n let from = 0;\n for (const change of this.sync.feed(data)) {\n this.piece(data.slice(from, change.at), change.open);\n from = change.at;\n }\n if (from < data.length) this.piece(data.slice(from), this.sync.open);\n }\n\n /**\n * `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\n * to the clients. `gone`: the entry was disposed first. A client joining then is sent nothing of that frame — its\n * screen, taken then, has all of it.\n */\n whenNoFrame(fn: (gone: boolean) => void): void {\n if (this.frame) this.waiting.push(fn);\n else fn(false);\n }\n\n /** Send what is pending now, a frame being held included (the process is stopping). */\n flush(): void {\n this.letFrameGo(false);\n this.flushPending();\n }\n\n /**\n * A client joins at the current offset: what arrived before it is in its snapshot and is not sent to it. (The registry\n * joins clients between frames, `whenNoFrame`; one joining mid-frame has what is held sent to the others first.)\n */\n add(key: K, client: PacedClient): void {\n this.letFrameGo(this.sync.open);\n this.flushPending();\n this.clients.set(key, {\n client,\n sent: 0,\n acked: 0,\n at: this.offset,\n continuedAt: null,\n screenNext: false,\n behind: false,\n mayPause: true,\n snapshotAt: this.timers.now(),\n catchUp: null,\n catchUpAfterFrame: false,\n });\n this.evaluate();\n }\n\n remove(key: K): void {\n const c = this.clients.get(key);\n if (!c) return;\n if (c.catchUp !== null) this.timers.clear(c.catchUp);\n this.clients.delete(key);\n if (this.paused?.by === c) this.release();\n this.evaluate();\n }\n\n /** It finished drawing `chars` more characters. */\n ack(key: K, chars: number): void {\n const c = this.clients.get(key);\n if (!c || !c.client.metered || !(chars > 0)) return;\n // Never more than it was sent: an ack can't pay for output to come (VS Code floors the count at 0 the same way).\n c.acked = Math.min(c.sent, c.acked + chars);\n if (c.behind) this.scheduleCatchUp(c);\n this.evaluate();\n }\n\n /** It was used (typed in, resized): it may pause the PTY again, and it may hold it now. */\n used(key: K): void {\n const c = this.clients.get(key);\n if (c) c.mayPause = true;\n this.evaluate();\n }\n\n /** Whether it is sent live output (not behind). */\n live(key: K): boolean {\n const c = this.clients.get(key);\n return !!c && !c.behind;\n }\n\n stats(key: K): PacerStats | null {\n const c = this.clients.get(key);\n return c ? { sent: c.sent, acked: c.acked, unacked: c.sent - c.acked, behind: c.behind } : null;\n }\n\n /** 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. */\n setFlow(flow: PtyFlow | null): void {\n this.letFrameGo(false);\n this.sync.reset();\n this.release();\n this.flow = flow;\n this.evaluate();\n }\n\n /**\n * The process ended: its last output goes out, no pause is left, and a client that is behind is sent the final\n * screen now, whatever CATCH_UP_MIN_MS says, instead of being left on a stale one (the registry tells it the PTY\n * ended once that screen is sent).\n */\n end(): void {\n this.letFrameGo(false);\n this.flushPending();\n this.setFlow(null);\n for (const c of [...this.clients.values()]) {\n if (!c.behind) continue;\n if (c.catchUp !== null) this.timers.clear(c.catchUp);\n c.catchUp = null;\n this.catchUp(c);\n }\n }\n\n /** The entry is gone: no pause left, no timer, no client. */\n dispose(): void {\n this.release();\n this.flow = null;\n if (this.window !== null) this.timers.clear(this.window);\n this.window = null;\n if (this.frame) this.timers.clear(this.frame.timer);\n this.frame = null;\n for (const c of this.clients.values()) if (c.catchUp !== null) this.timers.clear(c.catchUp);\n this.clients.clear();\n this.pending = [];\n this.pendingLength = 0;\n this.tail.clear();\n // Nobody waits for a frame of an entry that is gone.\n for (const fn of this.waiting.splice(0)) fn(true);\n }\n\n /** A piece of output after which a synchronized frame is `open` (or not): held while one is, else coalesced. */\n private piece(text: string, open: boolean): void {\n this.tail.push(text);\n if (this.frame) {\n this.hold(text);\n if (!open) this.frameEnded();\n else if (this.pendingLength > FRAME_HOLD_MAX_CHARS) this.letFrameGo(true);\n return;\n }\n if (open && !this.letGo) {\n // A frame starts: held from here, with what was pending before it, until it ends (one frame on the wire).\n this.frame = { timer: this.timers.set(() => this.letFrameGo(this.sync.open), FRAME_HOLD_MS) };\n this.hold(text);\n return;\n }\n if (!open) this.letGo = false;\n // What was pending ends where this piece starts: the tail has this piece already, the frame doesn't.\n if (this.pendingLength && this.pendingLength + text.length > MAX_FRAME_CHARS) this.flushPending(this.offset - text.length);\n if (this.window === null) {\n this.window = this.timers.set(() => this.windowEnd(), COALESCE_MS);\n this.deliver(text);\n return;\n }\n this.hold(text);\n }\n\n private hold(text: string): void {\n this.pending.push(text);\n this.pendingLength += text.length;\n }\n\n /** The frame being held ended: it goes out now, whole, and then what waited for its end. */\n private frameEnded(): void {\n if (!this.frame) return;\n this.timers.clear(this.frame.timer);\n this.frame = null;\n this.flushPending();\n this.afterFrame();\n }\n\n /**\n * Stop holding the frame (its cap, a client joining mid-frame, the process stopping): what is held goes out with\n * what is pending, and what waited for its end goes on. `stillOpen`: the rest of it flows as any output does.\n */\n private letFrameGo(stillOpen: boolean): void {\n if (!this.frame) return;\n this.timers.clear(this.frame.timer);\n this.frame = null;\n this.letGo = stillOpen;\n this.flushPending();\n this.afterFrame();\n }\n\n private afterFrame(): void {\n for (const fn of this.waiting.splice(0)) fn(false);\n this.evaluate();\n }\n\n private windowEnd(): void {\n this.window = null;\n // Quiet: the next output goes at once. A frame being held goes when it ends.\n if (!this.pendingLength || this.frame) return;\n this.window = this.timers.set(() => this.windowEnd(), COALESCE_MS);\n this.flushPending();\n }\n\n /** 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). */\n private flushPending(end = this.offset): void {\n if (!this.pendingLength) return;\n const frame = this.pending.length === 1 ? this.pending[0] : this.pending.join('');\n this.pending = [];\n this.pendingLength = 0;\n this.deliver(frame, end);\n }\n\n private deliver(frame: string, end = this.offset): void {\n for (const c of this.clients.values()) {\n if (c.behind) continue;\n c.sent += frame.length;\n c.at = end;\n try {\n c.client.send(frame, end);\n } catch {\n /* that client is gone */\n }\n }\n // Now that it was sent the whole frame (and so every query in it it may answer): one too far behind is sent no\n // more — unless it holds the PTY, which then waits for it instead.\n const holder = this.holder();\n for (const [key, c] of this.clients) {\n if (c.behind || !c.client.metered || c.sent - c.acked <= HIGH_WATERMARK) continue;\n if (key === holder && this.flow && c.mayPause) continue;\n this.fallBehind(c);\n }\n this.evaluate();\n }\n\n /**\n * It is sent no more live output until it catches up. Caught up from the tail last time, and fallen behind again before\n * it acked anything sent after (so before it drew past what it missed): it is slower than the output, and sending it all\n * again would only keep it behind — its next catch-up is a screen, which skips to where the output stands.\n */\n private fallBehind(c: ClientState): void {\n c.behind = true;\n c.screenNext = c.continuedAt !== null && c.acked <= c.continuedAt;\n }\n\n /**\n * Pause the PTY for its holder above HIGH_WATERMARK, resume it below LOW_WATERMARK — or when nobody holds it any more.\n * Never paused mid-frame: the rest of the frame could not be read, nor the frame sent, until the pause timed out.\n */\n private evaluate(): void {\n const key = this.holder();\n const h = key === null ? undefined : this.clients.get(key);\n const holds = !!h && !!this.flow && h.client.metered && !h.behind && h.mayPause;\n if (this.paused) {\n if (holds && this.paused.by === h && h.sent - h.acked >= LOW_WATERMARK) return; // still waiting for it\n this.release();\n }\n if (holds && !this.frame && h.sent - h.acked > HIGH_WATERMARK) this.pause(h);\n }\n\n private pause(h: ClientState): void {\n try {\n this.flow?.pause();\n } catch {\n return; // its process is gone: nothing to wait for\n }\n this.paused = { by: h, timer: this.timers.set(() => this.timedOut(h), PAUSE_TIMEOUT_MS) };\n }\n\n private release(): void {\n if (!this.paused) return;\n this.timers.clear(this.paused.timer);\n this.paused = null;\n try {\n this.flow?.resume();\n } catch {\n /* its process is gone */\n }\n }\n\n /** The PTY waited for its holder long enough: it goes on, and the holder is behind (what was pending went to it first). */\n private timedOut(h: ClientState): void {\n if (this.paused?.by !== h) return;\n // A frame begun in output read just before the pause goes to it too: it may hold a query it was chosen to answer.\n this.letFrameGo(this.sync.open);\n this.flushPending();\n this.fallBehind(h);\n h.mayPause = false;\n this.release();\n this.evaluate();\n }\n\n private scheduleCatchUp(c: ClientState): void {\n if (c.catchUp !== null || c.sent - c.acked >= LOW_WATERMARK) return;\n const wait = c.snapshotAt + CATCH_UP_MIN_MS - this.timers.now();\n if (wait > 0) {\n c.catchUp = this.timers.set(() => {\n c.catchUp = null;\n this.catchUp(c);\n }, wait);\n return;\n }\n this.catchUp(c);\n }\n\n /**\n * It caught up: what arrived meanwhile goes to the others (what it is sent now has it), then it is sent what it missed\n * from the tail, or a screen, and live output — between frames: its screen is never one drawn halfway, and what it\n * missed never ends inside one.\n */\n private catchUp(c: ClientState): void {\n if (!c.behind || ![...this.clients.values()].includes(c)) return;\n if (this.frame) {\n if (!c.catchUpAfterFrame) {\n c.catchUpAfterFrame = true;\n this.waiting.push(() => {\n c.catchUpAfterFrame = false;\n this.catchUp(c);\n });\n }\n return;\n }\n this.flushPending();\n const from = c.screenNext ? null : c.at;\n c.behind = false;\n c.screenNext = false;\n c.snapshotAt = this.timers.now();\n c.at = this.offset;\n let continued = false;\n try {\n continued = c.client.resync(from) === true;\n } catch {\n /* that client is gone */\n }\n c.continuedAt = continued ? c.sent : null;\n this.evaluate();\n }\n}\n","import crypto from 'node:crypto';\n\n/**\n * One-time tickets that let a dashboard page connect its Terminal tab straight to the PTY host, not through work web\n * (reported: typing lagged in the app while `work attach` in Windows Terminal — the same host, no work web — was\n * smooth; work web's event loop stalls every minute or so, and each keystroke and echo waited on it).\n *\n * work web asks for one with the host's token (which never leaves work web) after its own checks — the session may\n * run its agent here, it was started — and hands the page an address with the ticket. The host takes a connection\n * with it once: for that one terminal, from the page's own origin, within `TICKET_TTL_MS`. A ticket used for another\n * terminal or from another origin is burnt all the same. Pure but for the random ticket.\n */\n\nexport const TICKET_TTL_MS = 30_000;\n\n/** The origins a ticket may be for: a page served on this machine (work web's, the desktop app's window). */\nconst LOOPBACK_ORIGIN = /^https?:\\/\\/(?:127\\.0\\.0\\.1|localhost|\\[::1\\])(?::\\d{1,5})?$/;\n\nexport const isLoopbackOrigin = (origin: string): boolean => LOOPBACK_ORIGIN.test(origin);\n\nexport interface TicketBook {\n /** A ticket for this terminal and origin; null for an origin that isn't a page on this machine. */\n issue(id: string, origin: string): string | null;\n /** Whether this connection may use the ticket: true once, for its terminal, from its origin, before it expires. */\n redeem(ticket: string, id: string, origin: string | undefined): boolean;\n}\n\nexport function createTicketBook(now: () => number = Date.now): TicketBook {\n const book = new Map<string, { id: string; origin: string; expires: number }>();\n const sweep = () => {\n const t = now();\n for (const [k, v] of book) if (v.expires <= t) book.delete(k);\n };\n return {\n issue(id, origin) {\n if (!id || !isLoopbackOrigin(origin)) return null;\n sweep();\n const ticket = crypto.randomBytes(24).toString('hex');\n book.set(ticket, { id, origin, expires: now() + TICKET_TTL_MS });\n return ticket;\n },\n redeem(ticket, id, origin) {\n const t = book.get(ticket);\n if (!t) return false;\n book.delete(ticket); // once, whatever happens next\n return t.expires > now() && t.id === id && t.origin === origin;\n },\n };\n}\n","/**\n * What a terminal sends with nobody typing: answers to the agent's queries, and reports nobody asked for (focus\n * in/out, the mouse moving with no button down). Every attached client answers a query, and a hidden one still\n * reports focus, so none of these count as using a client (the PTY's size follows the client used last,\n * pty-host.ts). Only one of them answers the agent (terminal-rendering.md, \"Who answers a query\"). Pure.\n */\n\n/** One sequence of what a terminal sent on its own. */\nexport interface ReplyPart {\n text: string;\n /** An answer to a query (only the client answering the agent's queries gets it through); false: a focus or mouse-motion report. */\n answer: boolean;\n}\n\n/** Focus in/out, and the mouse moving with no button down (SGR motion reports, codes 35 + modifiers), which hovering sends. */\nconst REPORT = String.raw`\\x1b\\[[IO]|\\x1b\\[<(?:35|39|43|47|51|55|59|63);\\d+;\\d+M`;\n/**\n * Answers: device attributes, cursor position (and DECXCPR's `CSI ? row ; col R`), status, kitty keyboard flags,\n * DECRPM, window reports, OSC / DCS / APC replies. A cursor-position report at row 1 and columns 2–8 looks just like\n * Shift/Alt/Ctrl+F3 (`ESC[1;2R` …), so it is taken for the key.\n */\nconst 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\\\\`;\nconst PART = new RegExp(`(${REPORT})|(?:${ANSWER})`, 'y');\n\n/** `data` as the replies it is made of, in order; null when anything in it is not one (typing, or typing and replies in one frame). */\nexport function replyParts(data: string): ReplyPart[] | null {\n if (!data) return null;\n const parts: ReplyPart[] = [];\n PART.lastIndex = 0;\n while (PART.lastIndex < data.length) {\n const at = PART.lastIndex;\n const m = PART.exec(data);\n if (!m || m.index !== at || !m[0]) return null;\n parts.push({ text: m[0], answer: m[1] === undefined });\n }\n return parts;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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