@moberg_hr/work-tree 2.17.1 → 2.18.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 (261) hide show
  1. package/dist/{account-PA3RHK4E.js → account-TT5TOV7Y.js} +25 -22
  2. package/dist/{account-PA3RHK4E.js.map → account-TT5TOV7Y.js.map} +1 -1
  3. package/dist/{add-repo-QI7XUFKB.js → add-repo-LM5M2TW4.js} +20 -17
  4. package/dist/{add-repo-QI7XUFKB.js.map → add-repo-LM5M2TW4.js.map} +1 -1
  5. package/dist/{answer-EAVRRXCR.js → answer-Q47UH37K.js} +12 -9
  6. package/dist/{answer-EAVRRXCR.js.map → answer-Q47UH37K.js.map} +1 -1
  7. package/dist/{attach-T7YF5P37.js → attach-JMA4XCEB.js} +20 -17
  8. package/dist/{attach-T7YF5P37.js.map → attach-JMA4XCEB.js.map} +1 -1
  9. package/dist/bin.js +3 -3
  10. package/dist/{block-N63GSISZ.js → block-TTMTQ5WO.js} +13 -10
  11. package/dist/{block-N63GSISZ.js.map → block-TTMTQ5WO.js.map} +1 -1
  12. package/dist/{broadcast-OD4WMWM2.js → broadcast-MQL3PHVK.js} +9 -6
  13. package/dist/{broadcast-OD4WMWM2.js.map → broadcast-MQL3PHVK.js.map} +1 -1
  14. package/dist/{catchup-OSTBIVR3.js → catchup-DKD3BGTG.js} +14 -11
  15. package/dist/{catchup-OSTBIVR3.js.map → catchup-DKD3BGTG.js.map} +1 -1
  16. package/dist/{chunk-UBGZM3TD.js → chunk-3OUUWNK2.js} +6 -6
  17. package/dist/{chunk-UKEI5DJS.js → chunk-4J2F6OWM.js} +2 -2
  18. package/dist/{chunk-2H3WHT32.js → chunk-5JRO64D4.js} +2 -2
  19. package/dist/{chunk-4KL62W3H.js → chunk-63RNLC25.js} +2 -2
  20. package/dist/{chunk-JVN3AHWH.js → chunk-7PKIZVR7.js} +5 -5
  21. package/dist/{chunk-KNGK73TF.js → chunk-AQKPXFC2.js} +3 -3
  22. package/dist/{chunk-NFST7BLF.js → chunk-ARQSFOYE.js} +3 -3
  23. package/dist/chunk-BR6OWWAA.js +64 -0
  24. package/dist/chunk-BR6OWWAA.js.map +1 -0
  25. package/dist/{chunk-SPCANSN2.js → chunk-C2BFHQHX.js} +4 -4
  26. package/dist/{chunk-DHF2USLL.js → chunk-CZWZMRQ3.js} +17 -5
  27. package/dist/chunk-CZWZMRQ3.js.map +1 -0
  28. package/dist/{chunk-ZCFKFAOT.js → chunk-D77U5ELL.js} +2 -2
  29. package/dist/chunk-D77U5ELL.js.map +1 -0
  30. package/dist/{chunk-A5OQHOEV.js → chunk-DA2KILWV.js} +2 -2
  31. package/dist/{chunk-63HMFHNG.js → chunk-DLV7TRON.js} +2 -2
  32. package/dist/{chunk-ZFFWFVER.js → chunk-E25DJVBD.js} +2 -2
  33. package/dist/{chunk-LD5EGGW6.js → chunk-EP7LCLHB.js} +5 -5
  34. package/dist/{chunk-OX4QHT4Y.js → chunk-ESEIPUMT.js} +2 -2
  35. package/dist/{chunk-IYXZFXO5.js → chunk-FAGTMW6W.js} +2 -2
  36. package/dist/{chunk-GEMTSSVY.js → chunk-FJADRDML.js} +4 -4
  37. package/dist/{chunk-IWMODEU4.js → chunk-GR4LV3ZS.js} +4 -4
  38. package/dist/{chunk-REPFZIPP.js → chunk-HGB7BITW.js} +16 -70
  39. package/dist/chunk-HGB7BITW.js.map +1 -0
  40. package/dist/{chunk-NKHTQHYM.js → chunk-HREHEBL2.js} +9 -9
  41. package/dist/{chunk-4MBK25I7.js → chunk-IALCEDTH.js} +13 -13
  42. package/dist/{chunk-ZQY52HIP.js → chunk-JEH4X76F.js} +2 -2
  43. package/dist/{chunk-34WI4R2U.js → chunk-JIK4FY3E.js} +3 -3
  44. package/dist/{chunk-P5XCHHR6.js → chunk-JPXEX3XW.js} +2 -2
  45. package/dist/{chunk-DOYJR2HF.js → chunk-JUGF3YE7.js} +5 -4
  46. package/dist/chunk-JUGF3YE7.js.map +1 -0
  47. package/dist/chunk-KGHWHAVF.js +24 -0
  48. package/dist/chunk-KGHWHAVF.js.map +1 -0
  49. package/dist/{chunk-CI2M7BKU.js → chunk-KQ7QLBY2.js} +3 -3
  50. package/dist/{chunk-2PRMDZBI.js → chunk-KX6KZYU4.js} +3 -3
  51. package/dist/{chunk-UVZITL47.js → chunk-LK7HJGUC.js} +1 -1
  52. package/dist/chunk-LK7HJGUC.js.map +1 -0
  53. package/dist/{chunk-XNLJDPSH.js → chunk-LVNRPAQK.js} +9 -9
  54. package/dist/{chunk-UC7LKU2U.js → chunk-NBLF2SNP.js} +4 -4
  55. package/dist/{chunk-I3RYSDAH.js → chunk-NGB2K7HX.js} +2 -2
  56. package/dist/{chunk-OHMLCXRW.js → chunk-O22DNTKU.js} +21 -26
  57. package/dist/chunk-O22DNTKU.js.map +1 -0
  58. package/dist/{chunk-KC3A7ZKN.js → chunk-OEQASHE3.js} +54 -54
  59. package/dist/{chunk-24FC64HP.js → chunk-PLTFWTIE.js} +3 -3
  60. package/dist/chunk-PSEVXDTS.js +104 -0
  61. package/dist/chunk-PSEVXDTS.js.map +1 -0
  62. package/dist/{chunk-MSBPZVVJ.js → chunk-QEZGXU5Q.js} +5 -5
  63. package/dist/{chunk-3A3HSUBD.js → chunk-QHFUCX2J.js} +2 -2
  64. package/dist/{chunk-XGE3OPXP.js → chunk-RNEN6NUX.js} +3 -3
  65. package/dist/{chunk-WK5ZIO6B.js → chunk-SFFAPGA5.js} +2 -2
  66. package/dist/{chunk-O3YVUM4P.js → chunk-T3KZSJHU.js} +5 -5
  67. package/dist/{chunk-A4KVQ6ZI.js → chunk-TI2CNJLD.js} +4 -4
  68. package/dist/{chunk-7WOSK73E.js → chunk-U4INTLIY.js} +5 -5
  69. package/dist/chunk-UKPZXS5B.js +9 -0
  70. package/dist/{chunk-QWU67XGR.js → chunk-V6KHER6C.js} +5 -5
  71. package/dist/{chunk-UR2NJS4C.js → chunk-VEERK6HO.js} +2 -2
  72. package/dist/{chunk-7FYYBKJ3.js → chunk-VFRJO737.js} +8 -8
  73. package/dist/{chunk-3L67MINA.js → chunk-VFZI4SAH.js} +2 -2
  74. package/dist/{chunk-4TTIEI7I.js → chunk-VRMALBZK.js} +2 -2
  75. package/dist/{chunk-JHCR7H4Y.js → chunk-WIYDT3PY.js} +5 -29
  76. package/dist/chunk-WIYDT3PY.js.map +1 -0
  77. package/dist/{chunk-O6GOH6QL.js → chunk-WVZG5Q4L.js} +2 -2
  78. package/dist/{chunk-HN4BEMHV.js → chunk-XFWO5FYK.js} +3 -3
  79. package/dist/{chunk-DOESL4MD.js → chunk-XPX5AAYH.js} +3 -3
  80. package/dist/{chunk-XGRMJHE6.js → chunk-XUO5F4JU.js} +3 -3
  81. package/dist/{chunk-S6V3G3J5.js → chunk-YCCZKF4F.js} +3 -3
  82. package/dist/chunk-YQSWVHKK.js +33 -0
  83. package/dist/chunk-YQSWVHKK.js.map +1 -0
  84. package/dist/{chunk-MQXGUZAX.js → chunk-Z4MI3HBV.js} +5 -5
  85. package/dist/{chunk-VCWQ4VED.js → chunk-Z5TRUCIA.js} +9 -9
  86. package/dist/{chunk-FXJOUAWP.js → chunk-ZKSITAVC.js} +4 -4
  87. package/dist/{cleanup-6JAMAF6I.js → cleanup-MW27IU2D.js} +31 -28
  88. package/dist/{cleanup-6JAMAF6I.js.map → cleanup-MW27IU2D.js.map} +1 -1
  89. package/dist/{cli-K2CH3CIU.js → cli-QVGLGPQB.js} +3 -3
  90. package/dist/{color-EHNTMQIE.js → color-RGMFJAHN.js} +11 -8
  91. package/dist/{color-EHNTMQIE.js.map → color-RGMFJAHN.js.map} +1 -1
  92. package/dist/{config-4VEKBBLZ.js → config-AWVOZGZR.js} +11 -8
  93. package/dist/{config-4VEKBBLZ.js.map → config-AWVOZGZR.js.map} +1 -1
  94. package/dist/{diff-OOH5HOXG.js → diff-WJKZRFRM.js} +12 -9
  95. package/dist/{diff-OOH5HOXG.js.map → diff-WJKZRFRM.js.map} +1 -1
  96. package/dist/{digest-ZNYODJ3A.js → digest-OX5NEL2K.js} +11 -8
  97. package/dist/{digest-ZNYODJ3A.js.map → digest-OX5NEL2K.js.map} +1 -1
  98. package/dist/{fork-OFRN64IT.js → fork-4AAA7GAX.js} +32 -29
  99. package/dist/{fork-OFRN64IT.js.map → fork-4AAA7GAX.js.map} +1 -1
  100. package/dist/{history-QNEYVVPI.js → history-MMA6YXFH.js} +9 -6
  101. package/dist/{hook-3LE6BWLO.js → hook-MOC7MYLG.js} +16 -13
  102. package/dist/{hook-3LE6BWLO.js.map → hook-MOC7MYLG.js.map} +1 -1
  103. package/dist/{hydrate-2KSEV4E2.js → hydrate-EGS47UUM.js} +9 -6
  104. package/dist/{hydrate-2KSEV4E2.js.map → hydrate-EGS47UUM.js.map} +1 -1
  105. package/dist/{init-M664MBPZ.js → init-QOFM5BTW.js} +14 -11
  106. package/dist/{init-M664MBPZ.js.map → init-QOFM5BTW.js.map} +1 -1
  107. package/dist/{install-skills-LAFRMJ7N.js → install-skills-E24KULUM.js} +9 -6
  108. package/dist/install-skills-bin.js +8 -5
  109. package/dist/install-skills-bin.js.map +1 -1
  110. package/dist/{keep-I4BRQQWG.js → keep-WLDMR63Z.js} +11 -8
  111. package/dist/{keep-I4BRQQWG.js.map → keep-WLDMR63Z.js.map} +1 -1
  112. package/dist/{list-NUYPCYLY.js → list-YJ6BSG2M.js} +9 -6
  113. package/dist/{list-NUYPCYLY.js.map → list-YJ6BSG2M.js.map} +1 -1
  114. package/dist/{move-WYMMOZMK.js → move-AGSZHGWY.js} +21 -18
  115. package/dist/{move-WYMMOZMK.js.map → move-AGSZHGWY.js.map} +1 -1
  116. package/dist/{note-ZRWRTFJG.js → note-GCNBL5A2.js} +11 -8
  117. package/dist/{note-ZRWRTFJG.js.map → note-GCNBL5A2.js.map} +1 -1
  118. package/dist/{overlaps-YNU6JCTT.js → overlaps-X3YDTLTV.js} +15 -12
  119. package/dist/{overlaps-YNU6JCTT.js.map → overlaps-X3YDTLTV.js.map} +1 -1
  120. package/dist/{pin-36BGIIMW.js → pin-22MYV72V.js} +11 -8
  121. package/dist/{pin-36BGIIMW.js.map → pin-22MYV72V.js.map} +1 -1
  122. package/dist/{pr-6YPNUHRI.js → pr-YRQYEWL7.js} +27 -24
  123. package/dist/{pr-6YPNUHRI.js.map → pr-YRQYEWL7.js.map} +1 -1
  124. package/dist/{prune-LINCOW7H.js → prune-7RV6GMHU.js} +29 -26
  125. package/dist/{prune-LINCOW7H.js.map → prune-7RV6GMHU.js.map} +1 -1
  126. package/dist/{pty-host-CE57F776.js → pty-host-PUVNAZ3F.js} +16 -13
  127. package/dist/{pty-host-CE57F776.js.map → pty-host-PUVNAZ3F.js.map} +1 -1
  128. package/dist/{read-MX7ZURF3.js → read-BOB63DIH.js} +11 -8
  129. package/dist/{read-MX7ZURF3.js.map → read-BOB63DIH.js.map} +1 -1
  130. package/dist/{recent-FU4Z4AFU.js → recent-S2JIDTHB.js} +16 -13
  131. package/dist/{recent-FU4Z4AFU.js.map → recent-S2JIDTHB.js.map} +1 -1
  132. package/dist/{remove-BTZAZ6ZA.js → remove-EKBQROBE.js} +30 -27
  133. package/dist/{remove-BTZAZ6ZA.js.map → remove-EKBQROBE.js.map} +1 -1
  134. package/dist/{restart-AX3FNSDF.js → restart-UM7XOGDO.js} +11 -8
  135. package/dist/{restart-AX3FNSDF.js.map → restart-UM7XOGDO.js.map} +1 -1
  136. package/dist/{resume-LR4ILRBQ.js → resume-BFE6ETTN.js} +16 -13
  137. package/dist/{resume-LR4ILRBQ.js.map → resume-BFE6ETTN.js.map} +1 -1
  138. package/dist/{review-4K2FBZES.js → review-XQG3AEMG.js} +16 -62
  139. package/dist/review-XQG3AEMG.js.map +1 -0
  140. package/dist/{run-65HDAKBN.js → run-KFICX2JE.js} +9 -6
  141. package/dist/{run-65HDAKBN.js.map → run-KFICX2JE.js.map} +1 -1
  142. package/dist/{screen-NOYYOB5G.js → screen-2B66BGKO.js} +11 -8
  143. package/dist/{screen-NOYYOB5G.js.map → screen-2B66BGKO.js.map} +1 -1
  144. package/dist/{search-YQYEF4DW.js → search-3MXCGLOL.js} +9 -6
  145. package/dist/{search-YQYEF4DW.js.map → search-3MXCGLOL.js.map} +1 -1
  146. package/dist/{section-6HLNG5GQ.js → section-QJV7ENVX.js} +11 -8
  147. package/dist/{section-6HLNG5GQ.js.map → section-QJV7ENVX.js.map} +1 -1
  148. package/dist/{send-IBCRUS7B.js → send-LAAEMPZQ.js} +13 -10
  149. package/dist/{send-IBCRUS7B.js.map → send-LAAEMPZQ.js.map} +1 -1
  150. package/dist/{sessions-IJK4DPMU.js → sessions-TWN3F43J.js} +29 -26
  151. package/dist/{sessions-IJK4DPMU.js.map → sessions-TWN3F43J.js.map} +1 -1
  152. package/dist/{show-CSGVG5BL.js → show-JFRJVS3G.js} +10 -7
  153. package/dist/{show-CSGVG5BL.js.map → show-JFRJVS3G.js.map} +1 -1
  154. package/dist/{snooze-NNQXOPNI.js → snooze-RRPHFFMD.js} +11 -8
  155. package/dist/{snooze-NNQXOPNI.js.map → snooze-RRPHFFMD.js.map} +1 -1
  156. package/dist/{start-I3CLQ2CJ.js → start-XTEZKSA3.js} +11 -8
  157. package/dist/{start-I3CLQ2CJ.js.map → start-XTEZKSA3.js.map} +1 -1
  158. package/dist/{status-XCJGTMB4.js → status-2BFFMHO2.js} +13 -10
  159. package/dist/{status-XCJGTMB4.js.map → status-2BFFMHO2.js.map} +1 -1
  160. package/dist/{statusline-NEVXTHUY.js → statusline-B6U3ANSM.js} +3 -2
  161. package/dist/{statusline-NEVXTHUY.js.map → statusline-B6U3ANSM.js.map} +1 -1
  162. package/dist/{statusline-hook-H5MM2PA2.js → statusline-hook-SYRLMSDL.js} +7 -5
  163. package/dist/{statusline-hook-H5MM2PA2.js.map → statusline-hook-SYRLMSDL.js.map} +1 -1
  164. package/dist/{stop-JVMDCXB4.js → stop-I6WWTUFP.js} +11 -8
  165. package/dist/{stop-JVMDCXB4.js.map → stop-I6WWTUFP.js.map} +1 -1
  166. package/dist/{sync-E2GXLD6K.js → sync-SB5JN2EN.js} +29 -26
  167. package/dist/{sync-E2GXLD6K.js.map → sync-SB5JN2EN.js.map} +1 -1
  168. package/dist/{time-KBS66SV5.js → time-IEFF5FEV.js} +12 -9
  169. package/dist/{time-KBS66SV5.js.map → time-IEFF5FEV.js.map} +1 -1
  170. package/dist/{timesheet-XUMTURH5.js → timesheet-RRK4ENUU.js} +14 -11
  171. package/dist/{timesheet-XUMTURH5.js.map → timesheet-RRK4ENUU.js.map} +1 -1
  172. package/dist/{tree-CZUUTSZX.js → tree-G4ATBUTH.js} +28 -25
  173. package/dist/{tree-CZUUTSZX.js.map → tree-G4ATBUTH.js.map} +1 -1
  174. package/dist/{update-7NU3M4DL.js → update-LSDD3ZDO.js} +17 -14
  175. package/dist/{update-7NU3M4DL.js.map → update-LSDD3ZDO.js.map} +1 -1
  176. package/dist/{usage-GCZV3GDA.js → usage-CTT5CMQK.js} +15 -10
  177. package/dist/usage-CTT5CMQK.js.map +1 -0
  178. package/dist/usage-ask-YJNTOGXY.js +176 -0
  179. package/dist/usage-ask-YJNTOGXY.js.map +1 -0
  180. package/dist/{version-U2QIALPO.js → version-6UJN2CCE.js} +3 -2
  181. package/dist/{version-U2QIALPO.js.map → version-6UJN2CCE.js.map} +1 -1
  182. package/dist/{wait-OHES2ZLG.js → wait-2L67BLEO.js} +13 -10
  183. package/dist/{wait-OHES2ZLG.js.map → wait-2L67BLEO.js.map} +1 -1
  184. package/dist/wd-bin.js +2 -2
  185. package/dist/web/assets/{PtyView-CjtGMoNT.js → PtyView-DhDNPvL9.js} +2 -2
  186. package/dist/web/assets/{PtyView-CjtGMoNT.js.map → PtyView-DhDNPvL9.js.map} +1 -1
  187. package/dist/web/assets/{index-CBymxw_N.css → index-B1gUTG37.css} +1 -1
  188. package/dist/web/assets/index-CfBb7suR.js +126 -0
  189. package/dist/web/assets/index-CfBb7suR.js.map +1 -0
  190. package/dist/web/index.html +2 -2
  191. package/dist/{web-OQLZHYOM.js → web-MUO46QAX.js} +178 -159
  192. package/dist/web-MUO46QAX.js.map +1 -0
  193. package/npm-shrinkwrap.json +2 -2
  194. package/package.json +1 -1
  195. package/dist/chunk-DHF2USLL.js.map +0 -1
  196. package/dist/chunk-DOYJR2HF.js.map +0 -1
  197. package/dist/chunk-E22Y75WX.js +0 -9
  198. package/dist/chunk-JHCR7H4Y.js.map +0 -1
  199. package/dist/chunk-KL7RY6UG.js +0 -36
  200. package/dist/chunk-KL7RY6UG.js.map +0 -1
  201. package/dist/chunk-OHMLCXRW.js.map +0 -1
  202. package/dist/chunk-REPFZIPP.js.map +0 -1
  203. package/dist/chunk-UVZITL47.js.map +0 -1
  204. package/dist/chunk-ZCFKFAOT.js.map +0 -1
  205. package/dist/review-4K2FBZES.js.map +0 -1
  206. package/dist/usage-GCZV3GDA.js.map +0 -1
  207. package/dist/web/assets/index-BIugalNC.js +0 -126
  208. package/dist/web/assets/index-BIugalNC.js.map +0 -1
  209. package/dist/web-OQLZHYOM.js.map +0 -1
  210. /package/dist/{chunk-UBGZM3TD.js.map → chunk-3OUUWNK2.js.map} +0 -0
  211. /package/dist/{chunk-UKEI5DJS.js.map → chunk-4J2F6OWM.js.map} +0 -0
  212. /package/dist/{chunk-2H3WHT32.js.map → chunk-5JRO64D4.js.map} +0 -0
  213. /package/dist/{chunk-4KL62W3H.js.map → chunk-63RNLC25.js.map} +0 -0
  214. /package/dist/{chunk-JVN3AHWH.js.map → chunk-7PKIZVR7.js.map} +0 -0
  215. /package/dist/{chunk-KNGK73TF.js.map → chunk-AQKPXFC2.js.map} +0 -0
  216. /package/dist/{chunk-NFST7BLF.js.map → chunk-ARQSFOYE.js.map} +0 -0
  217. /package/dist/{chunk-SPCANSN2.js.map → chunk-C2BFHQHX.js.map} +0 -0
  218. /package/dist/{chunk-A5OQHOEV.js.map → chunk-DA2KILWV.js.map} +0 -0
  219. /package/dist/{chunk-63HMFHNG.js.map → chunk-DLV7TRON.js.map} +0 -0
  220. /package/dist/{chunk-ZFFWFVER.js.map → chunk-E25DJVBD.js.map} +0 -0
  221. /package/dist/{chunk-LD5EGGW6.js.map → chunk-EP7LCLHB.js.map} +0 -0
  222. /package/dist/{chunk-OX4QHT4Y.js.map → chunk-ESEIPUMT.js.map} +0 -0
  223. /package/dist/{chunk-IYXZFXO5.js.map → chunk-FAGTMW6W.js.map} +0 -0
  224. /package/dist/{chunk-GEMTSSVY.js.map → chunk-FJADRDML.js.map} +0 -0
  225. /package/dist/{chunk-IWMODEU4.js.map → chunk-GR4LV3ZS.js.map} +0 -0
  226. /package/dist/{chunk-NKHTQHYM.js.map → chunk-HREHEBL2.js.map} +0 -0
  227. /package/dist/{chunk-4MBK25I7.js.map → chunk-IALCEDTH.js.map} +0 -0
  228. /package/dist/{chunk-ZQY52HIP.js.map → chunk-JEH4X76F.js.map} +0 -0
  229. /package/dist/{chunk-34WI4R2U.js.map → chunk-JIK4FY3E.js.map} +0 -0
  230. /package/dist/{chunk-P5XCHHR6.js.map → chunk-JPXEX3XW.js.map} +0 -0
  231. /package/dist/{chunk-CI2M7BKU.js.map → chunk-KQ7QLBY2.js.map} +0 -0
  232. /package/dist/{chunk-2PRMDZBI.js.map → chunk-KX6KZYU4.js.map} +0 -0
  233. /package/dist/{chunk-XNLJDPSH.js.map → chunk-LVNRPAQK.js.map} +0 -0
  234. /package/dist/{chunk-UC7LKU2U.js.map → chunk-NBLF2SNP.js.map} +0 -0
  235. /package/dist/{chunk-I3RYSDAH.js.map → chunk-NGB2K7HX.js.map} +0 -0
  236. /package/dist/{chunk-KC3A7ZKN.js.map → chunk-OEQASHE3.js.map} +0 -0
  237. /package/dist/{chunk-24FC64HP.js.map → chunk-PLTFWTIE.js.map} +0 -0
  238. /package/dist/{chunk-MSBPZVVJ.js.map → chunk-QEZGXU5Q.js.map} +0 -0
  239. /package/dist/{chunk-3A3HSUBD.js.map → chunk-QHFUCX2J.js.map} +0 -0
  240. /package/dist/{chunk-XGE3OPXP.js.map → chunk-RNEN6NUX.js.map} +0 -0
  241. /package/dist/{chunk-WK5ZIO6B.js.map → chunk-SFFAPGA5.js.map} +0 -0
  242. /package/dist/{chunk-O3YVUM4P.js.map → chunk-T3KZSJHU.js.map} +0 -0
  243. /package/dist/{chunk-A4KVQ6ZI.js.map → chunk-TI2CNJLD.js.map} +0 -0
  244. /package/dist/{chunk-7WOSK73E.js.map → chunk-U4INTLIY.js.map} +0 -0
  245. /package/dist/{chunk-E22Y75WX.js.map → chunk-UKPZXS5B.js.map} +0 -0
  246. /package/dist/{chunk-QWU67XGR.js.map → chunk-V6KHER6C.js.map} +0 -0
  247. /package/dist/{chunk-UR2NJS4C.js.map → chunk-VEERK6HO.js.map} +0 -0
  248. /package/dist/{chunk-7FYYBKJ3.js.map → chunk-VFRJO737.js.map} +0 -0
  249. /package/dist/{chunk-3L67MINA.js.map → chunk-VFZI4SAH.js.map} +0 -0
  250. /package/dist/{chunk-4TTIEI7I.js.map → chunk-VRMALBZK.js.map} +0 -0
  251. /package/dist/{chunk-O6GOH6QL.js.map → chunk-WVZG5Q4L.js.map} +0 -0
  252. /package/dist/{chunk-HN4BEMHV.js.map → chunk-XFWO5FYK.js.map} +0 -0
  253. /package/dist/{chunk-DOESL4MD.js.map → chunk-XPX5AAYH.js.map} +0 -0
  254. /package/dist/{chunk-XGRMJHE6.js.map → chunk-XUO5F4JU.js.map} +0 -0
  255. /package/dist/{chunk-S6V3G3J5.js.map → chunk-YCCZKF4F.js.map} +0 -0
  256. /package/dist/{chunk-MQXGUZAX.js.map → chunk-Z4MI3HBV.js.map} +0 -0
  257. /package/dist/{chunk-VCWQ4VED.js.map → chunk-Z5TRUCIA.js.map} +0 -0
  258. /package/dist/{chunk-FXJOUAWP.js.map → chunk-ZKSITAVC.js.map} +0 -0
  259. /package/dist/{cli-K2CH3CIU.js.map → cli-QVGLGPQB.js.map} +0 -0
  260. /package/dist/{history-QNEYVVPI.js.map → history-MMA6YXFH.js.map} +0 -0
  261. /package/dist/{install-skills-LAFRMJ7N.js.map → install-skills-E24KULUM.js.map} +0 -0
