@moberg_hr/work-tree 2.9.2 → 2.10.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 (362) hide show
  1. package/dist/{account-3A7RQSUC.js → account-QSNXX5YV.js} +81 -98
  2. package/dist/account-QSNXX5YV.js.map +1 -0
  3. package/dist/{add-repo-YGDJZ6HG.js → add-repo-YZ32MLZG.js} +32 -28
  4. package/dist/{add-repo-YGDJZ6HG.js.map → add-repo-YZ32MLZG.js.map} +1 -1
  5. package/dist/{answer-GHVFFKNF.js → answer-Y4T5X446.js} +16 -13
  6. package/dist/{answer-GHVFFKNF.js.map → answer-Y4T5X446.js.map} +1 -1
  7. package/dist/{attach-LWOZKLTF.js → attach-XPYWYHDP.js} +25 -19
  8. package/dist/{attach-LWOZKLTF.js.map → attach-XPYWYHDP.js.map} +1 -1
  9. package/dist/bin.js +4 -4
  10. package/dist/{block-WVUT63QY.js → block-JVAGG5QA.js} +22 -13
  11. package/dist/block-JVAGG5QA.js.map +1 -0
  12. package/dist/{broadcast-WM423JGR.js → broadcast-FATIANHX.js} +11 -9
  13. package/dist/{broadcast-WM423JGR.js.map → broadcast-FATIANHX.js.map} +1 -1
  14. package/dist/{catchup-KJZTLHN7.js → catchup-OTI2KZG5.js} +17 -15
  15. package/dist/{catchup-KJZTLHN7.js.map → catchup-OTI2KZG5.js.map} +1 -1
  16. package/dist/{chunk-SBLK524A.js → chunk-27LWL6QE.js} +171 -143
  17. package/dist/chunk-27LWL6QE.js.map +1 -0
  18. package/dist/chunk-2HHIDWHH.js +50 -0
  19. package/dist/chunk-2HHIDWHH.js.map +1 -0
  20. package/dist/{chunk-KVQNJCXH.js → chunk-2K5TDJ7M.js} +5 -5
  21. package/dist/{chunk-PDWEPIL6.js → chunk-2MAZV5KS.js} +18 -2
  22. package/dist/chunk-2MAZV5KS.js.map +1 -0
  23. package/dist/{chunk-XEAFWIN6.js → chunk-2VRZVUM7.js} +13 -6
  24. package/dist/chunk-2VRZVUM7.js.map +1 -0
  25. package/dist/{chunk-UB3DOOPB.js → chunk-34E2LA3M.js} +34 -9
  26. package/dist/chunk-34E2LA3M.js.map +1 -0
  27. package/dist/{chunk-BV2PPIKP.js → chunk-353ZINJ2.js} +3 -3
  28. package/dist/{chunk-5QGCF3PS.js → chunk-3BSFVKMK.js} +2 -2
  29. package/dist/{chunk-XTDTM6JI.js → chunk-3S6L437Q.js} +4 -5
  30. package/dist/chunk-3S6L437Q.js.map +1 -0
  31. package/dist/{chunk-3NXRBRRJ.js → chunk-3XG23PLG.js} +17 -57
  32. package/dist/chunk-3XG23PLG.js.map +1 -0
  33. package/dist/{chunk-YHSB7IVZ.js → chunk-46XSWHCQ.js} +14 -5
  34. package/dist/{chunk-YHSB7IVZ.js.map → chunk-46XSWHCQ.js.map} +1 -1
  35. package/dist/{chunk-J36ULZBO.js → chunk-4K4S53KX.js} +2 -2
  36. package/dist/{chunk-2Z2O5LEA.js → chunk-4O4VQQEA.js} +6 -10
  37. package/dist/chunk-4O4VQQEA.js.map +1 -0
  38. package/dist/chunk-4TTYEMOY.js +180 -0
  39. package/dist/chunk-4TTYEMOY.js.map +1 -0
  40. package/dist/{chunk-TR7CTHJA.js → chunk-5R5JEQW7.js} +59 -81
  41. package/dist/chunk-5R5JEQW7.js.map +1 -0
  42. package/dist/chunk-63ZLPXRL.js +199 -0
  43. package/dist/chunk-63ZLPXRL.js.map +1 -0
  44. package/dist/{chunk-2YXY6S7G.js → chunk-66VPQOVZ.js} +17 -14
  45. package/dist/chunk-66VPQOVZ.js.map +1 -0
  46. package/dist/{chunk-F4EWBHTA.js → chunk-6J6U7JXN.js} +20 -5
  47. package/dist/chunk-6J6U7JXN.js.map +1 -0
  48. package/dist/{chunk-P2HOLCBF.js → chunk-6UTH3A76.js} +18 -2
  49. package/dist/{chunk-P2HOLCBF.js.map → chunk-6UTH3A76.js.map} +1 -1
  50. package/dist/{chunk-LIE5GVDG.js → chunk-6YMLYU5G.js} +15 -17
  51. package/dist/{chunk-LIE5GVDG.js.map → chunk-6YMLYU5G.js.map} +1 -1
  52. package/dist/chunk-7E5XPDKX.js +22 -0
  53. package/dist/chunk-7E5XPDKX.js.map +1 -0
  54. package/dist/chunk-7QNVFVG6.js +196 -0
  55. package/dist/chunk-7QNVFVG6.js.map +1 -0
  56. package/dist/chunk-7S2NQRWL.js +9 -0
  57. package/dist/{chunk-4MVT7QPZ.js.map → chunk-7S2NQRWL.js.map} +1 -1
  58. package/dist/{chunk-P4EQWC5W.js → chunk-ADIN3DTD.js} +2 -2
  59. package/dist/{chunk-JB6LU6JV.js → chunk-AHI2WVWP.js} +16 -24
  60. package/dist/chunk-AHI2WVWP.js.map +1 -0
  61. package/dist/{chunk-KUCMJHQW.js → chunk-AHYCZUPI.js} +2 -2
  62. package/dist/chunk-AQP6SCCJ.js +66 -0
  63. package/dist/chunk-AQP6SCCJ.js.map +1 -0
  64. package/dist/chunk-B5WDN63X.js +84 -0
  65. package/dist/chunk-B5WDN63X.js.map +1 -0
  66. package/dist/{chunk-SWKTDMLL.js → chunk-BNKVENDF.js} +8 -8
  67. package/dist/chunk-DAKJTB6N.js +76 -0
  68. package/dist/chunk-DAKJTB6N.js.map +1 -0
  69. package/dist/{chunk-3N3UQEC4.js → chunk-DCCC7LEP.js} +4 -3
  70. package/dist/chunk-DCCC7LEP.js.map +1 -0
  71. package/dist/chunk-E67DOUVU.js +289 -0
  72. package/dist/chunk-E67DOUVU.js.map +1 -0
  73. package/dist/{chunk-5NKXGQX4.js → chunk-E7WPTSHQ.js} +22 -22
  74. package/dist/chunk-EL3XL2OC.js +150 -0
  75. package/dist/chunk-EL3XL2OC.js.map +1 -0
  76. package/dist/{chunk-5WEBLABB.js → chunk-F3PEUOTP.js} +3 -3
  77. package/dist/{chunk-ICJPVSRY.js → chunk-FKM67CZZ.js} +53 -51
  78. package/dist/chunk-FKM67CZZ.js.map +1 -0
  79. package/dist/{chunk-VUNJVF6C.js → chunk-FMLE2WSN.js} +2 -2
  80. package/dist/{chunk-HP2QVRSQ.js → chunk-FSQJOZS4.js} +17 -10
  81. package/dist/chunk-FSQJOZS4.js.map +1 -0
  82. package/dist/chunk-FZHFD2AY.js +27 -0
  83. package/dist/chunk-FZHFD2AY.js.map +1 -0
  84. package/dist/{chunk-K2MOQVTJ.js → chunk-GZGJQKQT.js} +2 -2
  85. package/dist/{chunk-5WM24P5N.js → chunk-I6MILNM5.js} +2 -2
  86. package/dist/chunk-I6MILNM5.js.map +1 -0
  87. package/dist/{chunk-S3BAD4IR.js → chunk-ICXUTMGH.js} +2 -2
  88. package/dist/{chunk-BWD24JIP.js → chunk-IDQVTWLX.js} +5 -5
  89. package/dist/{chunk-Z2XY3PLX.js → chunk-IFQOOCT7.js} +8 -8
  90. package/dist/{chunk-JT5AR7PO.js → chunk-IKX3B26P.js} +78 -6
  91. package/dist/chunk-IKX3B26P.js.map +1 -0
  92. package/dist/{chunk-OMIMK3LB.js → chunk-IOHK45WE.js} +2 -2
  93. package/dist/{chunk-SG5LUMGE.js → chunk-JNBMANFM.js} +6 -3
  94. package/dist/chunk-JNBMANFM.js.map +1 -0
  95. package/dist/{chunk-XMWVBLMJ.js → chunk-JNCKZ3OF.js} +12 -34
  96. package/dist/chunk-JNCKZ3OF.js.map +1 -0
  97. package/dist/{chunk-6IUFNTBQ.js → chunk-JVBIWU7S.js} +4 -4
  98. package/dist/chunk-JVE2JFLV.js +15 -0
  99. package/dist/chunk-JVE2JFLV.js.map +1 -0
  100. package/dist/{chunk-7NSQVIIK.js → chunk-KDO7D46L.js} +3 -3
  101. package/dist/{chunk-GJ5V357G.js → chunk-KL4YYV37.js} +4 -4
  102. package/dist/chunk-KSVYR4G2.js +47 -0
  103. package/dist/chunk-KSVYR4G2.js.map +1 -0
  104. package/dist/{chunk-RYNBBSLY.js → chunk-KWHHB737.js} +6 -8
  105. package/dist/chunk-KWHHB737.js.map +1 -0
  106. package/dist/chunk-L22AWXWA.js +29 -0
  107. package/dist/chunk-L22AWXWA.js.map +1 -0
  108. package/dist/{chunk-ZGT4ZDGG.js → chunk-LJKF73JB.js} +8 -8
  109. package/dist/chunk-LJKF73JB.js.map +1 -0
  110. package/dist/{chunk-JWWG624P.js → chunk-LKESANVD.js} +6 -6
  111. package/dist/{chunk-RG7NJEN7.js → chunk-LZZCJAJQ.js} +11 -11
  112. package/dist/{chunk-AQJSY4CI.js → chunk-MM7344RC.js} +2 -2
  113. package/dist/{chunk-HMK3INUS.js → chunk-MQCDFSVF.js} +2 -2
  114. package/dist/{chunk-VJ7SVDED.js → chunk-MSJWQC7H.js} +6 -4
  115. package/dist/chunk-MSJWQC7H.js.map +1 -0
  116. package/dist/chunk-NWOCQVSL.js +307 -0
  117. package/dist/chunk-NWOCQVSL.js.map +1 -0
  118. package/dist/{chunk-RGUSVBGN.js → chunk-OCMNBOPX.js} +2 -2
  119. package/dist/{chunk-BNGX2JGD.js → chunk-PCNNW63Z.js} +16 -5
  120. package/dist/chunk-PCNNW63Z.js.map +1 -0
  121. package/dist/chunk-PHGVVFTF.js +1603 -0
  122. package/dist/chunk-PHGVVFTF.js.map +1 -0
  123. package/dist/{chunk-4NITDMDH.js → chunk-PPZP7CA7.js} +9 -186
  124. package/dist/chunk-PPZP7CA7.js.map +1 -0
  125. package/dist/{chunk-X4AXKO3A.js → chunk-RGLIW45S.js} +2 -2
  126. package/dist/{chunk-TQOHPNDW.js → chunk-RHDZPV6C.js} +2 -2
  127. package/dist/{chunk-3GIH4WTA.js → chunk-RJUMLWXP.js} +109 -104
  128. package/dist/chunk-RJUMLWXP.js.map +1 -0
  129. package/dist/chunk-RQFHA5BM.js +1443 -0
  130. package/dist/chunk-RQFHA5BM.js.map +1 -0
  131. package/dist/chunk-S3CTXKSN.js +17 -0
  132. package/dist/chunk-S3CTXKSN.js.map +1 -0
  133. package/dist/chunk-SJBEIYLK.js +16 -0
  134. package/dist/chunk-SJBEIYLK.js.map +1 -0
  135. package/dist/chunk-TIG7NHVO.js +231 -0
  136. package/dist/chunk-TIG7NHVO.js.map +1 -0
  137. package/dist/{chunk-4BZGUMP7.js → chunk-TKWUSJNQ.js} +36 -23
  138. package/dist/chunk-TKWUSJNQ.js.map +1 -0
  139. package/dist/{chunk-VGRZKBUK.js → chunk-UP2JTDBI.js} +3 -3
  140. package/dist/chunk-V4U5RGEG.js +59 -0
  141. package/dist/chunk-V4U5RGEG.js.map +1 -0
  142. package/dist/{chunk-V4IHZJD4.js → chunk-V7GCYL6A.js} +93 -196
  143. package/dist/chunk-V7GCYL6A.js.map +1 -0
  144. package/dist/{chunk-GBMY7IMP.js → chunk-VFH4SU3M.js} +34 -23
  145. package/dist/chunk-VFH4SU3M.js.map +1 -0
  146. package/dist/{chunk-JFN67PRA.js → chunk-VV3NFLLP.js} +16 -9
  147. package/dist/chunk-VV3NFLLP.js.map +1 -0
  148. package/dist/{chunk-AGTVDF4O.js → chunk-WKOJ7NXD.js} +4 -4
  149. package/dist/{chunk-4SZ7YW7N.js → chunk-WVV54JP3.js} +56 -58
  150. package/dist/chunk-WVV54JP3.js.map +1 -0
  151. package/dist/chunk-WY7QZ2P7.js +71 -0
  152. package/dist/chunk-WY7QZ2P7.js.map +1 -0
  153. package/dist/{chunk-YYBXQBW2.js → chunk-Y7T73SAP.js} +13 -3
  154. package/dist/chunk-Y7T73SAP.js.map +1 -0
  155. package/dist/{chunk-PKXHK5CJ.js → chunk-Z6ZMWFNV.js} +25 -7
  156. package/dist/chunk-Z6ZMWFNV.js.map +1 -0
  157. package/dist/{chunk-MPY2ZQBL.js → chunk-Z7I6DQAR.js} +42 -57
  158. package/dist/chunk-Z7I6DQAR.js.map +1 -0
  159. package/dist/{chunk-GNGXYXBC.js → chunk-ZRATYLBB.js} +2 -2
  160. package/dist/{cleanup-7E3YWQUC.js → cleanup-M5TY4FQS.js} +46 -34
  161. package/dist/{cleanup-7E3YWQUC.js.map → cleanup-M5TY4FQS.js.map} +1 -1
  162. package/dist/cli-446A536X.js +19 -0
  163. package/dist/{completion-MXX5TRIV.js → completion-IAH7WRKJ.js} +3 -2
  164. package/dist/{completion-MXX5TRIV.js.map → completion-IAH7WRKJ.js.map} +1 -1
  165. package/dist/{config-TUJNIUIO.js → config-JLORGUXN.js} +16 -13
  166. package/dist/{config-TUJNIUIO.js.map → config-JLORGUXN.js.map} +1 -1
  167. package/dist/{diff-PZKOXAU3.js → diff-4O5HXNZ7.js} +23 -20
  168. package/dist/{diff-PZKOXAU3.js.map → diff-4O5HXNZ7.js.map} +1 -1
  169. package/dist/{digest-XHDDBXA6.js → digest-IAAZXJCC.js} +13 -11
  170. package/dist/{digest-XHDDBXA6.js.map → digest-IAAZXJCC.js.map} +1 -1
  171. package/dist/{fork-HYWZW72R.js → fork-ULJYPEKY.js} +41 -28
  172. package/dist/{fork-HYWZW72R.js.map → fork-ULJYPEKY.js.map} +1 -1
  173. package/dist/{history-MRRY2VTS.js → history-JFZF22M7.js} +12 -10
  174. package/dist/{hook-OWP4H2MT.js → hook-UYOIQVJ7.js} +54 -20
  175. package/dist/hook-UYOIQVJ7.js.map +1 -0
  176. package/dist/{hydrate-ZTGARW3U.js → hydrate-DROI4RJ7.js} +14 -12
  177. package/dist/{hydrate-ZTGARW3U.js.map → hydrate-DROI4RJ7.js.map} +1 -1
  178. package/dist/{init-7VISW3JJ.js → init-FF75CQM7.js} +27 -19
  179. package/dist/{init-7VISW3JJ.js.map → init-FF75CQM7.js.map} +1 -1
  180. package/dist/install-skills-XSAHNBYD.js +22 -0
  181. package/dist/install-skills-bin.js +8 -6
  182. package/dist/install-skills-bin.js.map +1 -1
  183. package/dist/{list-5XWYT37A.js → list-5FEHBP6N.js} +15 -13
  184. package/dist/{list-5XWYT37A.js.map → list-5FEHBP6N.js.map} +1 -1
  185. package/dist/{move-PSAODKRK.js → move-422L6PPI.js} +33 -24
  186. package/dist/{move-PSAODKRK.js.map → move-422L6PPI.js.map} +1 -1
  187. package/dist/{note-7WQ2YC2F.js → note-AAXPD5VA.js} +14 -12
  188. package/dist/{note-7WQ2YC2F.js.map → note-AAXPD5VA.js.map} +1 -1
  189. package/dist/{overlaps-R27DEX36.js → overlaps-WPNUYOFF.js} +21 -11
  190. package/dist/{overlaps-R27DEX36.js.map → overlaps-WPNUYOFF.js.map} +1 -1
  191. package/dist/{pin-LS4WPLOE.js → pin-QXPF23BB.js} +14 -12
  192. package/dist/{pin-LS4WPLOE.js.map → pin-QXPF23BB.js.map} +1 -1
  193. package/dist/{pr-SMEC5O7O.js → pr-QLGXPKPQ.js} +46 -21
  194. package/dist/pr-QLGXPKPQ.js.map +1 -0
  195. package/dist/{prune-VA3V5B2I.js → prune-GRHKRRVT.js} +44 -32
  196. package/dist/{prune-VA3V5B2I.js.map → prune-GRHKRRVT.js.map} +1 -1
  197. package/dist/{pty-host-PN4A3X2Y.js → pty-host-XDDXA4SL.js} +135 -67
  198. package/dist/pty-host-XDDXA4SL.js.map +1 -0
  199. package/dist/{read-75DP75TI.js → read-YWKD2DGP.js} +13 -11
  200. package/dist/{read-75DP75TI.js.map → read-YWKD2DGP.js.map} +1 -1
  201. package/dist/{recent-YDSLMD6Y.js → recent-SI5BDVVH.js} +35 -26
  202. package/dist/recent-SI5BDVVH.js.map +1 -0
  203. package/dist/{remove-XPSU2VTR.js → remove-RXXCHY44.js} +48 -36
  204. package/dist/{remove-XPSU2VTR.js.map → remove-RXXCHY44.js.map} +1 -1
  205. package/dist/{restart-7EPW5VDV.js → restart-CPNDEXU6.js} +17 -15
  206. package/dist/{restart-7EPW5VDV.js.map → restart-CPNDEXU6.js.map} +1 -1
  207. package/dist/{resume-26Y6G4UT.js → resume-BLP4TTJK.js} +35 -20
  208. package/dist/resume-BLP4TTJK.js.map +1 -0
  209. package/dist/review-now-ADWZPELT.js +22 -0
  210. package/dist/review-now-ADWZPELT.js.map +1 -0
  211. package/dist/{run-IIURYUD2.js → run-JFCDJ3EV.js} +21 -15
  212. package/dist/run-JFCDJ3EV.js.map +1 -0
  213. package/dist/{screen-AORRCOZQ.js → screen-LBOPAUXV.js} +14 -12
  214. package/dist/{screen-AORRCOZQ.js.map → screen-LBOPAUXV.js.map} +1 -1
  215. package/dist/{search-Z3XD7ZNQ.js → search-AMEGRH24.js} +10 -8
  216. package/dist/{search-Z3XD7ZNQ.js.map → search-AMEGRH24.js.map} +1 -1
  217. package/dist/{section-6N7J4Y6J.js → section-73Z34PVE.js} +14 -12
  218. package/dist/{section-6N7J4Y6J.js.map → section-73Z34PVE.js.map} +1 -1
  219. package/dist/{send-SHHXHICL.js → send-IZBSEET5.js} +19 -16
  220. package/dist/send-IZBSEET5.js.map +1 -0
  221. package/dist/{sessions-AD5HPY2L.js → sessions-WVQ2U2W4.js} +58 -23
  222. package/dist/sessions-WVQ2U2W4.js.map +1 -0
  223. package/dist/{snooze-JZMIVMNS.js → snooze-7IBHY5MY.js} +13 -11
  224. package/dist/{snooze-JZMIVMNS.js.map → snooze-7IBHY5MY.js.map} +1 -1
  225. package/dist/{start-6VNWRLPK.js → start-AU62TW6M.js} +14 -12
  226. package/dist/{start-6VNWRLPK.js.map → start-AU62TW6M.js.map} +1 -1
  227. package/dist/{state-OZF4S7PG.js → state-IZV7DAPL.js} +8 -5
  228. package/dist/state-IZV7DAPL.js.map +1 -0
  229. package/dist/{status-YRBJR4YB.js → status-Z7OMNYZX.js} +38 -13
  230. package/dist/status-Z7OMNYZX.js.map +1 -0
  231. package/dist/{statusline-RSQMMCRN.js → statusline-VJFY7ZAB.js} +12 -11
  232. package/dist/{statusline-RSQMMCRN.js.map → statusline-VJFY7ZAB.js.map} +1 -1
  233. package/dist/{statusline-hook-OVWHHFBV.js → statusline-hook-JA7MNE5H.js} +4 -3
  234. package/dist/{statusline-hook-OVWHHFBV.js.map → statusline-hook-JA7MNE5H.js.map} +1 -1
  235. package/dist/{stop-A2Q4CO6Z.js → stop-PWNXSFBD.js} +14 -12
  236. package/dist/{stop-A2Q4CO6Z.js.map → stop-PWNXSFBD.js.map} +1 -1
  237. package/dist/{sync-GXXBOQ4W.js → sync-2BTZVDDG.js} +44 -32
  238. package/dist/{sync-GXXBOQ4W.js.map → sync-2BTZVDDG.js.map} +1 -1
  239. package/dist/{time-XKEMSDMN.js → time-CTCIAXIY.js} +15 -13
  240. package/dist/{time-XKEMSDMN.js.map → time-CTCIAXIY.js.map} +1 -1
  241. package/dist/{time-actions-DB7OQ2IS.js → time-actions-UYBOXET6.js} +5 -4
  242. package/dist/{timesheet-ZAZXN6LK.js → timesheet-BUFQ34FC.js} +24 -15
  243. package/dist/{timesheet-ZAZXN6LK.js.map → timesheet-BUFQ34FC.js.map} +1 -1
  244. package/dist/{todo-ODF7RI27.js → todo-2R7VID57.js} +4 -4
  245. package/dist/{tree-HJGFWO6G.js → tree-LQDPAXQA.js} +65 -45
  246. package/dist/tree-LQDPAXQA.js.map +1 -0
  247. package/dist/{update-6427PE7F.js → update-2IYJHY7H.js} +24 -14
  248. package/dist/{update-6427PE7F.js.map → update-2IYJHY7H.js.map} +1 -1
  249. package/dist/{usage-HIXH42ZH.js → usage-IR5GNF4R.js} +13 -11
  250. package/dist/{usage-HIXH42ZH.js.map → usage-IR5GNF4R.js.map} +1 -1
  251. package/dist/version-ONEI52TI.js +115 -0
  252. package/dist/version-ONEI52TI.js.map +1 -0
  253. package/dist/{wait-VHPP2B7P.js → wait-6DH34L53.js} +16 -13
  254. package/dist/{wait-VHPP2B7P.js.map → wait-6DH34L53.js.map} +1 -1
  255. package/dist/wd-bin.js +6 -6
  256. package/dist/web/assets/PtyView-kBcAOwHr.js +96 -0
  257. package/dist/web/assets/PtyView-kBcAOwHr.js.map +1 -0
  258. package/dist/web/assets/index-BgfR3N99.js +124 -0
  259. package/dist/web/assets/index-BgfR3N99.js.map +1 -0
  260. package/dist/web/assets/index-CKpHjII8.css +1 -0
  261. package/dist/web/index.html +2 -2
  262. package/dist/{web-QTXU66K5.js → web-RIHGV7YY.js} +2893 -444
  263. package/dist/web-RIHGV7YY.js.map +1 -0
  264. package/npm-shrinkwrap.json +2 -2
  265. package/package.json +1 -1
  266. package/plugins/work-tree/skills/wd-review/SKILL.md +1 -1
  267. package/plugins/work-tree/skills/work-sessions/SKILL.md +2 -2
  268. package/dist/account-3A7RQSUC.js.map +0 -1
  269. package/dist/block-WVUT63QY.js.map +0 -1
  270. package/dist/chunk-2YXY6S7G.js.map +0 -1
  271. package/dist/chunk-2Z2O5LEA.js.map +0 -1
  272. package/dist/chunk-3GIH4WTA.js.map +0 -1
  273. package/dist/chunk-3N3UQEC4.js.map +0 -1
  274. package/dist/chunk-3NXRBRRJ.js.map +0 -1
  275. package/dist/chunk-4BZGUMP7.js.map +0 -1
  276. package/dist/chunk-4MVT7QPZ.js +0 -9
  277. package/dist/chunk-4NITDMDH.js.map +0 -1
  278. package/dist/chunk-4SZ7YW7N.js.map +0 -1
  279. package/dist/chunk-5WM24P5N.js.map +0 -1
  280. package/dist/chunk-BNGX2JGD.js.map +0 -1
  281. package/dist/chunk-F4EWBHTA.js.map +0 -1
  282. package/dist/chunk-GBMY7IMP.js.map +0 -1
  283. package/dist/chunk-H7GHJ3CR.js +0 -551
  284. package/dist/chunk-H7GHJ3CR.js.map +0 -1
  285. package/dist/chunk-HP2QVRSQ.js.map +0 -1
  286. package/dist/chunk-ICJPVSRY.js.map +0 -1
  287. package/dist/chunk-JB6LU6JV.js.map +0 -1
  288. package/dist/chunk-JFN67PRA.js.map +0 -1
  289. package/dist/chunk-JT5AR7PO.js.map +0 -1
  290. package/dist/chunk-MPY2ZQBL.js.map +0 -1
  291. package/dist/chunk-PDWEPIL6.js.map +0 -1
  292. package/dist/chunk-PKXHK5CJ.js.map +0 -1
  293. package/dist/chunk-RCYI7SRA.js +0 -15
  294. package/dist/chunk-RCYI7SRA.js.map +0 -1
  295. package/dist/chunk-RYNBBSLY.js.map +0 -1
  296. package/dist/chunk-SBLK524A.js.map +0 -1
  297. package/dist/chunk-SG5LUMGE.js.map +0 -1
  298. package/dist/chunk-TR7CTHJA.js.map +0 -1
  299. package/dist/chunk-UB3DOOPB.js.map +0 -1
  300. package/dist/chunk-V4IHZJD4.js.map +0 -1
  301. package/dist/chunk-VJ7SVDED.js.map +0 -1
  302. package/dist/chunk-VTLDYH3C.js +0 -227
  303. package/dist/chunk-VTLDYH3C.js.map +0 -1
  304. package/dist/chunk-XEAFWIN6.js.map +0 -1
  305. package/dist/chunk-XMWVBLMJ.js.map +0 -1
  306. package/dist/chunk-XTDTM6JI.js.map +0 -1
  307. package/dist/chunk-YYBXQBW2.js.map +0 -1
  308. package/dist/chunk-ZDMJPEBO.js +0 -31
  309. package/dist/chunk-ZDMJPEBO.js.map +0 -1
  310. package/dist/chunk-ZGT4ZDGG.js.map +0 -1
  311. package/dist/cli-BHIBPUQG.js +0 -19
  312. package/dist/hook-OWP4H2MT.js.map +0 -1
  313. package/dist/install-skills-IIMTRQ4K.js +0 -20
  314. package/dist/pr-SMEC5O7O.js.map +0 -1
  315. package/dist/pty-host-PN4A3X2Y.js.map +0 -1
  316. package/dist/recent-YDSLMD6Y.js.map +0 -1
  317. package/dist/resume-26Y6G4UT.js.map +0 -1
  318. package/dist/run-IIURYUD2.js.map +0 -1
  319. package/dist/send-SHHXHICL.js.map +0 -1
  320. package/dist/sessions-AD5HPY2L.js.map +0 -1
  321. package/dist/state-OZF4S7PG.js.map +0 -1
  322. package/dist/status-YRBJR4YB.js.map +0 -1
  323. package/dist/tree-HJGFWO6G.js.map +0 -1
  324. package/dist/web/assets/PtyView-B7zFUh_M.js +0 -96
  325. package/dist/web/assets/PtyView-B7zFUh_M.js.map +0 -1
  326. package/dist/web/assets/index-BAxeogV4.css +0 -1
  327. package/dist/web/assets/index-C4cR3Hwy.js +0 -120
  328. package/dist/web/assets/index-C4cR3Hwy.js.map +0 -1
  329. package/dist/web-QTXU66K5.js.map +0 -1
  330. /package/dist/{chunk-KVQNJCXH.js.map → chunk-2K5TDJ7M.js.map} +0 -0
  331. /package/dist/{chunk-BV2PPIKP.js.map → chunk-353ZINJ2.js.map} +0 -0
  332. /package/dist/{chunk-5QGCF3PS.js.map → chunk-3BSFVKMK.js.map} +0 -0
  333. /package/dist/{chunk-J36ULZBO.js.map → chunk-4K4S53KX.js.map} +0 -0
  334. /package/dist/{chunk-P4EQWC5W.js.map → chunk-ADIN3DTD.js.map} +0 -0
  335. /package/dist/{chunk-KUCMJHQW.js.map → chunk-AHYCZUPI.js.map} +0 -0
  336. /package/dist/{chunk-SWKTDMLL.js.map → chunk-BNKVENDF.js.map} +0 -0
  337. /package/dist/{chunk-5NKXGQX4.js.map → chunk-E7WPTSHQ.js.map} +0 -0
  338. /package/dist/{chunk-5WEBLABB.js.map → chunk-F3PEUOTP.js.map} +0 -0
  339. /package/dist/{chunk-VUNJVF6C.js.map → chunk-FMLE2WSN.js.map} +0 -0
  340. /package/dist/{chunk-K2MOQVTJ.js.map → chunk-GZGJQKQT.js.map} +0 -0
  341. /package/dist/{chunk-S3BAD4IR.js.map → chunk-ICXUTMGH.js.map} +0 -0
  342. /package/dist/{chunk-BWD24JIP.js.map → chunk-IDQVTWLX.js.map} +0 -0
  343. /package/dist/{chunk-Z2XY3PLX.js.map → chunk-IFQOOCT7.js.map} +0 -0
  344. /package/dist/{chunk-OMIMK3LB.js.map → chunk-IOHK45WE.js.map} +0 -0
  345. /package/dist/{chunk-6IUFNTBQ.js.map → chunk-JVBIWU7S.js.map} +0 -0
  346. /package/dist/{chunk-7NSQVIIK.js.map → chunk-KDO7D46L.js.map} +0 -0
  347. /package/dist/{chunk-GJ5V357G.js.map → chunk-KL4YYV37.js.map} +0 -0
  348. /package/dist/{chunk-JWWG624P.js.map → chunk-LKESANVD.js.map} +0 -0
  349. /package/dist/{chunk-RG7NJEN7.js.map → chunk-LZZCJAJQ.js.map} +0 -0
  350. /package/dist/{chunk-AQJSY4CI.js.map → chunk-MM7344RC.js.map} +0 -0
  351. /package/dist/{chunk-HMK3INUS.js.map → chunk-MQCDFSVF.js.map} +0 -0
  352. /package/dist/{chunk-RGUSVBGN.js.map → chunk-OCMNBOPX.js.map} +0 -0
  353. /package/dist/{chunk-X4AXKO3A.js.map → chunk-RGLIW45S.js.map} +0 -0
  354. /package/dist/{chunk-TQOHPNDW.js.map → chunk-RHDZPV6C.js.map} +0 -0
  355. /package/dist/{chunk-VGRZKBUK.js.map → chunk-UP2JTDBI.js.map} +0 -0
  356. /package/dist/{chunk-AGTVDF4O.js.map → chunk-WKOJ7NXD.js.map} +0 -0
  357. /package/dist/{chunk-GNGXYXBC.js.map → chunk-ZRATYLBB.js.map} +0 -0
  358. /package/dist/{cli-BHIBPUQG.js.map → cli-446A536X.js.map} +0 -0
  359. /package/dist/{history-MRRY2VTS.js.map → history-JFZF22M7.js.map} +0 -0
  360. /package/dist/{install-skills-IIMTRQ4K.js.map → install-skills-XSAHNBYD.js.map} +0 -0
  361. /package/dist/{time-actions-DB7OQ2IS.js.map → time-actions-UYBOXET6.js.map} +0 -0
  362. /package/dist/{todo-ODF7RI27.js.map → todo-2R7VID57.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/platform/running-from.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { execFile } from 'node:child_process';\nimport { isPidAlive, killTreeAsync } from './process.js';\nimport { packageRoot } from './package-root.js';\nimport { getConfigDir } from './config.js';\n\n/**\n * Processes running from a folder — a dev server, a watcher, a built app\n * Claude started in a worktree — and what keeps a folder in use on Windows.\n * Archiving stops Claude, but not what it started in the background (`vite`\n * with `run_in_background`): that held a file in `node_modules`, so git\n * removed the worktree only in part, and Restore couldn't move what was left.\n *\n * Two kinds, kept apart on purpose:\n * - runs from it: its program is in the folder — the executable, or an\n * interpreter's script (`node <dir>/node_modules/vite/bin/vite.js`,\n * `dotnet <dir>/bin/App.dll`). Work's to stop, with the session's work.\n * - mentions it: anything else naming the folder (an editor opened on it,\n * a terminal). Named in a message, never stopped: it's the user's.\n */\n\nexport interface RunningProcess {\n pid: number;\n ppid: number;\n /** Its executable's file name (\"node.exe\"). */\n name: string;\n /** Its executable's full path, when the system says. */\n exe: string | null;\n /** Its command line ('' when it can't be read). */\n command: string;\n /** Its working folder, where the system says (Linux): a relative script (`node dist/server.js`) is under it. */\n cwd?: string | null;\n}\n\n/** Interpreters whose script is the program: the first argument that isn't an option. */\nconst INTERPRETERS = new Set(['node', 'bun', 'deno', 'python', 'python3', 'pythonw', 'py', 'dotnet', 'java', 'javaw', 'ruby', 'php']);\n\nconst win = process.platform === 'win32';\n\n/** A path as compared: absolute, normalised, `\\` and case-blind on Windows. */\nexport function normDir(p: string, windows = win): string {\n if (windows) return path.win32.normalize(p.replace(/\\//g, '\\\\')).replace(/\\\\+$/, '').toLowerCase();\n return path.posix.normalize(p).replace(/\\/+$/, '');\n}\n\nfunction under(p: string, dir: string, windows: boolean): boolean {\n const a = normDir(p, windows);\n const sep = windows ? '\\\\' : '/';\n return a === dir || a.startsWith(dir + sep);\n}\n\n/** A command line's words: quotes group, and are dropped (Windows' rules, roughly; enough to find a path). */\nexport function commandWords(command: string): string[] {\n const out: string[] = [];\n for (const m of command.matchAll(/\"([^\"]*)\"|(\\S+)/g)) out.push(m[1] ?? m[2]);\n return out;\n}\n\nconst bare = (file: string) =>\n file\n .split(/[\\\\/]/)\n .pop()!\n .toLowerCase()\n .replace(/\\.exe$/, '');\n\n/** Its program is in one of `dirs` (normalised with normDir): the executable, or an interpreter's script. */\nexport function runsFrom(p: RunningProcess, dirs: string[], windows = win): boolean {\n const words = commandWords(p.command);\n const exe = p.exe ?? words[0] ?? '';\n if (exe && dirs.some((d) => under(exe, d, windows))) return true;\n // Its version gone: python3.12, node22 (Linux names the binary itself).\n if (!INTERPRETERS.has(bare(exe || p.name).replace(/[\\d.]+$/, ''))) return false;\n // Its script: the first argument that isn't an option, or the first that names a program file (an option's value\n // comes first in `node -r ts-node/register <dir>/src/index.ts`). Not any later one: `node C:\\tools\\fmt.js <dir>\\a.ts`\n // runs a tool of yours on a file there, its program elsewhere.\n const args = words.slice(1);\n const first = args.find((w) => !w.startsWith('-'));\n const relative = (w: string) => !(windows ? path.win32.isAbsolute(w) : w.startsWith('/'));\n const scripts = [first, args.find((w) => SCRIPT_FILE.test(w))]\n .filter((w): w is string => !!w && (/[\\\\/]/.test(w) || (!!p.cwd && SCRIPT_FILE.test(w))))\n // A relative one is where the process works (`node dist/server.js`, `python manage.py`), when that's known.\n .map((w) => (relative(w) && p.cwd ? (windows ? path.win32.resolve(p.cwd, w) : path.posix.resolve(p.cwd, w)) : w));\n return scripts.some((w) => dirs.some((d) => under(w, d, windows)));\n}\n\nconst SCRIPT_FILE = /\\.(c|m)?(js|ts)$|\\.(py|dll|jar|rb|php)$/i;\n\n/** node-pty's own processes (the console it gives a terminal): work's, when it runs from a checkout. */\nexport function isPtyHelper(p: RunningProcess): boolean {\n return /[\\\\/]node-pty[\\\\/]/i.test(`${p.exe ?? ''} ${p.command}`) || /^(conpty|openconsole|winpty-agent)(\\.exe)?$/i.test(p.name);\n}\n\n/**\n * An editor's helper — a language server, the TypeScript server — even one running the worktree's own copy\n * (`node <wt>/node_modules/typescript/lib/tsserver.js`, VS Code's \"use the workspace version\"): the editor's, which\n * the user closes; stopping it only makes the editor report a crash. Known by what editors start them with.\n */\nexport function isEditorHelper(p: RunningProcess): boolean {\n const words = commandWords(p.command);\n if (words.some((w) => /^--(useNodeIpc|node-ipc|clientProcessId(=.*)?|cancellationPipeName)$/i.test(w))) return true;\n return words.slice(1).some((w) => /[\\\\/](tsserver|typingsInstaller)\\.js$|language-?server|langserver/i.test(w));\n}\n\n/** Where this work runs from: its `dist/bin.js` (an npm install, a linked checkout, the desktop app's copy). */\nexport function workBinPaths(): string[] {\n const root = packageRoot();\n return root ? [normDir(path.join(root, 'dist', 'bin.js'))] : [];\n}\n\n/**\n * One of work's own (the PTY host, a work web, a hook): this work's own `bin.js` running one of those — never\n * stopped, wherever it's installed (stopping the PTY host stops every session's Claude). Not any `bin.js web`:\n * a project's own would be spared, and keep its worktree in use.\n */\nexport function isWorkProcess(p: RunningProcess, bins: string[] = workBinPaths(), windows = win): boolean {\n if (bins.length === 0) return false;\n const raw = commandWords(p.command);\n return raw.some((w, i) => /^(pty-host|web|hook)$/.test(raw[i + 1] ?? '') && bins.includes(normDir(w, windows)));\n}\n\n/** It names one of `dirs` somewhere in its command line or executable path. */\nexport function mentions(p: RunningProcess, dirs: string[], windows = win): boolean {\n const norm = (s: string) => (windows ? s.replace(/\\//g, '\\\\').toLowerCase() : s);\n const text = `${norm(p.exe ?? '')} ${norm(p.command)}`;\n // The folder itself, or inside it: anything but more of a name may follow (a separator, a quote, `&`, `;`, the\n // end) — not feat-x2 or feat-x-old, which are other folders.\n return dirs.some((d) => {\n for (let at = text.indexOf(d); at >= 0; at = text.indexOf(d, at + 1)) {\n const next = text[at + d.length];\n if (next === undefined || !/[\\w.-]/.test(next)) return true;\n }\n return false;\n });\n}\n\nexport interface Holders {\n /** Run from the folders: stop these (each the top of its tree — its children go with it on Windows). */\n stoppable: RunningProcess[];\n /** Every one that runs from them, children too: POSIX kills one process at a time. */\n running?: RunningProcess[];\n /** Name the folders but run from elsewhere (an editor, a shell): the user's to close. */\n others: RunningProcess[];\n}\n\n/**\n * What runs from or names `dirs`, in `procs`. Never this process or one it runs under, never one in `spare` (the\n * PTY host and work web by their recorded pids) or under it, and never one of work's own by its command line\n * (isWorkProcess) — whatever folder they run from.\n */\nexport function holdersOf(\n procs: RunningProcess[],\n dirs: string[],\n self = process.pid,\n windows = win,\n spare: ReadonlySet<number> = new Set(),\n bins: string[] = workBinPaths(),\n): Holders {\n const norm = dirs.map((d) => normDir(d, windows));\n const byPid = new Map(procs.map((p) => [p.pid, p]));\n const mine = new Set<number>();\n for (let pid: number | undefined = self; pid && !mine.has(pid); pid = byPid.get(pid)?.ppid) mine.add(pid);\n // work's own (by pid or command line), and the terminal helpers they run (node-pty's, from where work is\n // installed — a checkout's node_modules). Not everything under them: a dev server a Claude started is a\n // descendant of the PTY host until that Claude is gone, and stopping it is the point.\n const ownWork = (q: RunningProcess) => spare.has(q.pid) || isWorkProcess(q, bins, windows);\n const spared = (p: RunningProcess): boolean => {\n if (ownWork(p)) return true;\n if (!isPtyHelper(p)) return false;\n const seen = new Set<number>();\n for (let q = byPid.get(p.ppid); q && !seen.has(q.pid); q = byPid.get(q.ppid)) {\n if (ownWork(q)) return true;\n seen.add(q.pid);\n }\n return false;\n };\n const candidates = procs.filter((p) => !mine.has(p.pid) && !spared(p));\n // An editor's helper is the user's, like the editor: named, never stopped.\n const running = candidates.filter((p) => runsFrom(p, norm, windows) && !isEditorHelper(p));\n const runningPids = new Set(running.map((p) => p.pid));\n return {\n stoppable: running.filter((p) => !runningPids.has(p.ppid)),\n running,\n others: candidates.filter((p) => !runningPids.has(p.pid) && mentions(p, norm, windows)),\n };\n}\n\n/** The pids work recorded for its PTY host and work web (and the dev server's): spared by every stop. */\nexport function workPids(dir = getConfigDir()): Set<number> {\n const out = new Set<number>();\n for (const file of ['pty-host.json', 'web.pid', 'web-dev.pid']) {\n try {\n const raw = fs.readFileSync(path.join(dir, file), 'utf-8').trim();\n const pid = raw.startsWith('{') ? (JSON.parse(raw) as { pid?: unknown }).pid : Number(raw.split(/\\s/)[0]);\n if (typeof pid === 'number' && Number.isInteger(pid) && pid > 0) out.add(pid);\n } catch {\n /* not running, or not recorded */\n }\n }\n return out;\n}\n\n/** \"node …\\vite\\bin\\vite.js --mode demo (PID 35464)\": its name and command, the folder shortened to \"…\". */\nexport function describeProcess(p: RunningProcess, dirs: string[], windows = win): string {\n const words = commandWords(p.command).slice(1);\n let args = words.join(' ');\n // The folder (normalised as normDir: `\\`, lower case on Windows) wherever it appears, as typed.\n for (const d of dirs) {\n // Char by char, and only where lower case keeps the length (an İ doesn't): the positions stay those of `args`.\n const fold = (s: string) =>\n windows\n ? [...s]\n .map((c) => {\n const l = (c === '/' ? '\\\\' : c).toLowerCase();\n return l.length === c.length ? l : c;\n })\n .join('')\n : s;\n for (let at = fold(args).indexOf(d); at >= 0; at = fold(args).indexOf(d)) args = args.slice(0, at) + '…' + args.slice(at + d.length);\n }\n if (args.length > 90) args = `${args.slice(0, 89)}…`;\n const name = bare(p.name || p.exe || '?');\n return `${name}${args ? ` ${args}` : ''} (PID ${p.pid})`;\n}\n\n/** Windows: `Get-CimInstance Win32_Process` as JSON (one object, or a list). */\nexport function parseCimProcesses(json: string): RunningProcess[] {\n let data: unknown;\n try {\n data = JSON.parse(json);\n } catch {\n return [];\n }\n const rows = Array.isArray(data) ? data : data ? [data] : [];\n const out: RunningProcess[] = [];\n for (const r of rows) {\n if (!r || typeof r !== 'object') continue;\n const o = r as Record<string, unknown>;\n if (typeof o.ProcessId !== 'number') continue;\n out.push({\n pid: o.ProcessId,\n ppid: typeof o.ParentProcessId === 'number' ? o.ParentProcessId : 0,\n name: typeof o.Name === 'string' ? o.Name : '',\n exe: typeof o.ExecutablePath === 'string' ? o.ExecutablePath : null,\n command: typeof o.CommandLine === 'string' ? o.CommandLine : '',\n });\n }\n return out;\n}\n\n/** macOS: `ps -A -o pid=,ppid=,args=`. */\nexport function parsePsProcesses(stdout: string): RunningProcess[] {\n const out: RunningProcess[] = [];\n for (const line of stdout.split(/\\r?\\n/)) {\n const m = /^\\s*(\\d+)\\s+(\\d+)\\s+(.*)$/.exec(line);\n if (!m) continue;\n const command = m[3].trim();\n const first = commandWords(command)[0] ?? '';\n out.push({\n pid: Number(m[1]),\n ppid: Number(m[2]),\n name: path.posix.basename(first),\n exe: first.startsWith('/') ? first : null,\n command,\n });\n }\n return out;\n}\n\n/** Read asynchronously: work web's requests wait behind a synchronous walk of /proc. */\nasync function linuxProcesses(): Promise<RunningProcess[]> {\n const out: RunningProcess[] = [];\n let pids: string[];\n try {\n pids = (await fs.promises.readdir('/proc')).filter((d) => /^\\d+$/.test(d));\n } catch {\n return out;\n }\n for (const d of pids) {\n try {\n const stat = await fs.promises.readFile(`/proc/${d}/stat`, 'utf-8');\n const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);\n const command = (await fs.promises.readFile(`/proc/${d}/cmdline`, 'utf-8'))\n .split('\\0')\n .filter(Boolean)\n .map((w) => (/\\s/.test(w) ? `\"${w}\"` : w))\n .join(' ');\n let exe: string | null = null;\n let cwd: string | null = null;\n try {\n exe = await fs.promises.readlink(`/proc/${d}/exe`);\n cwd = await fs.promises.readlink(`/proc/${d}/cwd`);\n } catch {\n /* another user's */\n }\n out.push({ pid: Number(d), ppid, name: exe ? path.posix.basename(exe) : '', exe, command, cwd });\n } catch {\n /* gone meanwhile */\n }\n }\n return out;\n}\n\nconst run = (cmd: string, args: string[]): Promise<string> =>\n new Promise((resolve) =>\n execFile(cmd, args, { encoding: 'utf-8', windowsHide: true, timeout: 20_000, maxBuffer: 64 * 1024 * 1024 }, (_err, stdout) =>\n resolve(stdout ?? ''),\n ),\n );\n\n/** Every process with its parent, executable and command line. Empty when they can't be read. */\nexport async function listProcesses(): Promise<RunningProcess[]> {\n if (process.platform === 'linux') return linuxProcesses();\n if (process.platform === 'win32') {\n return parseCimProcesses(\n await run('powershell', [\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n // UTF-8 out: the console's code page would turn a path with Š or č into ?.\n '[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine | ConvertTo-Json -Compress',\n ]),\n );\n }\n return parsePsProcesses(await run('ps', ['-A', '-o', 'pid=,ppid=,args=']));\n}\n\n/** Look up what runs from or names `dirs` now. */\nexport async function findHolders(\n dirs: string[],\n list: () => Promise<RunningProcess[]> = listProcesses,\n spare: ReadonlySet<number> = workPids(),\n): Promise<Holders> {\n const existing = dirs.filter((d) => fs.existsSync(d));\n if (existing.length === 0) return { stoppable: [], running: [], others: [] };\n return holdersOf(await list(), existing, process.pid, win, spare);\n}\n\n/**\n * What runs from `dirs`, by name, stopping nothing. Throws when the processes can't be read (none listed: there are\n * always some), so \"nothing runs there\" is never a guess.\n */\nexport async function runningFromNames(dirs: string[], list: () => Promise<RunningProcess[]> = listProcesses): Promise<string[]> {\n const procs = await list();\n if (procs.length === 0) throw new Error(\"couldn't read the running processes\");\n const h = await findHolders(dirs, async () => procs);\n const norm = dirs.map((d) => normDir(d));\n return h.stoppable.map((p) => describeProcess(p, norm));\n}\n\n/** How long a stop waits for what it stopped to be gone (its files let go) before going on. */\nconst EXIT_WAIT_MS = 3000;\n\n/**\n * Stop what runs from `dirs`, and say what: [\"node …\\vite\\bin\\vite.js --mode demo (PID 35464)\"]. Only processes\n * whose program is in the folders — never an editor open on them, never one of work's own. Windows stops each\n * tree; POSIX each process (a kill there is one process). Waits a moment for them to be gone, so the folder is\n * free when it returns.\n */\nexport async function stopRunningFrom(\n dirs: string[],\n io: {\n list?: () => Promise<RunningProcess[]>;\n kill?: (pid: number) => Promise<boolean> | boolean;\n alive?: (pid: number) => boolean;\n spare?: ReadonlySet<number>;\n waitMs?: number;\n } = {},\n): Promise<string[]> {\n const h = await findHolders(dirs, io.list, io.spare);\n const kill = io.kill ?? killTreeAsync;\n const alive = io.alive ?? isPidAlive;\n const targets = win ? h.stoppable : (h.running ?? h.stoppable);\n // All at once, and off the event loop (taskkill takes a few hundred ms each; work web answers meanwhile).\n const killed = await Promise.all(targets.map((p) => Promise.resolve(kill(p.pid)).catch(() => false)));\n const stopped = targets.filter((_, i) => killed[i]);\n for (const until = Date.now() + (io.waitMs ?? EXIT_WAIT_MS); stopped.some((p) => alive(p.pid)) && Date.now() < until;) {\n await new Promise((r) => setTimeout(r, 100));\n }\n const norm = dirs.map((d) => normDir(d));\n const named = new Set(h.stoppable.map((p) => p.pid));\n return stopped.filter((p) => named.has(p.pid)).map((p) => describeProcess(p, norm));\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,gBAAgB;AAkCzB,IAAM,eAAe,oBAAI,IAAI,CAAC,QAAQ,OAAO,QAAQ,UAAU,WAAW,WAAW,MAAM,UAAU,QAAQ,SAAS,QAAQ,KAAK,CAAC;AAEpI,IAAM,MAAM,QAAQ,aAAa;AAG1B,SAAS,Q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IAAI,MAAM,YAAY,MAAM,YAAY,KAAK;AACnD,QAAM,OAAO,KAAK,IAAI,CAAC,MAAM,QAAQ,CAAC,CAAC;AACvC,SAAO,EAAE,UAAU,IAAI,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AACxD;AAGA,IAAM,eAAe;AAQrB,eAAsB,gBACpB,MACA,KAMI,CAAC,GACc;AACnB,QAAM,IAAI,MAAM,YAAY,MAAM,GAAG,MAAM,GAAG,KAAK;AACnD,QAAM,OAAO,GAAG,QAAQ;AACxB,QAAM,QAAQ,GAAG,SAAS;AAC1B,QAAM,UAAU,MAAM,EAAE,YAAa,EAAE,WAAW,EAAE;AAEpD,QAAM,SAAS,MAAM,QAAQ,IAAI,QAAQ,IAAI,CAAC,MAAM,QAAQ,QAAQ,KAAK,EAAE,GAAG,CAAC,EAAE,MAAM,MAAM,KAAK,CAAC,CAAC;AACpG,QAAM,UAAU,QAAQ,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC;AAClD,aAAW,QAAQ,KAAK,IAAI,KAAK,GAAG,UAAU,eAAe,QAAQ,KAAK,CAAC,MAAM,MAAM,EAAE,GAAG,CAAC,KAAK,KAAK,IAAI,IAAI,SAAQ;AACrH,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,GAAG,CAAC;AAAA,EAC7C;AACA,QAAM,OAAO,KAAK,IAAI,CAAC,MAAM,QAAQ,CAAC,CAAC;AACvC,QAAM,QAAQ,IAAI,IAAI,EAAE,UAAU,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC;AACnD,SAAO,QAAQ,OAAO,CAAC,MAAM,MAAM,IAAI,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AACpF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/pty/output-status.ts","../src/core/pty/pty-pool.ts","../src/core/sessions/web-state.ts"],"sourcesContent":["import type { SessionAttention } from '../api-types.js';\n\n/**\n * A status for a session whose tool isn't Claude Code (config `aiCommand`,\n * e.g. opencode): no hooks report its turns, so the PTY host's \"last printed\n * anything\" stands in — a working agent redraws its spinner, an idle one\n * prints nothing. Working while it printed in the last `OUTPUT_WORKING_MS`,\n * idle after; never \"done, unseen\" or \"needs input\" (output can't tell a\n * finished turn from a question). Pure.\n */\n\nexport const OUTPUT_WORKING_MS = 10_000;\n\nexport interface PtyOutput {\n /** The tool's binary (the host's spawn spec). */\n tool?: string;\n /** When it last printed (ISO). */\n lastOutputAt?: string;\n startedAt: string;\n}\n\nexport function statusFromOutput(p: PtyOutput, now: number): SessionAttention | null {\n if (!p.tool || p.tool === 'claude' || !p.lastOutputAt) return null;\n const at = Date.parse(p.lastOutputAt);\n if (!Number.isFinite(at)) return null;\n const working = now - at < OUTPUT_WORKING_MS;\n return {\n state: working ? 'working' : 'idle',\n seen: true,\n since: p.lastOutputAt,\n updatedAt: p.lastOutputAt,\n stale: false,\n summary: `${working ? 'Printing' : 'Quiet'} — from its terminal output (${p.tool} has no status hooks)`,\n };\n}\n","import path from 'node:path';\nimport type { AgentAdapter } from '../agents/types.js';\nimport { agentFor, agentSettings, assistantAgent } from '../agents/index.js';\nimport { statusFromOutput, type PtyOutput } from './output-status.js';\nimport type { SessionAttention } from '../api-types.js';\nimport type { HostBeat } from './host-health.js';\nimport { PtyHostBusyError } from './pty-host-client.js';\nimport { noClaudeBecause } from '../archive/archiving.js';\nimport { findSession, sessionIdFor } from '../sessions/web-state.js';\nimport type { WorktreeSession } from '../sessions/history.js';\nimport { hostStartLockPath, type SpawnSpec, type HostInfo, type PtyInfo } from './pty-host-protocol.js';\nimport { dbPtySessions } from './pty-sessions-file.js';\nimport { ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { forgetPersistedSession } from './pty-sessions-file.js';\nimport { loadConfig } from '../platform/config.js';\nimport { hasEnvDelta, type EnvDelta } from '../platform/env-delta.js';\nimport { ensureHost, findHost, PtyHostClient, findHostPatient, PtyHostVersionError } from './pty-host-client.js';\nimport { logSwallowed, swallow } from '../platform/best-effort.js';\nimport { ASSISTANT_ID, prepareAssistantDir } from '../agents/assistant.js';\n\n/**\n * `work web`'s view of the Claude PTYs. The PTYs themselves live in the\n * PTY host (`work pty-host`, see core/pty-host.ts), a separate long-lived\n * process — so restarting or rebuilding `work web` never kills an agent,\n * and a real terminal (`work attach`) can share the same session.\n *\n * This module resolves a dashboard session to a spawn spec, asks the host\n * to spawn it on first attach, and keeps a small cache of which sessions\n * have a live PTY for the synchronous badge path (`peekPty`).\n */\n\nlet workBin = process.argv[1] ?? '';\n/** Whether this server may start the PTY host when none runs (not the dev server: see configurePtyPool). */\nlet mayStartHost = true;\nlet client: PtyHostClient | null = null;\nlet live = new Set<string>();\n/** The pids of those PTYs' processes (the Claudes the app runs). */\nlet livePids = new Set<number>();\n/** Each live PTY's tool and last output (for output-status.ts). */\nlet outputs = new Map<string, PtyOutput & { pid: number }>();\nlet refreshTimer: NodeJS.Timeout | null = null;\n/** The heartbeat (host-health.ts): each list request is one. */\nconst beat: HostBeat = { known: false, lastOkAt: null, latencyMs: null, lastError: null };\n\n/** How the host answered lately (for GET /api/pty-host/health). */\nexport function hostBeat(): HostBeat {\n return { ...beat };\n}\nconst REFRESH_MS = 2000;\n\n/** Called by `work web` at startup with the resolved `work` binary path,\n * which is what the host is spawned from. */\nexport function configurePtyPool(opts: { workBin: string; startHost?: boolean }): void {\n workBin = opts.workBin;\n // The dev server (`work web --dev`) uses the host that runs and never starts one: started\n // from a checkout's build, the long-lived host that owns every Claude would outlive it,\n // and the installed work would become a client of the checkout's code.\n mayStartHost = opts.startHost ?? true;\n}\n\n/** The `work` binary path, for routes that launch `work attach`. */\nexport function getWorkBin(): string {\n return workBin;\n}\n\nasync function getClient(spawnIfMissing: boolean): Promise<PtyHostClient | null> {\n if (client) {\n // Cheap liveness re-check happens in refresh(); a dead host surfaces\n // as a failed call, which resets `client` below.\n return client;\n }\n const info = spawnIfMissing && mayStartHost ? await ensureHost(workBin) : await findHost();\n if (!info && spawnIfMissing && !mayStartHost)\n throw new Error(\n \"No PTY host is running, and the dev server doesn't start one: start the installed work (its app or `work web`) first.\",\n );\n if (!info) return null;\n client = new PtyHostClient(info);\n startRefresh();\n return client;\n}\n\nasync function refresh(): Promise<void> {\n const t0 = Date.now();\n try {\n const c = await getClient(false);\n if (!c) {\n beat.known = false;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n return;\n }\n beat.known = true;\n const ptys = await c.list();\n beat.lastOkAt = Date.now();\n beat.latencyMs = beat.lastOkAt - t0;\n beat.lastError = null;\n live = new Set(ptys.filter((p) => !p.exited).map((p) => p.id));\n livePids = new Set(ptys.filter((p) => !p.exited).map((p) => p.pid));\n outputs = new Map(\n ptys.filter((p) => !p.exited).map((p) => [p.id, { tool: p.tool, lastOutputAt: p.lastOutputAt, startedAt: p.startedAt, pid: p.pid }]),\n );\n } catch (err) {\n // Host went away (or was restarted on a new port) — rediscover next tick.\n // A busy host is still a host (it is there, just not answering).\n beat.known = beat.known || err instanceof PtyHostBusyError;\n beat.lastError = (err as Error).message;\n client = null;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n }\n}\n\nfunction startRefresh(): void {\n if (refreshTimer) return;\n refreshTimer = setInterval(() => void refresh(), REFRESH_MS);\n refreshTimer.unref?.();\n}\n\n/** Connect to an already-running host at `work web` startup so badges for\n * PTYs that survived a web restart show immediately. Never spawns. */\n/** Re-read the host's PTY list now (the periodic refresh can be seconds old,\n * or not have run at all right after `work web` started). */\nexport async function syncPtyPool(): Promise<void> {\n await refresh();\n}\n\nexport async function initPtyPool(): Promise<void> {\n await refresh().catch(() => {});\n startRefresh();\n}\n\n/**\n * After a reboot (or a host crash) nothing is running but\n * `pty-sessions.json` still lists the sessions that were live. Starting the\n * host restores them; do that when there's something to restore, so\n * reopening `work web` picks up where you left off. Returns how many\n * sessions the host will bring back (0 = nothing to do).\n */\nexport async function resumePersistedSessions(): Promise<number> {\n let count: number;\n try {\n count = Object.keys(dbPtySessions.read()).length;\n } catch {\n return 0;\n }\n if (count === 0) return 0;\n if (await findHost().catch(() => true)) return 0; // already running\n await getClient(true);\n await refresh();\n return count;\n}\n\n/**\n * Where Claude runs for a session — the same directory `work tree` launches\n * in: the worktree for a single repo, the group root (parent of the\n * sub-repos) for a group.\n */\nexport { ASSISTANT_ID };\n\n/** The assistant runs config `assistantAgent` (Claude Code by default), in its folder written for that agent. */\nexport function assistantSpec(): { cwd: string; tool: ReturnType<AgentAdapter['launch']['tool']>; agentEnv?: EnvDelta } {\n const settings = agentSettings();\n const agent = assistantAgent(settings);\n // Work's own session, not any session's: the configured default account (`launch.env(null)`).\n const agentEnv = agent.launch.env?.(null);\n return { cwd: prepareAssistantDir(agent), tool: agent.launch.tool(settings), ...(hasEnvDelta(agentEnv) ? { agentEnv } : {}) };\n}\n\nexport function spawnSpecFor(session: WorktreeSession): SpawnSpec | null {\n const first = session.paths[0];\n if (!first) return null;\n const cwd = session.isGroup ? path.dirname(first) : first;\n const config = loadConfig();\n const launch = agentFor(config, session).launch;\n // The session's account: its agent's folder env, applied by the host over whatever environment it starts with.\n const agentEnv = launch.env?.(session);\n return { cwd, tool: launch.tool(config), port: session.port, ...(hasEnvDelta(agentEnv) ? { agentEnv } : {}) };\n}\n\n/**\n * Ensure a live PTY exists for the session (spawning Claude in the host if\n * needed) and return the host WebSocket URL to attach to. Null for an\n * unknown session.\n */\nexport async function ensurePty(sessionId: string, extra: { initialPrompt?: string } = {}): Promise<string | null> {\n // The dashboard assistant (Ctrl+K) is not a worktree: it runs in its own\n // folder, which is (re)written first (assistant.ts).\n const session = sessionId === ASSISTANT_ID ? null : findSession(sessionId);\n // Not for a session being archived, or archived: its Claude was stopped on\n // purpose (a Terminal tab still open on it reconnects and would start it).\n const refused = sessionId === ASSISTANT_ID ? null : noClaudeBecause(session, sessionId);\n if (refused) throw new Error(refused);\n const base = sessionId === ASSISTANT_ID ? assistantSpec() : session ? spawnSpecFor(session) : null;\n if (!base) return null;\n // The first prompt only applies to a fresh spawn (the host ignores the\n // spec when the session's PTY is already running).\n const spec = extra.initialPrompt ? { ...base, initialPrompt: extra.initialPrompt } : base;\n\n let c = await getClient(true);\n if (!c) return null;\n // A host from before accounts would start it on its own environment — another account than the session's.\n if (setsEnv(spec.agentEnv) && !(await hostTakesAgentEnv(c)) && !(await runsIn(c, sessionId))) throw new Error(OLD_HOST_ACCOUNTS);\n try {\n await c.spawn(sessionId, spec);\n } catch (err) {\n // Stale client (host restarted on a new port) — retry once, fresh.\n client = null;\n c = await getClient(true);\n if (!c) throw err;\n await c.spawn(sessionId, spec);\n }\n live.add(sessionId);\n return c.attachUrl(sessionId);\n}\n\n/** Side-effect-free check: does an active (non-exited) PTY exist for this\n * session? Served from the refresh cache — used by session-meta for the\n * \"running/idle\" badge, which must stay synchronous. */\n/** Every PTY in the host, fresh (never starts a host; [] without one). */\nexport async function listHostPtys(): Promise<PtyInfo[]> {\n const c = await getClient(false);\n return c ? c.list() : [];\n}\n\n/** Pids of the Claudes running in the PTY host (from the refresh cache). */\nexport function ptyPids(): ReadonlySet<number> {\n return livePids;\n}\n\n/** A status from its terminal output, for a session whose tool has no hooks (output-status.ts); null for Claude or no PTY. */\nexport function outputStatus(sessionId: string, now = Date.now()): SessionAttention | null {\n const o = outputs.get(sessionId);\n return o ? statusFromOutput(o, now) : null;\n}\n\n/** When a session's terminal last printed (ms, from the refresh cache); null with no PTY or a host that doesn't say. */\nexport function ptyLastOutputMs(sessionId: string): number | null {\n const at = outputs.get(sessionId)?.lastOutputAt;\n const ms = at ? Date.parse(at) : NaN;\n return Number.isFinite(ms) ? ms : null;\n}\n\n/** Its agent's process id in the host (from the refresh cache); null with no PTY. */\nexport function ptyPid(sessionId: string): number | null {\n return outputs.get(sessionId)?.pid ?? null;\n}\n\nexport function peekPty(sessionId: string): boolean {\n return live.has(sessionId);\n}\n\n/** A session's live PTY screen as text; null when there is none (never spawns). */\nexport async function readPtyScreen(sessionId: string): Promise<string | null> {\n if (!live.has(sessionId)) return null;\n const c = await getClient(false);\n return c ? c.screen(sessionId) : null;\n}\n\n/** Write to a session's live PTY. False when there is none (never spawns). */\nexport async function writeToPty(sessionId: string, data: string): Promise<boolean> {\n if (!live.has(sessionId)) return false;\n const c = await getClient(false);\n return c ? c.write(sessionId, data) : false;\n}\n\n/**\n * Restart a session's agent in the host, resuming its conversation, its terminals\n * kept attached (agent-restart.ts). A host from before that call: stopped and\n * started again (an open Terminal tab then offers Enter, as after a stop).\n */\nexport async function restartPty(sessionId: string): Promise<string | void> {\n let c = await getClient(false);\n if (!c) throw new Error('the PTY host is not running');\n let how: Awaited<ReturnType<PtyHostClient['restart']>>;\n try {\n how = await c.restart(sessionId);\n } catch (err) {\n // A stale client (the host restarted on a new port before the refresh noticed): once more, fresh.\n client = null;\n c = await getClient(false);\n if (!c) throw err;\n how = await c.restart(sessionId);\n }\n if (how === 'not-running') throw new Error('its agent is not running in the PTY host');\n if (how === 'unsupported') {\n await disposePty(sessionId);\n if (!(await ensurePty(sessionId))) throw new Error('its agent could not be started again');\n return OLD_HOST_RESTART;\n }\n}\n\n/**\n * Stop a session's agent and keep its session in the host (entry, restore record, attached terminals) until `resumePty`:\n * a switch of account moves its conversation files in between. `stopped`: a host from before the call stopped it the old\n * way (its terminals were told it ended; `resumePtyOnAccount` then starts it fresh); `gone`: nothing was running.\n */\nexport async function haltPty(sessionId: string): Promise<'halted' | 'stopped' | 'gone'> {\n let c = await getClient(false);\n if (!c) throw new Error('the PTY host is not running');\n let how: Awaited<ReturnType<PtyHostClient['halt']>>;\n try {\n how = await c.halt(sessionId);\n } catch (err) {\n // A stale client (the host restarted on a new port before the refresh noticed): once more, fresh.\n client = null;\n c = await getClient(false);\n if (!c) throw err;\n how = await c.halt(sessionId);\n }\n if (how === 'not-running') return 'gone';\n if (how === 'unsupported') {\n await disposePty(sessionId);\n return 'stopped';\n }\n return 'halted';\n}\n\n/** Why a switch of account can't be done in this PTY host now (it is from before accounts), or null: asked before halting. */\nexport async function accountSwitchRefusal(): Promise<string | null> {\n const c = await getClient(false);\n return c && !(await hostTakesAgentEnv(c)) ? OLD_HOST_ACCOUNTS : null;\n}\n\n/**\n * Start a halted session's agent again in place, on `opts.agentEnv` (its terminals carry on). `not-halted`: it isn't\n * halted any more — the host started it again by itself (HALT_RESUME_MS) or restarted, on its old spec.\n */\nexport async function resumePty(sessionId: string, opts: { agentEnv?: EnvDelta } = {}): Promise<'resumed' | 'not-halted'> {\n let c = await getClient(false);\n if (!c) throw new Error('the PTY host is not running');\n if (hasEnvDelta(opts.agentEnv) && !(await hostTakesAgentEnv(c))) throw new Error(OLD_HOST_ACCOUNTS);\n let how: Awaited<ReturnType<PtyHostClient['resume']>>;\n try {\n how = await c.resume(sessionId, opts);\n } catch (err) {\n client = null;\n c = await getClient(false);\n if (!c) throw err;\n how = await c.resume(sessionId, opts);\n }\n return how;\n}\n\n/**\n * Start the agent of a session `haltPty` stopped, on the account the session records NOW (after a switch: the new one;\n * after one that failed: the old): resumed in place with that environment, or — `stopped`, an older host — started\n * again from a fresh spec (its terminals show it ended; opening the session reconnects).\n */\nexport async function resumePtyOnAccount(sessionId: string, how: 'halted' | 'stopped'): Promise<string | void> {\n if (how === 'stopped') {\n if (!(await ensurePty(sessionId))) throw new Error('its agent could not be started again');\n return OLD_HOST_RESTART;\n }\n const session = findSession(sessionId);\n const spec = session ? spawnSpecFor(session) : null;\n if (!spec) throw new Error('unknown session');\n // Nothing in the delta means no account change to apply (the default, with no accounts configured): a plain resume.\n const agentEnv = hasEnvDelta(spec.agentEnv) ? spec.agentEnv : undefined;\n if ((await resumePty(sessionId, agentEnv ? { agentEnv } : {})) === 'resumed') return;\n // Started again meanwhile on its OLD spec (the host's own resume after HALT_RESUME_MS — a long move —, or a host\n // restart's restore): restarted in place on the account the session records now, so it doesn't stay on the old one.\n const c = await getClient(false);\n if (!c) throw new Error('the PTY host is not running');\n const restarted = await c.restart(sessionId, agentEnv ? { agentEnv } : {});\n if (restarted === 'restarted') return RESTARTED_AFTER_AUTO_RESUME;\n // Not running now (it ended), or a host that couldn't take the environment in place: started fresh from the new spec.\n if (restarted === 'unsupported') await disposePty(sessionId);\n if (!(await ensurePty(sessionId))) throw new Error('its agent could not be started again');\n return RESTARTED_AFTER_AUTO_RESUME;\n}\n\n/** What a switch says when its halted Claude had been started again (on the old account) before the move was done. */\nexport const RESTARTED_AFTER_AUTO_RESUME =\n 'it had been started again on its old account while the conversation moved, so it was restarted on the new one';\n\n/** Said when a session on a named account would start in a PTY host that drops the account (one from before accounts). */\nexport const OLD_HOST_ACCOUNTS = 'the PTY host is from before Claude accounts: run `work pty-host --restart`';\n\n/** The delta sets a variable (a session on a named account): what an older host would drop, starting it elsewhere. */\nconst setsEnv = (d: EnvDelta | undefined): boolean => !!d && Object.values(d).some((v) => typeof v === 'string');\n\n/** The host applies `agentEnv`; one that can't be asked right now is given the benefit of the doubt (its restart says). */\nasync function hostTakesAgentEnv(c: PtyHostClient): Promise<boolean> {\n const f = await c.features();\n return f === null || f.includes('agentEnv');\n}\n\n/** Its agent runs in this host now (a spawn would only attach to it). */\nasync function runsIn(c: PtyHostClient, sessionId: string): Promise<boolean> {\n return (await c.list()).some((p) => p.id === sessionId && !p.exited);\n}\n\n/** How a restart on a PTY host from before restart-in-place went: what differs, and the way to the real thing. */\nexport const OLD_HOST_RESTART =\n 'stopped and started again (an older PTY host: open terminals show it ended, and it runs with only the variables `hostEnv` keeps; `work pty-host --restart` gets restarts in place)';\n\n/** Kill one session's PTY (if any). Called before removing a worktree so\n * the Claude process doesn't hold its cwd open (Windows refuses to delete\n * a directory that is some process's working directory). */\nexport async function disposePty(sessionId: string): Promise<void> {\n live.delete(sessionId);\n let c = client;\n if (!c) {\n // A busy host (mid-restore) is waited for, not skipped: skipping left\n // Claude running inside the worktree about to be deleted. A host from\n // another build can't be talked to — nothing to do but proceed.\n let info: HostInfo | null;\n try {\n info = await findHostPatient();\n } catch (err) {\n if (err instanceof PtyHostVersionError) return;\n throw err; // still busy after waiting: let the caller report it\n }\n if (!info) return;\n c = new PtyHostClient(info);\n }\n await c.kill(sessionId).catch(swallow(`stop session ${sessionId} in the PTY host`));\n}\n\n/**\n * Stop a session's Claude in the PTY host before its worktree is deleted —\n * from any caller, including the CLI (`work remove` / prune / sync), which\n * doesn't run a pool. Never starts a host; waits for the process to exit\n * (the host's kill does) so Windows can then delete the directory.\n * Best-effort: no host, or a host that can't be reached, is a no-op.\n */\nexport async function stopSessionPty(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch } as WorktreeSession);\n live.delete(id);\n // Under the host START lock: a host that's starting holds it until it has\n // restored, so we either see it running (and kill the session) or know\n // none is — and then drop the session from the saved list so a later\n // start doesn't restore Claude into a worktree that's being deleted.\n const lock = hostStartLockPath();\n ensureFile(lock, '');\n await withFileLock(lock, async () => {\n let info;\n try {\n info = await findHostPatient();\n } catch (err) {\n // A host from another build can't be talked to; one still busy after\n // waiting is running and owns the session — leave both alone (and\n // never drop the saved entry: the host is what it belongs to).\n logSwallowed(`stop session ${id}: PTY host`, err);\n return;\n }\n if (info) await new PtyHostClient(info).kill(id).catch(swallow(`stop session ${id} in the PTY host`));\n else await forgetPersistedSession(id).catch(swallow(`forget saved session ${id}`));\n }).catch(swallow(`stop session ${id}: host start lock`));\n}\n\n/** `work web` shutdown. Deliberately does NOT kill anything: the PTYs belong\n * to the host and outlive the dashboard. Just stops polling. */\nexport function detachPtyPool(): void {\n if (refreshTimer) clearInterval(refreshTimer);\n refreshTimer = null;\n client = null;\n live = new Set();\n livePids = new Set();\n}\n","import { createFsWatcher, type FsWatcher } from '../platform/fs-watcher.js';\nimport { findSessionById, type WorktreeSession } from './history.js';\n\nexport { sessionIdFor } from './session-id.js';\n\n/** A session by id — a primary-key lookup (every /api/sessions/:id/*\n * request does one; it used to load and hash every row). */\nexport function findSession(sessionId: string): WorktreeSession | null {\n return findSessionById(sessionId);\n}\n\ninterface WatcherEntry {\n watcher: FsWatcher;\n subscribers: Set<() => void>;\n}\n\nconst sessionWatchers = new Map<string, WatcherEntry>();\nconst DEBOUNCE_MS = 150;\n\n/**\n * Subscribe to filesystem changes for a session's worktree(s). The watch is\n * started on first subscriber and stopped when the last one leaves —\n * reference-counted so the cost stays proportional to what's actually being\n * viewed in the browser. It is the shared fs-watcher: dependency and build\n * folders (node_modules, bin/obj, dist, …) are left out, and on Windows and\n * macOS it is one recursive OS watch per root. A chokidar watch over the\n * whole worktree used to open one watch per folder, node_modules included.\n *\n * Returns an unsubscribe function. Safe to call multiple times.\n */\nexport function subscribeSession(sessionId: string, onChange: () => void): () => void {\n const session = findSession(sessionId);\n if (!session)\n return () => {\n /* unknown session */\n };\n\n let entry = sessionWatchers.get(sessionId);\n if (!entry) {\n const subscribers = new Set<() => void>();\n const newEntry: WatcherEntry = {\n subscribers,\n watcher: createFsWatcher({\n roots: session.paths,\n debounceMs: DEBOUNCE_MS,\n onChange: () => {\n for (const cb of subscribers) {\n try {\n cb();\n } catch {\n /* swallow */\n }\n }\n },\n }),\n };\n sessionWatchers.set(sessionId, newEntry);\n entry = newEntry;\n }\n\n entry.subscribers.add(onChange);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n entry!.subscribers.delete(onChange);\n if (entry!.subscribers.size === 0) {\n entry!.watcher.stop();\n if (sessionWatchers.get(sessionId) === entry) {\n sessionWatchers.delete(sessionId);\n }\n }\n };\n}\n\n/**\n * Force-stop one session's watcher regardless of subscribers. Used before\n * removing a worktree: on Windows an open directory watch keeps a handle\n * on the tree and makes `git worktree remove` fail. Late unsubscribes from\n * the orphaned entry are harmless (see the identity check above).\n */\nexport async function disposeSessionWatcher(sessionId: string): Promise<void> {\n const entry = sessionWatchers.get(sessionId);\n if (!entry) return;\n sessionWatchers.delete(sessionId);\n entry.subscribers.clear();\n entry.watcher.stop();\n}\n\n/** Stop every active session watcher. Called on server shutdown. */\nexport function disposeAllWatchers(): void {\n for (const [, entry] of sessionWatchers) entry.watcher.stop();\n sessionWatchers.clear();\n}\n"],"mappings":";;;;;;;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I,EAAE,KAAK,EAAE,EAAE,MAAM,QAAQ,gBAAgB,EAAE,kBAAkB,CAAC;AAAA,QAC/F,OAAM,uBAAuB,EAAE,EAAE,MAAM,QAAQ,wBAAwB,EAAE,EAAE,CAAC;AAAA,EACnF,CAAC,EAAE,MAAM,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC;AACzD;AAIO,SAAS,gBAAsB;AACpC,MAAI,aAAc,eAAc,YAAY;AAC5C,iBAAe;AACf,WAAS;AACT,SAAO,oBAAI,IAAI;AACf,aAAW,oBAAI,IAAI;AACrB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/platform/throttle.ts","../src/core/diff/checkpoint-summary.ts"],"sourcesContent":["/**\n * Call `fn` at most once per `ms`: the first call goes through at once, and\n * calls inside the window collapse into one at its end (so the last state\n * always gets through). For events that make every client refetch.\n */\nexport function throttleTrailing(\n fn: () => void,\n ms: number,\n clock: { now: () => number; setTimeout: (cb: () => void, ms: number) => unknown } = {\n now: Date.now,\n setTimeout: (cb, t) => setTimeout(cb, t),\n },\n): () => void {\n let lastAt = -Infinity;\n let pending = false;\n return () => {\n const wait = lastAt + ms - clock.now();\n if (wait <= 0) {\n lastAt = clock.now();\n fn();\n return;\n }\n if (pending) return;\n pending = true;\n clock.setTimeout(() => {\n pending = false;\n lastAt = clock.now();\n fn();\n }, wait);\n };\n}\n\n/**\n * Run jobs one at a time, in the order they came: `run(fn)` resolves with\n * `fn`'s result once every earlier job finished. A failed job doesn't stop\n * the queue.\n */\nexport function createSerialQueue(): <T>(fn: () => Promise<T>) => Promise<T> {\n let tail: Promise<unknown> = Promise.resolve();\n return <T>(fn: () => Promise<T>) => {\n const run = tail.then(fn, fn);\n tail = run.catch(() => undefined);\n return run;\n };\n}\n","/**\n * Lazy, cached one-line summaries of what changed at a checkpoint.\n *\n * The diff between checkpoint `id-1` and `id` is rendered to a compact text\n * blob and handed to `claude -p` for a terse label. The result is cached in\n * the manifest `label` (see `setCheckpointLabel`) so each checkpoint is only\n * summarised once. If Claude is unavailable or times out, a cheap heuristic\n * label (\"3 files · +52 −8\") is returned instead so the UI never blocks on\n * an external binary.\n */\nimport { internalRunEnv } from '../platform/internal-run.js';\nimport spawn from '../platform/spawn.js';\nimport path from 'node:path';\nimport { computeRangeDiff } from './diff-pipeline.js';\nimport { loadManifest } from './checkpoint.js';\nimport { internalAgent, agentSettings } from '../agents/index.js';\nimport { killTree } from '../platform/process.js';\nimport { createSerialQueue } from '../platform/throttle.js';\nimport type { ParsedFile } from './diff-parse.js';\n\nexport interface SummaryRepo {\n /** Manifest key — the full repo path (see scope-routes `scopeRepos`). */\n name: string;\n root: string;\n}\n\n/** Cap on the diff text we feed Claude — keeps the prompt small and cheap. */\nconst MAX_DIFF_CHARS = 6000;\nconst MAX_LABEL_CHARS = 80;\n\n/** Render the delta into checkpoint `id` as `{ files, added, deleted, text }`. */\nfunction buildDelta(\n scopeHash: string,\n repos: SummaryRepo[],\n id: number,\n): { files: ParsedFile[]; added: number; deleted: number; text: string } {\n const manifest = loadManifest(scopeHash);\n const entry = manifest.entries.find((e) => e.id === id);\n const prev = manifest.entries.find((e) => e.id === id - 1);\n const all: ParsedFile[] = [];\n for (const repo of repos) {\n const toRef = entry?.repos[repo.name];\n if (!toRef) continue;\n // Missing prev sha (fresh repo) → diff against the empty tree by passing\n // the well-known empty-tree object isn't available here cheaply; fall\n // back to HEAD which yields the same files for the common case.\n const fromRef = prev?.repos[repo.name] ?? 'HEAD';\n try {\n all.push(...computeRangeDiff({ root: repo.root, fromRef, toRef }));\n } catch {\n /* skip a repo that fails to diff */\n }\n }\n let added = 0;\n let deleted = 0;\n for (const f of all) {\n added += f.added;\n deleted += f.deleted;\n }\n // Compact patch text: file header lines + their changed lines, truncated.\n const parts: string[] = [];\n let budget = MAX_DIFF_CHARS;\n for (const f of all) {\n const head = `### ${f.status} ${f.path} (+${f.added} -${f.deleted})\\n`;\n if (budget - head.length < 0) break;\n parts.push(head);\n budget -= head.length;\n for (const h of f.hunks) {\n for (const ln of h.lines) {\n if (ln.kind !== 'add' && ln.kind !== 'delete') continue;\n const prefix = ln.kind === 'add' ? '+' : '-';\n const line = `${prefix}${ln.content}\\n`;\n if (budget - line.length < 0) {\n budget = -1;\n break;\n }\n parts.push(line);\n budget -= line.length;\n }\n if (budget < 0) break;\n }\n if (budget < 0) break;\n }\n return { files: all, added, deleted, text: parts.join('') };\n}\n\n/** Cheap fallback label when Claude can't be reached. */\nfunction heuristicLabel(files: ParsedFile[], added: number, deleted: number): string {\n if (files.length === 0) return 'no changes';\n if (files.length === 1) {\n return `${path.basename(files[0].path)} +${added} −${deleted}`;\n }\n return `${files.length} files · +${added} −${deleted}`;\n}\n\n/** One internal run at a time, however many turns finish together. */\nconst internalQueue = createSerialQueue();\n\n/**\n * Run work's summarising agent (config `internalAgent`, Claude Code by\n * default: agents/ `oneShot`) with the prompt on stdin; resolve its trimmed\n * stdout, or null on error, timeout, or an agent that has no one-shot runs.\n * Async (never blocks the server event loop). `small`: a few words wanted.\n */\nexport function runInternal(prompt: string, timeoutMs = 25_000, opts: { small?: boolean } = {}): Promise<string | null> {\n const oneShot = internalAgent(agentSettings()).oneShot;\n if (!oneShot) return Promise.resolve(null);\n return internalQueue(() => runNow(prompt, timeoutMs, oneShot.command(opts)));\n}\n\nfunction runNow(\n prompt: string,\n timeoutMs: number,\n run: { cmd: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv },\n): Promise<string | null> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = (v: string | null) => {\n if (settled) return;\n settled = true;\n resolve(v);\n };\n let out = '';\n let child: ReturnType<typeof spawn>;\n try {\n // Text-only, no tools, neutral cwd, tagged internal (so it doesn't\n // trip work's own hooks) — the agent's oneShot.command.\n child = spawn(run.cmd, run.args, {\n stdio: ['pipe', 'pipe', 'ignore'],\n windowsHide: true,\n cwd: run.cwd,\n env: { ...run.env, ...internalRunEnv() }, // tagged by work, whatever the agent's command says\n });\n } catch {\n finish(null);\n return;\n }\n const timer = setTimeout(() => {\n // The whole tree: on Windows the agent may be a .cmd shim, and killing\n // only cmd.exe left the real one running, orphaned.\n if (child.pid) killTree(child.pid);\n else {\n try {\n child.kill();\n } catch {\n /* already gone */\n }\n }\n finish(null);\n }, timeoutMs);\n child.stdout?.on('data', (d: Buffer) => {\n out += d.toString();\n });\n child.on('error', () => {\n clearTimeout(timer);\n finish(null);\n });\n child.on('close', (code: number | null) => {\n clearTimeout(timer);\n finish(code === 0 && out.trim() ? out.trim() : null);\n });\n try {\n child.stdin?.write(prompt);\n child.stdin?.end();\n } catch {\n clearTimeout(timer);\n finish(null);\n }\n });\n}\n\n/** Normalise Claude's reply to a single terse line. */\nfunction cleanLabel(raw: string): string {\n const firstLine =\n raw\n .split('\\n')\n .map((l) => l.trim())\n .find(Boolean) ?? '';\n // Strip surrounding quotes / trailing punctuation, collapse whitespace.\n const cleaned = firstLine\n .replace(/^[\"'`]+|[\"'`]+$/g, '')\n .replace(/\\s+/g, ' ')\n .replace(/[.;]+$/, '')\n .trim();\n return cleaned.slice(0, MAX_LABEL_CHARS);\n}\n\n/**\n * Produce a one-line label for checkpoint `id`. Tries Claude; falls back to\n * a heuristic. Pure (no caching) — the caller persists the result.\n */\nexport async function summarizeCheckpoint(scopeHash: string, repos: SummaryRepo[], id: number): Promise<string> {\n const { files, added, deleted, text } = buildDelta(scopeHash, repos, id);\n if (files.length === 0) return 'no changes';\n const fallback = heuristicLabel(files, added, deleted);\n if (!text.trim()) return fallback;\n const prompt =\n 'Summarise this code change in 8 words or fewer, imperative mood, ' +\n 'no trailing punctuation. Output ONLY the summary line.\\n\\n' +\n text;\n const reply = await runInternal(prompt, 25_000, { small: true });\n if (!reply) return fallback;\n const label = cleanLabel(reply);\n return label || fallback;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAKO,SAAS,iBACd,IACA,IACA,QAAoF;AAAA,EAClF,KAAK,KAAK;AAAA,EACV,YAAY,CAAC,IAAI,MAAM,WAAW,IAAI,CAAC;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AM,UAAU,UACb,QAAQ,oBAAoB,EAAE,EAC9B,QAAQ,QAAQ,GAAG,EACnB,QAAQ,UAAU,EAAE,EACpB,KAAK;AACR,SAAO,QAAQ,MAAM,GAAG,eAAe;AACzC;AAMA,eAAsB,oBAAoB,WAAmB,OAAsB,IAA6B;AAC9G,QAAM,EAAE,OAAO,OAAO,SAAS,KAAK,IAAI,WAAW,WAAW,OAAO,EAAE;AACvE,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,WAAW,eAAe,OAAO,OAAO,OAAO;AACrD,MAAI,CAAC,KAAK,KAAK,EAAG,QAAO;AACzB,QAAM,SACJ,gIAEA;AACF,QAAM,QAAQ,MAAM,YAAY,QAAQ,MAAQ,EAAE,OAAO,KAAK,CAAC;AAC/D,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,QAAQ,WAAW,KAAK;AAC9B,SAAO,SAAS;AAClB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/pty/agent-restart.ts","../src/core/sessions/account-switch-rules.ts","../src/core/sessions/account-switch.ts","../src/core/sessions/account-switch-deps.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { findOnPath } from '../platform/find-on-path.js';\nimport type { PtyInfo } from './pty-host-protocol.js';\nimport { LATER_TEXT, restartCountsText } from './restart-view.js';\n\n/**\n * Restarting the agents in the PTY host — after their tool updated (Claude Code\n * replaced its binary; a running Claude keeps the old one until it starts again),\n * or when asked. A restart is its agent stopped and started again in place,\n * resuming its conversation; never in the middle of a turn: a session working or\n * waiting on you restarts when its turn ends.\n */\n\n/** Before this, an mtime isn't when the file was installed: npm unpacks every file dated 1985-10-26. */\nconst PACKED_MTIME_BEFORE = Date.parse('1990-01-01T00:00:00Z');\n\n/**\n * When the file a tool's command runs was installed, following links\n * (`~/.local/bin/claude` → `versions/2.1.296`): the later of its modification time\n * and its creation — an updater that copies the new file keeping its build date\n * still creates it now. A file npm unpacked with its fixed old date, on a system\n * that doesn't record creation, falls back to its change time (the unpacking).\n * Not the change time otherwise: a chmod or a relink moves it, and every running\n * agent would read as outdated. Null when it isn't on PATH.\n */\nexport function installedAt(cmd: string, find: (cmd: string) => string | null = findOnPath): number | null {\n const file = find(cmd);\n if (!file) return null;\n try {\n return installTime(fs.statSync(fs.realpathSync(file)));\n } catch {\n return null;\n }\n}\n\n/** installedAt's rule on a file's times. Pure. */\nexport function installTime(st: { mtimeMs: number; ctimeMs: number; birthtimeMs: number }): number {\n const real = (ms: number) => (ms >= PACKED_MTIME_BEFORE ? ms : null);\n const known = [real(st.mtimeMs), real(st.birthtimeMs)].filter((x): x is number => x !== null);\n return known.length ? Math.max(...known) : st.ctimeMs;\n}\n\n/**\n * `installedAt` per tool, read again only after `ttlMs`: a lookup walks PATH with a\n * stat per folder and extension, synchronously, and the dashboard asks every few\n * minutes per window.\n */\nexport function installedAtCache(ttlMs = 60_000, look: (cmd: string) => number | null = installedAt, now: () => number = Date.now) {\n const cache = new Map<string, { at: number | null; read: number }>();\n return (cmd: string): number | null => {\n const hit = cache.get(cmd);\n if (hit && now() - hit.read < ttlMs) return hit.at;\n const at = look(cmd);\n cache.set(cmd, { at, read: now() });\n return at;\n };\n}\n\n/**\n * The live PTYs whose process started before its tool's file was installed: they\n * run the version from before. A PTY whose tool isn't known (a host from before\n * `tool`) or isn't on PATH is left out: nothing says it's outdated. Pure.\n */\nexport function outdatedPtys(ptys: readonly PtyInfo[], toolInstalledAt: (tool: string) => number | null): PtyInfo[] {\n return ptys.filter((p) => {\n if (p.exited || !p.tool) return false;\n const at = toolInstalledAt(p.tool);\n const started = Date.parse(p.startedAt);\n return at !== null && Number.isFinite(started) && started < at;\n });\n}\n\n/** How recently a terminal printed for its agent to count as at work: a working one redraws its spinner, an idle one prints nothing. */\nexport const PRINTING_MS = 10_000;\n\n/**\n * At work, for a restart: what the agent itself says (Claude Code's own state for its process: mid-turn, or\n * waiting on you; at a permission dialog it prints nothing, so only this tells), or its status (the hooks' as\n * the dashboard reads it, corrected by the transcript and decayed) is working or waiting on you, or its\n * terminal printed in the last few seconds, which catches a turn both missed. An agent that says nothing and\n * has no status (a tool with no hooks or process state) has only the last: one silent at a prompt of its own\n * can't be told from idle. Pure.\n */\nexport function busyForRestart(\n state: 'working' | 'needs_input' | 'idle' | null,\n lastOutputMs: number | null,\n now = Date.now(),\n live: 'busy' | 'idle' | 'waiting' | null = null,\n): boolean {\n if (live === 'busy' || live === 'waiting') return true;\n if (state === 'working' || state === 'needs_input') return true;\n return lastOutputMs !== null && now - lastOutputMs < PRINTING_MS;\n}\n\n/** Which of `ids` restart now and which after their turn (working, or waiting on you). Pure. */\nexport function restartPlan(ids: readonly string[], busy: (id: string) => boolean): { now: string[]; later: string[] } {\n const now: string[] = [];\n const later: string[] = [];\n for (const id of new Set(ids)) (busy(id) ? later : now).push(id);\n return { now, later };\n}\n\n/** Restarts run this many at a time. */\nexport const RESTART_AT_ONCE = 3;\n\nexport interface RestarterDeps {\n /** Restart its agent in place (the host keeps attached terminals); a string: how it went instead (an older host). */\n restart: (id: string) => Promise<string | void>;\n /** Working, or waiting on you: not now. `turnEnded`: its turn just ended (the Stop), so the final message it\n * printed a moment ago isn't work going on. */\n busy: (id: string, opts?: { turnEnded?: boolean }) => boolean;\n /** Its agent runs in the host (a queued one stopped meanwhile needs nothing). */\n running: (id: string) => boolean;\n /** What one request (or one turn's end) decided, at once: one Activity run, not one per session. */\n report?: (notes: RestartNote[]) => void;\n /** When the waiting ones are looked at next (the Activity panel's schedule); null when nothing waits. */\n scheduled?: (nextAt: number | null) => void;\n changed?: () => void;\n /** A look again a little later (default setTimeout, unref'd): a turn-end the status hasn't caught up with yet. */\n later?: (fn: () => void, ms: number) => void;\n /**\n * Something else that restarts its agent anyway is waiting or under way (a switch of account, account-switch.ts): what\n * it is, in a few words; null: nothing. A restart asked for then is folded into it (answered as waiting, never a\n * second restart), and a queued one is dropped when its turn comes.\n */\n foldedInto?: (id: string) => string | null;\n}\n\nexport interface RestartNote {\n id: string;\n text: string;\n level: 'action' | 'info' | 'warn';\n}\n\ntype OneRestart = { ok: true; how: string } | { ok: false; error: string };\n\nexport interface RestartOutcome {\n now: string[];\n later: string[];\n failed: Array<{ id: string; error: string }>;\n}\n\n/** One request's decisions in a line, for its Activity run (restart-view.ts's wording). Pure. */\nexport function restartNotesSummary(notes: readonly RestartNote[]): string {\n const n = (level: RestartNote['level']) => notes.filter((x) => x.level === level).length;\n return restartCountsText({ restarted: n('action'), later: n('info'), failed: n('warn') });\n}\n\n/** While anything waits, how often it is looked at again: a turn whose end no hook reported, or a terminal that was\n * only redrawing (the printing check) — never left for the 5-minute sweep, which `--dev` and lean don't run. */\nexport const QUEUE_RECHECK_MS = 15_000;\n/** After a turn ends, how long before its agent is restarted: the Stop's own hooks (`work hook turn-end`: the\n * checkpoint, the status) run as its children, and stopping it at once would kill them mid-way. */\nexport const TURN_END_GRACE_MS = 10_000;\n\n/**\n * Restarts now what can go now, and the rest when their turn ends (`turnEnded`,\n * from the status hook — and once more a little later, should the status still\n * say working then) or on a later `retry` (a turn whose end no hook reported).\n * One restart per session at a time: asked again meanwhile, it shares that one's\n * outcome.\n */\nexport function createRestarter(deps: RestarterDeps) {\n const queued = new Set<string>();\n const inFlight = new Map<string, Promise<OneRestart>>();\n const later = deps.later ?? ((fn: () => void, ms: number) => void setTimeout(fn, ms).unref?.());\n\n /** Restart one: how it went (a different way, on an older host), or why not. */\n const one = (id: string): Promise<OneRestart> => {\n const running = inFlight.get(id);\n if (running) return running;\n queued.delete(id);\n const p = deps.restart(id).then(\n (how): OneRestart => ({ ok: true, how: how || 'restarted its agent (its conversation goes on)' }),\n (err: Error): OneRestart => ({ ok: false, error: err.message }),\n );\n inFlight.set(id, p);\n void p.finally(() => inFlight.delete(id));\n return p;\n };\n\n /** Restart these, RESTART_AT_ONCE at a time; each waits for its old process to exit. */\n const run = async (ids: string[], notes: RestartNote[]) => {\n const failed: RestartOutcome['failed'] = [];\n const ok = new Set<string>();\n const queue = [...ids];\n const worker = async () => {\n for (let id = queue.shift(); id !== undefined; id = queue.shift()) {\n const r = await one(id);\n if (r.ok) {\n ok.add(id);\n notes.push({ id, text: r.how, level: 'action' });\n } else {\n failed.push({ id, error: r.error });\n notes.push({ id, text: `couldn't restart its agent: ${r.error}`, level: 'warn' });\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(RESTART_AT_ONCE, queue.length) }, worker));\n return { done: ids.filter((id) => ok.has(id)), failed };\n };\n\n const finish = (notes: RestartNote[]) => {\n if (!notes.length) return;\n deps.report?.(notes);\n deps.changed?.();\n };\n\n /** Restart these (the caller found them running in the host: its list is fresh, `running` is a cache). */\n const request = async (ids: readonly string[]): Promise<RestartOutcome> => {\n const notes: RestartNote[] = [];\n const folded: string[] = [];\n for (const id of ids) {\n const into = deps.foldedInto?.(id);\n if (!into) continue;\n folded.push(id);\n notes.push({ id, text: `restarts with ${into} (no second restart)`, level: 'info' });\n }\n const plan = restartPlan(\n ids.filter((id) => !folded.includes(id)),\n (id) => deps.busy(id),\n );\n for (const id of plan.later) {\n queued.add(id);\n notes.push({ id, text: `${LATER_TEXT} (it is working or waiting on you)`, level: 'info' });\n }\n const { done, failed } = await run(plan.now, notes);\n finish(notes);\n tick();\n return { now: done, later: [...folded, ...plan.later], failed };\n };\n\n // While anything waits, it is looked at again every QUEUE_RECHECK_MS.\n let ticking = false;\n const tick = () => {\n if (ticking) return;\n if (queued.size === 0) {\n deps.scheduled?.(null);\n return;\n }\n ticking = true;\n deps.scheduled?.(Date.now() + QUEUE_RECHECK_MS);\n later(() => {\n ticking = false;\n void retry()\n .catch(() => {})\n .finally(tick);\n }, QUEUE_RECHECK_MS);\n };\n\n /** Restart the queued ones (or `only`) that can go now; a queued one stopped meanwhile is dropped. */\n const retry = async (only?: string, opts?: { turnEnded?: boolean }): Promise<void> => {\n const notes: RestartNote[] = [];\n const ready: string[] = [];\n for (const id of [...queued]) {\n if (only !== undefined && id !== only) continue;\n if (!deps.running(id)) {\n queued.delete(id);\n notes.push({ id, text: 'no longer waits to restart: it was stopped meanwhile (it starts on the new version)', level: 'info' });\n continue;\n }\n const into = deps.foldedInto?.(id);\n if (into) {\n queued.delete(id);\n notes.push({ id, text: `no longer waits to restart: ${into} restarts it`, level: 'info' });\n continue;\n }\n if (!deps.busy(id, opts)) ready.push(id);\n }\n await run(ready, notes);\n finish(notes);\n };\n\n return {\n request,\n retry: () => retry(),\n /** A session's turn ended: restart it if it was waiting for that — and if it still reads as busy, look again shortly. */\n turnEnded: (id: string): void => {\n if (!queued.has(id)) return;\n later(() => void retry(id, { turnEnded: true }).catch(() => {}), TURN_END_GRACE_MS);\n },\n queued: (): string[] => [...queued],\n /** Take one off the queue (it no longer waits for its turn); false when it wasn't waiting (not queued, or running now). */\n cancel: (id: string): boolean => {\n if (!queued.delete(id)) return false;\n if (queued.size === 0) deps.scheduled?.(null);\n deps.changed?.();\n return true;\n },\n /** Being restarted now (the host lists them as exited meanwhile: still this session's). */\n restarting: (): string[] => [...inFlight.keys()],\n };\n}\n\nexport type Restarter = ReturnType<typeof createRestarter>;\n","/**\n * When a switch of account is refused before anything is stopped or moved — the rules the real switch\n * (account-switch.ts) and the demo's (server/demo/demo-accounts.ts) share. Pure: no imports.\n */\n\n/** An account as the rules see it (agents/types.ts `AccountInfo`; the wire's `AccountWire`). */\nexport interface SwitchAccountInfo {\n name: string;\n /** Logged in; null: can't tell (macOS keeps Claude's credentials in the keychain) — allowed. */\n loggedIn: boolean | null;\n}\n\nexport interface SwitchFacts {\n /** Archived, or being archived right now. */\n archived: boolean;\n /** Its agent's accounts and the one it is on; null: its agent has none. */\n accounts: { list: readonly SwitchAccountInfo[]; current: string } | null;\n /** Where a switch already waiting for its turn (or being done now) goes; null: none. */\n pendingTo: string | null;\n /** Its agent runs in the PTY host (a switch can stop and start it there). */\n inHost: boolean;\n /** Its agent runs in a terminal outside work. */\n runningOutside: boolean;\n}\n\nexport type SwitchRefusal = { status: 400 | 409; error: string };\n\n/** Why the session can't be moved to `to` (status and reason), or null. In the order the user is told them. */\nexport function switchRefusal(to: string, f: SwitchFacts): SwitchRefusal | null {\n if (f.archived) return { status: 409, error: 'it is archived: restore it first' };\n if (!f.accounts) return { status: 409, error: \"its agent doesn't have accounts\" };\n const target = f.accounts.list.find((a) => a.name === to);\n if (!target) return { status: 400, error: `no account “${to}” (see \\`work account list\\`)` };\n if (target.loggedIn === false)\n return { status: 409, error: `nobody is logged in on “${to}”: run \\`work account add ${to}\\` again to log in, or /login on it` };\n if (f.pendingTo !== null)\n return { status: 409, error: `a switch is already waiting for its turn to end (to ${f.pendingTo || 'another account'})` };\n if (f.accounts.current === to) return { status: 409, error: `it already runs on “${to}”` };\n if (!f.inHost && f.runningOutside)\n return {\n status: 409,\n error: 'its Claude runs in a terminal outside work: stop it there first (its conversation would be moved from under it)',\n };\n return null;\n}\n","import type { AccountInfo } from '../agents/types.js';\nimport { createRestarter, type Restarter } from '../pty/agent-restart.js';\nimport type { WorktreeSession } from './session-types.js';\nimport type { ActivityLog } from '../platform/activity.js';\nimport { switchRefusal } from './account-switch-rules.js';\n\n/**\n * Moving a session to another account of its agent (Claude: another login, for when the first one's limit runs out).\n * The policy is here; I/O is passed in (account-routes.ts and web-server.ts give the real one, tests a fake).\n *\n * Refused: an unknown or archived session, an agent with no accounts, an unknown account, one nobody is logged in to, the\n * account it is on, a Claude running in a terminal outside work (a switch can't stop it), one switch already waiting.\n *\n * Not running in the PTY host: its conversations move and the account is recorded — the next start uses it. Running and\n * idle: its Claude is halted in the host (stopped, its terminals kept), the conversations move, the account is recorded, and it\n * is resumed in place on the new account — in that order, so nothing writes into the old folder while it moves. Working, or waiting\n * on you: after its turn — through the agent restarter's queue (agent-restart.ts), so the rule for \"not mid-turn\" is the\n * restart's own, with a switch as the thing that runs when its turn ends.\n */\n\nexport interface AccountSwitchDeps {\n session: (id: string) => WorktreeSession | null;\n /** Being archived right now (its Claude was stopped on purpose, and mustn't be started again). */\n beingArchived: (id: string) => boolean;\n /** Its agent's accounts; null: its agent has none. */\n accounts: (session: WorktreeSession) => { list: AccountInfo[]; current: string } | null;\n /** Move its conversations to `to`'s folders (puts back what it moved when it fails, and throws). */\n switchFiles: (session: WorktreeSession, to: string) => Promise<{ moved: string[] }>;\n /** Record the account on the session, in one transaction. */\n record: (session: WorktreeSession, to: string) => Promise<void>;\n /** Its Claude runs in the PTY host. */\n hostRuns: (id: string) => boolean;\n /** Its Claude runs in a terminal outside work. */\n runningOutside: (id: string) => boolean;\n /** A folder whose conversations the switch would move where another agent (of any account, not this session's own in\n * the host) runs now — its files would move from under it; null: none. */\n othersRunningIn?: (session: WorktreeSession, id: string) => string | null;\n /** Why the PTY host can't run it on another account (one from before accounts), or null. Asked before anything stops. */\n hostRefusal?: () => Promise<string | null>;\n /** Working, or waiting on you (`turnEnded`: its turn just ended, so what it printed a moment ago isn't work going on). */\n busy: (id: string, opts?: { turnEnded?: boolean }) => boolean;\n /** Stop its Claude in the host and keep its session (terminals attached) until `resume`: the files move only after it is stopped.\n * `stopped`: an older host stopped it the old way; `gone`: nothing was running. */\n halt: (id: string) => Promise<'halted' | 'stopped' | 'gone'>;\n /** Start it again after `halt`, on the account the session records now (so the old one after a switch that failed): in place\n * when it was `halted` (its terminals carry on), from a fresh spec when `stopped` (an older host). A string: how it went instead. */\n resume: (id: string, how: 'halted' | 'stopped') => Promise<string | void>;\n /** One line of what a switch decided, for the Activity panel. */\n note?: (id: string, text: string, level: 'action' | 'info' | 'warn') => void;\n changed?: () => void;\n scheduled?: (nextAt: number | null) => void;\n /** A look again a little later (the restarter's own default: setTimeout). */\n later?: (fn: () => void, ms: number) => void;\n /** Drop an agent restart waiting for its turn (agent-restart.ts): the switch restarts it anyway. True when one was waiting. */\n cancelRestart?: (id: string) => boolean;\n}\n\nexport type SwitchOutcome = 'switched' | 'queued' | 'recorded';\n\nexport type SwitchResult =\n { ok: true; outcome: SwitchOutcome; moved?: number } | { ok: false; status: 400 | 404 | 409 | 502; error: string };\n\nconst msg = (err: unknown) => (err instanceof Error ? err.message : String(err));\n\nexport function createAccountSwitcher(deps: AccountSwitchDeps) {\n /** Where each waiting (or running) switch goes. */\n const targets = new Map<string, string>();\n /** How many entries each finished switch moved, for the answer. */\n const movedBy = new Map<string, number>();\n\n const name = (s: WorktreeSession) => `${s.target} ${s.branch}`;\n\n /** Move the files and record the account; a failed record puts the files back. Returns how many entries moved. */\n const moveAndRecord = async (s: WorktreeSession, to: string, from: string): Promise<number> => {\n const { moved } = await deps.switchFiles(s, to);\n try {\n await deps.record(s, to);\n } catch (err) {\n // The files are in the new account's folders and the session still says the old one: back, or its --continue finds\n // nothing. A move back that fails is said with the error (its message names what is stuck where).\n const back = await deps.switchFiles({ ...s, account: to }, from).then(\n () => '',\n (e2: unknown) => `; and its conversations couldn't all be moved back: ${msg(e2)}`,\n );\n throw new Error(`${msg(err)}${back}`, { cause: err });\n }\n return moved.length;\n };\n\n /** What the restarter runs for a session (at once when idle, after its turn when not): the move, the record, the restart. */\n const perform = async (id: string): Promise<string | void> => {\n const to = targets.get(id);\n const s = deps.session(id);\n try {\n if (!to || !s) throw new Error('the session is gone');\n if (s.archivedAt || deps.beingArchived(id)) throw new Error('it was archived meanwhile');\n const acc = deps.accounts(s);\n if (!acc) throw new Error('its agent has no accounts');\n const from = acc.current;\n if (from === to) return `already on ${to}`;\n const before = await refusalBeforeStop(s, id);\n if (before) throw new Error(`stays on ${from}: ${before}`);\n // A restart of its agent that waited for this turn too would stop it a second time: the switch's restart does its job.\n if (deps.cancelRestart?.(id)) deps.note?.(id, 'its agent restart that waited for this turn is done by the switch instead', 'info');\n // Stopped first: a running (or just exiting) Claude writes to its transcript, and on Windows holds the file.\n let halted: 'halted' | 'stopped' | null = null;\n if (deps.hostRuns(id)) {\n let h: 'halted' | 'stopped' | 'gone';\n try {\n h = await deps.halt(id);\n } catch (err) {\n throw new Error(`stays on ${from}: couldn't stop its Claude: ${msg(err)}`, { cause: err });\n }\n if (h !== 'gone') halted = h;\n }\n /** Start it again on the account the session records (still the old one until the record is made). */\n const resume = async (): Promise<string | void> => (halted ? deps.resume(id, halted) : undefined);\n let moved: number;\n try {\n moved = await moveAndRecord(s, to, from);\n } catch (err) {\n // Put back (the move rolled itself back, a failed record moved the files back): it goes on running on the account it has.\n const back = await resume().then(\n () => '',\n (e2: unknown) => ` (and couldn't start its Claude again: ${msg(e2)}; opening the session starts it)`,\n );\n throw new Error(`stays on ${from}: ${msg(err)}${back}`, { cause: err });\n }\n movedBy.set(id, moved);\n if (!halted) {\n deps.note?.(id, `moved to the ${to} account (${moved} entries moved; its next start uses it)`, 'action');\n return `moved to the ${to} account`;\n }\n try {\n const how = await resume();\n deps.note?.(id, `moved to the ${to} account: its Claude restarted on it${how ? ` (${how})` : ''}`, 'action');\n return how || `moved to the ${to} account: its Claude restarted on it`;\n } catch (err) {\n // The account is recorded and the files are there: opening the session starts it on the new one.\n const why = `moved to the ${to} account, but its Claude couldn't be restarted: ${msg(err)} (opening the session starts it on ${to})`;\n deps.note?.(id, why, 'warn');\n throw new Error(why, { cause: err });\n }\n } catch (err) {\n if (s && !String(msg(err)).startsWith('moved to')) deps.note?.(id, `couldn't switch: ${msg(err)}`, 'warn');\n throw err;\n } finally {\n targets.delete(id);\n }\n };\n\n const restarter: Restarter = createRestarter({\n restart: perform,\n busy: deps.busy,\n // A queued switch is never dropped as \"stopped meanwhile\": perform handles a Claude no longer running (it records the account).\n running: () => true,\n changed: deps.changed,\n scheduled: deps.scheduled,\n later: deps.later,\n });\n\n /** What stops a switch before anything is stopped or moved: an older PTY host, another Claude in one of its folders. */\n const refusalBeforeStop = async (s: WorktreeSession, id: string): Promise<string | null> => {\n const other = deps.othersRunningIn?.(s, id);\n if (other) return `a Claude outside this session runs in ${other}`;\n return deps.hostRuns(id) ? ((await deps.hostRefusal?.()) ?? null) : null;\n };\n\n const pending = (id: string) => restarter.queued().includes(id) || restarter.restarting().includes(id);\n\n async function switchAccount(id: string, to: string): Promise<SwitchResult> {\n const s = deps.session(id);\n if (!s) return { ok: false, status: 404, error: 'unknown session' };\n const acc = deps.accounts(s);\n const inHost = deps.hostRuns(id);\n const refused = switchRefusal(to, {\n archived: !!s.archivedAt || deps.beingArchived(id),\n accounts: acc,\n pendingTo: pending(id) ? (targets.get(id) ?? '') : null,\n inHost,\n runningOutside: !inHost && deps.runningOutside(id),\n });\n if (refused) return { ok: false, ...refused };\n if (!acc) return { ok: false, status: 409, error: \"its agent doesn't have accounts\" }; // (refused above: for the type)\n\n const before = await refusalBeforeStop(s, id);\n if (before) return { ok: false, status: 409, error: `stays on ${acc.current}: ${before}` };\n\n if (!inHost) {\n // Nothing to stop: the files move and the account is recorded; the next start uses it.\n try {\n const moved = await moveAndRecord(s, to, acc.current);\n deps.note?.(id, `${name(s)}: moved to the ${to} account (${moved} entries moved; its next start uses it)`, 'action');\n deps.changed?.();\n return { ok: true, outcome: 'recorded', moved };\n } catch (err) {\n deps.note?.(id, `couldn't switch: ${msg(err)}`, 'warn');\n return { ok: false, status: 502, error: `stays on ${acc.current}: ${msg(err)}` };\n }\n }\n\n targets.set(id, to);\n movedBy.delete(id);\n const r = await restarter.request([id]);\n if (r.later.includes(id)) {\n deps.note?.(id, `will move to the ${to} account when its turn ends (it is working or waiting on you)`, 'info');\n return { ok: true, outcome: 'queued' };\n }\n const failed = r.failed.find((f) => f.id === id);\n if (failed) return { ok: false, status: 502, error: failed.error };\n return { ok: true, outcome: 'switched', moved: movedBy.get(id) };\n }\n\n return {\n switchAccount,\n /** Its turn ended: do the switch that waited for it. */\n turnEnded: (id: string) => restarter.turnEnded(id),\n /** Do the waiting switches that can go now (a turn whose end no hook reported). */\n retry: () => restarter.retry(),\n /** Sessions waiting for their turn to end, and where each goes. */\n waiting: (): Array<{ id: string; to: string }> => restarter.queued().map((id) => ({ id, to: targets.get(id) ?? '' })),\n /** The account a switch waiting for its turn, or being done now, moves it to; null: none. Either way its agent restarts. */\n restartsAnyway: (id: string): string | null => (pending(id) ? (targets.get(id) ?? '') : null),\n /** The account a session is waiting to move to (its turn first), or null. Kept in memory: a work web restart drops it. */\n pendingFor: (id: string): string | null => (restarter.queued().includes(id) ? (targets.get(id) ?? null) : null),\n /**\n * Drop the switch waiting for its turn to end. `running`: it is being done right now (too late to cancel); `none`:\n * nothing waits for it.\n */\n cancel: (id: string): 'cancelled' | 'running' | 'none' => {\n if (restarter.restarting().includes(id)) return 'running';\n const to = targets.get(id);\n if (!restarter.cancel(id)) return 'none';\n targets.delete(id);\n deps.note?.(id, `no longer moves to the ${to ?? 'other'} account: the switch was cancelled`, 'info');\n return 'cancelled';\n },\n };\n}\n\nexport type AccountSwitcher = ReturnType<typeof createAccountSwitcher>;\n\n/**\n * The switcher's `note` as Activity runs: one run per note, a failure (`warn`) failing it — so a switch that waited for its\n * turn and then couldn't be done lights the Activity dot, rather than passing as a run that went fine.\n */\nexport function accountSwitchNote(\n activity: Pick<ActivityLog, 'start'>,\n label: (id: string) => string | null,\n): NonNullable<AccountSwitchDeps['note']> {\n return (id, text, level) => {\n const name = label(id);\n const run = activity.start('accounts', 'Switching a Claude account');\n run.note(`${name ?? id}: ${text}`, { level, sessionId: name ? id : undefined });\n if (level === 'warn') run.fail(text);\n else run.done(text);\n };\n}\n","import path from 'node:path';\nimport { agentOf, liveAgents } from '../agents/index.js';\nimport { isArchiving } from '../archive/archiving.js';\nimport { accountSwitchRefusal, peekPty, ptyPid, ptyPids, haltPty, resumePtyOnAccount } from '../pty/pty-pool.js';\nimport type { AccountSwitchDeps } from './account-switch.js';\nimport { loadHistory, setSessionAccount } from './history.js';\nimport { agentsBySession } from './live-agents.js';\nimport { findSession } from './web-state.js';\n\n/** The real inputs of createAccountSwitcher (account-switch.ts); work web gives `busy`, the Activity notes and the broadcast. */\nexport function defaultAccountSwitchDeps(opts: Pick<AccountSwitchDeps, 'busy'> & Partial<AccountSwitchDeps>): AccountSwitchDeps {\n return {\n session: findSession,\n beingArchived: isArchiving,\n accounts: (s) => {\n const accounts = agentOf(s).accounts;\n return accounts ? { list: accounts.list(), current: accounts.current(s) } : null;\n },\n switchFiles: (s, to) => {\n const accounts = agentOf(s).accounts;\n if (!accounts) throw new Error('its agent has no accounts');\n return accounts.switchFiles(s, to);\n },\n record: async (s, to) => {\n if (!(await setSessionAccount(s.target, s.branch, to))) throw new Error('unknown session');\n },\n hostRuns: peekPty,\n // Claude Code's process files say one runs for it that isn't the host's (terminal-ws.ts, session-control-routes.ts).\n runningOutside: (id) => {\n const hostPids = ptyPids();\n return (agentsBySession(liveAgents(), loadHistory()).get(id) ?? []).some((c) => !hostPids.has(c.pid));\n },\n othersRunningIn: (s, id) => {\n const folders = agentOf(s).accounts?.folders(s) ?? [];\n if (!folders.length) return null;\n const own = ptyPid(id);\n const key = (p: string) => {\n const r = path.resolve(p).replace(/[\\\\/]+$/, '');\n return process.platform === 'win32' ? r.toLowerCase() : r;\n };\n const wanted = new Map(folders.map((f) => [key(f), f]));\n const other = liveAgents().find((a) => a.pid !== own && wanted.has(key(a.cwd)));\n return other ? (wanted.get(key(other.cwd)) ?? other.cwd) : null;\n },\n hostRefusal: accountSwitchRefusal,\n halt: haltPty,\n resume: resumePtyOnAccount,\n ...opts,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AAcf,IAAM,sBAAsB,KAAK,MAAM,sBAAsB;AAWtD,SAAS,YAAY,KAAa,OAAuC,YAA2B;AACzG,QAAM,OAAO,KAAK,GAAG;AACrB,MAAI,CAAC,KAAM,QAAO;AAClB,MAAI;AACF,WAAO,YAAY,GAAG,SAAS,GAAG,aAAa,IAAI,CAAC,CAAC;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,YAAY,IAAuE;AACjG,QAAM,OAAO,CAAC,OAAgB,MAAM,sBAAsB,KAAK;AAC/D,QAAM,QAAQ,CAAC,KAAK,GAAG,OAAO,GAAG,KAAK,GAAG,WAAW,CAAC,EAAE,OAAO,CAAC,MAAmB,MAAM,IAAI;AAC5F,SAAO,MAAM,SAAS,KAA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AkB,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAI,OAAM,IAAI,MAAM,iBAAiB;AAAA,IAC3F;AAAA,IACA,UAAU;AAAA;AAAA,IAEV,gBAAgB,CAAC,OAAO;AACtB,YAAM,WAAW,QAAQ;AACzB,cAAQ,gBAAgB,WAAW,GAAG,YAAY,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,IAAI,EAAE,GAAG,CAAC;AAAA,IACtG;AAAA,IACA,iBAAiB,CAAC,GAAG,OAAO;AAC1B,YAAM,UAAU,QAAQ,CAAC,EAAE,UAAU,QAAQ,CAAC,KAAK,CAAC;AACpD,UAAI,CAAC,QAAQ,OAAQ,QAAO;AAC5B,YAAM,MAAM,OAAO,EAAE;AACrB,YAAM,MAAM,CAAC,MAAc;AACzB,cAAM,IAAI,KAAK,QAAQ,CAAC,EAAE,QAAQ,WAAW,EAAE;AAC/C,eAAO,QAAQ,aAAa,UAAU,EAAE,YAAY,IAAI;AAAA,MAC1D;AACA,YAAM,SAAS,IAAI,IAAI,QAAQ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACtD,YAAM,QAAQ,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,OAAO,OAAO,IAAI,IAAI,EAAE,GAAG,CAAC,CAAC;AAC9E,aAAO,QAAS,OAAO,IAAI,IAAI,MAAM,GAAG,CAAC,KAAK,MAAM,MAAO;AAAA,IAC7D;AAAA,IACA,aAAa;AAAA,IACb,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,GAAG;AAAA,EACL;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/shared/setup-completions.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport chalk from 'chalk';\nimport spawn from 'cross-spawn';\n\nexport interface ShellProfile {\n shell: string;\n profilePath: string;\n completionLine: string;\n}\n\nexport type InstallResult = 'installed' | 'created-file' | 'already-exists' | 'error';\n\nexport interface CompletionResult {\n profile: ShellProfile;\n status: InstallResult;\n error?: string;\n}\n\nconst PS_COMPLETION_LINE = 'work completion --shell powershell | Out-String | Invoke-Expression';\nconst BASH_COMPLETION_LINE = 'eval \"$(work completion)\"';\nconst ZSH_COMPLETION_LINE = 'eval \"$(work completion --shell zsh)\"';\nconst FISH_COMPLETION_SCRIPT = `# work tab completions\nfunction __work_complete\n set -l cmd (commandline -opc)\n set -l cur (commandline -ct)\n work --get-yargs-completions $cmd $cur 2>/dev/null\nend\n\ncomplete -c work -f -a '(__work_complete)'`;\nconst MARKER = '# work tab completions';\nconst LEGACY_MARKER = '# work2 tab completions';\n\n/** Get the Windows Documents folder, handling OneDrive redirection. */\nfunction getWindowsDocumentsFolder(): string | null {\n // Try pwsh first, fall back to powershell.exe\n for (const exe of ['pwsh', 'powershell']) {\n const result = spawn.sync(exe, ['-NoProfile', '-Command', \"[Environment]::GetFolderPath('MyDocuments')\"], {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n windowsHide: true,\n });\n if (result.status === 0 && result.stdout) {\n const dir = result.stdout.toString().trim();\n if (dir) return dir;\n }\n }\n return null;\n}\n\n/** Check if an executable exists on PATH. */\nfunction executableExists(name: string): boolean {\n const cmd = process.platform === 'win32' ? 'where' : 'which';\n const result = spawn.sync(cmd, [name], {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n windowsHide: true,\n });\n return result.status === 0;\n}\n\n/** Detect available shell profiles for completion installation. */\nexport function detectShellProfiles(): ShellProfile[] {\n const profiles: ShellProfile[] = [];\n\n if (process.platform === 'win32') {\n const docs = getWindowsDocumentsFolder();\n if (!docs) return profiles;\n\n if (executableExists('pwsh')) {\n profiles.push({\n shell: 'PowerShell 7',\n profilePath: path.join(docs, 'PowerShell', 'Microsoft.PowerShell_profile.ps1'),\n completionLine: PS_COMPLETION_LINE,\n });\n }\n\n if (executableExists('powershell')) {\n profiles.push({\n shell: 'PowerShell 5.1',\n profilePath: path.join(docs, 'WindowsPowerShell', 'Microsoft.PowerShell_profile.ps1'),\n completionLine: PS_COMPLETION_LINE,\n });\n }\n } else {\n const shell = process.env.SHELL ?? '';\n const home = os.homedir();\n\n if (shell.includes('fish')) {\n // Fish uses a dedicated completions directory\n const fishConfigDir = process.env.XDG_CONFIG_HOME\n ? path.join(process.env.XDG_CONFIG_HOME, 'fish')\n : path.join(home, '.config', 'fish');\n profiles.push({\n shell: 'Fish',\n profilePath: path.join(fishConfigDir, 'completions', 'work.fish'),\n completionLine: FISH_COMPLETION_SCRIPT,\n });\n } else if (shell.includes('zsh')) {\n profiles.push({\n shell: 'Zsh',\n profilePath: path.join(home, '.zshrc'),\n completionLine: ZSH_COMPLETION_LINE,\n });\n } else if (shell.includes('bash')) {\n profiles.push({\n shell: 'Bash',\n profilePath: path.join(home, '.bashrc'),\n completionLine: BASH_COMPLETION_LINE,\n });\n }\n }\n\n return profiles;\n}\n\n/**\n * Strip a legacy `work2` completion block from a non-fish profile. Matches the\n * marker line and the next line (the install command). Returns content unchanged\n * if no legacy block is present.\n */\nfunction stripLegacyBlock(content: string): string {\n if (!content.includes(LEGACY_MARKER)) return content;\n const lines = content.split(/\\r?\\n/);\n const out: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].trim() === LEGACY_MARKER) {\n // Skip marker line and the following install line (if present)\n if (i + 1 < lines.length && /work2\\b/.test(lines[i + 1])) i++;\n continue;\n }\n out.push(lines[i]);\n }\n return out.join('\\n').replace(/\\n{3,}/g, '\\n\\n');\n}\n\n/** Idempotently install the completion line into a shell profile. */\nexport function installCompletionLine(profile: ShellProfile): CompletionResult {\n try {\n let createdFile = false;\n const isFish = profile.shell === 'Fish';\n\n let existingContent = '';\n if (fs.existsSync(profile.profilePath)) {\n existingContent = fs.readFileSync(profile.profilePath, 'utf-8');\n if (existingContent.includes(MARKER)) {\n return { profile, status: 'already-exists' };\n }\n } else {\n createdFile = true;\n }\n\n // Ensure parent directory exists\n fs.mkdirSync(path.dirname(profile.profilePath), { recursive: true });\n\n if (isFish) {\n // Fish: write the complete completion script to its own file\n fs.writeFileSync(profile.profilePath, profile.completionLine + '\\n');\n } else {\n // Bash/Zsh/PowerShell: strip any legacy `work2` block, then append new one.\n const cleaned = stripLegacyBlock(existingContent);\n const snippet = `\\n${MARKER}\\n${profile.completionLine}\\n`;\n fs.writeFileSync(profile.profilePath, cleaned + snippet);\n }\n\n return { profile, status: createdFile ? 'created-file' : 'installed' };\n } catch (err) {\n return {\n profile,\n status: 'error',\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/** Detect shells and install completions into each profile. */\nexport function setupCompletions(): CompletionResult[] {\n const profiles = detectShellProfiles();\n return profiles.map((p) => installCompletionLine(p));\n}\n\n/** Print colored results for each completion installation. */\nexport function printCompletionResults(results: CompletionResult[]): void {\n for (const r of results) {\n const label = `${r.profile.shell} (${r.profile.profilePath})`;\n\n switch (r.status) {\n case 'installed':\n console.log(chalk.green(` ✓ ${label} — completions added`));\n break;\n case 'created-file':\n console.log(chalk.green(` ✓ ${label} — profile created with completions`));\n break;\n case 'already-exists':\n console.log(chalk.gray(` · ${label} — already has completions`));\n break;\n case 'error':\n console.log(chalk.red(` ✗ ${label} — ${r.error}`));\n break;\n }\n }\n}\n\n/** Print manual instructions when no shells are detected. */\nexport function printManualInstructions(): void {\n console.log(chalk.yellow(' Could not detect shell profiles. Add completions manually:'));\n console.log('');\n console.log(chalk.gray(' PowerShell — add to $PROFILE:'));\n console.log(` ${PS_COMPLETION_LINE}`);\n console.log('');\n console.log(chalk.gray(' Bash/Zsh — add to ~/.bashrc or ~/.zshrc:'));\n console.log(` ${BASH_COMPLETION_LINE}`);\n console.log('');\n console.log(chalk.gray(' Fish — run:'));\n console.log(` work completion --shell fish > ~/.config/fish/completions/work.fish`);\n}\n"],"mappings":";;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,QA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gBAAQ,IAAI,MAAM,MAAM,YAAO,KAAK,0CAAqC,CAAC;AAC1E;AAAA,MACF,KAAK;AACH,gBAAQ,IAAI,MAAM,KAAK,UAAO,KAAK,iCAA4B,CAAC;AAChE;AAAA,MACF,KAAK;AACH,gBAAQ,IAAI,MAAM,IAAI,YAAO,KAAK,WAAM,EAAE,KAAK,EAAE,CAAC;AAClD;AAAA,IACJ;AAAA,EACF;AACF;AAGO,SAAS,0BAAgC;AAC9C,UAAQ,IAAI,MAAM,OAAO,8DAA8D,CAAC;AACxF,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,MAAM,KAAK,sCAAiC,CAAC;AACzD,UAAQ,IAAI,OAAO,kBAAkB,EAAE;AACvC,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,MAAM,KAAK,iDAA4C,CAAC;AACpE,UAAQ,IAAI,OAAO,oBAAoB,EAAE;AACzC,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,MAAM,KAAK,oBAAe,CAAC;AACvC,UAAQ,IAAI,yEAAyE;AACvF;","names":[]}
@@ -1,227 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- originUrl,
4
- ownerRepo,
5
- readGitConfig
6
- } from "./chunk-HMK3INUS.js";
7
-
8
- // src/core/pr/pr.ts
9
- import { execFile } from "child_process";
10
- function execAsync(cmd, args, cwd, timeout) {
11
- return new Promise((resolve, reject) => {
12
- execFile(cmd, args, { cwd, encoding: "utf-8", timeout, windowsHide: true }, (err, stdout) => {
13
- if (err) reject(err);
14
- else resolve(stdout ?? "");
15
- });
16
- });
17
- }
18
- function parsePrJson(stdout, repoAlias, currentUser) {
19
- const parsed = JSON.parse(stdout);
20
- const prs = Array.isArray(parsed) ? parsed : [];
21
- return prs.map((pr) => toPrInfo(pr, repoAlias, currentUser));
22
- }
23
- function toPrInfo(pr, repoAlias, currentUser) {
24
- {
25
- let checksStatus = "NONE";
26
- const checks = pr.statusCheckRollup ?? [];
27
- if (checks.length > 0) {
28
- const hasFailure = checks.some((c) => c.conclusion === "FAILURE" || c.conclusion === "TIMED_OUT" || c.conclusion === "CANCELLED");
29
- const hasPending = checks.some((c) => c.status === "IN_PROGRESS" || c.status === "QUEUED" || c.status === "PENDING");
30
- if (hasFailure) checksStatus = "FAILURE";
31
- else if (hasPending) checksStatus = "PENDING";
32
- else checksStatus = "SUCCESS";
33
- }
34
- let reviewDecision = "NONE";
35
- if (pr.reviewDecision === "APPROVED") reviewDecision = "APPROVED";
36
- else if (pr.reviewDecision === "CHANGES_REQUESTED") reviewDecision = "CHANGES_REQUESTED";
37
- else if (pr.reviewDecision === "REVIEW_REQUIRED") reviewDecision = "REVIEW_REQUIRED";
38
- let myReview = "NONE";
39
- if (currentUser) {
40
- const reviews = pr.reviews ?? [];
41
- for (let i = reviews.length - 1; i >= 0; i--) {
42
- if (reviews[i].author?.login?.toLowerCase() === currentUser.toLowerCase()) {
43
- const state = reviews[i].state;
44
- if (state === "APPROVED") myReview = "APPROVED";
45
- else if (state === "CHANGES_REQUESTED") myReview = "CHANGES_REQUESTED";
46
- else if (state === "COMMENTED") myReview = "COMMENTED";
47
- break;
48
- }
49
- }
50
- }
51
- return {
52
- number: pr.number ?? 0,
53
- title: pr.title ?? "",
54
- branch: pr.headRefName ?? "",
55
- url: pr.url ?? "",
56
- isDraft: pr.isDraft ?? false,
57
- checksStatus,
58
- reviewDecision,
59
- myReview,
60
- isMine: currentUser ? pr.author?.login?.toLowerCase() === currentUser.toLowerCase() : false,
61
- conflicting: pr.mergeable === "CONFLICTING",
62
- reviewRequested: !!currentUser && (pr.reviewRequests ?? []).some((r) => r?.login?.toLowerCase() === currentUser.toLowerCase()),
63
- repoAlias,
64
- // Only when who you are is known: isMine is false for all of them otherwise, and your own would read "by @you".
65
- ...currentUser && pr.author?.login ? { author: pr.author.login } : {},
66
- fork: pr.isCrossRepository === true
67
- };
68
- }
69
- }
70
- var PR_SEARCH_QUERY = `query($mine: String!, $asked: String!) {
71
- viewer { login }
72
- mine: search(query: $mine, type: ISSUE, first: 100) { issueCount nodes { ...pr } }
73
- asked: search(query: $asked, type: ISSUE, first: 100) { issueCount nodes { ...pr } }
74
- }
75
- fragment pr on PullRequest {
76
- number title url isDraft headRefName mergeable reviewDecision isCrossRepository
77
- author { login }
78
- repository { nameWithOwner }
79
- commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
80
- reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } } } }
81
- latestReviews(first: 20) { nodes { author { login } state } }
82
- }`;
83
- var PR_SEARCH_VARS = {
84
- mine: "is:pr is:open archived:false author:@me",
85
- asked: "is:pr is:open archived:false review-requested:@me"
86
- };
87
- function rollupAsChecks(state) {
88
- if (state === "FAILURE" || state === "ERROR") return [{ conclusion: "FAILURE", status: "COMPLETED" }];
89
- if (state === "PENDING" || state === "EXPECTED") return [{ conclusion: null, status: "PENDING" }];
90
- if (state === "SUCCESS") return [{ conclusion: "SUCCESS", status: "COMPLETED" }];
91
- return [];
92
- }
93
- function parsePrSearch(stdout, aliasesOf) {
94
- const data = JSON.parse(stdout)?.data ?? {};
95
- const user = (data.viewer?.login ?? "").trim();
96
- const seen = /* @__PURE__ */ new Set();
97
- const prs = [];
98
- let incomplete = false;
99
- for (const key of ["mine", "asked"]) {
100
- const result = data[key];
101
- const nodes = (result?.nodes ?? []).filter((n) => !!n && typeof n.number === "number");
102
- if ((result?.issueCount ?? 0) > nodes.length) incomplete = true;
103
- for (const n of nodes) {
104
- const pr = {
105
- ...n,
106
- statusCheckRollup: rollupAsChecks(n.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),
107
- reviews: (n.latestReviews?.nodes ?? []).filter((r) => !!r),
108
- reviewRequests: (n.reviewRequests?.nodes ?? []).map((r) => r?.requestedReviewer ?? null)
109
- };
110
- for (const alias of aliasesOf(n.repository?.nameWithOwner ?? "")) {
111
- const id = `${alias}#${n.number}`;
112
- if (seen.has(id)) continue;
113
- seen.add(id);
114
- prs.push(toPrInfo(pr, alias, user));
115
- }
116
- }
117
- }
118
- return { prs, incomplete };
119
- }
120
- function readSearch(stdout, aliasesOf) {
121
- try {
122
- return parsePrSearch(stdout, aliasesOf);
123
- } catch {
124
- return null;
125
- }
126
- }
127
- function githubRepoOf(configText) {
128
- const url = originUrl(configText);
129
- if (!url || !/(^|[@/.])github\.com[:/]/i.test(url)) return null;
130
- return ownerRepo(url)?.toLowerCase() ?? null;
131
- }
132
- var PR_LIST_LIMIT = 100;
133
- async function fetchPullRequests(repoPath, repoAlias, currentUser) {
134
- try {
135
- const stdout = await execAsync(
136
- "gh",
137
- [
138
- "pr",
139
- "list",
140
- "--state",
141
- "open",
142
- "--json",
143
- "number,title,headRefName,url,isDraft,statusCheckRollup,reviewDecision,reviews,reviewRequests,mergeable,author,isCrossRepository",
144
- "--limit",
145
- String(PR_LIST_LIMIT)
146
- ],
147
- repoPath,
148
- 15e3
149
- );
150
- if (!stdout) return [];
151
- return parsePrJson(stdout, repoAlias, currentUser);
152
- } catch {
153
- return null;
154
- }
155
- }
156
- async function getCurrentUser() {
157
- try {
158
- const stdout = await execAsync("gh", ["api", "user", "--jq", ".login"], process.cwd(), 5e3);
159
- return stdout.trim();
160
- } catch {
161
- return "";
162
- }
163
- }
164
- function defaultPrListDeps() {
165
- let user = null;
166
- return {
167
- search: async () => {
168
- try {
169
- return await execAsync(
170
- "gh",
171
- ["api", "graphql", "-f", `query=${PR_SEARCH_QUERY}`, "-f", `mine=${PR_SEARCH_VARS.mine}`, "-f", `asked=${PR_SEARCH_VARS.asked}`],
172
- process.cwd(),
173
- 2e4
174
- );
175
- } catch {
176
- return null;
177
- }
178
- },
179
- listRepo: async (repoPath, alias) => fetchPullRequests(repoPath, alias, await (user ??= getCurrentUser())),
180
- gitConfig: readGitConfig
181
- };
182
- }
183
- async function fetchAllPullRequests(repos, deps = defaultPrListDeps()) {
184
- const entries = Object.entries(repos);
185
- const onGithub = /* @__PURE__ */ new Map();
186
- const elsewhere = [];
187
- for (const [alias, repoPath] of entries) {
188
- const text = deps.gitConfig(repoPath);
189
- const gh = text ? githubRepoOf(text) : null;
190
- if (gh) onGithub.set(gh, [...onGithub.get(gh) ?? [], alias]);
191
- else elsewhere.push([alias, repoPath]);
192
- }
193
- const results = [];
194
- const incomplete = [];
195
- if (onGithub.size) {
196
- const out = await deps.search();
197
- const parsed = out ? readSearch(out, (repo) => onGithub.get(repo.toLowerCase()) ?? []) : null;
198
- if (parsed) {
199
- results.push(parsed.prs);
200
- if (parsed.incomplete) incomplete.push(...[...onGithub.values()].flat());
201
- } else {
202
- const asked = new Set(elsewhere.map(([a]) => a));
203
- for (const [alias, repoPath] of entries) if (!asked.has(alias)) elsewhere.push([alias, repoPath]);
204
- }
205
- }
206
- const listed = await Promise.all(elsewhere.map(([alias, repoPath]) => deps.listRepo(repoPath, alias)));
207
- results.push(...listed);
208
- incomplete.push(...elsewhere.filter((_, i) => listed[i] === null || listed[i].length >= PR_LIST_LIMIT).map(([alias]) => alias));
209
- const map = /* @__PURE__ */ new Map();
210
- for (const prList of results) {
211
- for (const pr of prList ?? []) {
212
- const existing = map.get(pr.branch);
213
- if (existing) {
214
- existing.push(pr);
215
- } else {
216
- map.set(pr.branch, [pr]);
217
- }
218
- }
219
- }
220
- return { map, incomplete };
221
- }
222
-
223
- export {
224
- githubRepoOf,
225
- fetchAllPullRequests
226
- };
227
- //# sourceMappingURL=chunk-VTLDYH3C.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/pr/pr.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { originUrl, ownerRepo, readGitConfig } from '../worktree/repo-scan.js';\n\nexport interface PullRequestInfo {\n number: number;\n title: string;\n branch: string;\n url: string;\n isDraft: boolean;\n checksStatus: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n reviewDecision: 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED' | 'NONE';\n /** Current user's latest review state on this PR. */\n myReview: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED' | 'NONE';\n /** Whether the current user is the PR author. */\n isMine: boolean;\n /** It can't merge as it is: a conflict with its base (checks say nothing about that). */\n conflicting: boolean;\n /** Your review was asked for, by name (a team's request isn't known here). */\n reviewRequested: boolean;\n /** Repo alias this PR belongs to (for distinguishing group PRs). */\n repoAlias: string;\n /** Its author's login (absent from a server before this). */\n author?: string;\n /** It comes from a fork: its branch isn't on origin (absent from a server before this). */\n fork?: boolean;\n}\n\n/**\n * Map from branch name to array of PRs (one per repo that has a PR for that branch).\n * Single-repo sessions will have at most 1 entry; groups can have multiple.\n */\nexport type BranchPrMap = Map<string, PullRequestInfo[]>;\n\nfunction execAsync(cmd: string, args: string[], cwd: string, timeout: number): Promise<string> {\n return new Promise((resolve, reject) => {\n // `windowsHide: true` prevents a console window from flashing on\n // Windows whenever the PRs pane refreshes. Without it, opening\n // the PRs pane in `work web` triggers a visible terminal popup\n // for every configured repo's `gh pr list` invocation.\n execFile(cmd, args, { cwd, encoding: 'utf-8', timeout, windowsHide: true }, (err, stdout) => {\n if (err) reject(err);\n else resolve(stdout ?? '');\n });\n });\n}\n\n/** The fields of `gh pr list --json …` this reads; all optional — it is someone else's output. */\ninterface GhPr {\n number?: number;\n title?: string;\n headRefName?: string;\n url?: string;\n isDraft?: boolean;\n mergeable?: string;\n reviewDecision?: string;\n author?: { login?: string } | null;\n isCrossRepository?: boolean;\n statusCheckRollup?: Array<{ conclusion?: string | null; status?: string | null }> | null;\n reviews?: Array<{ author?: { login?: string } | null; state?: string }> | null;\n reviewRequests?: Array<{ login?: string } | null> | null;\n}\n\n/** `gh pr list --json …` output as work's PR rows: checks, review, yours or not, conflicts, review asked of you. Pure. */\nexport function parsePrJson(stdout: string, repoAlias: string, currentUser: string): PullRequestInfo[] {\n const parsed = JSON.parse(stdout) as unknown;\n const prs: GhPr[] = Array.isArray(parsed) ? (parsed as GhPr[]) : [];\n return prs.map((pr) => toPrInfo(pr, repoAlias, currentUser));\n}\n\n/** One PR as work's row. */\nfunction toPrInfo(pr: GhPr, repoAlias: string, currentUser: string): PullRequestInfo {\n {\n let checksStatus: PullRequestInfo['checksStatus'] = 'NONE';\n const checks = pr.statusCheckRollup ?? [];\n if (checks.length > 0) {\n const hasFailure = checks.some((c) => c.conclusion === 'FAILURE' || c.conclusion === 'TIMED_OUT' || c.conclusion === 'CANCELLED');\n const hasPending = checks.some((c) => c.status === 'IN_PROGRESS' || c.status === 'QUEUED' || c.status === 'PENDING');\n if (hasFailure) checksStatus = 'FAILURE';\n else if (hasPending) checksStatus = 'PENDING';\n else checksStatus = 'SUCCESS';\n }\n\n let reviewDecision: PullRequestInfo['reviewDecision'] = 'NONE';\n if (pr.reviewDecision === 'APPROVED') reviewDecision = 'APPROVED';\n else if (pr.reviewDecision === 'CHANGES_REQUESTED') reviewDecision = 'CHANGES_REQUESTED';\n else if (pr.reviewDecision === 'REVIEW_REQUIRED') reviewDecision = 'REVIEW_REQUIRED';\n\n // Check current user's latest review state\n let myReview: PullRequestInfo['myReview'] = 'NONE';\n if (currentUser) {\n const reviews = pr.reviews ?? [];\n for (let i = reviews.length - 1; i >= 0; i--) {\n if (reviews[i].author?.login?.toLowerCase() === currentUser.toLowerCase()) {\n const state = reviews[i].state;\n if (state === 'APPROVED') myReview = 'APPROVED';\n else if (state === 'CHANGES_REQUESTED') myReview = 'CHANGES_REQUESTED';\n else if (state === 'COMMENTED') myReview = 'COMMENTED';\n break;\n }\n }\n }\n\n return {\n number: pr.number ?? 0,\n title: pr.title ?? '',\n branch: pr.headRefName ?? '',\n url: pr.url ?? '',\n isDraft: pr.isDraft ?? false,\n checksStatus,\n reviewDecision,\n myReview,\n isMine: currentUser ? pr.author?.login?.toLowerCase() === currentUser.toLowerCase() : false,\n conflicting: pr.mergeable === 'CONFLICTING',\n reviewRequested: !!currentUser && (pr.reviewRequests ?? []).some((r) => r?.login?.toLowerCase() === currentUser.toLowerCase()),\n repoAlias,\n // Only when who you are is known: isMine is false for all of them otherwise, and your own would read \"by @you\".\n ...(currentUser && pr.author?.login ? { author: pr.author.login } : {}),\n fork: pr.isCrossRepository === true,\n };\n }\n}\n\n/**\n * Your open PRs and the ones asking for your review, across every GitHub\n * repo, in ONE GraphQL call (about one API point). The list used to be a\n * `gh pr list` per enrolled repo every two minutes: 27 calls for 27 repos.\n * Start shows only these two kinds anyway.\n */\nexport const PR_SEARCH_QUERY = `query($mine: String!, $asked: String!) {\n viewer { login }\n mine: search(query: $mine, type: ISSUE, first: 100) { issueCount nodes { ...pr } }\n asked: search(query: $asked, type: ISSUE, first: 100) { issueCount nodes { ...pr } }\n}\nfragment pr on PullRequest {\n number title url isDraft headRefName mergeable reviewDecision isCrossRepository\n author { login }\n repository { nameWithOwner }\n commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }\n reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } } } }\n latestReviews(first: 20) { nodes { author { login } state } }\n}`;\n\n/** The search's two queries: open PRs by you, and open PRs asking you by name. */\nexport const PR_SEARCH_VARS = {\n mine: 'is:pr is:open archived:false author:@me',\n asked: 'is:pr is:open archived:false review-requested:@me',\n};\n\ninterface SearchNode extends Omit<GhPr, 'statusCheckRollup' | 'reviews' | 'reviewRequests'> {\n repository?: { nameWithOwner?: string } | null;\n commits?: { nodes?: Array<{ commit?: { statusCheckRollup?: { state?: string } | null } | null } | null> | null } | null;\n reviewRequests?: { nodes?: Array<{ requestedReviewer?: { login?: string } | null } | null> | null } | null;\n latestReviews?: { nodes?: Array<{ author?: { login?: string } | null; state?: string } | null> | null } | null;\n}\n\n/** A check rollup's one word, in the shape `gh pr list` gives (so one conversion reads both). */\nfunction rollupAsChecks(state: string | undefined): GhPr['statusCheckRollup'] {\n if (state === 'FAILURE' || state === 'ERROR') return [{ conclusion: 'FAILURE', status: 'COMPLETED' }];\n if (state === 'PENDING' || state === 'EXPECTED') return [{ conclusion: null, status: 'PENDING' }];\n if (state === 'SUCCESS') return [{ conclusion: 'SUCCESS', status: 'COMPLETED' }];\n return [];\n}\n\n/**\n * The search's answer as work's PR rows, each under the alias (or aliases)\n * enrolled for its repository; PRs of repos you haven't enrolled are left\n * out, as before. `incomplete` when a search found more than it returned. Pure.\n */\nexport function parsePrSearch(\n stdout: string,\n aliasesOf: (nameWithOwner: string) => string[],\n): { prs: PullRequestInfo[]; incomplete: boolean } {\n const data = (JSON.parse(stdout) as { data?: Record<string, unknown> } | null)?.data ?? {};\n const user = ((data.viewer as { login?: string } | undefined)?.login ?? '').trim();\n const seen = new Set<string>();\n const prs: PullRequestInfo[] = [];\n let incomplete = false;\n for (const key of ['mine', 'asked']) {\n const result = data[key] as { issueCount?: number; nodes?: Array<SearchNode | null> } | undefined;\n const nodes = (result?.nodes ?? []).filter((n): n is SearchNode => !!n && typeof n.number === 'number');\n if ((result?.issueCount ?? 0) > nodes.length) incomplete = true;\n for (const n of nodes) {\n const pr: GhPr = {\n ...n,\n statusCheckRollup: rollupAsChecks(n.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state),\n reviews: (n.latestReviews?.nodes ?? []).filter((r) => !!r),\n reviewRequests: (n.reviewRequests?.nodes ?? []).map((r) => r?.requestedReviewer ?? null),\n };\n for (const alias of aliasesOf(n.repository?.nameWithOwner ?? '')) {\n const id = `${alias}#${n.number}`;\n if (seen.has(id)) continue;\n seen.add(id);\n prs.push(toPrInfo(pr, alias, user));\n }\n }\n }\n return { prs, incomplete };\n}\n\n/** parsePrSearch, or null for an answer that isn't JSON. */\nfunction readSearch(stdout: string, aliasesOf: (nameWithOwner: string) => string[]): ReturnType<typeof parsePrSearch> | null {\n try {\n return parsePrSearch(stdout, aliasesOf);\n } catch {\n return null;\n }\n}\n\n/** `owner/name` (lowercase) of a repo's origin on github.com, from its `.git/config` text; null for another host or no origin. Pure. */\nexport function githubRepoOf(configText: string): string | null {\n const url = originUrl(configText);\n if (!url || !/(^|[@/.])github\\.com[:/]/i.test(url)) return null;\n return ownerRepo(url)?.toLowerCase() ?? null;\n}\n\n/**\n * Fetch open PRs for a repo using `gh` CLI (async, non-blocking).\n */\nconst PR_LIST_LIMIT = 100;\n\n/** Open PRs for a repo; null when gh couldn't say (missing, offline, not a GitHub repo). */\nasync function fetchPullRequests(repoPath: string, repoAlias: string, currentUser: string): Promise<PullRequestInfo[] | null> {\n try {\n const stdout = await execAsync(\n 'gh',\n [\n 'pr',\n 'list',\n '--state',\n 'open',\n '--json',\n 'number,title,headRefName,url,isDraft,statusCheckRollup,reviewDecision,reviews,reviewRequests,mergeable,author,isCrossRepository',\n '--limit',\n String(PR_LIST_LIMIT),\n ],\n repoPath,\n 15000,\n );\n if (!stdout) return [];\n return parsePrJson(stdout, repoAlias, currentUser);\n } catch {\n return null;\n }\n}\n\n/**\n * Fetch PRs for all configured repos (async, non-blocking).\n * Runs all repo fetches in parallel.\n * Returns a map from branch name → array of PRs across repos.\n */\nasync function getCurrentUser(): Promise<string> {\n try {\n const stdout = await execAsync('gh', ['api', 'user', '--jq', '.login'], process.cwd(), 5000);\n return stdout.trim();\n } catch {\n return '';\n }\n}\n\n/** What fetchAllPullRequests reaches outside (tests pass fakes). */\nexport interface PrListDeps {\n /** `gh api graphql` with the search: its stdout, or null when gh couldn't. */\n search: () => Promise<string | null>;\n /** One repo the old way (`gh pr list` there): not on github.com, or the search failed. */\n listRepo: (repoPath: string, alias: string) => Promise<PullRequestInfo[] | null>;\n /** A repo's `.git/config` text, or null. */\n gitConfig: (repoPath: string) => string | null;\n}\n\nfunction defaultPrListDeps(): PrListDeps {\n let user: Promise<string> | null = null;\n return {\n search: async () => {\n try {\n return await execAsync(\n 'gh',\n ['api', 'graphql', '-f', `query=${PR_SEARCH_QUERY}`, '-f', `mine=${PR_SEARCH_VARS.mine}`, '-f', `asked=${PR_SEARCH_VARS.asked}`],\n process.cwd(),\n 20000,\n );\n } catch {\n return null;\n }\n },\n listRepo: async (repoPath, alias) => fetchPullRequests(repoPath, alias, await (user ??= getCurrentUser())),\n gitConfig: readGitConfig,\n };\n}\n\n/**\n * The PRs for the dashboard: one search for every repo on github.com (yours,\n * and those asking your review), and the old per-repo list only for repos\n * elsewhere (GitHub Enterprise, no origin) — or for all of them when the\n * search fails. Returns a map from branch name → PRs across repos.\n */\nexport async function fetchAllPullRequests(\n repos: Record<string, string>,\n deps: PrListDeps = defaultPrListDeps(),\n): Promise<{ map: BranchPrMap; incomplete: string[] }> {\n const entries = Object.entries(repos);\n const onGithub = new Map<string, string[]>(); // owner/name → its aliases\n const elsewhere: Array<[string, string]> = [];\n for (const [alias, repoPath] of entries) {\n const text = deps.gitConfig(repoPath);\n const gh = text ? githubRepoOf(text) : null;\n if (gh) onGithub.set(gh, [...(onGithub.get(gh) ?? []), alias]);\n else elsewhere.push([alias, repoPath]);\n }\n\n const results: Array<PullRequestInfo[] | null> = [];\n const incomplete: string[] = [];\n if (onGithub.size) {\n const out = await deps.search();\n const parsed = out ? readSearch(out, (repo) => onGithub.get(repo.toLowerCase()) ?? []) : null;\n if (parsed) {\n results.push(parsed.prs);\n if (parsed.incomplete) incomplete.push(...[...onGithub.values()].flat());\n } else {\n // gh can't search (an old gh, no network): the old way, repo by repo.\n const asked = new Set(elsewhere.map(([a]) => a));\n for (const [alias, repoPath] of entries) if (!asked.has(alias)) elsewhere.push([alias, repoPath]);\n }\n }\n const listed = await Promise.all(elsewhere.map(([alias, repoPath]) => deps.listRepo(repoPath, alias)));\n results.push(...listed);\n // Repos whose list may be missing PRs: gh failed, or it hit the limit.\n incomplete.push(...elsewhere.filter((_, i) => listed[i] === null || listed[i]!.length >= PR_LIST_LIMIT).map(([alias]) => alias));\n\n const map: BranchPrMap = new Map();\n for (const prList of results) {\n for (const pr of prList ?? []) {\n const existing = map.get(pr.branch);\n if (existing) {\n existing.push(pr);\n } else {\n map.set(pr.branch, [pr]);\n }\n }\n }\n\n return { map, incomplete };\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,gBAAgB;AAiCzB,SAAS,UAAU,KAAa,MAAgB,KAAa,SAAkC;AAC7F,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AAKtC,aA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