@@ -1 +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/terminal-tickets.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 { 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';\n\nconst ATTACH_PATH = /^\\/ptys\\/([^/?]+)\\/attach(?:\\?|$)/;\nconst PTY_PATH = /^\\/ptys\\/([^/?]+)(\\/write|\\/screen|\\/restart|\\/halt|\\/resume)?$/;\nconst MAX_BODY = 1024 * 1024;\n\n/**\n * Input a terminal sends on its own, with nobody typing: focus in/out, answers to the agent's queries (device\n * attributes, cursor position, status, mode and keyboard-flag reports, window size), OSC / DCS / APC replies — and\n * the mouse moving with no button down (SGR motion reports, codes 35 + modifiers), which hovering over a terminal\n * sends. Every attached client answers a query, and a hidden one still reports focus, so these must not count as\n * using a client — only typing (keys, a paste, a click, a drag) does. A cursor-position report at row 1 and columns\n * 2–8 looks just like Shift/Alt/Ctrl+F3 (`ESC[1;2R` …), so it is taken for the key. Pure.\n */\nconst REPLY =\n /^(?:\\x1b\\[[IO]|\\x1b\\[[?>=][\\d;]*c|\\x1b\\[(?!1;[2-8]R)\\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\\\\|\\x1b\\[<(?:35|39|43|47|51|55|59|63);\\d+;\\d+M)+$/;\nexport function isTerminalReply(data: string): boolean {\n return REPLY.test(data);\n}\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 const registry = opts.registry ?? new PtyRegistry();\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 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 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 = 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 // Back to this client's grid first (a no-op when it is) — when someone typed in it, not for its own replies.\n if (size && !isTerminalReply(msg.data)) registry.resize(id, size.cols, size.rows);\n registry.write(id, msg.data);\n } else if (msg.type === 'resize' && Number.isInteger(msg.cols) && Number.isInteger(msg.rows)) {\n size = { cols: msg.cols, rows: msg.rows };\n registry.resize(id, msg.cols, msg.rows);\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 { 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';\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/** 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). Optional so test\n * fakes can fall back to the raw replay buffer. */\n serialize?(): string;\n /** The serialized screen once everything written so far is parsed (see\n * PtySession.serializeSettled). Optional: a fake's screen is its raw buffer. */\n serializeSettled?(): Promise<string>;\n /** Visible screen as plain text (PtySession.screenText). */\n screenText?(): string;\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}\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 ?? 120, spec.rows ?? 32, undefined, {\n tool: spec.tool,\n resume: spec.resume,\n port: spec.port,\n initialPrompt: spec.initialPrompt,\n env: spec.env,\n });\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 subscribers: Set<(data: string) => void>;\n exitSubscribers: Set<(code: number) => void>;\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}\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}\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 /** Serializes persistence writes inside this process. */\n private writeChain: Promise<void> = Promise.resolve();\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 }\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 const cols = spec.cols ?? 120;\n const rows = spec.rows ?? 32;\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 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 exitCode: null,\n lastOutputAt: Date.now(),\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 pty.setOutputHandler((data) => {\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 for (const cb of entry.subscribers) {\n try {\n cb(data);\n } catch {\n /* subscriber gone */\n }\n }\n });\n pty.onExit = (code) => {\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 /** 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 if (cols < 2 || rows < 2 || (cols === e.cols && rows === e.rows)) return;\n e.cols = cols;\n e.rows = rows;\n e.pty.resize(cols, rows);\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 attach(\n id: string,\n onData: (data: string) => void,\n onExit: (code: number) => void,\n ): {\n replay: ReplaySnapshot;\n ready: Promise<ReplaySnapshot>;\n start: () => void;\n detach: () => void;\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: string[] | null = settled ? [] : null;\n const sub = (d: string) => (held ? held.push(d) : onData(d));\n if (exitedWith === null) {\n e.subscribers.add(sub);\n e.exitSubscribers.add(onExit);\n }\n const snapshot = (data: string): ReplaySnapshot => ({ data, cols: e.cols, rows: e.rows });\n const replay = snapshot(restarting ? '' : e.pty.serialize?.() || e.replay);\n return {\n exitedWith,\n replay,\n ready: settled ? settled.call(e.pty).then((d) => snapshot(d || e.replay)) : Promise.resolve(replay),\n start: () => {\n const q = held;\n held = null;\n for (const d of q ?? []) onData(d);\n },\n detach: () => {\n e.subscribers.delete(sub);\n e.exitSubscribers.delete(onExit);\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 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 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 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 const stopped = await new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), timeoutMs);\n old.onExit = () => {\n clearTimeout(timer);\n resolve(true);\n };\n old.dispose();\n });\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 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 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 for (const e of this.entries.values()) {\n e.pty.onExit = undefined;\n e.subscribers.clear();\n e.exitSubscribers.clear();\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 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 };\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 snapshot[e.id] = { ...e.spec, 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 xtermHeadless from '@xterm/headless';\nimport xtermSerialize from '@xterm/addon-serialize';\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';\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\nconst { Terminal } = xtermHeadless;\nconst { SerializeAddon } = xtermSerialize;\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/** 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/** 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\nexport class PtySession {\n readonly pty: IPty;\n readonly terminal: InstanceType<typeof Terminal>;\n private readonly serializer = new SerializeAddon();\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 this.terminal = new Terminal({\n cols,\n rows,\n scrollback: 200,\n allowProposedApi: true,\n });\n this.terminal.loadAddon(this.serializer);\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> = 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 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 ...conptyOptions(process.platform, readUseBundledConpty()),\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 this.pty.onData((data) => {\n this.terminal.write(data);\n this.outputHandler?.(data);\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.terminal.resize(cols, rows);\n }\n }\n\n /**\n * The current screen + scrollback as escape sequences that redraw it\n * exactly (colors, cursor, modes, alt screen). 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(): string {\n try {\n return this.serializer.serialize();\n } catch {\n return '';\n }\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(): Promise<string> {\n return new Promise((resolve) => {\n try {\n this.terminal.write('', () => resolve(this.serialize()));\n } catch {\n resolve(this.serialize());\n }\n });\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 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 setOutputHandler(handler?: (data: string) => void) {\n this.outputHandler = handler;\n }\n\n dispose() {\n this.setOutputHandler(undefined);\n if (!this._exited) {\n try {\n this.pty.kill();\n } catch {\n /* PTY already exited */\n }\n }\n this.terminal.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 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,WAAW;;;ACAlB,OAAO,UAAU;AACjB,OAAOA,aAAY;AACnB,OAAOC,SAAQ;AACf,SAAS,uBAAuB;;;ACHhC,OAAOC,SAAQ;;;ACAf,OAAO,SAAwB;AAE/B,OAAO,gBAAgB;AACvB,OAAO,mBAAmB;AAC1B,OAAO,oBAAoB;AAK3B,OAAO,kBAAkB;AACzB,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;AACf,OAAOC,WAAU;;;ACZjB,OAAO,QAAQ;AACf,OAAO,UAAU;AAwBV,SAAS,0BACd,QACA,WAA4B,QAAQ,UACpC,OAAe,QAAQ,MACvB,IAAY,IACM;AAClB,QAAM,MAAwB,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,EAAE;AACtD,MAAI,aAAa,QAAS,QAAO;AACjC,aAAW,QAAQ;AAAA,IACjB,KAAK,KAAK,QAAQ,aAAa,GAAG,QAA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;AAClD,YAAM,UAAU,MAAM,SAAS,EAAE;AAAA,QAAM,CAAC,QACtC,eAAe,uBAAuB,eAAe,mBAAmB,OAAO;AAAA,MACjF;AACA,UAAI,QAAS,QAAO;AAIpB,sBAAgB;AAMhB,aAAO,aAAa;AAAA,IACtB,CAAC;AACD,QAAI,CAAC,QAAQ;AACX,WAAK,MAAM,KAAK,2BAA2B,CAAC;AAC5C;AAAA,IACF;AACA,SAAK,MAAM,KAAK,mCAAmC,OAAO,KAAK,IAAI,SAAS,QAAQ,GAAG,GAAG,CAAC;AAC3F,UAAM,WAAW,MAAM;AACrB,WAAK,OAAO,KAAK,EAAE,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC;AAAA,IAClD;AACA,YAAQ,GAAG,UAAU,QAAQ;AAC7B,YAAQ,GAAG,WAAW,QAAQ;AAC9B,UAAM,IAAI,QAAQ,MAAM;AAAA,IAAC,CAAC;AAAA,EAC5B;AACF;","names":["crypto","fs","fs","path","path","fs","pty","code","crypto","info","fs"]}
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/terminal-tickets.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 { 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';\n\nconst ATTACH_PATH = /^\\/ptys\\/([^/?]+)\\/attach(?:\\?|$)/;\nconst PTY_PATH = /^\\/ptys\\/([^/?]+)(\\/write|\\/screen|\\/restart|\\/halt|\\/resume)?$/;\nconst MAX_BODY = 1024 * 1024;\n\n/**\n * Input a terminal sends on its own, with nobody typing: focus in/out, answers to the agent's queries (device\n * attributes, cursor position, status, mode and keyboard-flag reports, window size), OSC / DCS / APC replies — and\n * the mouse moving with no button down (SGR motion reports, codes 35 + modifiers), which hovering over a terminal\n * sends. Every attached client answers a query, and a hidden one still reports focus, so these must not count as\n * using a client — only typing (keys, a paste, a click, a drag) does. A cursor-position report at row 1 and columns\n * 2–8 looks just like Shift/Alt/Ctrl+F3 (`ESC[1;2R` …), so it is taken for the key. Pure.\n */\nconst REPLY =\n /^(?:\\x1b\\[[IO]|\\x1b\\[[?>=][\\d;]*c|\\x1b\\[(?!1;[2-8]R)\\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\\\\|\\x1b\\[<(?:35|39|43|47|51|55|59|63);\\d+;\\d+M)+$/;\nexport function isTerminalReply(data: string): boolean {\n return REPLY.test(data);\n}\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 const registry = opts.registry ?? new PtyRegistry();\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 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 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 = 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 // Back to this client's grid first (a no-op when it is) — when someone typed in it, not for its own replies.\n if (size && !isTerminalReply(msg.data)) registry.resize(id, size.cols, size.rows);\n registry.write(id, msg.data);\n } else if (msg.type === 'resize' && Number.isInteger(msg.cols) && Number.isInteger(msg.rows)) {\n size = { cols: msg.cols, rows: msg.rows };\n registry.resize(id, msg.cols, msg.rows);\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 { 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';\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/** 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). Optional so test\n * fakes can fall back to the raw replay buffer. */\n serialize?(): string;\n /** The serialized screen once everything written so far is parsed (see\n * PtySession.serializeSettled). Optional: a fake's screen is its raw buffer. */\n serializeSettled?(): Promise<string>;\n /** Visible screen as plain text (PtySession.screenText). */\n screenText?(): string;\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}\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 ?? 120, spec.rows ?? 32, undefined, {\n tool: spec.tool,\n resume: spec.resume,\n port: spec.port,\n initialPrompt: spec.initialPrompt,\n env: spec.env,\n });\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 subscribers: Set<(data: string) => void>;\n exitSubscribers: Set<(code: number) => void>;\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}\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}\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 /** Serializes persistence writes inside this process. */\n private writeChain: Promise<void> = Promise.resolve();\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 }\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 const cols = spec.cols ?? 120;\n const rows = spec.rows ?? 32;\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 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 exitCode: null,\n lastOutputAt: Date.now(),\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 pty.setOutputHandler((data) => {\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 for (const cb of entry.subscribers) {\n try {\n cb(data);\n } catch {\n /* subscriber gone */\n }\n }\n });\n pty.onExit = (code) => {\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 /** 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 if (cols < 2 || rows < 2 || (cols === e.cols && rows === e.rows)) return;\n e.cols = cols;\n e.rows = rows;\n e.pty.resize(cols, rows);\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 attach(\n id: string,\n onData: (data: string) => void,\n onExit: (code: number) => void,\n ): {\n replay: ReplaySnapshot;\n ready: Promise<ReplaySnapshot>;\n start: () => void;\n detach: () => void;\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: string[] | null = settled ? [] : null;\n const sub = (d: string) => (held ? held.push(d) : onData(d));\n if (exitedWith === null) {\n e.subscribers.add(sub);\n e.exitSubscribers.add(onExit);\n }\n const snapshot = (data: string): ReplaySnapshot => ({ data, cols: e.cols, rows: e.rows });\n const replay = snapshot(restarting ? '' : e.pty.serialize?.() || e.replay);\n return {\n exitedWith,\n replay,\n ready: settled ? settled.call(e.pty).then((d) => snapshot(d || e.replay)) : Promise.resolve(replay),\n start: () => {\n const q = held;\n held = null;\n for (const d of q ?? []) onData(d);\n },\n detach: () => {\n e.subscribers.delete(sub);\n e.exitSubscribers.delete(onExit);\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 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 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 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 const stopped = await new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), timeoutMs);\n old.onExit = () => {\n clearTimeout(timer);\n resolve(true);\n };\n old.dispose();\n });\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 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 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 for (const e of this.entries.values()) {\n e.pty.onExit = undefined;\n e.subscribers.clear();\n e.exitSubscribers.clear();\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 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 };\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 snapshot[e.id] = { ...e.spec, 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 xtermHeadless from '@xterm/headless';\nimport xtermSerialize from '@xterm/addon-serialize';\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';\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\nconst { Terminal } = xtermHeadless;\nconst { SerializeAddon } = xtermSerialize;\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/** 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/** 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\nexport class PtySession {\n readonly pty: IPty;\n readonly terminal: InstanceType<typeof Terminal>;\n private readonly serializer = new SerializeAddon();\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 this.terminal = new Terminal({\n cols,\n rows,\n scrollback: 200,\n allowProposedApi: true,\n });\n this.terminal.loadAddon(this.serializer);\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> = 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 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 ...conptyOptions(process.platform, readUseBundledConpty()),\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 this.pty.onData((data) => {\n this.terminal.write(data);\n this.outputHandler?.(data);\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.terminal.resize(cols, rows);\n }\n }\n\n /**\n * The current screen + scrollback as escape sequences that redraw it\n * exactly (colors, cursor, modes, alt screen). 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(): string {\n try {\n return this.serializer.serialize();\n } catch {\n return '';\n }\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(): Promise<string> {\n return new Promise((resolve) => {\n try {\n this.terminal.write('', () => resolve(this.serialize()));\n } catch {\n resolve(this.serialize());\n }\n });\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 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 setOutputHandler(handler?: (data: string) => void) {\n this.outputHandler = handler;\n }\n\n dispose() {\n this.setOutputHandler(undefined);\n if (!this._exited) {\n try {\n this.pty.kill();\n } catch {\n /* PTY already exited */\n }\n }\n this.terminal.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 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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6,27 @@ import {
6
6
  import {
7
7
  sessionFromArgs,
8
8
  sessionPositionals
9
- } from "./chunk-NFST7BLF.js";
9
+ } from "./chunk-ARQSFOYE.js";
10
10
  import "./chunk-6AQRYLOB.js";
11
- import "./chunk-DOESL4MD.js";
11
+ import "./chunk-XPX5AAYH.js";
12
12
  import "./chunk-ZSHWP2VS.js";
13
13
  import "./chunk-CNZV3UCM.js";
14
14
  import "./chunk-HUXS3VAI.js";
15
- import "./chunk-ZCFKFAOT.js";
15
+ import "./chunk-D77U5ELL.js";
16
16
  import "./chunk-NEJVK5CF.js";
17
17
  import "./chunk-ALBTIOP3.js";
18
18
  import {
19
19
  agentOf
20
- } from "./chunk-OHMLCXRW.js";
21
- import "./chunk-JHCR7H4Y.js";
22
- import "./chunk-DOYJR2HF.js";
20
+ } from "./chunk-O22DNTKU.js";
21
+ import "./chunk-KGHWHAVF.js";
22
+ import "./chunk-WIYDT3PY.js";
23
+ import "./chunk-YQSWVHKK.js";
24
+ import "./chunk-JUGF3YE7.js";
23
25
  import "./chunk-HK6AZQ5Z.js";
24
26
  import "./chunk-7334DEPX.js";
25
27
  import "./chunk-MWIPHUAE.js";
26
- import "./chunk-REPFZIPP.js";
28
+ import "./chunk-HGB7BITW.js";
29
+ import "./chunk-BR6OWWAA.js";
27
30
  import "./chunk-VHENFC2S.js";
28
31
  import "./chunk-QOSAWNOU.js";
29
32
  import "./chunk-D2J3AD6L.js";
@@ -63,4 +66,4 @@ var readCommand = {
63
66
  export {
64
67
  readCommand
65
68
  };
66
- //# sourceMappingURL=read-MX7ZURF3.js.map
69
+ //# sourceMappingURL=read-BOB63DIH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/read.ts"],"sourcesContent":["import chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { agentOf } from '../core/agents/index.js';\nimport { sessionFromArgs, sessionPositionals } from './shared/session-arg.js';\nimport { formatConversation, READ_AS_DATA } from './shared/conversation-format.js';\n\n/** `work read` — a session's latest messages: yours, its agent's, its tool calls (agents/: the conversation, in work's own terms). */\nexport const readCommand: CommandModule = {\n command: 'read [target] [branch]',\n describe: \"A session's latest messages — yours, its agent's and its tool calls (default: the session for this folder)\",\n builder: (yargs) =>\n sessionPositionals(yargs)\n .option('last', { type: 'number', default: 20, describe: 'How many messages (newest last)' })\n .option('json', { type: 'boolean', default: false, describe: 'The entries as JSON: { at, role: you|agent|tool, text, tool? }' }),\n handler: (argv) => {\n const s = sessionFromArgs(argv);\n if (!s) return;\n const agent = agentOf(s);\n if (!agent.conversation) {\n console.error(chalk.red(`work can't read ${agent.name}'s conversations yet.`));\n process.exitCode = 1;\n return;\n }\n const last = Math.max(1, Math.min(500, Math.floor(Number(argv.last) || 20)));\n const entries = agent.conversation.read(s, { last });\n // On stderr either way: an agent parsing the JSON reads it too.\n if (entries.length) console.error(chalk.gray(`${s.target} · ${s.branch} — ${READ_AS_DATA}`));\n if (argv.json) {\n process.stdout.write(JSON.stringify(entries, null, 2) + '\\n');\n return;\n }\n if (entries.length === 0) {\n console.error(chalk.yellow(`No conversation found for ${s.target} · ${s.branch}.`));\n return;\n }\n console.log(formatConversation(entries, agent.name));\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,WAAW;AAOX,IAAM,cAA6B;AAAA,EACxC,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,CAAC,UACR,mBAAmB,KAAK,EACrB,OAAO,QAAQ,EAAE,MAAM,UAAU,SAAS,IAAI,UAAU,kCAAkC,CAAC,EAC3F,OAAO,QAAQ,EAAE,MAAM,WAAW,SAAS,OAAO,UAAU,iEAAiE,CAAC;AAAA,EACnI,SAAS,CAAC,SAAS;AACjB,UAAM,IAAI,gBAAgB,IAAI;AAC9B,QAAI,CAAC,EAAG;AACR,UAAM,QAAQ,QAAQ,CAAC;AACvB,QAAI,CAAC,MAAM,cAAc;AACvB,cAAQ,MAAM,MAAM,IAAI,mBAAmB,MAAM,IAAI,uBAAuB,CAAC;AAC7E,cAAQ,WAAW;AACnB;AAAA,IACF;AACA,UAAM,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,KAAK,MAAM,OAAO,KAAK,IAAI,KAAK,EAAE,CAAC,CAAC;AAC3E,UAAM,UAAU,MAAM,aAAa,KAAK,GAAG,EAAE,KAAK,CAAC;AAEnD,QAAI,QAAQ,OAAQ,SAAQ,MAAM,MAAM,KAAK,GAAG,EAAE,MAAM,SAAM,EAAE,MAAM,WAAM,YAAY,EAAE,CAAC;AAC3F,QAAI,KAAK,MAAM;AACb,cAAQ,OAAO,MAAM,KAAK,UAAU,SAAS,MAAM,CAAC,IAAI,IAAI;AAC5D;AAAA,IACF;AACA,QAAI,QAAQ,WAAW,GAAG;AACxB,cAAQ,MAAM,MAAM,OAAO,6BAA6B,EAAE,MAAM,SAAM,EAAE,MAAM,GAAG,CAAC;AAClF;AAAA,IACF;AACA,YAAQ,IAAI,mBAAmB,SAAS,MAAM,IAAI,CAAC;AAAA,EACrD;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/commands/read.ts"],"sourcesContent":["import chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { agentOf } from '../core/agents/index.js';\nimport { sessionFromArgs, sessionPositionals } from './shared/session-arg.js';\nimport { formatConversation, READ_AS_DATA } from './shared/conversation-format.js';\n\n/** `work read` — a session's latest messages: yours, its agent's, its tool calls (agents/: the conversation, in work's own terms). */\nexport const readCommand: CommandModule = {\n command: 'read [target] [branch]',\n describe: \"A session's latest messages — yours, its agent's and its tool calls (default: the session for this folder)\",\n builder: (yargs) =>\n sessionPositionals(yargs)\n .option('last', { type: 'number', default: 20, describe: 'How many messages (newest last)' })\n .option('json', { type: 'boolean', default: false, describe: 'The entries as JSON: { at, role: you|agent|tool, text, tool? }' }),\n handler: (argv) => {\n const s = sessionFromArgs(argv);\n if (!s) return;\n const agent = agentOf(s);\n if (!agent.conversation) {\n console.error(chalk.red(`work can't read ${agent.name}'s conversations yet.`));\n process.exitCode = 1;\n return;\n }\n const last = Math.max(1, Math.min(500, Math.floor(Number(argv.last) || 20)));\n const entries = agent.conversation.read(s, { last });\n // On stderr either way: an agent parsing the JSON reads it too.\n if (entries.length) console.error(chalk.gray(`${s.target} · ${s.branch} — ${READ_AS_DATA}`));\n if (argv.json) {\n process.stdout.write(JSON.stringify(entries, null, 2) + '\\n');\n return;\n }\n if (entries.length === 0) {\n console.error(chalk.yellow(`No conversation found for ${s.target} · ${s.branch}.`));\n return;\n }\n console.log(formatConversation(entries, agent.name));\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,WAAW;AAOX,IAAM,cAA6B;AAAA,EACxC,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,CAAC,UACR,mBAAmB,KAAK,EACrB,OAAO,QAAQ,EAAE,MAAM,UAAU,SAAS,IAAI,UAAU,kCAAkC,CAAC,EAC3F,OAAO,QAAQ,EAAE,MAAM,WAAW,SAAS,OAAO,UAAU,iEAAiE,CAAC;AAAA,EACnI,SAAS,CAAC,SAAS;AACjB,UAAM,IAAI,gBAAgB,IAAI;AAC9B,QAAI,CAAC,EAAG;AACR,UAAM,QAAQ,QAAQ,CAAC;AACvB,QAAI,CAAC,MAAM,cAAc;AACvB,cAAQ,MAAM,MAAM,IAAI,mBAAmB,MAAM,IAAI,uBAAuB,CAAC;AAC7E,cAAQ,WAAW;AACnB;AAAA,IACF;AACA,UAAM,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,KAAK,MAAM,OAAO,KAAK,IAAI,KAAK,EAAE,CAAC,CAAC;AAC3E,UAAM,UAAU,MAAM,aAAa,KAAK,GAAG,EAAE,KAAK,CAAC;AAEnD,QAAI,QAAQ,OAAQ,SAAQ,MAAM,MAAM,KAAK,GAAG,EAAE,MAAM,SAAM,EAAE,MAAM,WAAM,YAAY,EAAE,CAAC;AAC3F,QAAI,KAAK,MAAM;AACb,cAAQ,OAAO,MAAM,KAAK,UAAU,SAAS,MAAM,CAAC,IAAI,IAAI;AAC5D;AAAA,IACF;AACA,QAAI,QAAQ,WAAW,GAAG;AACxB,cAAQ,MAAM,MAAM,OAAO,6BAA6B,EAAE,MAAM,SAAM,EAAE,MAAM,GAAG,CAAC;AAClF;AAAA,IACF;AACA,YAAQ,IAAI,mBAAmB,SAAS,MAAM,IAAI,CAAC;AAAA,EACrD;AACF;","names":[]}