@moberg_hr/work-tree 2.23.2 → 2.23.4

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 (294) hide show
  1. package/dist/{account-6ZQ3VFA2.js → account-TSSDZ7HI.js} +26 -27
  2. package/dist/{account-6ZQ3VFA2.js.map → account-TSSDZ7HI.js.map} +1 -1
  3. package/dist/{add-repo-WXDEKZRX.js → add-repo-X6BY6Y7G.js} +20 -21
  4. package/dist/{add-repo-WXDEKZRX.js.map → add-repo-X6BY6Y7G.js.map} +1 -1
  5. package/dist/{answer-L55DWMR5.js → answer-44MKEQDP.js} +12 -12
  6. package/dist/{attach-KLVI7BHS.js → attach-4442NY36.js} +21 -22
  7. package/dist/{attach-KLVI7BHS.js.map → attach-4442NY36.js.map} +1 -1
  8. package/dist/bin.js +4 -4
  9. package/dist/{block-BRNRP226.js → block-KH7GT6KC.js} +17 -18
  10. package/dist/{block-BRNRP226.js.map → block-KH7GT6KC.js.map} +1 -1
  11. package/dist/{broadcast-GQE7H3MF.js → broadcast-RHPRE6OM.js} +10 -10
  12. package/dist/{catchup-ZMG4OWF2.js → catchup-POW3OD2J.js} +15 -15
  13. package/dist/{child-MPXXJ2QX.js → child-Y5H7NS7I.js} +18 -15
  14. package/dist/child-Y5H7NS7I.js.map +1 -0
  15. package/dist/{chunk-A53OR6P5.js → chunk-2TXH75I4.js} +7 -7
  16. package/dist/{chunk-HCYES6U7.js → chunk-32CMRR6M.js} +2 -2
  17. package/dist/{chunk-VQEMPGJL.js → chunk-4FCPWNZD.js} +2 -2
  18. package/dist/{chunk-PSALWCBD.js → chunk-4VQJQ6CO.js} +5 -5
  19. package/dist/{chunk-DK3UMOX7.js → chunk-55MJYS5Q.js} +2 -2
  20. package/dist/{chunk-773UJC5C.js → chunk-5C5NTOZT.js} +7 -7
  21. package/dist/{chunk-NREZVTBP.js → chunk-6ER6IBFJ.js} +2 -2
  22. package/dist/chunk-6SOIHZYE.js +9 -0
  23. package/dist/{chunk-MMEFW2PI.js → chunk-7FY6V6SF.js} +7 -7
  24. package/dist/{chunk-ZPDCVDE2.js → chunk-7GMENM2D.js} +2 -2
  25. package/dist/{chunk-JVOQSU6R.js → chunk-7L3D3SZA.js} +6 -6
  26. package/dist/{chunk-VPZ5ILKT.js → chunk-7VDNNWPU.js} +5 -5
  27. package/dist/{chunk-NWKVTUTN.js → chunk-B34R6TQO.js} +399 -192
  28. package/dist/chunk-B34R6TQO.js.map +1 -0
  29. package/dist/{chunk-6S3DYLGH.js → chunk-BLCQOJDB.js} +6 -6
  30. package/dist/{chunk-XB4SCJWD.js → chunk-BMZ4KPUT.js} +7 -7
  31. package/dist/{chunk-XIN6XUFL.js → chunk-D4XRXS3P.js} +2 -2
  32. package/dist/{chunk-2JLG65GB.js → chunk-D7ZWESWW.js} +3 -3
  33. package/dist/{chunk-KJAE7WO5.js → chunk-DIBXT67T.js} +2 -2
  34. package/dist/{chunk-VNZBFVGY.js → chunk-EFCWSWZK.js} +6 -6
  35. package/dist/{chunk-HBYXSFLN.js → chunk-F44FMA67.js} +5 -5
  36. package/dist/{chunk-BBI4YQTS.js → chunk-FC5WCLWJ.js} +18 -18
  37. package/dist/{chunk-MYXEX6BB.js → chunk-FCMPVWE7.js} +33 -10
  38. package/dist/chunk-FCMPVWE7.js.map +1 -0
  39. package/dist/{chunk-C5BBVVHW.js → chunk-FFRNSK4S.js} +2 -2
  40. package/dist/{chunk-ETWP7MDS.js → chunk-FX4KMK4M.js} +1 -1
  41. package/dist/chunk-FX4KMK4M.js.map +1 -0
  42. package/dist/{chunk-RGKGJOES.js → chunk-H2QFMDSU.js} +9 -9
  43. package/dist/{chunk-LOFGDH5B.js → chunk-IEKDHKGO.js} +2 -2
  44. package/dist/{chunk-EORL2V7P.js → chunk-IN52DQRN.js} +2 -2
  45. package/dist/{chunk-G4VKMMIC.js → chunk-IUOY42LA.js} +15 -15
  46. package/dist/{chunk-XT3FON6A.js → chunk-J5NSFIQ5.js} +5 -5
  47. package/dist/{chunk-HUGHF45U.js → chunk-JIQ2XXFX.js} +3 -3
  48. package/dist/{chunk-M2P722BR.js → chunk-JPUNYEQR.js} +2 -2
  49. package/dist/{chunk-T5GJVUSL.js → chunk-KBEP7BJP.js} +2 -2
  50. package/dist/chunk-KPAT46RL.js +21 -0
  51. package/dist/chunk-KPAT46RL.js.map +1 -0
  52. package/dist/{chunk-HO5KESIB.js → chunk-LC44HSCM.js} +4 -4
  53. package/dist/{chunk-NLU6MBYT.js → chunk-LCMLUSBQ.js} +12 -12
  54. package/dist/{chunk-SF3DIIKN.js → chunk-M7GVYIAB.js} +3 -3
  55. package/dist/{chunk-SUHANL3G.js → chunk-MC5T6J2V.js} +7 -7
  56. package/dist/{chunk-ZG6HB4BO.js → chunk-MFZRX6GM.js} +13 -17
  57. package/dist/chunk-MFZRX6GM.js.map +1 -0
  58. package/dist/{chunk-GNIYYXQX.js → chunk-MSXMX7C7.js} +2 -2
  59. package/dist/{chunk-XL4YNA3L.js → chunk-NIMROXWE.js} +22 -13
  60. package/dist/chunk-NIMROXWE.js.map +1 -0
  61. package/dist/{chunk-IUVMVNIO.js → chunk-NTBTO4SJ.js} +6 -6
  62. package/dist/{chunk-LW6VCL6S.js → chunk-NUWP3CGK.js} +7 -7
  63. package/dist/{chunk-NS7WH53I.js → chunk-O45NATRC.js} +2 -2
  64. package/dist/{chunk-APHVSSLI.js → chunk-OJ23FAT5.js} +2 -2
  65. package/dist/{chunk-QAIG5FSQ.js → chunk-OOVYRRGT.js} +3 -3
  66. package/dist/{chunk-XBWS77S2.js → chunk-OTY7XB5J.js} +2 -2
  67. package/dist/chunk-OU3BTWR6.js +482 -0
  68. package/dist/chunk-OU3BTWR6.js.map +1 -0
  69. package/dist/{chunk-MYASALCU.js → chunk-OYNVFQM5.js} +9 -9
  70. package/dist/{chunk-QMWV4UKB.js → chunk-PLEILEF4.js} +3 -3
  71. package/dist/{chunk-WH6DAD6D.js → chunk-PX7BDJQV.js} +2 -2
  72. package/dist/{chunk-GF7RAQFD.js → chunk-QNLWGTNI.js} +3 -3
  73. package/dist/{chunk-KWJ6S4NZ.js → chunk-S5Z247FI.js} +9 -9
  74. package/dist/{chunk-BGQ6NUU7.js → chunk-S77BGUVD.js} +4 -4
  75. package/dist/{chunk-K6FD5WDW.js → chunk-UGZ6WBYP.js} +8 -8
  76. package/dist/{chunk-QSSCVTFG.js → chunk-UVRGRMN4.js} +4 -4
  77. package/dist/{chunk-7HQSILMM.js → chunk-V4RNP62T.js} +4 -4
  78. package/dist/{chunk-7BH2PUYY.js → chunk-W3OU74ER.js} +5 -5
  79. package/dist/{chunk-CRAGAIOS.js → chunk-W4KMOS7T.js} +11 -11
  80. package/dist/{chunk-LCYYJFSZ.js → chunk-WD7XHWRQ.js} +5 -5
  81. package/dist/{chunk-ZHK5XOV5.js → chunk-XMWMC5R2.js} +60 -60
  82. package/dist/{chunk-BZOYUBK4.js → chunk-XXOOR3IV.js} +6 -6
  83. package/dist/{chunk-ED6YLB4S.js → chunk-YQSWVHKK.js} +13 -13
  84. package/dist/chunk-YQSWVHKK.js.map +1 -0
  85. package/dist/{chunk-DNC2ZJOF.js → chunk-ZCRIGDCK.js} +7 -7
  86. package/dist/{chunk-P53UYZZ4.js → chunk-ZU2265JN.js} +2 -2
  87. package/dist/{cleanup-DRELB6UC.js → cleanup-HTM3VX4O.js} +38 -40
  88. package/dist/{cleanup-DRELB6UC.js.map → cleanup-HTM3VX4O.js.map} +1 -1
  89. package/dist/{cli-C3U2BC44.js → cli-6UA7NFOP.js} +4 -4
  90. package/dist/{color-T75ANAWG.js → color-GLNALQJU.js} +14 -14
  91. package/dist/{config-KI6JOXKW.js → config-MC6A5AOY.js} +16 -17
  92. package/dist/{config-KI6JOXKW.js.map → config-MC6A5AOY.js.map} +1 -1
  93. package/dist/{coordinate-4PPZN4U4.js → coordinate-JRJX7LN6.js} +26 -16
  94. package/dist/coordinate-JRJX7LN6.js.map +1 -0
  95. package/dist/{diff-NDZPRQV7.js → diff-ABQL4OGG.js} +15 -16
  96. package/dist/{diff-NDZPRQV7.js.map → diff-ABQL4OGG.js.map} +1 -1
  97. package/dist/{digest-H5YFX5WR.js → digest-K5LVRZJ2.js} +12 -12
  98. package/dist/{fork-HHHATXVI.js → fork-SYSHOZEC.js} +33 -35
  99. package/dist/{fork-HHHATXVI.js.map → fork-SYSHOZEC.js.map} +1 -1
  100. package/dist/{history-3Z7AS2AC.js → history-UPV5FKKH.js} +10 -10
  101. package/dist/{hook-KOK7NKCO.js → hook-HKZEOBBJ.js} +31 -24
  102. package/dist/hook-HKZEOBBJ.js.map +1 -0
  103. package/dist/{hydrate-VI3XSZQH.js → hydrate-W6LXQTDU.js} +11 -11
  104. package/dist/{init-7NOKRHNJ.js → init-DXALHRTW.js} +18 -19
  105. package/dist/{init-7NOKRHNJ.js.map → init-DXALHRTW.js.map} +1 -1
  106. package/dist/{install-skills-TL5D7HZU.js → install-skills-COQUL6LG.js} +11 -9
  107. package/dist/install-skills-bin.js +10 -8
  108. package/dist/install-skills-bin.js.map +1 -1
  109. package/dist/{keep-G62GSDOQ.js → keep-5725FMZD.js} +12 -12
  110. package/dist/{list-CEVAZQ4V.js → list-HCD535CS.js} +11 -11
  111. package/dist/{move-ISAW6RDM.js → move-I46P3OHI.js} +24 -25
  112. package/dist/{move-ISAW6RDM.js.map → move-I46P3OHI.js.map} +1 -1
  113. package/dist/{note-YIVFXTGM.js → note-EJMRTSDZ.js} +12 -12
  114. package/dist/{overlaps-YBEHBRRK.js → overlaps-7KFBI2B2.js} +18 -19
  115. package/dist/{overlaps-YBEHBRRK.js.map → overlaps-7KFBI2B2.js.map} +1 -1
  116. package/dist/{pin-J4IDSHRG.js → pin-QR3CSLIU.js} +13 -13
  117. package/dist/{pr-Z7CPBBGT.js → pr-IOWS2QWR.js} +26 -27
  118. package/dist/{pr-Z7CPBBGT.js.map → pr-IOWS2QWR.js.map} +1 -1
  119. package/dist/{prune-UA3UDZSM.js → prune-GUSIRD4X.js} +35 -37
  120. package/dist/{prune-UA3UDZSM.js.map → prune-GUSIRD4X.js.map} +1 -1
  121. package/dist/{pty-host-JIQUP62K.js → pty-host-BFPESGGA.js} +29 -32
  122. package/dist/{pty-host-JIQUP62K.js.map → pty-host-BFPESGGA.js.map} +1 -1
  123. package/dist/{read-DG4PCLFH.js → read-VL5G36JG.js} +17 -13
  124. package/dist/{read-DG4PCLFH.js.map → read-VL5G36JG.js.map} +1 -1
  125. package/dist/{recent-PGD6QYAH.js → recent-WXDFS3EQ.js} +21 -22
  126. package/dist/{recent-PGD6QYAH.js.map → recent-WXDFS3EQ.js.map} +1 -1
  127. package/dist/{remove-TPLA64HP.js → remove-FID7UAFE.js} +36 -38
  128. package/dist/{remove-TPLA64HP.js.map → remove-FID7UAFE.js.map} +1 -1
  129. package/dist/{report-K3OTT2ED.js → report-4ZFCDVGT.js} +16 -13
  130. package/dist/report-4ZFCDVGT.js.map +1 -0
  131. package/dist/{restart-477IX2JX.js → restart-NO3V563I.js} +14 -15
  132. package/dist/{restart-477IX2JX.js.map → restart-NO3V563I.js.map} +1 -1
  133. package/dist/{resume-OYBAJCYE.js → resume-HXJQMNLX.js} +21 -22
  134. package/dist/{resume-OYBAJCYE.js.map → resume-HXJQMNLX.js.map} +1 -1
  135. package/dist/{review-6PWFSBAO.js → review-F54E75RF.js} +11 -11
  136. package/dist/{review-now-AT2SPPRO.js → review-now-K3GBWULH.js} +2 -2
  137. package/dist/{run-XEHF2N4A.js → run-X7VJAHIA.js} +10 -10
  138. package/dist/{screen-SFU6TCDV.js → screen-2HPSFMT5.js} +12 -12
  139. package/dist/{search-VJ3BGWPX.js → search-XNWJXKLY.js} +10 -10
  140. package/dist/{section-ZLINSTGS.js → section-GF4S3RHQ.js} +14 -14
  141. package/dist/{send-NBP2WYBG.js → send-W3W42FBF.js} +26 -16
  142. package/dist/send-W3W42FBF.js.map +1 -0
  143. package/dist/{sessions-UT4I7A43.js → sessions-PQV6NZKZ.js} +31 -33
  144. package/dist/{sessions-UT4I7A43.js.map → sessions-PQV6NZKZ.js.map} +1 -1
  145. package/dist/{show-RK2EWOR6.js → show-75JNPHZZ.js} +11 -11
  146. package/dist/{snooze-T2WWIKZN.js → snooze-R3IISMDC.js} +12 -12
  147. package/dist/{start-AWHOIA3Q.js → start-PD6MO5H5.js} +12 -12
  148. package/dist/{state-HK67C4UA.js → state-KUP4OEXR.js} +2 -2
  149. package/dist/{status-QE2DA6RR.js → status-ZJDIGGFB.js} +15 -16
  150. package/dist/{status-QE2DA6RR.js.map → status-ZJDIGGFB.js.map} +1 -1
  151. package/dist/{statusline-Z5HLKDIA.js → statusline-SZPL3QBC.js} +5 -5
  152. package/dist/{statusline-hook-VPPS3PFO.js → statusline-hook-6BNEVENM.js} +4 -4
  153. package/dist/{stop-YOU3P3ZR.js → stop-CID5EBHG.js} +12 -12
  154. package/dist/{sync-74EFTPBJ.js → sync-VV4MLQ4Q.js} +35 -37
  155. package/dist/{sync-74EFTPBJ.js.map → sync-VV4MLQ4Q.js.map} +1 -1
  156. package/dist/{time-ZGMZZ5OY.js → time-THNKOLZK.js} +14 -14
  157. package/dist/{time-actions-VAGRSY5B.js → time-actions-6L4RQ3A7.js} +3 -3
  158. package/dist/{timesheet-N74LPF5M.js → timesheet-5DYIZGCM.js} +20 -21
  159. package/dist/{timesheet-N74LPF5M.js.map → timesheet-5DYIZGCM.js.map} +1 -1
  160. package/dist/{todo-UVKGOG7D.js → todo-VHYBQC3I.js} +2 -2
  161. package/dist/{tree-FXTCWC6D.js → tree-HCKKRJ6Y.js} +37 -39
  162. package/dist/{tree-FXTCWC6D.js.map → tree-HCKKRJ6Y.js.map} +1 -1
  163. package/dist/{update-5QSRHIWH.js → update-MJ4DQLAN.js} +20 -21
  164. package/dist/{update-5QSRHIWH.js.map → update-MJ4DQLAN.js.map} +1 -1
  165. package/dist/{usage-CW7CDFU3.js → usage-XLLVYWBE.js} +12 -12
  166. package/dist/{usage-ask-V2SIRW4F.js → usage-ask-QBLLIHE3.js} +11 -11
  167. package/dist/version-ATSNJMTH.js +31 -0
  168. package/dist/version-ATSNJMTH.js.map +1 -0
  169. package/dist/{wait-XXC3I6DK.js → wait-NIPHM5DN.js} +13 -13
  170. package/dist/wd-bin.js +3 -3
  171. package/dist/web/assets/{PtyView-BLTE5F3E.js → PtyView-DCwMId37.js} +2 -2
  172. package/dist/web/assets/{PtyView-BLTE5F3E.js.map → PtyView-DCwMId37.js.map} +1 -1
  173. package/dist/web/assets/{index-BiadbzE6.js → index-AQoEcgyy.js} +27 -27
  174. package/dist/web/assets/index-AQoEcgyy.js.map +1 -0
  175. package/dist/web/index.html +1 -1
  176. package/dist/{web-SUSR4IAK.js → web-NMS22ZDZ.js} +198 -92
  177. package/dist/web-NMS22ZDZ.js.map +1 -0
  178. package/npm-shrinkwrap.json +2 -2
  179. package/package.json +1 -1
  180. package/plugins/work-tree/skills/work-sessions/SKILL.md +35 -50
  181. package/dist/child-MPXXJ2QX.js.map +0 -1
  182. package/dist/chunk-4CXUVBOD.js +0 -76
  183. package/dist/chunk-4CXUVBOD.js.map +0 -1
  184. package/dist/chunk-BMPTUIP4.js +0 -105
  185. package/dist/chunk-BMPTUIP4.js.map +0 -1
  186. package/dist/chunk-DYKA3LO3.js +0 -9
  187. package/dist/chunk-ED6YLB4S.js.map +0 -1
  188. package/dist/chunk-ETWP7MDS.js.map +0 -1
  189. package/dist/chunk-MYXEX6BB.js.map +0 -1
  190. package/dist/chunk-NWKVTUTN.js.map +0 -1
  191. package/dist/chunk-SJBEIYLK.js +0 -16
  192. package/dist/chunk-SJBEIYLK.js.map +0 -1
  193. package/dist/chunk-TC3H7I6O.js +0 -196
  194. package/dist/chunk-TC3H7I6O.js.map +0 -1
  195. package/dist/chunk-TNJF7T33.js +0 -17
  196. package/dist/chunk-TNJF7T33.js.map +0 -1
  197. package/dist/chunk-XL4YNA3L.js.map +0 -1
  198. package/dist/chunk-ZG6HB4BO.js.map +0 -1
  199. package/dist/coordinate-4PPZN4U4.js.map +0 -1
  200. package/dist/hook-KOK7NKCO.js.map +0 -1
  201. package/dist/report-K3OTT2ED.js.map +0 -1
  202. package/dist/send-NBP2WYBG.js.map +0 -1
  203. package/dist/version-RJ4PCHPB.js +0 -117
  204. package/dist/version-RJ4PCHPB.js.map +0 -1
  205. package/dist/web/assets/index-BiadbzE6.js.map +0 -1
  206. package/dist/web-SUSR4IAK.js.map +0 -1
  207. /package/dist/{answer-L55DWMR5.js.map → answer-44MKEQDP.js.map} +0 -0
  208. /package/dist/{broadcast-GQE7H3MF.js.map → broadcast-RHPRE6OM.js.map} +0 -0
  209. /package/dist/{catchup-ZMG4OWF2.js.map → catchup-POW3OD2J.js.map} +0 -0
  210. /package/dist/{chunk-A53OR6P5.js.map → chunk-2TXH75I4.js.map} +0 -0
  211. /package/dist/{chunk-HCYES6U7.js.map → chunk-32CMRR6M.js.map} +0 -0
  212. /package/dist/{chunk-VQEMPGJL.js.map → chunk-4FCPWNZD.js.map} +0 -0
  213. /package/dist/{chunk-PSALWCBD.js.map → chunk-4VQJQ6CO.js.map} +0 -0
  214. /package/dist/{chunk-DK3UMOX7.js.map → chunk-55MJYS5Q.js.map} +0 -0
  215. /package/dist/{chunk-773UJC5C.js.map → chunk-5C5NTOZT.js.map} +0 -0
  216. /package/dist/{chunk-NREZVTBP.js.map → chunk-6ER6IBFJ.js.map} +0 -0
  217. /package/dist/{chunk-DYKA3LO3.js.map → chunk-6SOIHZYE.js.map} +0 -0
  218. /package/dist/{chunk-MMEFW2PI.js.map → chunk-7FY6V6SF.js.map} +0 -0
  219. /package/dist/{chunk-ZPDCVDE2.js.map → chunk-7GMENM2D.js.map} +0 -0
  220. /package/dist/{chunk-JVOQSU6R.js.map → chunk-7L3D3SZA.js.map} +0 -0
  221. /package/dist/{chunk-VPZ5ILKT.js.map → chunk-7VDNNWPU.js.map} +0 -0
  222. /package/dist/{chunk-6S3DYLGH.js.map → chunk-BLCQOJDB.js.map} +0 -0
  223. /package/dist/{chunk-XB4SCJWD.js.map → chunk-BMZ4KPUT.js.map} +0 -0
  224. /package/dist/{chunk-XIN6XUFL.js.map → chunk-D4XRXS3P.js.map} +0 -0
  225. /package/dist/{chunk-2JLG65GB.js.map → chunk-D7ZWESWW.js.map} +0 -0
  226. /package/dist/{chunk-KJAE7WO5.js.map → chunk-DIBXT67T.js.map} +0 -0
  227. /package/dist/{chunk-VNZBFVGY.js.map → chunk-EFCWSWZK.js.map} +0 -0
  228. /package/dist/{chunk-HBYXSFLN.js.map → chunk-F44FMA67.js.map} +0 -0
  229. /package/dist/{chunk-BBI4YQTS.js.map → chunk-FC5WCLWJ.js.map} +0 -0
  230. /package/dist/{chunk-C5BBVVHW.js.map → chunk-FFRNSK4S.js.map} +0 -0
  231. /package/dist/{chunk-RGKGJOES.js.map → chunk-H2QFMDSU.js.map} +0 -0
  232. /package/dist/{chunk-LOFGDH5B.js.map → chunk-IEKDHKGO.js.map} +0 -0
  233. /package/dist/{chunk-EORL2V7P.js.map → chunk-IN52DQRN.js.map} +0 -0
  234. /package/dist/{chunk-G4VKMMIC.js.map → chunk-IUOY42LA.js.map} +0 -0
  235. /package/dist/{chunk-XT3FON6A.js.map → chunk-J5NSFIQ5.js.map} +0 -0
  236. /package/dist/{chunk-HUGHF45U.js.map → chunk-JIQ2XXFX.js.map} +0 -0
  237. /package/dist/{chunk-M2P722BR.js.map → chunk-JPUNYEQR.js.map} +0 -0
  238. /package/dist/{chunk-T5GJVUSL.js.map → chunk-KBEP7BJP.js.map} +0 -0
  239. /package/dist/{chunk-HO5KESIB.js.map → chunk-LC44HSCM.js.map} +0 -0
  240. /package/dist/{chunk-NLU6MBYT.js.map → chunk-LCMLUSBQ.js.map} +0 -0
  241. /package/dist/{chunk-SF3DIIKN.js.map → chunk-M7GVYIAB.js.map} +0 -0
  242. /package/dist/{chunk-SUHANL3G.js.map → chunk-MC5T6J2V.js.map} +0 -0
  243. /package/dist/{chunk-GNIYYXQX.js.map → chunk-MSXMX7C7.js.map} +0 -0
  244. /package/dist/{chunk-IUVMVNIO.js.map → chunk-NTBTO4SJ.js.map} +0 -0
  245. /package/dist/{chunk-LW6VCL6S.js.map → chunk-NUWP3CGK.js.map} +0 -0
  246. /package/dist/{chunk-NS7WH53I.js.map → chunk-O45NATRC.js.map} +0 -0
  247. /package/dist/{chunk-APHVSSLI.js.map → chunk-OJ23FAT5.js.map} +0 -0
  248. /package/dist/{chunk-QAIG5FSQ.js.map → chunk-OOVYRRGT.js.map} +0 -0
  249. /package/dist/{chunk-XBWS77S2.js.map → chunk-OTY7XB5J.js.map} +0 -0
  250. /package/dist/{chunk-MYASALCU.js.map → chunk-OYNVFQM5.js.map} +0 -0
  251. /package/dist/{chunk-QMWV4UKB.js.map → chunk-PLEILEF4.js.map} +0 -0
  252. /package/dist/{chunk-WH6DAD6D.js.map → chunk-PX7BDJQV.js.map} +0 -0
  253. /package/dist/{chunk-GF7RAQFD.js.map → chunk-QNLWGTNI.js.map} +0 -0
  254. /package/dist/{chunk-KWJ6S4NZ.js.map → chunk-S5Z247FI.js.map} +0 -0
  255. /package/dist/{chunk-BGQ6NUU7.js.map → chunk-S77BGUVD.js.map} +0 -0
  256. /package/dist/{chunk-K6FD5WDW.js.map → chunk-UGZ6WBYP.js.map} +0 -0
  257. /package/dist/{chunk-QSSCVTFG.js.map → chunk-UVRGRMN4.js.map} +0 -0
  258. /package/dist/{chunk-7HQSILMM.js.map → chunk-V4RNP62T.js.map} +0 -0
  259. /package/dist/{chunk-7BH2PUYY.js.map → chunk-W3OU74ER.js.map} +0 -0
  260. /package/dist/{chunk-CRAGAIOS.js.map → chunk-W4KMOS7T.js.map} +0 -0
  261. /package/dist/{chunk-LCYYJFSZ.js.map → chunk-WD7XHWRQ.js.map} +0 -0
  262. /package/dist/{chunk-ZHK5XOV5.js.map → chunk-XMWMC5R2.js.map} +0 -0
  263. /package/dist/{chunk-BZOYUBK4.js.map → chunk-XXOOR3IV.js.map} +0 -0
  264. /package/dist/{chunk-DNC2ZJOF.js.map → chunk-ZCRIGDCK.js.map} +0 -0
  265. /package/dist/{chunk-P53UYZZ4.js.map → chunk-ZU2265JN.js.map} +0 -0
  266. /package/dist/{cli-C3U2BC44.js.map → cli-6UA7NFOP.js.map} +0 -0
  267. /package/dist/{color-T75ANAWG.js.map → color-GLNALQJU.js.map} +0 -0
  268. /package/dist/{digest-H5YFX5WR.js.map → digest-K5LVRZJ2.js.map} +0 -0
  269. /package/dist/{history-3Z7AS2AC.js.map → history-UPV5FKKH.js.map} +0 -0
  270. /package/dist/{hydrate-VI3XSZQH.js.map → hydrate-W6LXQTDU.js.map} +0 -0
  271. /package/dist/{install-skills-TL5D7HZU.js.map → install-skills-COQUL6LG.js.map} +0 -0
  272. /package/dist/{keep-G62GSDOQ.js.map → keep-5725FMZD.js.map} +0 -0
  273. /package/dist/{list-CEVAZQ4V.js.map → list-HCD535CS.js.map} +0 -0
  274. /package/dist/{note-YIVFXTGM.js.map → note-EJMRTSDZ.js.map} +0 -0
  275. /package/dist/{pin-J4IDSHRG.js.map → pin-QR3CSLIU.js.map} +0 -0
  276. /package/dist/{review-6PWFSBAO.js.map → review-F54E75RF.js.map} +0 -0
  277. /package/dist/{review-now-AT2SPPRO.js.map → review-now-K3GBWULH.js.map} +0 -0
  278. /package/dist/{run-XEHF2N4A.js.map → run-X7VJAHIA.js.map} +0 -0
  279. /package/dist/{screen-SFU6TCDV.js.map → screen-2HPSFMT5.js.map} +0 -0
  280. /package/dist/{search-VJ3BGWPX.js.map → search-XNWJXKLY.js.map} +0 -0
  281. /package/dist/{section-ZLINSTGS.js.map → section-GF4S3RHQ.js.map} +0 -0
  282. /package/dist/{show-RK2EWOR6.js.map → show-75JNPHZZ.js.map} +0 -0
  283. /package/dist/{snooze-T2WWIKZN.js.map → snooze-R3IISMDC.js.map} +0 -0
  284. /package/dist/{start-AWHOIA3Q.js.map → start-PD6MO5H5.js.map} +0 -0
  285. /package/dist/{state-HK67C4UA.js.map → state-KUP4OEXR.js.map} +0 -0
  286. /package/dist/{statusline-Z5HLKDIA.js.map → statusline-SZPL3QBC.js.map} +0 -0
  287. /package/dist/{statusline-hook-VPPS3PFO.js.map → statusline-hook-6BNEVENM.js.map} +0 -0
  288. /package/dist/{stop-YOU3P3ZR.js.map → stop-CID5EBHG.js.map} +0 -0
  289. /package/dist/{time-ZGMZZ5OY.js.map → time-THNKOLZK.js.map} +0 -0
  290. /package/dist/{time-actions-VAGRSY5B.js.map → time-actions-6L4RQ3A7.js.map} +0 -0
  291. /package/dist/{todo-UVKGOG7D.js.map → todo-VHYBQC3I.js.map} +0 -0
  292. /package/dist/{usage-CW7CDFU3.js.map → usage-XLLVYWBE.js.map} +0 -0
  293. /package/dist/{usage-ask-V2SIRW4F.js.map → usage-ask-QBLLIHE3.js.map} +0 -0
  294. /package/dist/{wait-XXC3I6DK.js.map → wait-NIPHM5DN.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/platform/ai-launcher.ts","../src/core/platform/best-effort.ts","../src/core/worktree/own-checkout.ts","../src/core/agents/types.ts","../src/core/agents/index.ts","../src/core/agents/claude/tool-update.ts","../src/core/agents/claude/startup-question.ts","../src/core/agents/claude/temp-folders.ts","../src/core/agents/claude/activity.ts","../src/core/agents/claude/folder-trust.ts","../src/core/agents/claude/setup-copy.ts","../src/core/agents/claude/tool-shell.ts","../src/core/agents/claude/adapter.ts","../src/core/agents/claude/files.ts","../src/core/conversations/jsonl.ts","../src/core/agents/claude/transcript-entry.ts","../src/core/agents/claude/transcript.ts","../src/core/agents/claude/background-commands.ts","../src/core/agents/claude/pr-links.ts","../src/core/agents/claude/entries.ts","../src/core/agents/claude/hooks.ts","../src/core/agents/claude/permission.ts","../src/core/agents/session-hooks.ts","../src/core/agents/claude/session-settings.ts","../src/core/agents/claude/live.ts","../src/core/agents/typing.ts","../src/core/agents/claude/workspace.ts","../src/core/agents/claude/skills.ts","../src/core/agents/claude/usage.ts","../src/core/agents/claude/account-move.ts","../src/core/agents/claude/account-admin.ts","../src/core/platform/package-root.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { WorkConfig } from './config.js';\n\n/** Resolved AI tool spec ready for spawning. */\nexport interface AiToolSpec {\n /** Executable name. */\n cmd: string;\n /** Arguments always prepended (from any extra tokens in `aiCommand`). */\n baseArgs: string[];\n /** Flag injected when resuming a prior session. Empty string disables. */\n resumeFlag: string;\n /**\n * Flag used to pass an initial prompt as a file (followed by the file path).\n * Empty string disables — prompt-file content will be inlined via `promptFlag`\n * instead, if available.\n */\n promptFileFlag: string;\n /**\n * Flag used to pass an inline prompt (followed by the prompt string).\n * Empty string means the prompt is appended as a positional argument\n * (Claude's behavior).\n */\n promptFlag: string;\n}\n\nexport interface AiLaunchOpts {\n resume?: boolean;\n promptFile?: string;\n /** Inline prompt (used by CLI `--prompt`). */\n initialPrompt?: string;\n}\n\n/**\n * Per-tool flag presets. Looked up by the binary in `aiCommand`. Users can\n * override any individual flag via `config.aiCommandFlags`.\n */\nexport const AI_TOOL_PRESETS: Record<\n string,\n {\n resume: string;\n promptFile: string;\n prompt: string;\n }\n> = {\n claude: {\n resume: '--continue',\n promptFile: '--prompt-file',\n prompt: '', // positional\n },\n opencode: {\n resume: '--continue',\n promptFile: '', // no file flag — content gets inlined via promptFlag\n prompt: '--prompt',\n },\n};\n\n/** Display names for the init picker. */\nexport const KNOWN_TOOLS = [\n { name: 'Claude Code (claude)', value: 'claude' },\n { name: 'OpenCode (opencode)', value: 'opencode' },\n] as const;\n\n/**\n * Resolve the configured AI tool. Falls back to the `claude` preset so default\n * behavior is preserved when no `aiCommand` is set.\n */\nexport function getAiTool(config: Pick<WorkConfig, 'aiCommand' | 'aiCommandFlags'>): AiToolSpec {\n const command = (config.aiCommand ?? 'claude').trim();\n const parts = command.split(/\\s+/).filter(Boolean);\n const cmd = parts[0] || 'claude';\n const baseArgs = parts.slice(1);\n const preset = AI_TOOL_PRESETS[cmd] ?? AI_TOOL_PRESETS.claude;\n const overrides = config.aiCommandFlags ?? {};\n return {\n cmd,\n baseArgs,\n resumeFlag: overrides.resume ?? preset.resume,\n promptFileFlag: overrides.promptFile ?? preset.promptFile,\n promptFlag: overrides.prompt ?? preset.prompt,\n };\n}\n\n/** Build the final `{ cmd, args }` to spawn for the given launch options. */\nexport function buildAiLaunchArgs(tool: AiToolSpec, opts: AiLaunchOpts = {}): { cmd: string; args: string[] } {\n const args = [...tool.baseArgs];\n if (opts.resume && tool.resumeFlag) args.push(tool.resumeFlag);\n\n let inlinePrompt = opts.initialPrompt;\n if (opts.promptFile) {\n if (tool.promptFileFlag) {\n args.push(tool.promptFileFlag, opts.promptFile);\n } else if (tool.promptFlag) {\n // Tool has no prompt-file flag — read the file and pass inline instead.\n try {\n inlinePrompt = fs.readFileSync(opts.promptFile, 'utf-8');\n } catch {\n /* leave inlinePrompt as-is */\n }\n }\n }\n if (inlinePrompt) {\n if (tool.promptFlag) args.push(tool.promptFlag, inlinePrompt);\n else args.push(inlinePrompt);\n }\n return { cmd: tool.cmd, args };\n}\n","import { debugLog } from './logger.js';\n\n/**\n * \"Best effort\" without flying blind. Plenty of work's side paths must never\n * break the main one — a Claude hook must not block the turn, a failed\n * status write must not fail a request — so errors are swallowed. But a\n * silent `catch {}` makes those failures invisible when someone asks \"why\n * didn't my session show up / get restored / get a status?\". These helpers\n * swallow AND record to ~/.work/debug.log (rotated), labelled.\n *\n * Use for failures that would explain a symptom. Plain noise — unlinking a\n * file that's already gone, writing to a socket that just closed — can stay\n * a bare catch.\n */\n\nexport function logSwallowed(label: string, err: unknown): void {\n const e = err as { code?: string; message?: string } | null;\n const detail = e?.message ?? String(err);\n debugLog('WARN', `[best-effort] ${label}: ${e?.code ? `${e.code} ` : ''}${detail}`);\n}\n\n/** Run `fn`; on throw, log it and return `fallback`. */\nexport function bestEffort<T>(label: string, fn: () => T, fallback?: T): T | undefined {\n try {\n return fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** Async variant; also catches rejections. */\nexport async function bestEffortAsync<T>(label: string, fn: () => Promise<T>, fallback?: T): Promise<T | undefined> {\n try {\n return await fn();\n } catch (err) {\n logSwallowed(label, err);\n return fallback;\n }\n}\n\n/** For promise chains: `.catch(swallow('label'))`. */\nexport function swallow(label: string): (err: unknown) => undefined {\n return (err) => {\n logSwallowed(label, err);\n return undefined;\n };\n}\n","import path from 'node:path';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport { checkedOutBranch } from '../git/git-head.js';\n\n/**\n * A session on a repo's own checkout (`work tree <repo>` with no branch):\n * the repo's folder itself, not a worktree work made. Branches are work's to\n * manage — a new piece of work gets its own worktree — so that checkout stays\n * on its branch: its Claude is told so on every prompt (the turn-start hook),\n * and the PR watch never archives it.\n */\n\nconst key = (p: string) => path.resolve(p).replace(/\\\\/g, '/').replace(/\\/+$/, '').toLowerCase();\n\n/** Whether the session's folder is one of the configured repos' own folders. */\nexport function isOwnCheckout(s: Pick<WorktreeSession, 'paths'>, repos: Record<string, string>): boolean {\n const own = new Set(Object.values(repos).map(key));\n return s.paths.some((p) => own.has(key(p)));\n}\n\n/** What its Claude is told at the start of each turn there. Pure. */\nexport function ownCheckoutNote(s: Pick<WorktreeSession, 'target' | 'branch'>): string {\n const branch = s.branch || 'its branch';\n return (\n `[work] This folder is ${s.target}'s own checkout, which work keeps on ${branch}. ` +\n `Don't create, switch or check out branches here, and don't open pull requests from it — work manages branches. ` +\n `If the task needs a branch of its own, say so and ask the user to start a worktree for it (\\`work tree ${s.target} <branch>\\`).`\n );\n}\n\n/**\n * `branch` is the one a repo's own folder is on (reported: New worktree with \"main\" said the branch is already\n * checked out, while `work tree <repo>` opened it). A branch can be checked out in one place, so asking for that one\n * means the repo's own checkout: the same as naming no branch. Never for a group (it has no one checkout). The\n * branch is read from the HEAD file: no git.\n */\nexport function ownsBranch(\n target: string,\n branch: string,\n config: { repos: Record<string, string>; groups?: Record<string, string[]> },\n read: (checkout: string) => string | null = checkedOutBranch,\n): boolean {\n if (!branch || config.groups?.[target]) return false;\n const repo = config.repos[target];\n return !!repo && read(repo) === branch;\n}\n\n/**\n * The projects as the New worktree dialog lists them: each repo with the branch its own folder is on now (reported:\n * a session started with no branch name landed on a feature branch the repo's folder had been left on, not on main —\n * the dialog didn't say where \"the project as it is\" was). `ownBranch` null: detached, or its folder can't be read.\n * The branch is read from the HEAD file: no git.\n */\nexport function projectList(\n config: { repos: Record<string, string>; groups?: Record<string, string[]> },\n read: (checkout: string) => string | null = checkedOutBranch,\n): {\n singles: Array<{ name: string; kind: 'single'; path: string; ownBranch: string | null }>;\n groups: Array<{ name: string; kind: 'group'; members: string[] }>;\n} {\n return {\n singles: Object.entries(config.repos).map(([name, p]) => ({ name, kind: 'single' as const, path: p, ownBranch: read(p) })),\n groups: Object.entries(config.groups ?? {}).map(([name, members]) => ({ name, kind: 'group' as const, members })),\n };\n}\n","import type { WorktreeSession } from '../sessions/session-types.js';\nimport type { AiToolSpec } from '../platform/ai-launcher.js';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { StatusEvent } from '../status/status-event.js';\nimport type { PermissionRequest } from '../api-types.js';\nimport type { UsageAccount } from '../usage/usage.js';\nimport type { EnvDelta } from '../platform/env-delta.js';\n\n/**\n * What work needs from a coding agent (Claude Code today; Codex, Copilot CLI\n * or opencode later), so the rest of work asks the agent instead of reading\n * Claude Code's files itself. `launch` every agent has; every other\n * capability is optional, and a feature whose capability an agent lacks says\n * so instead of going quiet.\n */\n\n/**\n * One line of a session's conversation, in work's own terms (not any agent's\n * file format). Every timestamped line of the agent's record becomes at\n * least one: `other` keeps the lines that aren't messages, because work time\n * measures the gaps between all of them.\n */\nexport interface ConversationEntry {\n /** When it was written (ISO); '' when the agent's line says no time. */\n at: string;\n /** You typed it; the agent wrote it (text may be empty: a line of only its thinking); a tool call it made; a tool's result coming back to it; anything else. */\n role: 'you' | 'agent' | 'tool' | 'tool-result' | 'other';\n /** The text; for a tool call, what it does (\"npm test\", a file path). */\n text: string;\n /** For a tool call: the tool's name (Bash, Edit, …). */\n tool?: string;\n /** The line's own id, when the agent gives one (the same line read twice counts once). */\n id?: string;\n /** A subagent's line: its own context, not the session's conversation. */\n sidechain?: true;\n /** On an agent message: the size of the request that produced it (prompt incl. cached) and of the reply, in tokens. `cached` is the cache-read part of `prompt`. */\n usage?: { prompt: number; reply: number; cached?: number };\n /** The agent's id for the message this line is part of: several lines (one per content block) repeat one message's usage, so a token count takes it once per id. */\n message?: string;\n /** On an agent message: the model that wrote it. */\n model?: string;\n /** The agent's own bookkeeping (a meta line, a compaction summary): no message of yours or its, and no turn's work. */\n meta?: true;\n /** An `other` line that is still part of a turn's work: a shell command you ran through it and its output, a background task's result. */\n turn?: true;\n}\n\n/** A file of an agent's conversations. */\nexport interface ConversationFile {\n file: string;\n mtimeMs: number;\n size: number;\n}\n\nexport interface AgentConversation {\n /** Where its conversations about this session are kept: one file per conversation, one JSON value per line. */\n files(session: WorktreeSession): ConversationFile[];\n /** The files whose token usage counts: its conversations and what they handed to subagents (kept apart, not in `files`). Absent: `files`. */\n usageFiles?(session: WorktreeSession): ConversationFile[];\n /** A file's parsed lines (in order) as conversation entries. */\n entries(lines: readonly unknown[]): ConversationEntry[];\n /** Its context window for a model, given how much a request used (some models have a larger one). */\n contextWindow(model: string | undefined, used: number): number;\n /** The newest `last` messages — yours, its, its tool calls — oldest first. */\n read(session: WorktreeSession, opts: { last: number }): ConversationEntry[];\n /** Where to put an archived conversation's files back so the agent resumes it in the session's folder; absent: Restore starts fresh (the archive keeps them). */\n restoreDir?(session: WorktreeSession): string | null;\n /** The newest write to its conversations for work in `cwd` (ms; 0: none): \"is it busy in this folder right now?\" without a session (a `wd` scope). */\n lastWriteMs?(cwd: string): number;\n /** A background agent its conversation started (one that runs on after the turn that started it ended) is still at it\n * after `ms` (the turn's end): the session is still at work though its turn ended — and what that agent is, when it says. */\n backgroundWorkSince?(session: WorktreeSession, ms: number, now?: number): BackgroundWork | null;\n /** Background commands (a build, tests, a dev server) its conversation started since `sinceMs` — the agent\n * process's start — and that haven't ended: stopping the agent would stop them (idle sleep keeps it awake). */\n backgroundCommands?(session: WorktreeSession, sinceMs: number): number;\n /** What those commands are, newest first, each in a line (the session list names what runs while its prompt is free). */\n backgroundCommandNames?(session: WorktreeSession, sinceMs: number): string[];\n /**\n * The pull requests a stretch of its conversation file names as the session's own (made or worked on by it), in\n * file order — Claude Code writes a line for each. `text`: whole lines of a conversation file; a line cut at either\n * end is skipped. Absent: the agent doesn't say, and a session's PRs come from its branches alone.\n */\n prLinks?(text: string): ConversationPrLink[];\n}\n\n/** A pull request a conversation says the session made or worked on (`AgentConversation.prLinks`). */\nexport interface ConversationPrLink {\n url: string;\n number: number;\n /** The host's name for its repo (`owner/name`), as the agent wrote it; '' when it didn't. */\n repo: string;\n /** ISO, when the line says. */\n at?: string;\n}\n\n/** Whose conversations a resume check looks in: a session's (its account), or the environment the agent will start with (`env` wins). */\nexport interface ResumeVia {\n session?: Pick<WorktreeSession, 'account'> | null;\n env?: Readonly<Record<string, string | undefined>>;\n}\n\n/** Starting it: every agent has this. */\nexport interface AgentLaunch {\n /** Its binary and flags: config `aiCommand` / `aiCommandFlags` when they name this agent, else its defaults. */\n tool(config: Pick<WorkConfig, 'aiCommand' | 'aiCommandFlags'> | null): AiToolSpec;\n /**\n * Its resume flag finds a conversation in this folder. Passing it where there is none errors out (Claude Code: \"No conversation found to continue\"), so every launch path asks.\n * `via` says whose conversations: the session (its account's folder) or the environment it will run with (what the PTY host restores from).\n */\n canResume(cwd: string, via?: ResumeVia): boolean;\n /** Where to start a session to pick up its conversation (a group may have worked in its root or a repo), and whether there is one. */\n resumeLaunch(session: WorktreeSession): { launchPath: string; hasConversation: boolean };\n /** The environment to start it with: what a parent session of this agent set (it would think it runs inside one) taken out. */\n cleanEnv(env: Record<string, string | undefined>): Record<string, string | undefined>;\n /**\n * What the agent's environment must differ by for this session (Claude: its account's `CLAUDE_CONFIG_DIR`), applied\n * OVER whatever environment it would inherit — a name set to a value, or `null` to take it out. `null` session: work's\n * own runs (the assistant, one-shot summaries), on the configured default. Absent: nothing to change.\n */\n env?(session: Pick<WorktreeSession, 'account'> | null): EnvDelta;\n /**\n * The tool as work starts it for a session, its hooks (session-hooks.ts) given to this process alone — never written\n * into the user's settings, where every other agent run on the machine would fire them (Claude: `--settings` with\n * work's own file, claude/session-settings.ts). Applied at every spawn, restore and restart, so a stored tool from\n * before gets it too. Absent: started as `tool` says (no hooks).\n */\n sessionTool?(tool: AiToolSpec, o?: { write?: boolean }): AiToolSpec;\n /**\n * A running process of it, by its command line, was started with `sessionTool`'s hooks. One that wasn't — started\n * before this build, by an older work — still needs the hooks older builds put in its own settings (`AgentEvents.bridge`).\n */\n startedWithSessionHooks?(commandLine: string): boolean;\n /**\n * Before work starts a session's agent in `cwd` (a folder work made or you added): tell the agent that folder is\n * trusted, so it doesn't stop at its own \"do you trust this folder?\" (Claude: claude/folder-trust.ts). Absent: nothing.\n */\n trustFolder?(session: Pick<WorktreeSession, 'account'> | null, cwd: string): void;\n /**\n * The tool with more folders it may read and write as its own (Claude: `--add-dir` each): a child session gets its\n * coordinator's scratch folders, where the task files and what they share are (session-children.ts). Absent: none.\n */\n withFolders?(tool: AiToolSpec, folders: readonly string[]): AiToolSpec;\n}\n\n/** Whether a keystroke may answer a permission request now (the dialog on its screen is that request's), and if not, why. */\nexport type DialogCheck = { ok: true } | { ok: false; reason: 'no-dialog' | 'other-request' | 'not-default' };\n\n/** Typing into its terminal. */\nexport interface AgentInput {\n /** Type `text` into its prompt and submit it (`write`: the PTY; `wait`: a pause, for tests). */\n submit(write: (data: string) => Promise<boolean>, text: string, wait?: (ms: number) => Promise<void>): Promise<boolean>;\n /**\n * A question it is stopped at before its first turn, read from its terminal's screen (\"do you trust this\n * folder?\"): what it asks in a line, or null. Absent: it has none work knows. Never answered by work.\n */\n startupQuestion?(screen: string): string | null;\n /** Its permission dialog on a terminal screen; absent: work can't answer its prompts by keystroke. */\n permissionDialog?: {\n check(screen: string, req: PermissionRequest): DialogCheck;\n keys: { allow: string; deny: string };\n };\n}\n\n/**\n * A text-only, one-shot run of the agent, for work's own summaries (checkpoint\n * names, catch-up, archive summaries, the Jira watch's choice, a group's\n * instructions file): the prompt on stdin, the answer on stdout. The prompt\n * carries text work doesn't control (diffs, transcripts, issues), so: no\n * tools, none of the user's MCP servers, a neutral folder, and the env tagged\n * so the agent's own hooks don't fire into work (internal-claude.ts).\n */\nexport interface AgentOneShot {\n /** How to start one; `small`: a few words are wanted (a smaller, cheaper model). */\n command(opts: { small?: boolean }): { cmd: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv };\n /**\n * Optional: a one-shot run that may READ a folder — a pull request's temporary checkout, for the Reviews AI step\n * (review-tree.ts). Read-only file tools only, confined to `cwd`; nothing that runs a command, writes, or reaches\n * the network; none of the folder's own settings, hooks or MCP servers (they are the PR author's), but its\n * instructions file (the repo's conventions); the env tagged internal like `command`. Absent: the agent has no\n * such mode, and callers use the text-only `command` with the diff alone.\n */\n readOnly?: AgentReadOnly;\n}\n\n/** The agent's read-only one-shot in a folder (`AgentOneShot.readOnly`), and what only the agent knows about it. */\nexport interface AgentReadOnly {\n command(opts: { small?: boolean; cwd: string; deny?: string[] }): { cmd: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv };\n /**\n * A file of the folder (its path relative to it, `/` or `\\`) the agent would read as its own settings — hooks, env,\n * permissions, tool servers: deleted from the copy before the run (the folder is someone else's). Whatever case it's\n * written in: a case-blind file system opens `.Claude/settings.json` as the settings file.\n */\n isSettingsFile(relPath: string): boolean;\n /** What the run's prompt says of the folder in the agent's own words: its tools, and which of its files it was given. */\n promptLines: string[];\n /**\n * The same for a run in YOUR folder (a session's own changes, core/review/local-review-tree.ts): nothing is\n * deleted there. Absent: the agent's read-only run is for a temporary checkout only.\n */\n localLines?: string[];\n /**\n * The files the repos' own settings forbid reading, as rules for `command`'s `deny` (the run loads none of the\n * folder's settings, so they wouldn't hold otherwise). `sub`: the repo's folder under where the run starts.\n */\n denyRules?(repos: ReadonlyArray<{ dir: string; sub: string | null }>): string[];\n /**\n * Whether the installed agent can run it as it was measured (Claude: its version, at least the one its flags were\n * measured on). Not ok: no checkout run, and `why` says so. Absent: always.\n */\n available?(): Promise<{ ok: boolean; why?: string }>;\n}\n\n/** One running agent process, as its adapter reads it (Claude: ~/.claude/sessions/<pid>.json). */\nexport interface LiveAgent {\n pid: number;\n /** Its conversation's id (two on one conversation would both write to it). */\n conversationId: string;\n cwd: string;\n busy: boolean;\n /** What the agent says it is doing: mid-turn, at its prompt, or waiting on you (a permission, a dialog). */\n state: 'busy' | 'idle' | 'waiting' | 'shell' | null;\n /** When that last changed (ms). */\n stateAt: number | null;\n /** While waiting: what for (\"input needed\", \"dialog open\"). */\n waitingFor: string | null;\n startedAt: number | null;\n}\n\n/** Which of its processes run now, wherever they were started (a terminal of yours included). */\nexport interface AgentLive {\n /** `table`: a process table the caller already has (pid → executable). */\n running(table?: ReadonlyMap<number, string>): LiveAgent[];\n /**\n * A command line that is one of its own tool shells (what runs a command it was asked to run, background ones\n * included): what that command is, in a line. Null: something else (an MCP server, a helper). Absent: none known.\n */\n toolShell?(command: string): string | null;\n}\n\n/** A point in an agent's turn work hooks into: a prompt arrives, the turn ends, the agent notifies (a permission prompt, idle). */\nexport type TurnEdge = 'turn-start' | 'turn-end' | 'notify';\n\n/** One of work's hooks in a folder's own settings (the Ctrl+K assistant's): the command an agent runs at a turn edge, under an owner. */\nexport interface WorkHook {\n owner: string;\n edge: TurnEdge;\n command: string;\n timeoutSec?: number;\n}\n\n/**\n * How work hears an agent's turns: hooks the agent runs at each edge (given to the processes work starts,\n * `AgentLaunch.sessionTool`), and what it sends them.\n */\nexport interface AgentEvents {\n /**\n * Take hooks of these owners out of the agent's own settings (every account's): work once installed them there, and\n * every agent run on the machine fired them (session-hooks.ts `RETIRED_HOOK_OWNERS`). Settings already without them\n * aren't written.\n */\n removeInstalled(hooks: ReadonlyArray<{ owner: string; edge: TurnEdge }>): Promise<void>;\n /**\n * While agents started before the update still run (they have no `sessionTool` hooks of their own, and the agent\n * reads its settings live), put work's hooks in its own settings — the very commands `sessionTool` gives, so an agent\n * that has both runs each once — under owners `removeInstalled` takes out once those agents are gone.\n */\n bridge(): Promise<void>;\n /** What a hook was sent (its stdin, parsed): the folder it fired in, and the status event it means. */\n read(edge: TurnEdge, payload: unknown): { cwd?: string; status: StatusEvent | null };\n /** The hook output that hands `text` (pending notes) to the agent: at a turn's start as more context, at its end as \"go on with this\". */\n handOver(edge: 'turn-start' | 'turn-end', text: string): string;\n}\n\n/** A command the agent may run without asking: exactly this, or (`prefix`) this and anything after it. */\nexport interface AllowRule {\n command: string;\n prefix?: boolean;\n}\n\n/** Setting up a folder work runs the agent in (the Ctrl+K assistant's, ~/.work/assistant). */\nexport interface AgentWorkspace {\n /** Write the agent's own settings for `dir`: what it may run without asking, and work's hooks there. Never the user's own local settings. Returns the files it wrote (relative to `dir`), so another agent's can be removed later. */\n write(dir: string, o: { allow: AllowRule[]; hooks: WorkHook[] }): string[];\n}\n\n/** Giving the agent work's skills (how to use `work` and `wd -c`): SKILL.md folders, the Agent Skills format. */\nexport interface AgentSkills {\n /** Make work's skills available to it, user-wide: from `skillsDir` (null: not found next to work — one that needs the files says so). Its outcome in a line; never throws for a missing agent. */\n install(o: { skillsDir: string | null }): Promise<{ ok: boolean; message: string }>;\n}\n\n/** Its plan limits (5-hour, weekly), as the last readings work recorded per account. */\nexport interface AgentUsageSource {\n read(): UsageAccount[];\n /**\n * Work web's start: put in place (or, `enabled: false`, take away) what records the readings (Claude: its status line).\n * A lean server passes `lean` and expects nothing changed. Loaded lazily: the hook processes import the adapter too.\n */\n setup?(o: { enabled: boolean; lean: boolean }): Promise<string>;\n /** `work usage --restore`: give the agent's own setting back now. */\n restore?(): Promise<{ ok: boolean; message: string }>;\n /**\n * Ask the agent for what its readings can't carry (Claude: a model's own weekly window, as Fable's, `usage-ask.ts`)\n * and record it; throttled by the agent, so it may be called on every request. Never throws.\n */\n refresh?(): Promise<void>;\n /**\n * Whether the user has a status line of their own for this agent (Claude: one in any account's settings that isn't\n * work's). The dashboard asks about work's own line only when they don't: theirs stays theirs.\n */\n ownStatusLine?(): boolean;\n}\n\n/** One of an agent's accounts (Claude: a config folder with its own login). */\nexport interface AccountInfo {\n name: string;\n /** Where its login, settings and conversations live. */\n dir: string;\n /** The one new sessions use. */\n isDefault: boolean;\n /** Logged in; null: can't tell (macOS keeps Claude's credentials in the keychain). */\n loggedIn: boolean | null;\n}\n\n/** The sessions on an account, as \"target · branch\": the live ones, and the archived ones (whose Restore would need it). */\nexport interface AccountUsers {\n live: string[];\n archived: string[];\n}\n\n/**\n * A refusal of an account change the user can act on (an unknown name, a folder that can't be one, sessions still on it).\n * `sessions` names the sessions that stopped a removal; `kind` says whether they are live ones (always a refusal) or\n * archived ones (a refusal unless forced).\n */\nexport class AccountAdminError extends Error {\n constructor(\n message: string,\n readonly sessions: string[] = [],\n readonly kind?: 'live' | 'archived',\n ) {\n super(message);\n }\n}\n\n/** One thing a copy of an account's setup to another does (`AgentAccountAdmin.setupPlan`). */\nexport interface AccountSetupItem {\n /** What kind of thing it is, in the agent's own words (Claude: file, folder, settings, mcp, marketplace, plugin). */\n kind: string;\n name: string;\n does: 'adds' | 'replaces' | 'merges into';\n /** Something to know of it (a sign-in it needs on the other account, where it comes from). */\n note?: string;\n}\n\nexport interface AccountSetupResult extends AccountSetupItem {\n ok: boolean;\n error?: string;\n}\n\n/** Adding, choosing and forgetting an agent's accounts (`work account`). Never deletes an account's folder: its login and conversations are the user's. */\nexport interface AgentAccountAdmin {\n /** Record a new account (its folder: `dir`, else the agent's default place for it), made when missing. Returns the folder. */\n add(name: string, dir?: string): Promise<string>;\n /** New sessions use this account. */\n setDefault(name: string): Promise<void>;\n /**\n * Forget an account (its folder stays). `usedBy` is asked under the config's lock, right before the write: live\n * sessions on it are always a refusal, archived ones too (their Restore would start on another account) — a caller\n * that was told to go ahead anyway passes none.\n */\n remove(name: string, usedBy: () => AccountUsers): Promise<void>;\n /** Start the agent's own CLI in this terminal on the account, so the user logs in (blocks until it exits). */\n login(name: string): void;\n /**\n * The same CLI as `login` starts, for a terminal work starts itself (the dashboard's login terminal, in the PTY host):\n * its command and how its environment differs for the account. In the agent's own permission mode, as every start.\n * Throws an AccountAdminError for an unknown account.\n */\n loginLaunch(name: string): { tool: AiToolSpec; agentEnv: EnvDelta };\n /** Give the account work's skills (the install at setup reaches only the accounts there were then). */\n installSkills(name: string): { ok: boolean; message: string };\n /**\n * What copying `from`'s setup to `to` would do (its instructions, agents, commands, settings, tool servers,\n * plugins — never a login, a token or a conversation): a read. Empty: `to` is set up the same already. Throws an\n * AccountAdminError for an unknown account, or one copied to itself. Absent: the agent has no setup to copy.\n */\n setupPlan?(from: string, to: string): AccountSetupItem[];\n /** Do it, each thing reported; one that fails is said and the rest still go. Nothing on `to` is deleted. */\n copySetup?(from: string, to: string): Promise<AccountSetupResult[]>;\n}\n\n/** Running a session on one of several logins of the agent, and moving it from one to another. */\nexport interface AgentAccounts {\n list(): AccountInfo[];\n /** The account new sessions use. */\n defaultName(): string;\n /** An account of that name exists. */\n has(name: string): boolean;\n /** The name of the account a session runs on. */\n current(session: Pick<WorktreeSession, 'account'>): string;\n /**\n * Move the session's conversations (whatever the agent keeps per folder it runs in) from its account to `to`, merging;\n * puts back what it moved and throws when it fails. It records nothing and starts nothing: the caller stops the agent\n * first, records the account, and starts it again.\n */\n switchFiles(session: WorktreeSession, to: string): Promise<{ moved: string[] }>;\n /** The folders whose conversations a switch moves (where its agent runs for the session): another agent running in one\n * of them would have its files moved from under it, so the switch is refused while one does. */\n folders(session: Pick<WorktreeSession, 'paths' | 'isGroup'>): string[];\n /** Managing the accounts themselves; absent: they are set up some other way. */\n admin?: AgentAccountAdmin;\n}\n\nexport interface AgentAdapter {\n /** The agent's binary name (`claude`, `codex`, …). */\n id: string;\n /** How work names it to you (\"Claude Code\"). */\n name: string;\n launch: AgentLaunch;\n /** Reading its conversations; absent: work can't for this agent. */\n conversation?: AgentConversation;\n /** Hearing its turns through hooks; absent: no hook status (the PTY host's output stands in). */\n events?: AgentEvents;\n /** Its running processes; absent: work sees only the ones the PTY host runs. */\n live?: AgentLive;\n /** Typing into its terminal (every agent: at least text, a pause, Enter). */\n input: AgentInput;\n /** Text-only one-shot runs for work's summaries; absent: work writes none with this agent. */\n oneShot?: AgentOneShot;\n /** The project instructions file it reads (CLAUDE.md; Codex, Copilot and opencode read AGENTS.md): a group's combined one is written under this name. */\n instructionsFile: string;\n /** The line in an instructions file that makes it read another (Claude's `@api/CLAUDE.md`), for a\n * session folder's file (session-instructions.ts); absent: it can't import, and a group's combined file is copied instead. */\n instructionsImport?(relPath: string): string;\n /** Folders whose changes mean it did something (its conversations, its process state): work web watches them to refresh the dashboard at once. */\n activityRoots?(): string[];\n /** The folders where it writes a session's scratch files (an artifact's HTML before it is published): the pane beside\n * the terminal may show a file in one of these, as well as the session's own files; absent: only those. */\n tempFolders?(session: Pick<WorktreeSession, 'paths' | 'isGroup'>): string[];\n /** Installing work's skills for it (skills.ts); absent: it isn't told about `work`'s commands. */\n skills?: AgentSkills;\n /** Its settings in a folder work runs it in (the Ctrl+K assistant); absent: only the instructions file is written, and it asks before every command. */\n workspace?: AgentWorkspace;\n /** Its usage limits; absent: the meter has nothing for this agent. */\n usage?: AgentUsageSource;\n /** Several logins to run sessions on, and moving a session between them; absent: one login. */\n accounts?: AgentAccounts;\n /** Keeping the installed tool up to date (work web, hourly; setting `claudeCode.autoUpdate`); absent: left as installed. */\n selfUpdate?: AgentSelfUpdate;\n}\n\n/** Look for a newer version of the tool and install it the way it was installed. */\nexport interface AgentSelfUpdate {\n /** Whether the user turned it off (its setting). */\n enabled(config: unknown): boolean;\n /** Look, and update when there is a newer one: one line for Activity, and whether it failed / installed a new one. */\n run(): Promise<{ text: string; failed: boolean; updated: boolean }>;\n}\n\n/** A background agent at work after its turn ended: what it is, in its own words (its description), when it says. */\nexport interface BackgroundWork {\n what: string | null;\n}\n","import path from 'node:path';\nimport { isAgentId } from '../platform/config.js';\nimport { configView } from '../platform/config-cache.js';\nimport { getAiTool, type AiToolSpec } from '../platform/ai-launcher.js';\nimport { logSwallowed } from '../platform/best-effort.js';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport type { SessionAgentWire } from '../api-types.js';\nimport { claudeAgent } from './claude/adapter.js';\nimport type { AgentAdapter, AgentConversation, LiveAgent } from './types.js';\nimport { typeThenEnter } from './typing.js';\n\nexport type { AgentAdapter, AgentLaunch, AgentUsageSource, ConversationEntry, LiveAgent, ResumeVia, TurnEdge, WorkHook } from './types.js';\n\ntype ToolConfig = Pick<WorkConfig, 'aiCommand' | 'aiCommandFlags'> | null;\nexport type AgentSettings = Pick<WorkConfig, 'aiCommand' | 'aiCommandFlags' | 'internalAgent' | 'assistantAgent'>;\n\n/**\n * The config's agent settings (aiCommand, aiCommandFlags, internalAgent, assistantAgent), read again only when\n * config.json changed (config-cache.ts, shared with the accounts' reader): the agent lookups run per session on every\n * session-list build, and a full loadConfig each time was a read and a parse per row.\n */\nconst settingsView = configView((p): AgentSettings => {\n if (!p) return {};\n return {\n ...(typeof p.aiCommand === 'string' ? { aiCommand: p.aiCommand } : {}),\n ...(p.aiCommandFlags && typeof p.aiCommandFlags === 'object'\n ? { aiCommandFlags: p.aiCommandFlags as AgentSettings['aiCommandFlags'] }\n : {}),\n ...(isAgentId(p.internalAgent) ? { internalAgent: p.internalAgent } : {}),\n ...(isAgentId(p.assistantAgent) ? { assistantAgent: p.assistantAgent } : {}),\n };\n});\nexport function agentSettings(): AgentSettings {\n return settingsView();\n}\n\n/** The agent a session runs, with the config's settings (cached): `agentFor(agentSettings(), session)`. */\nexport function agentOf(session?: Pick<WorktreeSession, 'agent'> | null): AgentAdapter {\n return agentFor(agentSettings(), session);\n}\n\n/** The agents work has an adapter for, by binary name. */\nconst ADAPTERS = new Map<string, AgentAdapter>([[claudeAgent.id, claudeAgent]]);\n\n/**\n * Add an adapter (another agent — Codex, Copilot CLI — or a test's): from\n * then on sessions created with it record it, and every reader, hook and\n * launch path uses it. Returns a function that takes it out again.\n */\nexport function registerAgent(a: AgentAdapter): () => void {\n const before = ADAPTERS.get(a.id);\n ADAPTERS.set(a.id, a);\n return () => {\n if (before) ADAPTERS.set(a.id, before);\n else ADAPTERS.delete(a.id);\n };\n}\n\n/** work has an adapter for this agent (it can be recorded on a session and read). */\nexport function isKnownAgent(id: string | undefined): id is string {\n return !!id && ADAPTERS.has(id);\n}\n\n/**\n * An agent work has no adapter for (opencode, or whatever `aiCommand`\n * names): it starts — the binary, its preset flags — but nothing else is\n * known about it. It never resumes (a resume flag where there is no\n * conversation can error out), and every other capability reads as \"not\n * available for <tool>\".\n */\nfunction plainAgent(id: string): AgentAdapter {\n return {\n id,\n name: id,\n launch: {\n tool: (config) => getAiTool(config && getAiTool(config).cmd === id ? config : { aiCommand: id }),\n canResume: () => false,\n resumeLaunch: (s) => ({ launchPath: s.isGroup ? path.dirname(s.paths[0] ?? '') : (s.paths[0] ?? ''), hasConversation: false }),\n cleanEnv: (env) => ({ ...env }),\n },\n // Text, a pause, Enter — and no dialog to answer by keystroke (its screen is unknown).\n input: { submit: typeThenEnter },\n // The shared convention (Codex, Copilot CLI, opencode read it).\n instructionsFile: 'AGENTS.md',\n };\n}\n\n/** Every agent work has an adapter for (whose hooks work web installs, whose running processes it reads). */\nexport function knownAgents(): AgentAdapter[] {\n return [...ADAPTERS.values()];\n}\n\n/** The newest write any known agent made to its conversations for work in `cwd` (ms; 0: none). */\nexport function agentWriteMs(cwd: string): number {\n return Math.max(0, ...knownAgents().map((a) => a.conversation?.lastWriteMs?.(cwd) ?? 0));\n}\n\n/** Every known agent's activity folders (`activityRoots`). */\nexport function activityRoots(): string[] {\n return knownAgents().flatMap((a) => a.activityRoots?.() ?? []);\n}\n\n/** A conversation line's time (ms; NaN when it has none), as its agent reads it: what JSON-lines windows are cut by (jsonl.ts). */\nexport function lineTimeOf(conv: Pick<AgentConversation, 'entries'>): (line: unknown) => number {\n return (line) => {\n const at = conv.entries([line])[0]?.at;\n return at ? Date.parse(at) : NaN;\n };\n}\n\n/** Every known agent's running processes, wherever they were started (each agent's `live`). */\nexport function liveAgents(table?: ReadonlyMap<number, string>): LiveAgent[] {\n return knownAgents().flatMap((a) => a.live?.running(table) ?? []);\n}\n\n/** The agent the Ctrl+K assistant runs (config `assistantAgent`; Claude Code by default). */\nexport function assistantAgent(config: Pick<WorkConfig, 'assistantAgent'> | null): AgentAdapter {\n return agentById(config?.assistantAgent ?? 'claude');\n}\n\n/** The agent that writes work's own summaries (config `internalAgent`; Claude Code by default). */\nexport function internalAgent(config: Pick<WorkConfig, 'internalAgent'> | null): AgentAdapter {\n return agentById(config?.internalAgent ?? 'claude');\n}\n\n/** An agent as the dashboard is told about it: its name and which capabilities its adapter has. */\nexport function agentWire(a: AgentAdapter): SessionAgentWire {\n return {\n id: a.id,\n name: a.name,\n can: {\n read: !!a.conversation,\n hooks: !!a.events,\n live: !!a.live,\n answer: !!a.input.permissionDialog,\n accounts: !!a.accounts,\n },\n };\n}\n\n/** The adapter for an agent by its binary name (`claude`; anything else: a plain one). */\nexport function agentById(id: string): AgentAdapter {\n return ADAPTERS.get(id) ?? plainAgent(id);\n}\n\n/**\n * The tool as work starts it for a session (`AgentLaunch.sessionTool`: Claude's carries work's hooks with `--settings`),\n * by the agent its binary names. One that can't be prepared (its settings file can't be written) starts as it is,\n * without hooks — said in the debug log: a session that doesn't start is worse than one the dashboard sees less of.\n */\nexport function sessionToolFor(tool: AiToolSpec, o: { write?: boolean } = {}): AiToolSpec {\n const prepare = agentById(tool.cmd).launch.sessionTool;\n if (!prepare) return tool;\n try {\n return prepare(tool, o);\n } catch (e) {\n logSwallowed(`prepare ${tool.cmd}'s hooks`, e);\n return tool;\n }\n}\n\n/**\n * Before work starts a session's agent in `cwd`: the folder trusted on its account (`AgentLaunch.trustFolder`). One that\n * can't be written is said in the debug log and the agent starts anyway: at worst it asks, as it would have.\n */\nexport function trustAgentFolder(agent: AgentAdapter, session: Pick<WorktreeSession, 'account'> | null, cwd: string): void {\n try {\n agent.launch.trustFolder?.(session, cwd);\n } catch (e) {\n logSwallowed(`trust ${cwd} for ${agent.id}`, e);\n }\n}\n\n/** The agent a new session records: the configured one, when work has an adapter for it (undefined: it follows `aiCommand`). */\nexport function agentToRecord(config: ToolConfig): string | undefined {\n const cmd = getAiTool(config ?? {}).cmd;\n return isKnownAgent(cmd) ? cmd : undefined;\n}\n\n/**\n * The agent a session runs: the one it recorded when it was created\n * (`WorktreeSession.agent`, an agent work has an adapter for), else the\n * configured default (`aiCommand`, Claude Code when unset). An unknown\n * command is never pinned: a session follows `aiCommand` as it is (a wrapper\n * like `node my-agent.js` would otherwise come back as a bare `node`).\n */\nexport function agentFor(config: ToolConfig, session?: Pick<WorktreeSession, 'agent'> | null): AgentAdapter {\n return agentById(isKnownAgent(session?.agent) ? session.agent : getAiTool(config ?? {}).cmd);\n}\n\nexport type { AccountInfo, AccountUsers, AgentAccounts, AgentAccountAdmin } from './types.js';\nexport { AccountAdminError } from './types.js';\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { json, withDb } from '../../platform/db.js';\nimport { findOnPath } from '../../platform/find-on-path.js';\nimport { launchFor } from '../../platform/batch-launch.js';\nimport spawn from '../../platform/spawn.js';\nimport { killTreeAsync } from '../../platform/process.js';\nimport { atLeast, parseClaudeVersion, runVersion } from './version.js';\n\n/**\n * work keeps Claude Code up to date (asked for: \"Update available! Run: brew upgrade claude-code — i don't want to run\n * it, work should keep it up to date\"). Every so often work web asks npm for the newest Claude Code; when the one\n * installed is older, it runs the update the way it was installed — Homebrew's cask or formula, Claude's own installer\n * (`claude update`) or a global npm install — and then the sessions move onto it between turns (agent-restart.ts:\n * a running Claude keeps the binary it started with). The setting `claudeCode.autoUpdate` (on by default) turns it off.\n *\n * A version it tried and couldn't get (Homebrew's cask can come a few hours after npm) is tried again only after\n * RETRY_SAME_MS, so a lagging cask isn't asked every hour.\n */\n\nexport type ClaudeInstallKind = 'brew-cask' | 'brew-formula' | 'native' | 'npm' | 'unknown';\n\nexport interface ClaudeInstall {\n kind: ClaudeInstallKind;\n /** The file `claude` really runs (links followed). */\n file: string;\n /** How to update it; null for an install work doesn't know how to update. */\n update: { cmd: string; args: string[] } | null;\n}\n\nconst slash = (p: string) => p.replace(/\\\\/g, '/');\n\n/**\n * How Claude Code was installed, from the file `claude` really runs, and the command that updates it that way. Pure.\n * /opt/homebrew/Caskroom/claude-code/2.1.323/claude → Homebrew cask: <prefix>/bin/brew upgrade --cask claude-code\n * /opt/homebrew/Cellar/claude-code/2.1.323/bin/claude → Homebrew formula: <prefix>/bin/brew upgrade claude-code\n * ~/.local/share/claude/versions/2.1.323 → Claude's own installer: claude update\n * <prefix>/lib/node_modules/@anthropic-ai/claude-code/cli.js → npm: npm install -g @anthropic-ai/claude-code@latest\n */\nexport function claudeInstallOf(realFile: string, platform: NodeJS.Platform = process.platform): ClaudeInstall {\n const f = slash(realFile);\n const brewAt = (marker: string) => {\n const i = f.indexOf(marker);\n return i > 0 ? path.join(realFile.slice(0, i), 'bin', 'brew') : null;\n };\n const cask = brewAt('/Caskroom/claude-code/');\n if (cask) return { kind: 'brew-cask', file: realFile, update: { cmd: cask, args: ['upgrade', '--cask', 'claude-code'] } };\n const formula = brewAt('/Cellar/claude-code/');\n if (formula) return { kind: 'brew-formula', file: realFile, update: { cmd: formula, args: ['upgrade', 'claude-code'] } };\n if (/\\/claude\\/versions\\/[^/]+$/.test(f) || /\\/\\.local\\/bin\\/claude(\\.exe)?$/.test(f))\n return { kind: 'native', file: realFile, update: { cmd: realFile, args: ['update'] } };\n const npmAt = f.indexOf('/node_modules/@anthropic-ai/claude-code/');\n if (npmAt > 0) {\n // <prefix>/lib/node_modules on Unix, <prefix>/node_modules on Windows; npm sits in <prefix>/bin or <prefix>.\n const modules = realFile.slice(0, npmAt);\n const prefix = path.basename(path.dirname(modules)) === 'lib' ? path.dirname(path.dirname(modules)) : path.dirname(modules);\n const npm = platform === 'win32' ? path.join(prefix, 'npm.cmd') : path.join(prefix, 'bin', 'npm');\n return { kind: 'npm', file: realFile, update: { cmd: npm, args: ['install', '-g', '@anthropic-ai/claude-code@latest'] } };\n }\n return { kind: 'unknown', file: realFile, update: null };\n}\n\n/** The newest Claude Code on npm (its `latest` tag): every install kind publishes from it. Null: couldn't ask. */\nexport async function latestClaudeVersion(fetchImpl: typeof fetch = fetch, timeoutMs = 15_000): Promise<string | null> {\n try {\n const res = await fetchImpl('https://registry.npmjs.org/@anthropic-ai%2Fclaude-code/latest', {\n signal: AbortSignal.timeout(timeoutMs),\n headers: { accept: 'application/json' },\n });\n if (!res.ok) return null;\n const v = ((await res.json()) as { version?: unknown }).version;\n return typeof v === 'string' && parseClaudeVersion(v) ? v : null;\n } catch {\n return null;\n }\n}\n\n/** A version tried and not got is tried again after this long (a Homebrew cask that comes after npm). */\nexport const RETRY_SAME_MS = 12 * 3600_000;\nconst KEY = 'claude:update-tried';\n\nfunction lastTried(): { version: string; at: number } | null {\n return withDb((d) => {\n const row = d.prepare('SELECT value FROM meta WHERE key = ?').get(KEY) as { value: string } | undefined;\n const v = row ? (json.parse(row.value) as { version?: unknown; at?: unknown } | null) : null;\n return v && typeof v.version === 'string' && typeof v.at === 'number' ? { version: v.version, at: v.at } : null;\n });\n}\n\nfunction noteTried(version: string, at: number): void {\n withDb((d) => d.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)').run(KEY, JSON.stringify({ version, at })));\n}\n\nexport type UpdateCheck =\n | { kind: 'up-to-date'; installed: string }\n | { kind: 'updated'; from: string; to: string }\n | { kind: 'not-yet'; installed: string; latest: string; why: string }\n | { kind: 'waiting'; installed: string; latest: string }\n | { kind: 'cannot'; why: string };\n\nexport interface ToolUpdateIo {\n /** The file `claude` runs, links followed (null: not on PATH). */\n find: () => string | null;\n /** Its version (`claude --version`, parsed), or null. */\n installed: (file: string) => Promise<string | null>;\n latest: () => Promise<string | null>;\n /** Run the update: whether it exited 0, and the end of what it printed. */\n run: (cmd: string, args: string[]) => Promise<{ ok: boolean; output: string }>;\n tried?: () => { version: string; at: number } | null;\n noteTried?: (version: string, at: number) => void;\n now?: () => number;\n platform?: NodeJS.Platform;\n}\n\n/**\n * Look, and update when there is a newer one: what happened. After an update the installed version is asked again,\n * so \"updated\" means it really changed (Homebrew's cask may not have the version npm has yet: \"not-yet\").\n */\nexport async function keepClaudeUpdated(io: ToolUpdateIo = realToolUpdateIo()): Promise<UpdateCheck> {\n const now = (io.now ?? Date.now)();\n const file = io.find();\n if (!file) return { kind: 'cannot', why: \"claude isn't on PATH\" };\n const install = claudeInstallOf(file, io.platform);\n const installed = await io.installed(file);\n if (!installed) return { kind: 'cannot', why: \"Claude Code's version can't be told (claude --version gave none)\" };\n const latest = await io.latest();\n if (!latest) return { kind: 'cannot', why: \"couldn't ask npm for the newest Claude Code\" };\n if (atLeast(parseClaudeVersion(installed)!, parseClaudeVersion(latest)!)) return { kind: 'up-to-date', installed };\n if (!install.update)\n return { kind: 'cannot', why: `Claude Code ${latest} is out, but work doesn't know how to update this install (${file})` };\n const tried = (io.tried ?? lastTried)();\n if (tried && tried.version === latest && now - tried.at < RETRY_SAME_MS) return { kind: 'waiting', installed, latest };\n (io.noteTried ?? noteTried)(latest, now);\n const r = await io.run(install.update.cmd, install.update.args);\n const after = (await io.installed(io.find() ?? file)) ?? installed;\n if (after !== installed) return { kind: 'updated', from: installed, to: after };\n const said = r.output.trim().split('\\n').slice(-3).join(' · ').slice(0, 300);\n return {\n kind: 'not-yet',\n installed,\n latest,\n why: r.ok\n ? `${install.update.cmd.split(/[\\\\/]/).pop()} found nothing newer yet${said ? ` (${said})` : ''}`\n : `the update failed: ${said || 'no output'}`,\n };\n}\n\n/** How long an update may take (Homebrew updates its own lists first). */\nexport const UPDATE_TIMEOUT_MS = 10 * 60_000;\n\nfunction runUpdate(cmd: string, args: string[]): Promise<{ ok: boolean; output: string }> {\n return new Promise((resolve) => {\n const launch = launchFor(cmd, args);\n if ('refused' in launch) return resolve({ ok: false, output: launch.refused });\n let out = '';\n let settled = false;\n const done = (ok: boolean) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve({ ok, output: out.slice(-4000) });\n };\n // Homebrew asks nothing when there's no terminal; no analytics prompt, no cleanup of other formulae.\n const env = { ...process.env, HOMEBREW_NO_ENV_HINTS: '1', HOMEBREW_NO_INSTALL_CLEANUP: '1', NONINTERACTIVE: '1' };\n const child = spawn(launch.cmd, launch.args, { cwd: os.homedir(), env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });\n const timer = setTimeout(() => {\n if (child.pid) void killTreeAsync(child.pid);\n else child.kill();\n out += '\\n(timed out)';\n done(false);\n }, UPDATE_TIMEOUT_MS);\n child.stdout?.on('data', (d: Buffer) => (out += d.toString()));\n child.stderr?.on('data', (d: Buffer) => (out += d.toString()));\n child.on('error', (e) => ((out += `\\n${e.message}`), done(false)));\n child.on('close', (code) => done(code === 0));\n });\n}\n\nexport function realToolUpdateIo(): ToolUpdateIo {\n return {\n find: () => {\n const f = findOnPath('claude');\n if (!f) return null;\n try {\n return fs.realpathSync(f);\n } catch {\n return f;\n }\n },\n installed: async (file) => {\n const text = await runVersion(file);\n const v = text ? parseClaudeVersion(text) : null;\n return v ? v.join('.') : null;\n },\n latest: () => latestClaudeVersion(),\n run: runUpdate,\n };\n}\n\n/** One line for Activity. Pure. */\nexport function updateCheckText(r: UpdateCheck): string {\n switch (r.kind) {\n case 'up-to-date':\n return `Claude Code is up to date (${r.installed})`;\n case 'updated':\n return `updated Claude Code ${r.from} → ${r.to}; sessions move onto it between turns`;\n case 'waiting':\n return `Claude Code ${r.latest} is out; tried already, trying again later (this is ${r.installed})`;\n case 'not-yet':\n return `Claude Code ${r.latest} is out, still on ${r.installed}: ${r.why}`;\n case 'cannot':\n return r.why;\n }\n}\n","/**\n * Claude Code's question before it starts in a folder it hasn't been told to trust, as its terminal shows it:\n *\n * Accessing workspace: <folder>\n * Quick safety check: Is this a project you created or one you trust? …\n * ❯ 1. Yes, I trust this folder\n * 2. No, exit\n *\n * (older versions: \"Do you trust the files in this folder?\" over \"1. Yes, proceed\"; 2.1.3xx: unnumbered, \"No, exit\" first\n * and the cursor on \"❯ Yes, I trust this folder\"). Recognised by its two answers being the last thing on the screen, in\n * either order: a conversation that only mentions the question (a resumed one repaints its history) ends with\n * Claude's prompt, not with them. Pure.\n */\nconst YES = /^\\s*[❯>]?\\s*(?:1\\.\\s+)?Yes, (?:I trust this folder|proceed)\\s*$/;\nconst NO = /^\\s*[❯>]?\\s*(?:\\d\\.\\s+)?No, exit\\s*$/;\n/** How many of the screen's last lines the answers must be among (the answers, then \"Enter to confirm · Esc to cancel\"). */\nconst TAIL_LINES = 6;\n\nexport const TRUST_QUESTION = 'Claude asks whether you trust this folder: answer in its terminal';\n\nexport function claudeStartupQuestion(screen: string): string | null {\n const tail = screen\n .split(/\\r?\\n/)\n .map((l) => l.replace(/[│┃|]/g, ' ').trimEnd())\n .filter((l) => l.trim())\n .slice(-TAIL_LINES);\n return tail.some((l) => YES.test(l)) && tail.some((l) => NO.test(l)) ? TRUST_QUESTION : null;\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { encodeProjectDir, sessionRunFolders } from './activity.js';\nimport type { WorktreeSession } from '../../sessions/session-types.js';\n\n/**\n * Where Claude Code keeps a session's scratch files — an artifact's HTML before it is published, a mockup, a report —\n * so the pane beside the terminal can show them (`work show`, a click on the path): `/tmp/claude-<uid>` on macOS and\n * Linux (that folder, not `$TMPDIR`: measured, macOS's `$TMPDIR` is under /var/folders and Claude doesn't use it), and\n * `%TEMP%\\claude` on Windows; then one folder per folder it runs in, named as its projects folders are. Pure.\n */\nexport function claudeTempRoot(\n platform: NodeJS.Platform = process.platform,\n uid: number = typeof process.getuid === 'function' ? process.getuid() : -1,\n tmpdir: string = os.tmpdir(),\n): string {\n return platform === 'win32' ? path.win32.join(tmpdir, 'claude') : `/tmp/claude-${uid}`;\n}\n\n/** This session's own, by name: one per folder its Claude runs in (its root and each repo). Pure. */\nexport function claudeTempFolders(session: Pick<WorktreeSession, 'paths' | 'isGroup'>, root: string = claudeTempRoot()): string[] {\n const join = root.includes('\\\\') ? path.win32.join : path.posix.join;\n return sessionRunFolders(session, false).map((folder) => join(root, encodeProjectDir(folder)));\n}\n\nexport interface TempFolderIo {\n realpath(p: string): string;\n lstat(p: string): { isDirectory(): boolean; isSymbolicLink(): boolean; uid: number; mode: number };\n}\n// The OS's own realpath, as the file's is resolved (findTempFile): on Windows it also turns a short 8.3 name\n// (`C:\\Users\\RUNNER~1\\…`, often %TEMP%'s) into the long one, so the folder and the file are named alike.\nconst realIo: TempFolderIo = { realpath: (p) => fs.realpathSync.native(p), lstat: (p) => fs.lstatSync(p) };\n\n/**\n * The scratch root as it really is, or null when it can't be trusted. `/tmp` is shared by every user, so anyone could\n * make `/tmp/claude-<uid>` first, or a link there pointing at a folder of yours: only its parent's links are followed\n * (macOS's /tmp is /private/tmp), and the root itself must be a real folder — on macOS and Linux one owned by us that\n * nobody else may write to or read (Claude makes it 0700).\n */\nexport function trustedTempRoot(\n root: string = claudeTempRoot(),\n platform: NodeJS.Platform = process.platform,\n uid: number = typeof process.getuid === 'function' ? process.getuid() : -1,\n io: TempFolderIo = realIo,\n): string | null {\n const p = platform === 'win32' ? path.win32 : path.posix;\n try {\n const real = p.join(io.realpath(p.dirname(root)), p.basename(root));\n const st = io.lstat(real);\n if (!st.isDirectory() || st.isSymbolicLink()) return null;\n if (platform !== 'win32' && (st.uid !== uid || (st.mode & 0o077) !== 0)) return null;\n return real;\n } catch {\n return null;\n }\n}\n\n/**\n * The scratch folders a session's files may be shown from: its own (`claudeTempFolders`) under a trusted root, each a\n * real folder (a link is never followed, so what is shown is always under the root it names). Missing ones are left out.\n */\nexport function sessionTempFolders(\n session: Pick<WorktreeSession, 'paths' | 'isGroup'>,\n root: string = claudeTempRoot(),\n platform: NodeJS.Platform = process.platform,\n uid: number = typeof process.getuid === 'function' ? process.getuid() : -1,\n io: TempFolderIo = realIo,\n): string[] {\n const real = trustedTempRoot(root, platform, uid, io);\n if (!real) return [];\n return claudeTempFolders(session, real).filter((f) => {\n try {\n const st = io.lstat(f);\n return st.isDirectory() && !st.isSymbolicLink();\n } catch {\n return false;\n }\n });\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport type { WorktreeSession } from '../../sessions/session-types.js';\nimport { claudeAccounts, configDirEnv, sessionAccount } from './accounts.js';\n\n/**\n * Claude Code writes each session as JSONL under\n * `~/.claude/projects/<encoded-cwd>/`, where the encoded path replaces every\n * non-alphanumeric character with `-`. These files get rewritten on every\n * message, so their mtimes reflect actual conversation activity — which is\n * what the user cares about, not when `work tree` was last invoked.\n */\nexport function encodeProjectDir(p: string): string {\n return path.resolve(p).replace(/[^A-Za-z0-9]/g, '-');\n}\n\nexport interface ProjectFile {\n file: string;\n mtimeMs: number;\n size: number;\n}\n\n/** A folder's transcript names, and when and at which folder mtime they were read. */\nconst listings = new Map<string, { at: number; dirMtimeMs: number; names: string[] }>();\n/** The longest a folder's names are reused while its mtime says unchanged:\n * NTFS doesn't always update a folder's mtime at once when a file is added. */\nexport const NAMES_MAX_AGE_MS = 2000;\n\n/**\n * The transcripts in a Claude project folder (name, mtime, size). The\n * folder's names are read again when the folder changed (its mtime) or are\n * NAMES_MAX_AGE_MS old: one stat instead of a directory read for the three\n * readers each session-list build has per session (activity, name, context\n * use). Each file is stat'ed every time, so sizes and times are exact.\n * Bounded by the folders there are.\n */\nexport function projectTranscripts(projectDir: string, now = Date.now()): ProjectFile[] {\n let dirMtimeMs: number;\n try {\n dirMtimeMs = fs.statSync(projectDir).mtimeMs;\n } catch {\n listings.delete(projectDir);\n return []; // no conversation here yet\n }\n let hit = listings.get(projectDir);\n if (!hit || hit.dirMtimeMs !== dirMtimeMs || now - hit.at >= NAMES_MAX_AGE_MS) {\n let names: string[] = [];\n try {\n names = fs.readdirSync(projectDir).filter((n) => n.endsWith('.jsonl'));\n } catch {\n /* gone meanwhile */\n }\n hit = { at: now, dirMtimeMs, names };\n listings.set(projectDir, hit);\n }\n const files: ProjectFile[] = [];\n for (const name of hit.names) {\n try {\n const file = path.join(projectDir, name);\n const st = fs.statSync(file);\n files.push({ file, mtimeMs: st.mtimeMs, size: st.size });\n } catch {\n /* vanished */\n }\n }\n return files;\n}\n\nfunction latestJsonlMtimeMs(projectDir: string): number {\n let latest = 0;\n for (const f of projectTranscripts(projectDir)) if (f.mtimeMs > latest) latest = f.mtimeMs;\n return latest;\n}\n\n/** An account's projects folder: `<its config folder, or ~/.claude>/projects`. */\nexport function projectsRootOf(configDir?: string): string {\n return path.join(configDir || path.join(os.homedir(), '.claude'), 'projects');\n}\n\n/**\n * Every account's projects folder, the default account's first; `first` (an account name) goes in front of the others —\n * a session's own account is looked in before the rest. Each folder once.\n */\nexport function claudeProjectsRoots(first?: string): string[] {\n const accounts = claudeAccounts();\n const ordered = first ? [...accounts.filter((a) => a.name === first), ...accounts.filter((a) => a.name !== first)] : accounts;\n const seen = new Set<string>();\n const out: string[] = [];\n for (const a of ordered) {\n const root = projectsRootOf(a.dir);\n const key = path.resolve(root);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(root);\n }\n return out;\n}\n\n/** Its newest transcript write in ONE config folder's projects (`~/.claude` without one). */\nconst activityIn = (launchPath: string, configDir?: string): number =>\n latestJsonlMtimeMs(path.join(projectsRootOf(configDir), encodeProjectDir(launchPath)));\n\n/**\n * The newest transcript write for work in `launchPath`: in that config folder's projects when `configDir` is given, else\n * the newest across every account (where no session is known: a `wd` scope, the PR watch's \"was it used lately\").\n */\nexport function getClaudeActivityMs(launchPath: string, configDir?: string): number {\n if (configDir) return activityIn(launchPath, configDir);\n let latest = 0;\n for (const root of claudeProjectsRoots()) latest = Math.max(latest, latestJsonlMtimeMs(path.join(root, encodeProjectDir(launchPath))));\n return latest;\n}\n\n/**\n * True when the AI tool's resume flag (`--continue`) will actually find a\n * conversation for this exact cwd. Claude Code errors out with \"No conversation\n * found to continue\" when the flag is passed in a directory it has never run\n * in, so callers gate on this before adding it.\n */\nexport function hasClaudeConversation(dir: string, configDir?: string): boolean {\n // One folder, never every account's: `--continue` finds only the conversations of the config folder it runs with.\n return activityIn(dir, configDir) > 0;\n}\n\n/**\n * The folders Claude may have been run in for a session — the cwds its conversations are keyed by: for a group its\n * root(s) and each sub-repo, for a single repo the repo path. `existing`: only the ones still on disk (a launch needs\n * one), else all (a switch of account moves the conversations of a folder that is gone too).\n */\nexport function sessionRunFolders(session: Pick<WorktreeSession, 'paths' | 'isGroup'>, existing = true): string[] {\n const paths = existing ? session.paths.filter((p) => fs.existsSync(p)) : session.paths;\n const out = new Set<string>();\n if (session.isGroup) {\n for (const p of paths) out.add(path.dirname(p)); // group root(s)\n for (const p of paths) out.add(p); // sub-repos\n } else {\n for (const p of paths) out.add(p);\n }\n return [...out];\n}\n\n/**\n * Pick the directory to relaunch Claude in when resuming a session.\n *\n * Claude's `--continue` only finds a conversation when the launch cwd matches\n * the directory the transcript was written for. A group session may have been\n * worked in the group root OR inside a specific sub-repo, and a session may\n * have no transcript at all (Claude was never actually used). So we consider\n * every plausible cwd — group root(s) and each sub-repo for groups, the repo\n * path for single-repo sessions — and pick the one with the most recent\n * transcript.\n *\n * Returns `hasConversation: false` (with the default launch path) when no\n * transcript exists anywhere; the caller should then start a fresh session\n * instead of passing `--continue`, which would error out and drop the user\n * back to the shell.\n */\nexport function resolveResumeLaunch(session: WorktreeSession): {\n launchPath: string;\n hasConversation: boolean;\n} {\n const existing = session.paths.filter((p) => fs.existsSync(p));\n const first = existing[0] ?? session.paths[0];\n // Default cwd: group root (parent of a sub-repo) for groups, the repo path\n // itself for single-repo sessions.\n const defaultPath = session.isGroup ? path.dirname(first) : first;\n\n const candidates = sessionRunFolders(session);\n\n // The session's own account: its conversations are in that account's folder.\n const configDir = configDirEnv(sessionAccount(session)).CLAUDE_CONFIG_DIR;\n let launchPath = defaultPath;\n let bestMs = 0;\n for (const c of candidates) {\n const ms = activityIn(c, configDir);\n if (ms > bestMs) {\n bestMs = ms;\n launchPath = c;\n }\n }\n return { launchPath, hasConversation: bestMs > 0 };\n}\n\n/** Watch root: `~/.claude/projects/`. The web server subscribes to mtime\n * changes here and re-broadcasts `sessions-changed` so the sidebar\n * badges refresh without polling. */\nexport function claudeProjectsRoot(): string {\n return projectsRootOf();\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteFile, withFileLockSync } from '../../platform/fs-safe.js';\nimport { accountDir, defaultAccountDir, sessionAccount } from './accounts.js';\nimport { globalConfigFile, withTrusted } from './setup-copy.js';\nimport type { WorktreeSession } from '../../sessions/session-types.js';\n\n/**\n * A folder work starts a session's Claude in is marked trusted in that session's account first (reported: a new\n * worktree, or a session switched to another account, stopped at Claude Code's \"Is this a project you created or one\n * you trust?\" though work had made the folder itself, from a repo you added).\n *\n * Why not trust the folder your repos are in once: Claude Code's trust walks up only to the git repo's root, and each\n * repo and worktree is a root of its own, so a parent's entry never reaches one (measured on 2.1.323, `bS`/`SS`). The\n * entry has to be the folder's own: `projects[<folder>].hasTrustDialogAccepted` in the account's global config\n * (`~/.claude.json` for the default folder, `<dir>/.claude.json` for another).\n *\n * Only a folder work starts a session in: its worktree, a repo you added, or a group's root over them. Written only\n * when missing, under the config's lock with the rest of the file as Claude Code left it; never a file that doesn't\n * exist yet (an account never started is set up by Claude Code itself) or can't be read.\n */\nexport interface TrustIo {\n read(file: string): string | null;\n /** Under the file's lock: read it again, change it, write it. */\n update(file: string, change: (text: string) => string | null): void;\n}\n\nexport const realTrustIo: TrustIo = {\n read(file) {\n try {\n return fs.readFileSync(file, 'utf-8');\n } catch {\n return null;\n }\n },\n update(file, change) {\n withFileLockSync(file, () => {\n const next = change(fs.readFileSync(file, 'utf-8'));\n if (next !== null) atomicWriteFile(file, next);\n });\n },\n};\n\nconst isTrusted = (config: unknown, folder: string): boolean => {\n if (!config || typeof config !== 'object') return false;\n const projects = (config as { projects?: unknown }).projects;\n if (!projects || typeof projects !== 'object') return false;\n const entry = (projects as Record<string, unknown>)[folder];\n return !!entry && typeof entry === 'object' && (entry as { hasTrustDialogAccepted?: unknown }).hasTrustDialogAccepted === true;\n};\n\nconst parse = (text: string | null): unknown => {\n if (text === null) return undefined;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n};\n\n/** The config's text with these folders trusted, or null when they all are already or it can't be read. Pure. */\nexport function trustedConfigText(text: string, folders: readonly string[]): string | null {\n const config = parse(text);\n if (config === undefined || typeof config !== 'object' || config === null || Array.isArray(config)) return null;\n const missing = folders.filter((f) => !isTrusted(config, f));\n return missing.length ? `${JSON.stringify(withTrusted(config, missing), null, 2)}\\n` : null;\n}\n\n/** Mark these folders trusted in this account's global config. Returns the ones it marked (none: all were already). */\nexport function trustFoldersIn(configFile: string, folders: readonly string[], io: TrustIo = realTrustIo): string[] {\n const keys = [...new Set(folders.map((f) => path.resolve(f)))];\n const config = parse(io.read(configFile));\n // Missing or unreadable: Claude Code's own state is never replaced by a guess.\n if (config === undefined) return [];\n const missing = keys.filter((f) => !isTrusted(config, f));\n if (!missing.length) return [];\n io.update(configFile, (text) => trustedConfigText(text, missing));\n return missing;\n}\n\n/** The global config of the account a session runs on. */\nexport function sessionConfigFile(session: Pick<WorktreeSession, 'account'> | null): string {\n const dir = (session ? accountDir(sessionAccount(session)) : null) ?? defaultAccountDir();\n return globalConfigFile(dir);\n}\n\n/** Before work starts a session's Claude in `cwd`: that folder trusted on the session's account. */\nexport function trustSessionFolder(session: Pick<WorktreeSession, 'account'> | null, cwd: string, io: TrustIo = realTrustIo): string[] {\n return trustFoldersIn(sessionConfigFile(session), [cwd], io);\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { applyEnvDelta, type EnvDelta } from '../../platform/env-delta.js';\nimport { atomicWriteFile, ensureFile, withFileLockSync } from '../../platform/fs-safe.js';\nimport spawn from '../../platform/spawn.js';\nimport { accountDirKey, defaultAccountDir } from './accounts.js';\n\n/**\n * Copy one Claude account's SETUP to another (reported: a second account starts empty — none of the first one's MCP\n * servers, plugins, CLAUDE.md, agents, commands or permissions — so a session moved to it lost its tools).\n *\n * What goes across:\n * - files and folders that are yours: `CLAUDE.md`, `agents/`, `commands/`, each of `skills/` (not `synced`, which\n * Claude Code manages), your status line's script;\n * - `settings.json` and `settings.local.json`, MERGED (`mergeSettings`): never `statusLine` or work's own hooks, which\n * work sets up per account;\n * - user-scope MCP servers, marketplaces and enabled plugins, through the `claude` CLI run AS the target account, so\n * Claude Code's own locking and install logic do the writing (its `.claude.json` is rewritten by every running\n * Claude; a plugin's files are fetched, not copied).\n *\n * What never goes across: logins and tokens (`.credentials.json`, an MCP server's sign-in), conversations, history,\n * usage and caches. A server that needs a sign-in needs it once more on the target account.\n * Nothing on the target is deleted: what it has and the source hasn't stays.\n */\n\nexport interface SetupAccount {\n name: string;\n /** Its config folder. */\n dir: string;\n}\n\nexport type SetupKind = 'file' | 'folder' | 'settings' | 'mcp' | 'marketplace' | 'plugin' | 'trust';\n\n/** The one item a copy lists for the folders the source account trusts. */\nexport const TRUSTED_FOLDERS = 'trusted folders';\n\nexport interface SetupItem {\n kind: SetupKind;\n /** What it is, as the list names it: `CLAUDE.md`, `agents/`, `atlassian`, `mtk@moberg-plugins`. */\n name: string;\n /** What the copy does with it. */\n does: 'adds' | 'replaces' | 'merges into';\n /** Something to know of it (a sign-in needed, where it comes from). */\n note?: string;\n}\n\nexport interface SetupResult extends SetupItem {\n ok: boolean;\n /** Why it didn't go (not ok). */\n error?: string;\n}\n\n/** Where an account's global config (`mcpServers` and Claude Code's own state) is: `~/.claude.json` for the default folder, inside the folder for another. */\nexport function globalConfigFile(dir: string, home: string = os.homedir()): string {\n return accountDirKey(dir) === accountDirKey(path.join(home, '.claude'))\n ? path.join(home, '.claude.json')\n : path.join(dir, '.claude.json');\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\nconst same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n\n/** Settings a copy never carries: work sets them up for each account itself. */\nconst NEVER_COPIED = new Set(['statusLine']);\n/** Settings that are maps: the source's entries are added over the target's. */\nconst MAPS = new Set(['enabledPlugins', 'extraKnownMarketplaces', 'mcpServers', 'env', 'skillOverrides']);\n\n/**\n * The target's settings with the source's merged in. Lists of rules (`permissions.allow` / `deny` / `ask`) are joined,\n * each rule once; maps take the source's entries over the target's; a hook goes across unless it is work's own\n * (`_workHookOwner`: set up per account) or the target has it already; anything else is the source's value. What only\n * the target has stays. Pure.\n */\nexport function mergeSettings(source: Record<string, unknown>, target: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...target };\n for (const [key, value] of Object.entries(source)) {\n if (NEVER_COPIED.has(key)) continue;\n if (key === 'hooks') {\n if (!isObject(value)) continue;\n const hooks: Record<string, unknown[]> = {};\n for (const [event, list] of Object.entries(isObject(target.hooks) ? target.hooks : {}))\n hooks[event] = Array.isArray(list) ? [...list] : [];\n for (const [event, list] of Object.entries(value)) {\n for (const entry of Array.isArray(list) ? list : []) {\n if (isObject(entry) && '_workHookOwner' in entry) continue;\n if (!(hooks[event] ??= []).some((have) => same(have, entry))) hooks[event].push(entry);\n }\n }\n if (Object.keys(hooks).length) out.hooks = hooks;\n } else if (key === 'permissions' && isObject(value)) {\n const have = isObject(target.permissions) ? target.permissions : {};\n const merged: Record<string, unknown> = { ...have };\n for (const [k, v] of Object.entries(value)) {\n merged[k] = Array.isArray(v) ? [...new Set([...(Array.isArray(have[k]) ? (have[k] as unknown[]) : []), ...v])] : v;\n }\n out.permissions = merged;\n } else if (MAPS.has(key) && isObject(value)) {\n out[key] = { ...(isObject(target[key]) ? target[key] : {}), ...value };\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * What merging `source` into `target` would change, in a few words each (found on the first real use: the plan said\n * \"merges into settings\" for one plugin that would be switched back on, which is the thing to know before saying\n * yes). Names only, never a value that could be a key (`env`). Pure.\n */\nexport function settingsChanges(source: Record<string, unknown>, target: Record<string, unknown>): string[] {\n const merged = mergeSettings(source, target);\n const out: string[] = [];\n for (const key of Object.keys(merged)) {\n const now = merged[key];\n const was = target[key];\n if (same(now, was)) continue;\n if (key === 'enabledPlugins' && isObject(now)) {\n const before = isObject(was) ? was : {};\n for (const [id, on] of Object.entries(now))\n if (before[id] !== on) out.push(`${on === true ? 'turns on' : 'turns off'} plugin ${id}${id in before ? '' : ' (new here)'}`);\n } else if (key === 'permissions' && isObject(now)) {\n const before = isObject(was) ? was : {};\n for (const [k, v] of Object.entries(now)) {\n if (same(v, before[k])) continue;\n if (Array.isArray(v)) {\n const n = v.length - (Array.isArray(before[k]) ? (before[k] as unknown[]).length : 0);\n out.push(`adds ${n} ${k} rule${n === 1 ? '' : 's'}`);\n } else out.push(`sets permissions.${k}`);\n }\n } else if (key === 'hooks' && isObject(now)) {\n const count = (h: unknown) => (isObject(h) ? Object.values(h).reduce((n: number, l) => n + (Array.isArray(l) ? l.length : 0), 0) : 0);\n const n = count(now) - count(was);\n out.push(`adds ${n} of your hook${n === 1 ? '' : 's'}`);\n } else if (MAPS.has(key) && isObject(now)) {\n const before = isObject(was) ? was : {};\n const names = Object.keys(now).filter((k) => !same(now[k], before[k]));\n out.push(`${key}: ${names.slice(0, 4).join(', ')}${names.length > 4 ? ` and ${names.length - 4} more` : ''}`);\n } else out.push(`sets ${key}`);\n }\n return out;\n}\n\n/** What `claude plugin marketplace add` is given for a marketplace as Claude Code recorded it; null: a kind we don't know how to add. */\nexport function marketplaceAddArgs(source: unknown): string[] | null {\n if (!isObject(source)) return null;\n const sparse =\n Array.isArray(source.sparsePaths) && source.sparsePaths.every((p) => typeof p === 'string') ? (source.sparsePaths as string[]) : [];\n const where =\n source.source === 'github' && typeof source.repo === 'string'\n ? source.repo\n : source.source === 'directory' && typeof source.path === 'string'\n ? source.path\n : (source.source === 'git' || source.source === 'url') && typeof source.url === 'string'\n ? source.url\n : null;\n // Never an option in the place of a source (a name starting with a dash).\n if (!where || where.startsWith('-') || sparse.some((p) => p.startsWith('-'))) return null;\n return ['plugin', 'marketplace', 'add', where, '--scope', 'user', ...(sparse.length ? ['--sparse', ...sparse] : [])];\n}\n\n/** The files and folders of an account that are the user's own setup. `skills/synced` is Claude Code's. */\nconst FILES = ['CLAUDE.md', 'statusline-command.sh'];\nconst FOLDERS = ['agents', 'commands'];\nconst SETTINGS = ['settings.json', 'settings.local.json'];\n\nexport interface SetupIo {\n exists: (p: string) => boolean;\n isDir: (p: string) => boolean;\n list: (dir: string) => string[];\n readJson: (file: string) => unknown;\n /** A file's bytes; null when it can't be read. */\n read: (file: string) => Buffer | null;\n}\n\n/**\n * Every file of `from` (a file, or a folder and all under it) is in `to` with the same content: copying it would\n * change nothing (found on the first real use: a second copy listed CLAUDE.md, the agents and every skill as\n * \"replaces\" though they were identical). What `to` has besides doesn't matter: a copy deletes nothing. Pure but for `io`.\n */\nexport function alreadyThere(from: string, to: string, io: SetupIo): boolean {\n if (io.isDir(from)) return io.isDir(to) && io.list(from).every((name) => alreadyThere(path.join(from, name), path.join(to, name), io));\n const a = io.read(from);\n const b = io.read(to);\n return !!a && !!b && a.equals(b);\n}\n\n/** Where a marketplace comes from, as one key: two names for one source are one marketplace (`moberghr` and `moberghr-claude-helpers`). */\nexport function marketplaceKey(source: unknown): string | null {\n const args = marketplaceAddArgs(source);\n return args ? args[3].replace(/\\\\/g, '/').replace(/\\/+$/, '').toLowerCase() : null;\n}\n\nexport const realSetupIo: SetupIo = {\n exists: (p) => fs.existsSync(p),\n isDir: (p) => {\n try {\n return fs.statSync(p).isDirectory();\n } catch {\n return false;\n }\n },\n list: (dir) => {\n try {\n return fs.readdirSync(dir);\n } catch {\n return [];\n }\n },\n read: (file) => {\n try {\n return fs.readFileSync(file);\n } catch {\n return null;\n }\n },\n readJson: (file) => {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown;\n } catch {\n return null;\n }\n },\n};\n\nconst objectAt = (v: unknown, key: string): Record<string, unknown> =>\n isObject(v) && isObject(v[key]) ? (v[key] as Record<string, unknown>) : {};\n\n/** The user-scope MCP servers of an account, by name (its global config's `mcpServers`). */\nexport function userMcpServers(dir: string, io: SetupIo = realSetupIo): Record<string, unknown> {\n return objectAt(io.readJson(globalConfigFile(dir)), 'mcpServers');\n}\n\n/**\n * The folders an account answered \"yes, I trust this folder\" for (its global config's `projects[<folder>]\n * .hasTrustDialogAccepted`), as Claude Code wrote them. A folder under a trusted one is trusted too, so one entry\n * for the folder your worktrees are in covers every session.\n */\nexport function trustedFolders(dir: string, io: SetupIo = realSetupIo): string[] {\n return Object.entries(objectAt(io.readJson(globalConfigFile(dir)), 'projects'))\n .filter(([, p]) => isObject(p) && p.hasTrustDialogAccepted === true)\n .map(([folder]) => folder);\n}\n\n/**\n * The folders `from` trusts that `to` doesn't yet (reported: on a second account every session stopped at \"do you\n * trust this folder?\", though the first had been told long ago). Only ones that still exist: a removed worktree's\n * isn't carried. The same person on the same computer said yes to each, so it is theirs to carry — and only when\n * they ask for the copy.\n */\nexport function trustToCopy(from: SetupAccount, to: SetupAccount, io: SetupIo = realSetupIo): string[] {\n const have = new Set(trustedFolders(to.dir, io));\n return trustedFolders(from.dir, io).filter((folder) => !have.has(folder) && io.isDir(folder));\n}\n\n/** The target's global config with these folders trusted: each one's other state stays, and everything else of the file. Pure. */\nexport function withTrusted(config: unknown, folders: readonly string[]): Record<string, unknown> {\n const base = isObject(config) ? config : {};\n const projects = { ...objectAt(base, 'projects') };\n for (const folder of folders)\n projects[folder] = { ...(isObject(projects[folder]) ? projects[folder] : {}), hasTrustDialogAccepted: true };\n return { ...base, projects };\n}\n\n/**\n * What a copy from `from` to `to` would do, in the order it is done: a read (nothing is changed or started). Only\n * what differs is listed, so an account already set up the same gives an empty plan.\n */\nexport function planSetupCopy(from: SetupAccount, to: SetupAccount, io: SetupIo = realSetupIo): SetupItem[] {\n const items: SetupItem[] = [];\n const there = (rel: string) => io.exists(path.join(to.dir, rel));\n // Only what a copy would change: a file or folder the target has with the same content already isn't listed.\n const differs = (rel: string) => !alreadyThere(path.join(from.dir, rel), path.join(to.dir, rel), io);\n for (const f of FILES)\n if (io.exists(path.join(from.dir, f)) && differs(f)) items.push({ kind: 'file', name: f, does: there(f) ? 'replaces' : 'adds' });\n for (const d of FOLDERS)\n if (io.isDir(path.join(from.dir, d)) && io.list(path.join(from.dir, d)).length && differs(d))\n items.push({ kind: 'folder', name: `${d}/`, does: there(d) ? 'merges into' : 'adds' });\n for (const skill of io.list(path.join(from.dir, 'skills')).filter((s) => s !== 'synced' && io.isDir(path.join(from.dir, 'skills', s))))\n if (differs(path.join('skills', skill)))\n items.push({ kind: 'folder', name: `skills/${skill}/`, does: there(path.join('skills', skill)) ? 'replaces' : 'adds' });\n for (const s of SETTINGS) {\n const source = io.readJson(path.join(from.dir, s));\n if (!isObject(source)) continue;\n const target = io.readJson(path.join(to.dir, s));\n const have = isObject(target) ? target : {};\n if (!same(mergeSettings(source, have), have))\n items.push({\n kind: 'settings',\n name: s,\n does: 'merges into',\n // What it would change, by name; the rest of the file stays (the status line and work's hooks always).\n note: settingsChanges(source, have).join('; '),\n });\n }\n const servers = userMcpServers(from.dir, io);\n const haveServers = userMcpServers(to.dir, io);\n for (const [name, def] of Object.entries(servers)) {\n if (same(haveServers[name], def)) continue;\n const remote = isObject(def) && (def.type === 'http' || def.type === 'sse');\n items.push({\n kind: 'mcp',\n name,\n does: name in haveServers ? 'replaces' : 'adds',\n ...(remote ? { note: `needs its own sign-in on ${to.name}: /mcp → ${name} → Authenticate` } : {}),\n });\n }\n const markets = io.readJson(path.join(from.dir, 'plugins', 'known_marketplaces.json'));\n const haveMarkets = io.readJson(path.join(to.dir, 'plugins', 'known_marketplaces.json'));\n // By where each comes from, not its name: Claude Code names one after its own manifest, so the same marketplace\n // can carry another name on the other account (found on the first real use: two were offered again).\n const haveSources = new Set(\n Object.values(isObject(haveMarkets) ? haveMarkets : {})\n .map((m) => marketplaceKey(isObject(m) ? m.source : null))\n .filter((k): k is string => k !== null),\n );\n for (const [name, m] of Object.entries(isObject(markets) ? markets : {})) {\n if (isObject(haveMarkets) && name in haveMarkets) continue;\n const key = marketplaceKey(isObject(m) ? m.source : null);\n if (key && haveSources.has(key)) continue;\n const args = marketplaceAddArgs(isObject(m) ? m.source : null);\n if (args) items.push({ kind: 'marketplace', name, does: 'adds', note: args[3] });\n }\n const enabled = objectAt(io.readJson(path.join(from.dir, 'settings.json')), 'enabledPlugins');\n const installed = objectAt(io.readJson(path.join(to.dir, 'plugins', 'installed_plugins.json')), 'plugins');\n for (const [id, on] of Object.entries(enabled))\n if (on === true && !(id in installed)) items.push({ kind: 'plugin', name: id, does: 'adds', note: 'installed from its marketplace' });\n const trust = trustToCopy(from, to, io);\n if (trust.length) {\n // The few nearest the top say the most: a folder trusts everything under it.\n const first = [...trust].sort((a, b) => a.length - b.length || a.localeCompare(b)).slice(0, 3);\n items.push({\n kind: 'trust',\n name: TRUSTED_FOLDERS,\n does: 'adds',\n note: `${trust.length} folder${trust.length === 1 ? '' : 's'} ${from.name} trusts, so ${to.name} doesn’t ask again: ${first.join(', ')}${trust.length > first.length ? ` and ${trust.length - first.length} more` : ''}`,\n });\n }\n return items;\n}\n\n/** Runs `claude <args>` as an account (argv only, §1.1; `input`: its stdin). */\nexport type SetupRun = (args: string[], env: EnvDelta, input?: string) => { ok: boolean; out: string };\n\nconst runClaude: SetupRun = (args, env, input) => {\n const r = spawn.sync('claude', args, {\n encoding: 'utf8',\n timeout: 180_000,\n windowsHide: true,\n stdio: 'pipe',\n env: applyEnvDelta(process.env, env) as NodeJS.ProcessEnv,\n ...(input !== undefined ? { input } : {}),\n });\n const text = (v: unknown) => (typeof v === 'string' ? v : '');\n return { ok: !r.error && r.status === 0, out: r.error ? r.error.message : `${text(r.stderr)}\\n${text(r.stdout)}` };\n};\n\nconst lastLine = (out: string) =>\n out\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean)\n .pop() ?? 'it failed';\n\n/** The environment that makes `claude` act on an account's folder: nothing set for the default one. */\nexport function setupEnv(dir: string): EnvDelta {\n return accountDirKey(dir) === accountDirKey(defaultAccountDir()) ? { CLAUDE_CONFIG_DIR: null } : { CLAUDE_CONFIG_DIR: dir };\n}\n\n/** One settings file merged under its lock, written whole (§5.2: a file that stays a file). */\nfunction mergeSettingsFile(fromFile: string, toFile: string): void {\n const source = JSON.parse(fs.readFileSync(fromFile, 'utf-8')) as unknown;\n if (!isObject(source)) throw new Error('its settings are not an object');\n fs.mkdirSync(path.dirname(toFile), { recursive: true });\n ensureFile(toFile, '{}\\n');\n withFileLockSync(toFile, () => {\n let target: unknown = {};\n try {\n target = JSON.parse(fs.readFileSync(toFile, 'utf-8'));\n } catch {\n // An empty or broken file is replaced by the merge of nothing.\n }\n atomicWriteFile(toFile, `${JSON.stringify(mergeSettings(source, isObject(target) ? target : {}), null, 2)}\\n`);\n });\n}\n\n/** The folders marked trusted in the target's global config, under its lock, the rest of the file as it is (§5.2). */\nfunction trustFolders(file: string, folders: readonly string[]): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n ensureFile(file, '{}\\n');\n withFileLockSync(file, () => {\n let config: unknown;\n try {\n config = JSON.parse(fs.readFileSync(file, 'utf-8'));\n } catch {\n // Unreadable: Claude Code's own state must not be replaced by a guess.\n throw new Error('its config file can’t be read');\n }\n atomicWriteFile(file, `${JSON.stringify(withTrusted(config, folders), null, 2)}\\n`);\n });\n}\n\n/**\n * Do the copy: every item of the plan as it is now, one after another, each reported. One that fails is said and the\n * rest still go. `run`: a test's.\n */\nexport async function applySetupCopy(from: SetupAccount, to: SetupAccount, run: SetupRun = runClaude): Promise<SetupResult[]> {\n if (accountDirKey(from.dir) === accountDirKey(to.dir)) throw new Error('an account’s setup can’t be copied to itself');\n const env = setupEnv(to.dir);\n const servers = userMcpServers(from.dir);\n const markets = realSetupIo.readJson(path.join(from.dir, 'plugins', 'known_marketplaces.json'));\n const results: SetupResult[] = [];\n for (const item of planSetupCopy(from, to)) {\n try {\n const rel = item.name.replace(/\\/$/, '');\n if (item.kind === 'file') {\n fs.mkdirSync(to.dir, { recursive: true });\n fs.copyFileSync(path.join(from.dir, rel), path.join(to.dir, rel));\n } else if (item.kind === 'folder') {\n // Symlinks are not followed out of the folder: a link is copied as a link.\n fs.cpSync(path.join(from.dir, rel), path.join(to.dir, rel), { recursive: true, force: true, verbatimSymlinks: true });\n } else if (item.kind === 'settings') {\n mergeSettingsFile(path.join(from.dir, rel), path.join(to.dir, rel));\n } else if (item.kind === 'mcp') {\n if (item.does === 'replaces') run(['mcp', 'remove', item.name, '--scope', 'user'], env);\n // Its definition goes on stdin: a server's env or headers may hold a key, which must not be on a command line.\n const r = run(['mcp', 'add-json', item.name, '-', '--scope', 'user'], env, JSON.stringify(servers[item.name]));\n if (!r.ok) throw new Error(lastLine(r.out));\n } else if (item.kind === 'marketplace') {\n const args = marketplaceAddArgs(\n isObject(markets) && isObject(markets[item.name]) ? (markets[item.name] as Record<string, unknown>).source : null,\n );\n if (!args) throw new Error('work doesn’t know how to add this kind of marketplace');\n const r = run(args, env);\n if (!r.ok) throw new Error(lastLine(r.out));\n } else if (item.kind === 'trust') {\n trustFolders(globalConfigFile(to.dir), trustToCopy(from, to));\n } else {\n const r = run(['plugin', 'install', item.name, '--scope', 'user', '-y'], env);\n if (!r.ok) throw new Error(lastLine(r.out));\n }\n results.push({ ...item, ok: true });\n } catch (err) {\n results.push({ ...item, ok: false, error: err instanceof Error ? err.message : String(err) });\n }\n }\n return results;\n}\n\n/** \"Copied 9 of 11 things from default to admin; 2 failed\" / \"admin already has default's setup.\" Pure. */\nexport function setupSummary(results: readonly SetupResult[], from: string, to: string): string {\n if (results.length === 0) return `${to} already has ${from}'s setup: nothing to copy.`;\n const ok = results.filter((r) => r.ok).length;\n const failed = results.length - ok;\n return `Copied ${ok} of ${results.length} thing${results.length === 1 ? '' : 's'} from ${from} to ${to}${failed ? `; ${failed} failed` : ''}.`;\n}\n","/**\n * Claude Code's Bash tool runs each command in a shell of its own, its command line:\n *\n * /bin/zsh -c source <config dir>/shell-snapshots/snapshot-zsh-<n>.sh 2>/dev/null || true && … && eval '<command>' \\\n * < /dev/null && pwd -P >| /tmp/claude-<n>-cwd\n *\n * (measured on 2.1.323; bash and Git Bash on Windows alike). Recognised by its snapshot file; what it runs is the\n * `eval`'s argument, its quotes undone, in one line. Null: not one of its tool shells (an MCP server, a helper). Pure.\n */\nconst SNAPSHOT = /shell-snapshots[\\\\/]snapshot-/;\nconst EVAL = /\\beval '((?:[^']|'\"'\"')*)'/;\n\nexport function claudeToolShell(command: string): string | null {\n if (!SNAPSHOT.test(command)) return null;\n const m = EVAL.exec(command);\n const what = (m ? m[1].replace(/'\"'\"'/g, \"'\") : command).replace(/\\\\012/g, '\\n');\n const line = what.trim().split(/\\r?\\n/)[0].replace(/\\s+/g, ' ');\n return line.length > 120 ? `${line.slice(0, 119)}…` : line;\n}\n","import { keepClaudeUpdated, updateCheckText } from './tool-update.js';\nimport { claudeStartupQuestion } from './startup-question.js';\nimport { sessionTempFolders } from './temp-folders.js';\nimport { trustSessionFolder } from './folder-trust.js';\nimport { claudeToolShell } from './tool-shell.js';\nimport path from 'node:path';\nimport { backgroundWorkSince, listTranscripts, listUsageFiles } from './files.js';\nimport { backgroundCommandNames, backgroundCommandsRunning } from './background-commands.js';\nimport { claudePrLinks } from './pr-links.js';\nimport { getAiTool } from '../../platform/ai-launcher.js';\nimport {\n claudeProjectsRoots,\n encodeProjectDir,\n getClaudeActivityMs,\n hasClaudeConversation,\n projectsRootOf,\n resolveResumeLaunch,\n} from './activity.js';\nimport { withoutParentSession } from './env.js';\nimport { accountDir, accountEnv, configDirEnv, defaultAccountName, sessionAccount } from './accounts.js';\nimport { readTranscriptTail } from './transcript.js';\nimport { claudeContextWindow, claudeEntries } from './entries.js';\nimport { claudeEvents } from './hooks.js';\nimport { sessionSettingsFile, startedWithSessionSettings, withSessionSettings } from './session-settings.js';\nimport { claudeSessionsDirs, readLiveClaudes } from './live.js';\nimport { ANSWER_KEYS, checkDialog } from './permission.js';\nimport { typeThenEnter } from '../typing.js';\nimport {\n CLAUDE_READ_ONLY_LINES,\n CLAUDE_READ_ONLY_LOCAL_LINES,\n claudeReadDenyRules,\n claudeSettingsFile,\n internalClaudeReadOnlySpawn,\n internalClaudeSpawn,\n} from './internal.js';\nimport { claudeWorkspace } from './workspace.js';\nimport { claudeSkills } from './skills.js';\nimport { claudeUsage } from './usage.js';\nimport { claudeAccountSwitch } from './account-move.js';\n\n/** A few words (checkpoint names, once per changed turn): a small model does. */\nexport const CLAUDE_SMALL_MODEL = 'haiku';\nimport type { AgentAdapter, ConversationEntry } from '../types.js';\n\nexport { claudeEntries } from './entries.js';\n\n/**\n * Claude Code as an agent (types.ts): its conversations are the JSONL\n * transcripts under ~/.claude/projects/<folder>/ (claude-entries.ts reads\n * their lines). Reading the latest messages reads from the end — the newest\n * transcripts, a tail of each — since a transcript runs to many megabytes of\n * tool output.\n */\n\n/** How much of each transcript's end `read` takes, and how many transcripts at most. */\nconst TAIL_BYTES = 4 * 1024 * 1024;\nconst MAX_FILES = 3;\n\n/** What `read` shows: your prompts, its messages, its tool calls — not results, empty lines or a subagent's. */\nconst shown = (e: ConversationEntry) => !e.sidechain && (e.role === 'you' || e.role === 'tool' || (e.role === 'agent' && e.text !== ''));\n\nexport const claudeAgent: AgentAdapter = {\n id: 'claude',\n name: 'Claude Code',\n launch: {\n // The configured command when it is Claude (`claude --model opus`); plain `claude` otherwise.\n tool: (config) => getAiTool(config && getAiTool(config).cmd === 'claude' ? config : {}),\n canResume: (cwd, via) =>\n hasClaudeConversation(cwd, via?.env ? via.env.CLAUDE_CONFIG_DIR : configDirEnv(sessionAccount(via?.session)).CLAUDE_CONFIG_DIR),\n resumeLaunch: (s) => resolveResumeLaunch(s),\n cleanEnv: (env) => withoutParentSession(env),\n // The session's account (null: work's own runs, on the configured default).\n env: (session) => accountEnv(session ? sessionAccount(session) : defaultAccountName()),\n // `--settings ~/.work/claude-settings.json`: work's hooks and status line for this Claude alone.\n // (`write: false`: the dev server names the file the installed work wrote, never its own build.)\n sessionTool: (tool, o) => withSessionSettings(tool, sessionSettingsFile(o)),\n startedWithSessionHooks: startedWithSessionSettings,\n // Its folder marked trusted on the session's account (`projects[<cwd>].hasTrustDialogAccepted`).\n trustFolder: (s, cwd) => void trustSessionFolder(s, cwd),\n // `--add-dir=<folder>` each, one argument, never twice (a restore's stored tool may have them already).\n withFolders: (tool, folders) => claudeWithFolders(tool, folders),\n },\n conversation: {\n files: (s) => listTranscripts(s),\n usageFiles: (s) => listUsageFiles(s),\n entries: claudeEntries,\n contextWindow: claudeContextWindow,\n read(session, { last }) {\n const files = listTranscripts(session).sort((a, b) => b.mtimeMs - a.mtimeMs);\n const got: ConversationEntry[] = [];\n for (const f of files.slice(0, MAX_FILES)) {\n got.push(...claudeEntries(readTranscriptTail(f.file, TAIL_BYTES)).filter(shown));\n if (got.length >= last) break; // the newest file had enough\n }\n return got.sort((a, b) => a.at.localeCompare(b.at)).slice(-last);\n },\n // Its projects folder for the folder Claude runs in (the worktree, or a group's root): `--continue` finds it there.\n lastWriteMs: (cwd) => getClaudeActivityMs(cwd),\n backgroundWorkSince,\n backgroundCommands: backgroundCommandsRunning,\n backgroundCommandNames,\n prLinks: claudePrLinks,\n // In the session's own account's projects folder: that is where its `--continue` looks.\n restoreDir: (s) => {\n const cwd = s.isGroup && s.paths[0] ? path.dirname(s.paths[0]) : s.paths[0];\n return cwd ? path.join(projectsRootOf(accountDir(sessionAccount(s)) ?? undefined), encodeProjectDir(cwd)) : null;\n },\n },\n events: claudeEvents,\n // Its transcripts, and the per-process state files (a Claude opened or closed in a terminal tab shows at once), of every account.\n activityRoots: () => [...new Set([...claudeProjectsRoots(), ...claudeSessionsDirs()])],\n // Its scratch folders for the session (an artifact's HTML before it is published): the pane beside the terminal shows files there.\n tempFolders: (s) => sessionTempFolders(s),\n live: { running: (table) => readLiveClaudes(undefined, undefined, table), toolShell: claudeToolShell },\n input: {\n submit: typeThenEnter,\n // Before its first turn in a folder it wasn't told to trust: its own question, which no hook reports.\n startupQuestion: claudeStartupQuestion,\n // Its dialog: \"Do you want to …?\" over a menu with \"❯ 1. Yes\"; Enter takes Yes, Esc is \"No, and tell Claude what to do differently\".\n permissionDialog: { check: checkDialog, keys: { allow: ANSWER_KEYS.allow, deny: ANSWER_KEYS.deny } },\n },\n // `claude -p --tools \"\" --strict-mcp-config [--model haiku]` in a neutral folder, tagged internal.\n // Read-only in a folder (a PR's checkout): `claude -p --restricted --tools Read,Grep,Glob --setting-sources user --add-dir <it> …`.\n oneShot: {\n command: ({ small }) => ({ cmd: 'claude', ...internalClaudeSpawn(small ? { model: CLAUDE_SMALL_MODEL } : {}) }),\n readOnly: {\n command: ({ small, cwd, deny }) => ({\n cmd: 'claude',\n ...internalClaudeReadOnlySpawn({ cwd, ...(small ? { model: CLAUDE_SMALL_MODEL } : {}), ...(deny ? { deny } : {}) }),\n }),\n isSettingsFile: claudeSettingsFile,\n promptLines: CLAUDE_READ_ONLY_LINES,\n localLines: CLAUDE_READ_ONLY_LOCAL_LINES,\n denyRules: (repos) => claudeReadDenyRules(repos),\n // Its flags were measured on one Claude Code (READ_ONLY_MIN_VERSION): an older one gets no checkout run.\n // Loaded when a review asks: the hook processes load this adapter on every turn edge.\n available: async () => (await import('./version.js')).claudeReadOnlyAvailable(),\n },\n },\n instructionsFile: 'CLAUDE.md',\n // CLAUDE.md's own import syntax (Claude Code reads the file it names, relative to this one).\n instructionsImport: (relPath) => `@${relPath}`,\n workspace: claudeWorkspace,\n skills: claudeSkills,\n // Claude Code kept up to date the way it was installed (tool-update.ts).\n selfUpdate: {\n enabled: (config) => (config as { claudeCode?: { autoUpdate?: boolean } } | null)?.claudeCode?.autoUpdate !== false,\n run: async () => {\n const r = await keepClaudeUpdated();\n return {\n text: updateCheckText(r),\n failed: r.kind === 'cannot' || (r.kind === 'not-yet' && r.why.startsWith('the update failed')),\n updated: r.kind === 'updated',\n };\n },\n },\n usage: claudeUsage,\n accounts: claudeAccountSwitch,\n};\n\n/**\n * Claude with more folders: `--add-dir=<folder>` each. Never `--add-dir <folder>`: Claude's `--add-dir` takes any\n * number of folders, so the session's first prompt, which comes next on the command line, was taken for another\n * folder and Claude started with no task (reported: every `work child spawn` lost its task; the coordinator re-sent\n * each one by hand, as a note, and the children answered in the review UI instead of `work report`). A pair of ours\n * from before (a restored session's stored tool, a folder we add) becomes the one-argument form; never twice. Pure.\n */\nexport function claudeWithFolders<T extends { baseArgs: string[] }>(tool: T, folders: readonly string[]): T {\n if (!folders.length) return tool;\n const ours = new Set(folders);\n const args: string[] = [];\n const have = new Set<string>();\n for (let i = 0; i < tool.baseArgs.length; i++) {\n const a = tool.baseArgs[i];\n const next = tool.baseArgs[i + 1];\n if (a === '--add-dir' && next !== undefined && ours.has(next)) {\n args.push(`--add-dir=${next}`);\n have.add(next);\n i++;\n continue;\n }\n if (a.startsWith('--add-dir=')) have.add(a.slice('--add-dir='.length));\n args.push(a);\n }\n const add = folders.filter((f) => !have.has(f));\n const changed = add.length || args.length !== tool.baseArgs.length;\n return changed ? { ...tool, baseArgs: [...args, ...add.map((f) => `--add-dir=${f}`)] } : tool;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { claudeProjectsRoots, encodeProjectDir, projectTranscripts } from './activity.js';\nimport { sessionAccount } from './accounts.js';\nimport type { WorktreeSession } from '../../sessions/session-types.js';\nimport type { BackgroundWork, ConversationFile } from '../types.js';\n\n/**\n * Where Claude Code keeps a session's conversations: its transcripts under\n * ~/.claude/projects/<encoded folder>/ — the Claude adapter's `files`. A\n * group's are in its root's folder (Claude runs in the group root).\n */\n\n/**\n * Every Claude Code transcript of this session's conversations (group: its root): its own account's projects folder\n * first, then the other accounts' (a switch moves them, but one left behind is still its conversation), each file once.\n */\nexport function listTranscripts(session: WorktreeSession): ConversationFile[] {\n const dirs = session.isGroup ? [...new Set(session.paths.map((p) => path.dirname(p)))] : session.paths;\n const roots = claudeProjectsRoots(sessionAccount(session));\n const seen = new Set<string>();\n const out: ConversationFile[] = [];\n for (const d of dirs)\n for (const root of roots)\n for (const f of projectTranscripts(path.join(root, encodeProjectDir(d)))) {\n if (seen.has(f.file)) continue;\n seen.add(f.file);\n out.push(f);\n }\n return out;\n}\n\n/**\n * Its transcripts and their subagents' (`<conversation>/subagents/agent-*.jsonl`, beside `<conversation>.jsonl`):\n * a subagent's tokens are spent on the plan too, though its lines aren't in the conversation's file.\n */\nexport function listUsageFiles(session: WorktreeSession): ConversationFile[] {\n const out: ConversationFile[] = [];\n for (const t of listTranscripts(session)) {\n out.push(t);\n const dir = path.join(t.file.replace(/\\.jsonl$/, ''), 'subagents');\n let names: string[];\n try {\n names = fs.readdirSync(dir);\n } catch {\n continue; // no subagents in this one\n }\n for (const name of names) {\n if (!name.startsWith('agent-') || !name.endsWith('.jsonl')) continue;\n const file = path.join(dir, name);\n try {\n const st = fs.statSync(file);\n out.push({ file, mtimeMs: st.mtimeMs, size: st.size });\n } catch {\n /* gone meanwhile */\n }\n }\n }\n return out;\n}\n\n/** The newest transcript Claude wrote for this session. */\nexport function latestTranscript(session: WorktreeSession): ConversationFile | null {\n let best: ConversationFile | null = null;\n for (const t of listTranscripts(session)) if (!best || t.mtimeMs > best.mtimeMs) best = t;\n return best;\n}\n\n/** Only the conversations written around the turn that ended are looked in (the rest are other days' work). */\nconst AROUND_TURN_MS = 60_000;\n/**\n * A background agent quiet this long is taken as done (hung, killed). Long, since quiet isn't done: one waiting on a\n * test run or its own review lanes writes nothing for many minutes (15 read a running review as Idle), and the\n * question is only asked while Claude Code itself still says busy (withLiveClaude), which ends with a killed one.\n */\nconst AGENT_QUIET_MS = 60 * 60_000;\n/** It is asked on every sessions list while it applies: an answer is reused this long. */\nconst ANSWER_FOR_MS = 2_000;\nconst answers = new Map<string, { at: number; work: BackgroundWork | null }>();\n\n/**\n * A background agent of this session's conversation is still at it after `sinceMs` (a turn's end) — it wrote since,\n * or that turn started it (lookForBackgroundWork) — and what it is (its own description; `what` null when it gives\n * none); null when there is none: that turn handed its work to it. Claude Code keeps each subagent's transcript in `<conversation>/subagents/agent-*.jsonl`\n * with a `.meta.json` beside it saying how it was asked for — `requestShape: \"background\"` runs on after the turn\n * that started it ends, and its end comes back as a new turn (a `<task-notification>`).\n */\nexport function backgroundWorkSince(session: WorktreeSession, sinceMs: number, now = Date.now()): BackgroundWork | null {\n const key = `${session.paths.join('|')}|${sinceMs}`;\n const kept = answers.get(key);\n if (kept && now - kept.at >= 0 && now - kept.at < ANSWER_FOR_MS) return kept.work;\n const work = lookForBackgroundWork(session, sinceMs, Math.max(sinceMs, now - AGENT_QUIET_MS), now - AGENT_QUIET_MS);\n if (answers.size > 200) answers.clear();\n answers.set(key, { at: now, work });\n return work;\n}\n\n/** An agent's own words for itself (its meta's `description`), on one line; null when it gives none. */\nfunction whatOf(meta: object): string | null {\n const d = (meta as { description?: unknown }).description;\n return typeof d === 'string' && d.trim() ? d.trim().replace(/\\s+/g, ' ') : null;\n}\n\n/**\n * A background subagent of a conversation written around `sinceMs` (the turn's end), still at it: written within the\n * quiet limit (after `afterMs` when it wrote since the turn ended), or — not written since — started for that turn\n * (its meta written in the minute before the turn ended: the turn started it, then ended; reported: a review just\n * started read Idle until its first write), and written within the quiet limit (`quietFrom`).\n */\nfunction lookForBackgroundWork(session: WorktreeSession, sinceMs: number, afterMs: number, quietFrom = afterMs): BackgroundWork | null {\n for (const t of listTranscripts(session)) {\n if (t.mtimeMs < sinceMs - AROUND_TURN_MS) continue;\n const dir = path.join(t.file.replace(/\\.jsonl$/, ''), 'subagents');\n let names: string[];\n try {\n names = fs.readdirSync(dir);\n } catch {\n continue; // no subagents in this one\n }\n for (const name of names) {\n if (!name.endsWith('.jsonl')) continue;\n const file = path.join(dir, name);\n try {\n const written = fs.statSync(file).mtimeMs;\n if (written <= quietFrom) continue;\n const metaFile = file.replace(/\\.jsonl$/, '.meta.json');\n const startedForTurn = fs.statSync(metaFile).mtimeMs >= sinceMs - AROUND_TURN_MS;\n if (written <= afterMs && !startedForTurn) continue;\n const meta: unknown = JSON.parse(fs.readFileSync(metaFile, 'utf8'));\n if (meta && typeof meta === 'object' && (meta as { requestShape?: unknown }).requestShape === 'background')\n return { what: whatOf(meta) };\n } catch {\n /* gone meanwhile, or no meta beside it: not one we can tell is in the background */\n }\n }\n }\n return null;\n}\n","import fs from 'node:fs';\n\n/**\n * Reading JSON-lines files — an agent's conversations (agents/: one JSON\n * value per line; what a line means is its adapter's). Only an end is read —\n * they get large — so the first line of a tail may be partial and is skipped.\n */\n\nexport const TAIL_BYTES = 256 * 1024;\n\n/** One line of a JSON-lines file: an object, as written (its meaning is the agent's). */\nexport type JsonLine = Record<string, unknown>;\n\nfunction parseLines(text: string): JsonLine[] {\n const out: JsonLine[] = [];\n for (const raw of text.split('\\n')) {\n const line = raw.trim();\n if (!line.startsWith('{')) continue;\n try {\n const entry = JSON.parse(line) as unknown;\n if (entry && typeof entry === 'object' && !Array.isArray(entry)) out.push(entry as JsonLine);\n } catch {\n // partial first line, or a line being written right now\n }\n }\n return out;\n}\n\n/** The lines in the last `bytes` of a file, oldest first. [] when unreadable. */\nexport function readJsonlTail(transcriptPath: string | undefined, bytes = TAIL_BYTES): JsonLine[] {\n if (!transcriptPath) return [];\n let text: string;\n try {\n const fd = fs.openSync(transcriptPath, 'r');\n try {\n const size = fs.fstatSync(fd).size;\n const start = Math.max(0, size - bytes);\n const buf = Buffer.alloc(size - start);\n fs.readSync(fd, buf, 0, buf.length, start);\n text = buf.toString('utf-8');\n } finally {\n fs.closeSync(fd);\n }\n } catch {\n return [];\n }\n return parseLines(text);\n}\n\nexport interface JsonlWindow {\n /** Oldest first; may start before `sinceMs` (the caller filters). */\n lines: JsonLine[];\n /** The file's earlier part was left unread: `maxBytes` ran out before an\n * entry older than `sinceMs` turned up, so earlier entries in the\n * window are missing. */\n partial: boolean;\n}\n\n/** First read; doubled until the window is covered. */\nexport const SINCE_CHUNK_BYTES = 2 * 1024 * 1024;\n/** The most one transcript is read for a window. */\nexport const SINCE_MAX_BYTES = 64 * 1024 * 1024;\n\n/**\n * Every line at or after `sinceMs`: reads the file from its end in growing\n * chunks until a line older than that shows up (or the file's start), so\n * a busy day's morning is never silently cut off by a fixed tail. Async —\n * the digest reads many of these per request and must not stall the\n * event loop (terminal relays, hooks). [] + not partial when unreadable.\n */\nexport async function readJsonlSince(\n transcriptPath: string,\n sinceMs: number,\n /** A line's time (ms; NaN when it has none) — the agent's (`lineTimeOf`). */\n timeOf: (line: JsonLine) => number,\n opts: { chunkBytes?: number; maxBytes?: number } = {},\n): Promise<JsonlWindow> {\n const chunk = Math.max(1, opts.chunkBytes ?? SINCE_CHUNK_BYTES);\n const max = Math.max(chunk, opts.maxBytes ?? SINCE_MAX_BYTES);\n let fh: fs.promises.FileHandle;\n try {\n fh = await fs.promises.open(transcriptPath, 'r');\n } catch {\n return { lines: [], partial: false };\n }\n try {\n const size = (await fh.stat()).size;\n let bytes = Math.min(chunk, size);\n for (;;) {\n const start = size - bytes;\n const buf = Buffer.alloc(bytes);\n await fh.read(buf, 0, bytes, start);\n const lines = parseLines(buf.toString('utf-8'));\n const earliest = lines.map(timeOf).find((ms) => Number.isFinite(ms));\n if (start === 0 || (earliest !== undefined && earliest < sinceMs)) return { lines, partial: false };\n if (bytes >= max) return { lines, partial: true };\n bytes = Math.min(size, bytes * 2, max);\n }\n } catch {\n return { lines: [], partial: false };\n } finally {\n await fh.close();\n }\n}\n","/**\n * The shape of Claude Code transcript lines, and reading their content —\n * pure, so the demo and the digest can use it without the file reader\n * (transcript.ts).\n */\n\n/** One transcript line, loosely typed: only the fields we read. */\nexport interface TranscriptEntry {\n type?: string;\n timestamp?: string;\n message?: {\n role?: string;\n id?: string;\n model?: string;\n content?: unknown;\n usage?: Record<string, unknown>;\n };\n [k: string]: unknown;\n}\n\n/** A content block of a message (text, tool_use, tool_result, …). */\nexport interface ContentBlock {\n type?: string;\n text?: string;\n id?: string;\n name?: string;\n input?: unknown;\n tool_use_id?: string;\n}\n\n/** A message's content as blocks (a plain string becomes one text block). */\nexport function contentBlocks(entry: TranscriptEntry): ContentBlock[] {\n const c = entry.message?.content;\n if (typeof c === 'string') return [{ type: 'text', text: c }];\n if (!Array.isArray(c)) return [];\n return c.filter((b): b is ContentBlock => !!b && typeof b === 'object');\n}\n","import { readJsonlTail, TAIL_BYTES } from '../../conversations/jsonl.js';\nimport type { TranscriptEntry } from './transcript-entry.js';\n\n/**\n * Claude Code's transcripts (`~/.claude/projects/<dir>/<id>.jsonl`): the\n * JSON-lines reader (jsonl.ts), typed as Claude's entries.\n */\n\nexport { contentBlocks, type ContentBlock, type TranscriptEntry } from './transcript-entry.js';\n\n/** The entries in the last `bytes` of a transcript, oldest first. [] when unreadable. */\nexport function readTranscriptTail(transcriptPath: string | undefined, bytes = TAIL_BYTES): TranscriptEntry[] {\n return readJsonlTail(transcriptPath, bytes) as TranscriptEntry[];\n}\n","import type { WorktreeSession } from '../../sessions/session-types.js';\nimport { listTranscripts } from './files.js';\nimport { readTranscriptTail } from './transcript.js';\n\n/**\n * Background commands a Claude conversation started and that haven't ended,\n * from its transcript — what keeps idle sleep away from a Claude whose prompt\n * is free while a build, a test run or a dev server it started goes on\n * (stopping the Claude stops those: they're its children).\n *\n * Claude Code writes a background command as a tool call with\n * `run_in_background`; its result says `Command running in background with\n * ID: <task id>`; its end comes back as a `<task-notification>` naming the\n * call (`<tool-use-id>`) and the task (`<task-id>`); a stop is a `TaskStop`\n * (`KillShell` / `KillBash` before) naming the task. Started, not ended, not\n * stopped: running. A call that failed (its result an error) never ran.\n *\n * `sinceMs`: only calls made after it — the Claude process's start: a\n * restarted Claude lost its old background commands without a word, and they\n * mustn't keep it awake forever. Pure; returns the calls' ids.\n */\nexport function openBackgroundCommands(lines: readonly unknown[], sinceMs = 0): string[] {\n return openBackgroundCommandInfo(lines, sinceMs).map((c) => c.id);\n}\n\n/** What a background call is, in a line: the agent's own description of it, else the command's first line. */\nfunction whatOf(input: Record<string, unknown>): string | null {\n const pick = [input.description, input.command].find((v): v is string => typeof v === 'string' && !!v.trim());\n if (!pick) return null;\n const line = pick.trim().split(/\\r?\\n/)[0].replace(/\\s+/g, ' ');\n return line.length > 100 ? `${line.slice(0, 99)}…` : line;\n}\n\n/** The same, with what each one is (`what`: its description, else its command; null when it gives neither), in the order started. */\nexport function openBackgroundCommandInfo(lines: readonly unknown[], sinceMs = 0): { id: string; what: string | null }[] {\n const started = new Map<string, string | null>(); // tool-use id → task id\n const whats = new Map<string, string | null>();\n const ended = new Set<string>(); // tool-use ids\n const endedTasks = new Set<string>();\n for (const line of lines) {\n if (!line || typeof line !== 'object') continue;\n const l = line as { type?: unknown; timestamp?: unknown; message?: { content?: unknown } };\n // An end notice counts wherever Claude Code wrote it: queued (`queue-operation`, a `queued_command`\n // attachment), delivered in a message, or in an `api-request-blob` — one finished command's was only there.\n const raw = JSON.stringify(line);\n if (raw.includes('<task-notification>')) {\n for (const m of raw.matchAll(/<tool-use-id>\\s*([^<\\s\\\\\"]+)/g)) ended.add(m[1]);\n for (const m of raw.matchAll(/<task-id>\\s*([^<\\s\\\\\"]+)/g)) endedTasks.add(m[1]);\n }\n // Starts and results from the conversation's own lines only: the `api-request-blob` copies of earlier messages\n // made a call stopped since read as started again (59 of 259 looked open in a real transcript).\n if (l.type !== 'user' && l.type !== 'assistant') continue;\n const at = typeof l.timestamp === 'string' ? Date.parse(l.timestamp) : NaN;\n const content = l.message?.content;\n const blocks: unknown[] = Array.isArray(content) ? content : typeof content === 'string' ? [{ type: 'text', text: content }] : [];\n for (const b of blocks) {\n if (!b || typeof b !== 'object') continue;\n const block = b as {\n type?: unknown;\n id?: unknown;\n name?: unknown;\n input?: unknown;\n tool_use_id?: unknown;\n content?: unknown;\n is_error?: unknown;\n text?: unknown;\n };\n const input = (block.input ?? {}) as Record<string, unknown>;\n if (block.type === 'tool_use' && typeof block.id === 'string') {\n const bg = input.run_in_background;\n // Seen again (a resumed conversation repeats it): what's known of it stays.\n if ((bg === true || bg === 'true') && !(at < sinceMs) && !started.has(block.id)) {\n started.set(block.id, null);\n whats.set(block.id, whatOf(input));\n }\n if (block.name === 'TaskStop' || block.name === 'KillShell' || block.name === 'KillBash') {\n for (const k of ['task_id', 'shell_id', 'bash_id']) if (typeof input[k] === 'string') endedTasks.add(input[k] as string);\n }\n }\n if (block.type === 'tool_result' && typeof block.tool_use_id === 'string' && started.has(block.tool_use_id)) {\n if (block.is_error === true) ended.add(block.tool_use_id);\n const text = typeof block.content === 'string' ? block.content : JSON.stringify(block.content ?? '');\n const task = /running in background with ID:\\s*([A-Za-z0-9_-]+)/.exec(text)?.[1];\n if (task) started.set(block.tool_use_id, task);\n }\n }\n }\n return [...started]\n .filter(([use, task]) => !ended.has(use) && !(task && endedTasks.has(task)))\n .map(([use]) => ({ id: use, what: whats.get(use) ?? null }));\n}\n\n/** How much of the newest transcript is read: a long session's start may be beyond it (the process check covers that). */\nconst TAIL_BYTES = 4 * 1024 * 1024;\n\n/** Background commands the session's newest conversation started since `sinceMs` and that are still running. */\nexport function backgroundCommandsRunning(session: WorktreeSession, sinceMs: number): number {\n return openIn(session, sinceMs).length;\n}\n\n/** What those are, newest first (one that says nothing of itself left out): \"Run the backend tests\". */\nexport function backgroundCommandNames(session: WorktreeSession, sinceMs: number): string[] {\n return openIn(session, sinceMs)\n .map((c) => c.what)\n .filter((w): w is string => !!w)\n .reverse();\n}\n\n/** The last answer per conversation file: the session list asks while a command runs, and the tail is megabytes. */\nconst kept = new Map<string, { size: number; mtimeMs: number; sinceMs: number; open: { id: string; what: string | null }[] }>();\n\nfunction openIn(session: WorktreeSession, sinceMs: number): { id: string; what: string | null }[] {\n const newest = listTranscripts(session).sort((a, b) => b.mtimeMs - a.mtimeMs)[0];\n if (!newest || newest.mtimeMs < sinceMs) return [];\n const had = kept.get(newest.file);\n if (had && had.size === newest.size && had.mtimeMs === newest.mtimeMs && had.sinceMs === sinceMs) return had.open;\n const open = openBackgroundCommandInfo(readTranscriptTail(newest.file, TAIL_BYTES), sinceMs);\n if (kept.size > 200) kept.clear();\n kept.set(newest.file, { size: newest.size, mtimeMs: newest.mtimeMs, sinceMs, open });\n return open;\n}\n","import type { ConversationPrLink } from '../types.js';\n\n/**\n * The pull requests a stretch of a Claude Code transcript names as its session's: Claude Code writes a\n * `{\"type\":\"pr-link\",\"prNumber\":…,\"prUrl\":…,\"prRepository\":\"owner/name\",\"timestamp\":…}` line whenever its session\n * makes a PR or works on one (again each time it looks at it, so one PR has many). Each PR once here, in the order\n * first seen. Lines are looked at only when they mention `pr-link` (a transcript is mostly other lines, megabytes of\n * them); a line that doesn't parse — cut at a chunk's edge — is skipped: the same PR is linked again later. Pure.\n */\nexport function claudePrLinks(text: string): ConversationPrLink[] {\n const out = new Map<string, ConversationPrLink>();\n let from = 0;\n for (;;) {\n const hit = text.indexOf('\"pr-link\"', from);\n if (hit < 0) break;\n const start = text.lastIndexOf('\\n', hit) + 1;\n const nl = text.indexOf('\\n', hit);\n const end = nl < 0 ? text.length : nl;\n from = end + 1;\n let o: unknown;\n try {\n o = JSON.parse(text.slice(start, end));\n } catch {\n continue;\n }\n const e = o as { type?: unknown; prNumber?: unknown; prUrl?: unknown; prRepository?: unknown; timestamp?: unknown } | null;\n if (!e || e.type !== 'pr-link') continue;\n if (typeof e.prUrl !== 'string' || !/^https?:\\/\\//i.test(e.prUrl) || e.prUrl.length > 500) continue;\n if (typeof e.prNumber !== 'number' || !Number.isInteger(e.prNumber) || e.prNumber <= 0) continue;\n if (out.has(e.prUrl)) continue;\n out.set(e.prUrl, {\n url: e.prUrl,\n number: e.prNumber,\n repo: typeof e.prRepository === 'string' && e.prRepository.length <= 200 ? e.prRepository : '',\n ...(typeof e.timestamp === 'string' && Number.isFinite(Date.parse(e.timestamp)) ? { at: e.timestamp } : {}),\n });\n }\n return [...out.values()];\n}\n","import { contentBlocks, type TranscriptEntry } from './transcript-entry.js';\nimport type { ConversationEntry } from '../types.js';\n\n/**\n * Claude Code's transcript lines (~/.claude/projects/<folder>/<id>.jsonl) as\n * conversation entries (types.ts) — the one place work reads Claude's line\n * format. Pure (no I/O): shared by everything that reads a conversation.\n */\n\n/** Text Claude Code writes as a \"user\" line that you didn't type: slash\n * command echoes, the local-command caveat, subagent task notifications,\n * the \"[Request interrupted by user]\" marker. */\nconst NOT_TYPED =\n /^\\s*(<command-name>|<command-message>|<local-command-|<system-reminder>|<bash-|<task-notification>|\\[Request interrupted|Caveat: )/;\n\n/** The text you typed, when this line is one of your prompts (not a tool result, echo, meta or subagent line). */\nexport function promptText(e: TranscriptEntry): string | null {\n if (e.type !== 'user' || e.isSidechain === true || e.isMeta === true) return null;\n const blocks = contentBlocks(e);\n // A tool result is Claude's own loop, not you.\n if (blocks.some((b) => b.type === 'tool_result')) return null;\n const text = blocks\n .filter((b) => b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim();\n if (!text || NOT_TYPED.test(text)) return null;\n return text;\n}\n\nconst MAX_TOOL_DETAIL = 400;\n\nfunction str(input: unknown, key: string): string | undefined {\n const v = (input as Record<string, unknown> | null)?.[key];\n return typeof v === 'string' && v.trim() ? v : undefined;\n}\n\n/** The part of a tool call a person needs to judge it. */\nexport function describeToolUse(tool: string, input: unknown): string {\n const detail =\n (tool === 'Bash' || tool === 'PowerShell' ? str(input, 'command') : undefined) ??\n str(input, 'file_path') ??\n str(input, 'notebook_path') ??\n str(input, 'url') ??\n str(input, 'query') ??\n str(input, 'pattern') ??\n str(input, 'description') ??\n (input && typeof input === 'object' ? JSON.stringify(input) : '');\n const flat = detail.replace(/\\s*\\r?\\n\\s*/g, ' ⏎ ').trim();\n return flat.length > MAX_TOOL_DETAIL ? flat.slice(0, MAX_TOOL_DETAIL - 1) + '…' : flat;\n}\n\nconst num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);\n\n/**\n * A slash command you typed between turns (`/model`, `/clear`, `/exit`,\n * `/compact`) and its output: written as user lines, but no turn — Claude\n * doesn't work on them. A `!` command (`<bash-input>`) and a background\n * task's result (`<task-notification>`) are turns.\n */\nfunction isCommandEcho(e: TranscriptEntry): boolean {\n const text = contentBlocks(e)\n .map((b) => (typeof b.text === 'string' ? b.text : ''))\n .join('')\n .trimStart();\n return /^<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat)>/.test(text);\n}\n\n/** Claude Code's own lines: meta, a compaction summary, one shown only in the transcript view. */\nconst isMetaLine = (e: TranscriptEntry) => e.isMeta === true || e.isCompactSummary === true || e.isVisibleInTranscriptOnly === true;\n\n/** One transcript line's entries: each line gives at least one. One with no time keeps `at: ''` (search and context usage read it; what counts time skips it). */\nfunction lineEntries(e: TranscriptEntry): ConversationEntry[] {\n const at = typeof e.timestamp === 'string' ? e.timestamp : '';\n const meta = isMetaLine(e);\n const base = {\n at,\n ...(typeof e.uuid === 'string' && e.uuid ? { id: e.uuid } : {}),\n ...(e.isSidechain === true ? { sidechain: true as const } : {}),\n ...(meta ? { meta: true as const } : {}),\n };\n // A compaction summary is written as a user line, but you didn't type it.\n const prompt = meta ? null : promptText(e);\n if (prompt) return [{ ...base, role: 'you', text: prompt }];\n const blocks = contentBlocks(e);\n if (e.type === 'user' && blocks.some((b) => b.type === 'tool_result')) return [{ ...base, role: 'tool-result', text: '' }];\n // Any other line of yours that isn't a slash command's echo is a turn's work: a `!` command, its output, a task's result.\n if (e.type === 'user') return [{ ...base, role: 'other', text: '', ...(!meta && !isCommandEcho(e) ? { turn: true as const } : {}) }];\n if (e.type !== 'assistant') return [{ ...base, role: 'other', text: '' }];\n\n const out: ConversationEntry[] = [];\n const text = blocks\n .filter((b) => b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim();\n const u = e.message?.usage;\n const usage =\n u && typeof u === 'object'\n ? {\n prompt: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens),\n reply: num(u.output_tokens),\n ...(num(u.cache_read_input_tokens) ? { cached: num(u.cache_read_input_tokens) } : {}),\n }\n : null;\n const model = typeof e.message?.model === 'string' ? e.message.model : undefined;\n const messageId = typeof e.message?.id === 'string' && e.message.id ? e.message.id : undefined;\n // A meta line (Claude Code's own) is Claude's line for work time, but no message of its.\n out.push({\n ...base,\n role: 'agent',\n text: meta ? '' : text,\n ...(usage && usage.prompt + usage.reply > 0 ? { usage } : {}),\n ...(model ? { model } : {}),\n ...(messageId ? { message: messageId } : {}),\n });\n for (const b of blocks) {\n if (b.type === 'tool_use' && typeof b.name === 'string')\n out.push({ ...base, role: 'tool', tool: b.name, text: describeToolUse(b.name, b.input) });\n }\n return out;\n}\n\n/** Claude transcript lines (parsed JSON, in file order) as conversation entries. */\nexport function claudeEntries(lines: readonly unknown[]): ConversationEntry[] {\n const out: ConversationEntry[] = [];\n for (const l of lines) if (l && typeof l === 'object') out.push(...lineEntries(l as TranscriptEntry));\n return out;\n}\n\n/**\n * A Claude conversation's window: 1M, as every current model has it as it comes (Opus and Sonnet 4.6 and later,\n * Haiku 5.5, Fable, Mythos), or 200k for the older models (`SMALL_MODELS`) — unless the id says `[1m]` or the\n * usage is more than 200k could hold. The transcript names the model and nothing more, so this decides it: Opus\n * 5.5 at 190k read as \"96% full\" while Claude Code's own line said 19%, and Fable 5.2 at 163k as 82%.\n */\nexport const SMALL_WINDOW = 200_000;\nexport const LARGE_WINDOW = 1_000_000;\n/** The 200k models: Claude 3.x (`claude-3-7-sonnet-…`) and Opus/Sonnet/Haiku 4 up to 4.5 (`claude-opus-4-…`,\n * `claude-opus-4-1`, `claude-sonnet-4-5-…`, `claude-haiku-4-5-…`), also on Bedrock (`us.anthropic.claude-sonnet-4-5-…-v1:0`)\n * and Vertex (`claude-sonnet-4-5@…`). 4.6 and later are 1M. */\nconst SMALL_MODELS = /(^|[./:])claude-(?:[1-3](?!\\d)|(?:opus|sonnet|haiku)-4(?:-[0-5])?(?!\\d|-[6-9]))/i;\nexport function claudeContextWindow(model: string | undefined, used: number): number {\n if (used > SMALL_WINDOW || (model && /\\[1m\\]/i.test(model))) return LARGE_WINDOW;\n return model && SMALL_MODELS.test(model) ? SMALL_WINDOW : LARGE_WINDOW;\n}\n","import path from 'node:path';\nimport { setUpAccounts } from './accounts.js';\nimport { pendingToolUse } from './permission.js';\nimport { contentBlocks, readTranscriptTail } from './transcript.js';\nimport type { StatusEvent } from '../../status/status-event.js';\nimport type { AgentEvents, TurnEdge } from '../types.js';\nimport { BRIDGE_OWNER, RETIRED_HOOK_OWNERS, SESSION_HOOKS } from '../session-hooks.js';\n\n/**\n * Claude Code's side of work's hooks (types.ts `AgentEvents`): the JSON Claude Code sends them on stdin, and how notes\n * go back. The hooks themselves come with each Claude work starts (session-settings.ts, `--settings`); what work web\n * once wrote into ~/.claude/settings.json and each account's is taken out (`removeInstalled`).\n *\n * The installer (and its file lock) is loaded only to clean up: every hook process imports this adapter, on every turn\n * edge, and reading a payload needs none of it.\n */\n\ntype Installer = typeof import('../../platform/command-hook-installer.js');\nlet installer: Installer | null = null;\nconst loadInstaller = async (): Promise<Installer> => (installer ??= await import('../../platform/command-hook-installer.js'));\n\n/** Claude Code's hook event for each of work's turn edges. */\nexport const CLAUDE_EVENT: Record<TurnEdge, string> = {\n 'turn-start': 'UserPromptSubmit',\n 'turn-end': 'Stop',\n notify: 'Notification',\n};\n\n/** What Claude Code sends a hook on stdin (the fields work reads). */\ninterface ClaudeHookPayload {\n cwd?: string;\n /** UserPromptSubmit */\n prompt?: string;\n /** Notification */\n message?: string;\n /** Notification: permission_prompt, idle_prompt, elicitation_dialog, auth_success… */\n notification_type?: string;\n /** Stop (and others): the conversation's JSONL transcript. */\n transcript_path?: string;\n}\n\nconst asPayload = (p: unknown): ClaudeHookPayload => (p && typeof p === 'object' ? (p as ClaudeHookPayload) : {});\nconst str = (v: unknown) => (typeof v === 'string' ? v : undefined);\n\n/** A Claude hook payload as a status event (the turn edge it came from known). */\n/**\n * Text of the last assistant message in a Claude Code transcript, for the\n * \"done\" summary. Null when unreadable or there's no assistant text yet.\n */\nexport function lastAssistantText(transcriptPath: string | undefined): string | null {\n const entries = readTranscriptTail(transcriptPath);\n for (let i = entries.length - 1; i >= 0; i--) {\n if (entries[i].type !== 'assistant') continue;\n const text = contentBlocks(entries[i])\n .filter((b) => b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text)\n .join('\\n')\n .trim();\n if (text) return text;\n }\n return null;\n}\n\nexport function claudeStatusEvent(edge: TurnEdge, payload: unknown): StatusEvent | null {\n const p = asPayload(payload);\n switch (edge) {\n case 'turn-start':\n return { kind: 'prompt', prompt: str(p.prompt) };\n case 'turn-end':\n return { kind: 'stop', lastMessage: lastAssistantText(str(p.transcript_path)) ?? undefined };\n case 'notify': {\n // Which call the permission prompt is about: the transcript has it,\n // the hook message only names the tool.\n const request = pendingToolUse(readTranscriptTail(str(p.transcript_path)));\n const type = str(p.notification_type);\n return { kind: 'notification', message: str(p.message), ...(type ? { type } : {}), ...(request ? { request } : {}) };\n }\n }\n}\n\nconst toClaude = (h: { owner: string; edge: TurnEdge }) => ({ owner: h.owner, event: CLAUDE_EVENT[h.edge] });\n\n/** Every account's settings file: the default's first (`~/.claude/settings.json`); a configured account's only once its folder exists. */\nconst settingsFiles = (): string[] => setUpAccounts().map((a) => path.join(a.dir, 'settings.json'));\n\nexport const claudeEvents: AgentEvents = {\n removeInstalled: async (hooks) => {\n const inst = await loadInstaller();\n // One account's file that can't be written is reported by the editor and doesn't keep the others from being cleaned.\n for (const file of settingsFiles()) await inst.removeCommandHooks(hooks.map(toClaude), file);\n },\n bridge: async () => {\n const inst = await loadInstaller();\n const { workCommand } = await import('../../platform/work-command.js');\n const add = SESSION_HOOKS.map((h) => ({\n owner: BRIDGE_OWNER[h.edge],\n event: CLAUDE_EVENT[h.edge],\n // Word for word what session-settings.ts gives: a Claude with both runs it once.\n command: workCommand(['hook', h.event]),\n timeoutSec: h.timeoutSec,\n }));\n // The other retired owners' entries (a lean server's checkpoint hooks, the separate ones of before) go meanwhile.\n const kept = new Set(add.map((a) => `${a.owner} ${a.event}`));\n const remove = RETIRED_HOOK_OWNERS.map(toClaude).filter((r) => !kept.has(`${r.owner} ${r.event}`));\n for (const file of settingsFiles()) await inst.syncCommandHooks(add, remove, file);\n },\n read: (edge, payload) => ({ cwd: str(asPayload(payload).cwd), status: claudeStatusEvent(edge, payload) }),\n // turn-start: stdout is added to the prompt. turn-end: `decision: block`\n // keeps Claude in the turn and feeds `reason` back to it.\n handOver: (edge, text) => (edge === 'turn-start' ? text + '\\n' : JSON.stringify({ decision: 'block', reason: text }) + '\\n'),\n};\n","import path from 'node:path';\nimport { contentBlocks, type TranscriptEntry } from './transcript.js';\nimport type { PermissionRequest } from '../../api-types.js';\n\nexport type { PermissionRequest } from '../../api-types.js';\n\n/**\n * \"Claude needs your permission to use Bash\" says which tool, not what it\n * wants to run. The transcript does: the tool call Claude is blocked on is\n * the newest `tool_use` with no `tool_result` yet. That is what the inbox\n * shows next to Allow / Deny, so you approve the command, not the tool.\n */\n\n// The part of a tool call a person needs to judge it: claude-entries.ts (one reader of Claude's lines).\nexport { describeToolUse } from './entries.js';\nimport { describeToolUse } from './entries.js';\n\n/**\n * The tool call Claude is waiting on, or null. With parallel calls Claude\n * Code asks about them in order, so it is the first unanswered call of the\n * newest assistant run (older unanswered calls belong to interrupted turns).\n */\nexport function pendingToolUse(entries: TranscriptEntry[]): PermissionRequest | null {\n const answered = new Set<string>();\n for (const e of entries) {\n for (const b of contentBlocks(e)) {\n if (b.type === 'tool_result' && typeof b.tool_use_id === 'string') answered.add(b.tool_use_id);\n }\n }\n let found: PermissionRequest | null = null;\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i];\n if (e.type === 'user') {\n if (found) break; // start of the run that holds the newest pending call\n continue;\n }\n if (e.type !== 'assistant') continue;\n const blocks = contentBlocks(e);\n for (let j = blocks.length - 1; j >= 0; j--) {\n const b = blocks[j];\n if (b.type !== 'tool_use' || typeof b.name !== 'string') continue;\n if (typeof b.id === 'string' && answered.has(b.id)) continue;\n found = { tool: b.name, detail: describeToolUse(b.name, b.input) };\n }\n }\n return found;\n}\n\n// ---- the dialog on screen -----------------------------------------------\n\n/** Claude Code's permission dialog: a \"Do you want to …?\" question over a\n * numbered menu whose first option is Yes. */\nconst QUESTION_RE = /Do you want to\\b/;\nconst YES_SELECTED_RE = /❯\\s*1\\.\\s*Yes\\b/;\n\n/** Whitespace and box-drawing borders go: the dialog is drawn in a box,\n * so a wrapped command reads \"…permission-│\\n│ request.ts…\". */\nconst squash = (s: string) => s.replace(/[\\s\\u2500-\\u257f]+/g, '');\n\n/** Text that must be on screen for the dialog to be about THIS request:\n * the start of the command (terminal wrapping only breaks it at spaces we\n * squash away), or the file name. */\nexport function screenAnchor(req: PermissionRequest): string {\n if (req.tool === 'Bash' || req.tool === 'PowerShell') return squash(req.detail.split(' ⏎ ')[0]).slice(0, 40);\n if (/[\\\\/]/.test(req.detail) && !/^https?:/.test(req.detail)) return path.basename(req.detail.replace(/\\\\/g, '/'));\n return '';\n}\n\nexport type { DialogCheck } from '../types.js';\nimport type { DialogCheck } from '../types.js';\n\n/**\n * May we answer by keystroke? Only while the screen shows the permission\n * dialog, for the request the user was shown, with \"1. Yes\" highlighted\n * (so Enter means Yes). Anything else — already answered, a different\n * prompt, the user moved the cursor in their terminal — and we don't type.\n */\nexport function checkDialog(screen: string, req: PermissionRequest): DialogCheck {\n if (!QUESTION_RE.test(screen)) return { ok: false, reason: 'no-dialog' };\n const anchor = screenAnchor(req);\n if (anchor && !squash(screen).includes(anchor)) return { ok: false, reason: 'other-request' };\n if (!YES_SELECTED_RE.test(screen)) return { ok: false, reason: 'not-default' };\n return { ok: true };\n}\n\n/** Keys that answer the dialog: Enter on the highlighted Yes; Esc is Claude\n * Code's \"No, and tell Claude what to do differently\". */\nexport const ANSWER_KEYS = { allow: '\\r', deny: '\\x1b' } as const;\nexport type PermissionAnswer = keyof typeof ANSWER_KEYS;\n","import type { TurnEdge } from './types.js';\n\n/**\n * work's hooks, as every session's agent runs them: one per turn edge — `turn-start` (seal the checkpoint step,\n * record \"working\", attach pending comments), `turn-end` (checkpoint, record \"done\", deliver) — and the notification\n * (permission prompts). Given to the agents work starts, never written into the user's own settings: a Claude work\n * didn't start (another project, a plain `claude`) runs none of them (Claude's: session-settings.ts, `--settings`).\n */\nexport interface SessionHook {\n edge: TurnEdge;\n /** `work hook <event>`. */\n event: string;\n timeoutSec: number;\n}\n\nexport const SESSION_HOOKS: readonly SessionHook[] = [\n { edge: 'turn-start', event: 'turn-start', timeoutSec: 10 },\n { edge: 'turn-end', event: 'turn-end', timeoutSec: 10 },\n { edge: 'notify', event: 'status-notify', timeoutSec: 5 },\n];\n\n/** The owner a bridged hook (`AgentEvents.bridge`) is written under: one of the retired ones, so their removal takes it. */\nexport const BRIDGE_OWNER: Record<TurnEdge, string> = { 'turn-start': 'web-turn', 'turn-end': 'web-turn', notify: 'web-status' };\n\n/**\n * The hooks work web once wrote into the user's own settings (every owner it used, at every edge): taken out at its\n * start, since the agents it starts carry their own now — left there, every other Claude on the machine ran them, with\n * whatever `work` its PATH found (an old one printed its usage as a hook error on every turn).\n */\nexport const RETIRED_HOOK_OWNERS: ReadonlyArray<{ owner: string; edge: TurnEdge }> = [\n 'web',\n 'web-turn',\n 'web-status',\n 'web-checkpoint',\n].flatMap((owner) => (['turn-start', 'turn-end', 'notify'] as const).map((edge) => ({ owner, edge })));\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from '../../platform/config-dir.js';\nimport { atomicWriteFile } from '../../platform/fs-safe.js';\nimport { loadConfig } from '../../platform/config.js';\nimport { workCommand, type WorkInvocationDeps } from '../../platform/work-command.js';\nimport type { AiToolSpec } from '../../platform/ai-launcher.js';\nimport { SESSION_HOOKS } from '../session-hooks.js';\nimport { CLAUDE_EVENT } from './hooks.js';\n\n/**\n * work's hooks and status line for the Claudes work starts, and only those: a settings file of work's own\n * (`~/.work/claude-settings.json`) handed to each with `claude --settings <it>`. Claude Code adds hooks from it to the\n * user's and the project's (measured: a UserPromptSubmit hook in each ran), and its status line takes the place of the\n * user's for that process — the hook runs the user's own after recording the plan limits (statusline-hook.ts).\n *\n * Before, work web wrote them into `~/.claude/settings.json` (and each account's): every Claude on the machine ran\n * them, with whatever `work` its PATH found first, and the file — often in a dotfiles repo — changed at each start.\n *\n * Each command names the work that wrote the file (work-command.ts), so the hooks run the build that knows their names.\n * Written again at every spawn (the PTY host's, or a launch in a terminal): after an update it names the new one.\n */\n\nexport const SESSION_SETTINGS_NAME = 'claude-settings.json';\n\n/** What the Claudes work starts may run without asking: only what work itself confines (see claudeSessionSettings). */\nexport const SESSION_ALLOW: readonly string[] = ['Bash(work child:*)', 'Bash(work report:*)'];\n\nexport const sessionSettingsPath = (): string => path.join(getConfigDir(), SESSION_SETTINGS_NAME);\n\n/** The settings themselves. `statusLine: false` (config `usage.statusLine: false`): the user's own line, untouched. */\nexport function claudeSessionSettings(o: { statusLine: boolean; invocation?: WorkInvocationDeps }): Record<string, unknown> {\n const hooks: Record<string, unknown[]> = {};\n for (const h of SESSION_HOOKS) {\n (hooks[CLAUDE_EVENT[h.edge]] ??= []).push({\n hooks: [{ type: 'command', command: workCommand(['hook', h.event], o.invocation), timeout: h.timeoutSec }],\n });\n }\n // Claude's alone (no turn edge): a conversation's start tells it that it runs in work (work-intro.ts).\n hooks.SessionStart = [{ hooks: [{ type: 'command', command: workCommand(['hook', 'session-start'], o.invocation), timeout: 10 }] }];\n // …and its exit: a turn or question it was in is over (session-status.ts markAgentEnded).\n hooks.SessionEnd = [{ hooks: [{ type: 'command', command: workCommand(['hook', 'session-end'], o.invocation), timeout: 10 }] }];\n // …and a turn an API error ended (StopFailure, fired instead of Stop): it isn't working any more (hook.ts turnFailed).\n hooks.StopFailure = [{ hooks: [{ type: 'command', command: workCommand(['hook', 'stop-failure'], o.invocation), timeout: 10 }] }];\n return {\n hooks,\n // A coordinator's own sessions (session-children.ts): `work child` acts only on the sessions the one running it\n // started, and only once you granted it (`work coordinate --on`, never allowed here: Claude running it asks you);\n // `work report` reaches only the session that started this one. Everything else that drives another session\n // (`work send / stop / answer`) keeps asking.\n permissions: { allow: [...SESSION_ALLOW] },\n ...(o.statusLine ? { statusLine: { type: 'command', command: workCommand(['hook', 'statusline'], o.invocation) } } : {}),\n };\n}\n\n/** Write the file when it differs from what's there (a spawn mustn't rewrite it for nothing); its path. */\nexport function writeSessionSettings(o: { statusLine?: boolean; invocation?: WorkInvocationDeps } = {}): string {\n const file = sessionSettingsPath();\n const config = loadConfig();\n // work's own line, when chosen, needs the hook even with the limits' reading turned off.\n const statusLine = o.statusLine ?? (config?.usage?.statusLine !== false || config?.claudeStatusLine === 'work');\n const text = JSON.stringify(claudeSessionSettings({ statusLine, invocation: o.invocation }), null, 2) + '\\n';\n let now: string | null = null;\n try {\n now = fs.readFileSync(file, 'utf-8');\n } catch {\n /* not there yet */\n }\n if (now !== text) {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n atomicWriteFile(file, text);\n }\n return file;\n}\n\nconst isOurs = (p: string | undefined) => !!p && path.basename(p) === SESSION_SETTINGS_NAME;\n\n/** The file to name: written when `write` (the default), or when it isn't there yet (a Claude given a missing file won't start). */\nexport function sessionSettingsFile(o: { write?: boolean } = {}): string {\n const file = sessionSettingsPath();\n return o.write === false && fs.existsSync(file) ? file : writeSessionSettings();\n}\n\n/** A Claude's command line names work's file: it was started with work's hooks. */\nexport const startedWithSessionSettings = (commandLine: string): boolean => commandLine.includes(SESSION_SETTINGS_NAME);\n\n/**\n * The tool as work starts it for a session: `--settings <work's file>` first, once — an older one (a restore entry\n * written before, or under another home) replaced. `file`: tests.\n */\nexport function withSessionSettings(tool: AiToolSpec, file: string = sessionSettingsFile()): AiToolSpec {\n const rest: string[] = [];\n for (let i = 0; i < tool.baseArgs.length; i++) {\n if (tool.baseArgs[i] === '--settings' && isOurs(tool.baseArgs[i + 1])) {\n i++;\n continue;\n }\n rest.push(tool.baseArgs[i]!);\n }\n return { ...tool, baseArgs: ['--settings', file, ...rest] };\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { bootTime, processTable } from '../../platform/process.js';\nimport { claudeAccounts } from './accounts.js';\nimport type { LiveAgent } from '../types.js';\n\n/**\n * Claude Code's running processes (the Claude adapter's `live`): which\n * Claudes are running right now, wherever they were started — your\n * terminal tabs included, which the dashboard otherwise only knows about\n * through hooks and transcript writes (an idle one produces neither).\n *\n * Claude Code keeps a file per running interactive/headless Claude in\n * ~/.claude/sessions/<pid>.json (pid, conversation id, cwd, busy/idle).\n * That is Claude Code's own file, not a documented interface, so it is read\n * defensively: anything without the fields we need is skipped, and if the\n * format changes the signal just goes quiet — nothing else depends on it.\n * A pid is believed only if a process with a Claude-ish name runs under it\n * and the file was written since this boot (pids are reused, fast on\n * Windows — §1.6).\n */\n\ntype LiveClaude = LiveAgent;\n\ntype Obj = Record<string, unknown>;\nconst isObj = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v);\n\n/** One ~/.claude/sessions/<pid>.json, or null if it lacks what we need. */\nexport function parseLiveClaude(raw: unknown): LiveClaude | null {\n if (!isObj(raw)) return null;\n const { pid, sessionId, cwd, status, startedAt, statusUpdatedAt, waitingFor } = raw;\n if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return null;\n if (typeof sessionId !== 'string' || !sessionId || typeof cwd !== 'string' || !cwd) return null;\n return {\n pid,\n conversationId: sessionId,\n cwd,\n busy: status === 'busy',\n // `shell`: its prompt is free while a background command it started (a build, tests, a dev server) still runs.\n state: status === 'busy' || status === 'idle' || status === 'waiting' || status === 'shell' ? status : null,\n stateAt: typeof statusUpdatedAt === 'number' ? statusUpdatedAt : null,\n waitingFor: typeof waitingFor === 'string' && waitingFor ? waitingFor : null,\n startedAt: typeof startedAt === 'number' ? startedAt : null,\n };\n}\n\n/** The executable a running Claude shows up as (native build, or via node). */\nconst CLAUDE_EXE = /^(claude|node)(\\.exe)?$/i;\n\n/** Keep the ones whose pid is a live Claude started since this boot. */\nexport function aliveOnly(list: LiveClaude[], table: ReadonlyMap<number, string>, bootMs: number): LiveClaude[] {\n return list.filter((c) => {\n const name = table.get(c.pid);\n if (!name || !CLAUDE_EXE.test(name)) return false;\n return c.startedAt === null || c.startedAt >= bootMs - 60_000;\n });\n}\n\n// ------------------------------------------------------------------ reading\n\nconst TTL_MS = 5000;\nlet cache: { at: number; key: string; list: LiveClaude[] } | null = null;\n\nexport function claudeSessionsDir(): string {\n return path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'sessions');\n}\n\n/**\n * Where running Claudes write their process files: every account's `sessions/` folder. With no account configured it is\n * the one folder it always was (`claudeSessionsDir`, which follows a `CLAUDE_CONFIG_DIR` the user set themselves).\n */\nexport function claudeSessionsDirs(): string[] {\n const accounts = claudeAccounts();\n if (accounts.length <= 1) return [claudeSessionsDir()];\n return [...new Set(accounts.map((a) => path.join(a.dir, 'sessions')))];\n}\n\n/** One folder's process files that are live Claudes. */\nfunction readDir(dir: string, table: () => ReadonlyMap<number, string>): LiveClaude[] {\n let names: string[];\n try {\n names = fs.readdirSync(dir).filter((n) => /^\\d+\\.json$/.test(n));\n } catch {\n return [];\n }\n const parsed: LiveClaude[] = [];\n for (const n of names) {\n try {\n const c = parseLiveClaude(JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8')) as unknown);\n if (c) parsed.push(c);\n } catch {\n /* half-written or not ours: skip */\n }\n }\n return parsed.length ? aliveOnly(parsed, table(), bootTime()) : [];\n}\n\n/**\n * The running Claudes (cached for a few seconds: this lists every process), of every account — or of one `dir` when\n * given. With `table`, a process table the caller already has (the session list's background one): read against it,\n * and neither read nor written to the cache — the guard against a second Claude keeps its own, synchronous view.\n */\nexport function readLiveClaudes(dir?: string, now = Date.now(), table?: ReadonlyMap<number, string>): LiveClaude[] {\n const dirs = dir ? [dir] : claudeSessionsDirs();\n const key = dirs.join('|');\n // Only the whole list is cached; one folder asked for by name is read as it is.\n const cached = !table && !dir;\n if (cached && cache && now - cache.at < TTL_MS && cache.key === key) return cache.list;\n // The process table is read once, and only when a folder has a process file to check.\n let procs: ReadonlyMap<number, string> | undefined = table;\n const procTable = () => (procs ??= processTable());\n const list = dirs.flatMap((d) => readDir(d, procTable));\n if (cached) cache = { at: now, key, list };\n return list;\n}\n","import type { AgentInput } from './types.js';\n\n/** Between the text and Enter: Claude Code (and others) read a burst of input as a paste, and a `\\r` in it as part of the paste. */\nexport const SUBMIT_DELAY_MS = 250;\n\n/**\n * Type `text` into a terminal prompt and submit it: the text, a pause, then\n * Enter as `\\r` (what the Enter key sends; a `\\n` only adds a line to the\n * prompt, which left every pushed note sitting unsent in the input box),\n * written apart from the text.\n */\nexport const typeThenEnter: AgentInput['submit'] = async (write, text, wait = (ms) => new Promise((r) => setTimeout(r, ms))) => {\n if (!(await write(text))) return false;\n await wait(SUBMIT_DELAY_MS);\n return write('\\r');\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteFile } from '../../platform/fs-safe.js';\nimport { CLAUDE_EVENT } from './hooks.js';\nimport type { AgentWorkspace, AllowRule } from '../types.js';\n\n/**\n * Claude Code's side of a folder work runs it in (types.ts `AgentWorkspace`;\n * the Ctrl+K assistant's): the folder's project settings,\n * `.claude/settings.json` — its permission rules and its command hooks.\n * Those are work's; the user's own \"don't ask again\" choices go to\n * `.claude/settings.local.json`, which this never touches.\n */\n\n/** A rule in Claude Code's terms: `Bash(cmd)` is exactly that command, `Bash(cmd:*)` that and anything after. */\nexport const claudeAllowRule = (r: AllowRule): string => `Bash(${r.command}${r.prefix ? ':*' : ''})`;\n\nexport const claudeWorkspace: AgentWorkspace = {\n write(dir, { allow, hooks }) {\n fs.mkdirSync(path.join(dir, '.claude'), { recursive: true });\n const byEvent: Record<string, Array<{ hooks: Array<{ type: 'command'; command: string; timeout?: number }> }>> = {};\n for (const h of hooks) {\n (byEvent[CLAUDE_EVENT[h.edge]] ??= []).push({\n hooks: [{ type: 'command', command: h.command, ...(h.timeoutSec ? { timeout: h.timeoutSec } : {}) }],\n });\n }\n const settings = { permissions: { allow: allow.map(claudeAllowRule) }, hooks: byEvent };\n atomicWriteFile(path.join(dir, '.claude', 'settings.json'), JSON.stringify(settings, null, 2) + '\\n');\n return [path.join('.claude', 'settings.json')];\n },\n};\n","import { applyEnvDelta, type EnvDelta } from '../../platform/env-delta.js';\nimport spawn from '../../platform/spawn.js';\nimport { setUpAccounts, type ClaudeAccount } from './accounts.js';\nimport { configView } from '../../platform/config-cache.js';\nimport type { AgentSkills } from '../types.js';\n\n/**\n * Claude Code's side of work's skills (types.ts `AgentSkills`): they ship as\n * a Claude Code plugin (`work-tree`, .claude-plugin/marketplace.json →\n * plugins/work-tree), so installing them is registering that marketplace and\n * installing the plugin, user-wide, with the `claude` CLI. Claude reads the\n * plugin from the marketplace, not from the local folder.\n */\n\nexport const MARKETPLACE_REPO = 'moberghr/moberg-plugins';\nexport const MARKETPLACE_NAME = 'moberg-plugins';\nexport const PLUGIN_SPEC = 'work-tree@moberg-plugins';\n/**\n * The other plugins of that marketplace work installs with its own (setting `claudePlugins`): by default the Moberg\n * toolkit, mtk (asked for: \"can we make our moberg toolkit be shipped with work?\"). Names in moberg-plugins only.\n */\nexport const DEFAULT_EXTRA_PLUGINS: readonly string[] = ['mtk'];\n/** The same rule as settings-schema.ts SETTING_PATTERNS.pluginName (a test keeps them equal). */\nexport const PLUGIN_NAME_PATTERN = '^[a-z0-9][a-z0-9-]*$';\n\n/** The configured plugins, read without making ~/.work (postinstall runs this, and must write nothing there). */\nconst configuredSpecs = configView((raw) => pluginSpecs(raw));\n\n/** work's plugin and the configured others, as `name@moberg-plugins`. Pure. */\nexport function pluginSpecs(config: { claudePlugins?: unknown } | null | undefined): string[] {\n const raw = config?.claudePlugins;\n const names = Array.isArray(raw) ? raw.filter((n): n is string => typeof n === 'string') : [...DEFAULT_EXTRA_PLUGINS];\n const ok = new RegExp(PLUGIN_NAME_PATTERN);\n return [\n ...new Set([\n PLUGIN_SPEC,\n ...names\n .map((n) => n.trim())\n .filter((n) => ok.test(n) && n !== 'work-tree')\n .map((n) => `${n}@${MARKETPLACE_NAME}`),\n ]),\n ];\n}\n\n/** Runs `claude <args>` (argv only, §1.1), with `env` applied over this process's environment (an account's `CLAUDE_CONFIG_DIR`); injectable for tests. */\nexport type ClaudeRun = (args: string[], env?: EnvDelta) => { ok: boolean; stdout: string; stderr?: string };\n\nconst runClaude: ClaudeRun = (args, env) => {\n const r = spawn.sync('claude', args, {\n encoding: 'utf8',\n timeout: 60_000,\n windowsHide: true,\n stdio: 'pipe',\n ...(env ? { env: applyEnvDelta(process.env, env) as NodeJS.ProcessEnv } : {}),\n });\n const text = (v: unknown) => (typeof v === 'string' ? v : '');\n return { ok: !r.error && r.status === 0, stdout: text(r.stdout), stderr: r.error ? r.error.message : text(r.stderr) };\n};\n\n/** The last line a command printed, for a failure's reason. */\nconst lastLine = (r: { stdout: string; stderr?: string }) =>\n `${r.stderr ?? ''}\\n${r.stdout}`\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean)\n .pop() ?? '';\n\n/** Whether `claude plugin list --json` (an array of `{ id: \"name@marketplace\", … }`) lists `spec` (default: work's plugin). */\nexport function isInstalled(listJson: string, spec: string = PLUGIN_SPEC): boolean {\n try {\n const list = JSON.parse(listJson) as unknown;\n return Array.isArray(list) && list.some((p) => !!p && typeof p === 'object' && (p as { id?: unknown }).id === spec);\n } catch {\n return false;\n }\n}\n\n/**\n * Installs the plugins (`specs`: work's first) for ONE account: `run` carries that account's environment. One already\n * installed is updated to the marketplace's newest (the marketplace's list refreshed first), so mtk stays current.\n */\nfunction installFor(\n run: (args: string[]) => ReturnType<ClaudeRun>,\n specs: readonly string[] = [PLUGIN_SPEC],\n): { ok: boolean; message: string } {\n if (!run(['--version']).ok) return { ok: false, message: 'Claude Code (the `claude` CLI) is not installed' };\n const list = run(['plugin', 'marketplace', 'list']);\n if (!(list.ok && list.stdout.includes(MARKETPLACE_NAME))) {\n const add = run(['plugin', 'marketplace', 'add', MARKETPLACE_REPO, '--scope', 'user', '--sparse', '.claude-plugin']);\n if (!add.ok)\n return {\n ok: false,\n message: `could not register the Claude Code plugin marketplace (run \\`claude plugin marketplace add ${MARKETPLACE_REPO}\\`)`,\n };\n } else if (specs.length > 1) run(['plugin', 'marketplace', 'update', MARKETPLACE_NAME]);\n const said: string[] = [];\n const failed: string[] = [];\n let listed: string | null = null;\n for (const spec of specs) {\n const install = run(['plugin', 'install', spec, '--scope', 'user']);\n if (install.ok) {\n // `install` of one installed before succeeds and changes nothing: `update` brings it to the marketplace's newest.\n if (spec !== PLUGIN_SPEC) run(['plugin', 'update', spec]);\n said.push(`installed the Claude Code plugin ${spec}`);\n continue;\n }\n // Installed before is fine (`claude plugin list --json` has it): then brought up to date; anything else (offline, a\n // timeout, auth) is a failure, with how to do it by hand.\n listed ??= run(['plugin', 'list', '--json']).stdout;\n if (isInstalled(listed, spec)) {\n if (spec !== PLUGIN_SPEC) run(['plugin', 'update', spec]);\n said.push(`the Claude Code plugin ${spec} is installed`);\n continue;\n }\n const why = lastLine(install);\n failed.push(\n `could not install the Claude Code plugin ${spec}${why ? ` (${why})` : ''}: run \\`claude plugin install ${spec} --scope user\\``,\n );\n }\n return failed.length ? { ok: false, message: [...failed, ...said].join('; ') } : { ok: true, message: said.join('; ') };\n}\n\n/**\n * The plugin lives in each account's config folder (`~/.claude/plugins`, or the account's own): installed once per account,\n * with that account's `CLAUDE_CONFIG_DIR`. With no account configured it is the single plain run it always was.\n */\nexport function claudeSkillsWith(\n run: ClaudeRun,\n accounts: () => ClaudeAccount[] = setUpAccounts,\n specs: () => string[] = configuredSpecs,\n): AgentSkills {\n return {\n async install() {\n const list = accounts();\n const all = specs();\n if (list.length <= 1) return installFor((args) => run(args), all);\n const results = list.map((a) => {\n // The default account takes any inherited folder out, so it never lands in another account's.\n const env: EnvDelta = a.name === 'default' ? { CLAUDE_CONFIG_DIR: null } : { CLAUDE_CONFIG_DIR: a.dir };\n return { name: a.name, ...installFor((args) => run(args, env), all) };\n });\n return { ok: results.every((r) => r.ok), message: results.map((r) => `${r.name}: ${r.message}`).join('; ') };\n },\n };\n}\n\nexport const claudeSkills: AgentSkills = claudeSkillsWith(runClaude);\n\n/** Work's plugin into ONE account's folder: a new account (`work account add`), which the install at setup didn't reach. */\nexport function installClaudeSkillsFor(dir: string, run: ClaudeRun = runClaude): { ok: boolean; message: string } {\n return installFor((args) => run(args, { CLAUDE_CONFIG_DIR: dir }), configuredSpecs());\n}\n","import { readReadings } from '../../usage/usage-store.js';\nimport { claudeAccounts } from './accounts.js';\nimport { accountOf } from './rate-limits.js';\nimport { savedPath, userStatusLine } from './statusline-run.js';\nimport type { UsageAccount } from '../../usage/usage.js';\nimport type { AgentUsageSource } from '../types.js';\nimport type { UnwrapOutcome } from './statusline.js';\n\n// The installer (statusline.ts: the settings editor, its lock) loads only when work web or `work usage --restore` asks:\n// every hook process imports the adapter, and none of them needs it.\ntype Installer = typeof import('./statusline.js');\nlet installer: Installer | undefined;\nconst loadInstaller = async (): Promise<Installer> => (installer ??= await import('./statusline.js'));\n// The same for asking Claude Code (usage-ask.ts): only work web and `work usage` ask.\ntype Asker = typeof import('./usage-ask.js');\nlet asker: Asker | undefined;\nconst loadAsker = async (): Promise<Asker> => (asker ??= await import('./usage-ask.js'));\n\n/** What `work usage --restore` says it did for Claude (`saved`: where the copy of the user's line is, when it isn't ~/.work/statusline.json). */\nexport function restoreMessage(o: UnwrapOutcome, saved = '~/.work/statusline.json'): string {\n switch (o) {\n case 'restored':\n return 'Your own status line is back (work no longer reads the plan limits from it).';\n case 'not-ours':\n return \"Its status line isn't work's: left as it is.\";\n case 'kept':\n return `work's status line left in place: the copy of yours (${saved}) is missing or damaged. Set yours again with /statusline in Claude Code.`;\n case 'failed':\n return \"Its settings couldn't be changed (see above).\";\n }\n}\n\n/**\n * The readings, one per account the status-line hook saw. The hook names an account by its folder (`accountOf`:\n * `default` or `cfg-<hash>`, since it loads no config); here each is given the name it has in config `claudeAccounts`, and\n * the one new sessions use is marked. A folder that is no account (any more) keeps its hash.\n */\nfunction namedReadings(): UsageAccount[] {\n const accounts = claudeAccounts();\n const byKey = new Map<string, { name: string; isDefault: boolean }>();\n for (const a of accounts) if (!byKey.has(accountOf(a.dir))) byKey.set(accountOf(a.dir), { name: a.name, isDefault: a.isDefault });\n return readReadings('claude').map((r) => {\n const known = byKey.get(r.account);\n return known ? { ...r, account: known.name, ...(known.isDefault ? { isDefault: true } : {}) } : r;\n });\n}\n\n/**\n * Plan limits from what the status-line hook recorded (usage-store.ts). The hook is the status line of the Claudes work\n * starts (session-settings.ts; config `usage.statusLine: false` leaves it out); setup only gives back the user's own line\n * where an older work web wrapped it in their settings.\n */\nexport const claudeUsage: AgentUsageSource = {\n read: namedReadings,\n // A model's own weekly window (Fable's) is in no status line: asked of Claude Code, at most every 5 minutes an account.\n async refresh() {\n await (await loadAsker()).askClaudeUsage();\n },\n // A line in any account's own settings (an older work web's wrap counts as the line it saved).\n ownStatusLine: () => claudeAccounts().some((a) => userStatusLine({ configDir: a.dir }) !== null),\n async setup() {\n const done = await (await loadInstaller()).unwrapAllStatusLines();\n const restored = done.filter((d) => d.outcome === 'restored').map((d) => d.account);\n return restored.length > 0\n ? `your own status line given back in ${restored.join(', ')} (work's Claudes carry their own now)`\n : \"status line: nothing of work's in your settings\";\n },\n async restore() {\n const done = await (await loadInstaller()).unwrapAllStatusLines();\n const accounts = claudeAccounts();\n const ok = done.every((d) => d.outcome === 'restored' || d.outcome === 'not-ours');\n if (done.length === 1) return { ok, message: restoreMessage(done[0]!.outcome) };\n const message = done\n .map((d) => {\n const dir = accounts.find((a) => a.name === d.account)?.dir;\n return `${d.account}: ${restoreMessage(d.outcome, dir ? savedPath(dir) : undefined)}`;\n })\n .join('\\n');\n return { ok, message };\n },\n};\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { WorktreeSession } from '../../sessions/session-types.js';\nimport { loadConfig } from '../../platform/config.js';\nimport { isOwnCheckout } from '../../worktree/own-checkout.js';\nimport type { AccountInfo, AgentAccounts } from '../types.js';\nimport { accountDir, claudeAccounts, defaultAccountName, isLoggedIn, sessionAccount } from './accounts.js';\nimport { claudeAccountAdmin } from './account-admin.js';\nimport { encodeProjectDir, projectsRootOf, sessionRunFolders } from './activity.js';\n\n/**\n * Moving a session's conversations from one Claude account's folder to another's (a switch of account): for each folder\n * its Claude runs in, what is in `<from>/projects/<encoded cwd>/` — transcripts, subagents, memory — goes to the same\n * place under `<to>/projects/`, merged with what is there. Nothing is overwritten: a file the target already has under the\n * same name stays the one with the newer write, and the other is kept beside it under a suffix. A move that fails part\n * way puts back what it moved.\n */\n\nexport interface MoveResult {\n /** What went across: the new paths of the entries moved (the files and folders that had no counterpart in the target). */\n moved: string[];\n}\n\n/** A move that failed: what it was doing, and whether everything it had moved is back where it was. */\nexport class AccountMoveError extends Error {\n constructor(\n message: string,\n /** The entry that failed. */\n readonly failed: string,\n /** Entries put back. */\n readonly restored: string[],\n /** Entries that could not be put back (still in the target's folder): the move's failure left them there. */\n readonly stuck: string[],\n ) {\n super(message);\n }\n}\n\n/** One thing done, to be undone in reverse: `from` became `to`. */\ninterface Step {\n from: string;\n to: string;\n}\n\nconst isDir = (p: string) => {\n try {\n return fs.statSync(p).isDirectory();\n } catch {\n return false;\n }\n};\nconst exists = (p: string) => {\n try {\n fs.lstatSync(p);\n return true;\n } catch {\n return false;\n }\n};\nconst mtime = (p: string) => {\n try {\n return fs.statSync(p).mtimeMs;\n } catch {\n return 0;\n }\n};\n\n/** A rename; across volumes (EXDEV) or where Windows refuses a rename of a folder (EPERM), a copy and then a delete. */\nfunction moveEntry(from: string, to: string): void {\n fs.mkdirSync(path.dirname(to), { recursive: true });\n try {\n fs.renameSync(from, to);\n return;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'EXDEV' && code !== 'EPERM') throw err;\n }\n // Copy first, delete after: a copy that fails leaves the original whole (the half-copy is removed). Each file keeps its\n // times: a transcript's mtime is what `--continue` picks the newest by, and what a merge keeps the newer of.\n try {\n fs.cpSync(from, to, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true });\n } catch (err) {\n fs.rmSync(to, { recursive: true, force: true });\n throw err;\n }\n try {\n fs.rmSync(from, { recursive: true, force: true });\n } catch (err) {\n // The original went only in part (a file in use stopped the delete): not moved. What the delete took is put back from\n // the copy — never over what is still there —, and only then is the copy taken back, so the entry is whole where it\n // was. Should putting it back fail, the copy stays too: in both places, never in neither.\n try {\n fs.cpSync(to, from, { recursive: true, force: false, errorOnExist: false, preserveTimestamps: true });\n } catch (back) {\n const why = (e: unknown) => (e instanceof Error ? e.message : String(e));\n throw new Error(`${why(err)}; what its delete took couldn't be put back (${why(back)}), so it is kept at ${to} too`, {\n cause: back,\n });\n }\n try {\n fs.rmSync(to, { recursive: true, force: true });\n } catch {\n /* the copy stays (whole or in part): every file is still in `from`, some in both */\n }\n throw err;\n }\n}\n\n/** `<name>.from-<tag>`, or with a number when that is taken too. */\nfunction suffixed(file: string, tag: string): string {\n const base = `${file}.from-${tag}`;\n if (!exists(base)) return base;\n for (let n = 2; ; n++) if (!exists(`${base}-${n}`)) return `${base}-${n}`;\n}\n\n/** Move what is in `src` into `dst`, merging; every step is recorded in `steps` (and in `moved` when it brought something over). */\nfunction mergeInto(src: string, dst: string, tag: string, steps: Step[], moved: string[]): void {\n if (!exists(dst)) {\n moveEntry(src, dst);\n steps.push({ from: src, to: dst });\n moved.push(dst);\n return;\n }\n if (isDir(src) && isDir(dst)) {\n for (const name of fs.readdirSync(src)) mergeInto(path.join(src, name), path.join(dst, name), tag, steps, moved);\n // What is left of it is empty (everything went across): removed so no stray folder stays behind. Never recursive.\n try {\n fs.rmdirSync(src);\n } catch {\n /* not empty or in use: leave it */\n }\n return;\n }\n // The same name, and not two folders: keep both. The newer write holds the name (the conversation as it stands);\n // the other is kept beside it with a suffix naming where it came from.\n if (mtime(dst) >= mtime(src)) {\n const kept = suffixed(dst, tag);\n moveEntry(src, kept);\n steps.push({ from: src, to: kept });\n moved.push(kept);\n } else {\n const older = suffixed(dst, `${tag}-older`);\n moveEntry(dst, older);\n steps.push({ from: dst, to: older });\n moveEntry(src, dst);\n steps.push({ from: src, to: dst });\n moved.push(dst);\n }\n}\n\n/** Put the steps back, newest first; what could not be undone is returned. */\nfunction undo(steps: Step[]): { restored: string[]; stuck: string[] } {\n const restored: string[] = [];\n const stuck: string[] = [];\n for (const s of [...steps].reverse()) {\n try {\n moveEntry(s.to, s.from);\n restored.push(s.from);\n } catch {\n stuck.push(s.to);\n }\n }\n return { restored, stuck };\n}\n\n/**\n * The newest conversation of a projects folder — the `<id>.jsonl` `--continue` resumes — and its `<id>/` folder\n * (subagents, tool results) when there is one: what is this session's in a folder other conversations share.\n */\nfunction latestConversation(dir: string): string[] {\n let best: { name: string; at: number } | null = null;\n for (const name of fs.readdirSync(dir)) {\n if (!name.endsWith('.jsonl')) continue;\n const at = mtime(path.join(dir, name));\n if (!best || at > best.at) best = { name, at };\n }\n if (!best) return [];\n const id = best.name.slice(0, -'.jsonl'.length);\n return [best.name, ...(isDir(path.join(dir, id)) ? [id] : [])];\n}\n\n/**\n * Move a session's conversations from the account folder `fromDir` to `toDir` (each an account's `CLAUDE_CONFIG_DIR`, or\n * `~/.claude`). `tag` names the account they came from, for the suffix of a file kept beside one of the same name.\n * `onlyLatest`: a folder others share (a repo's own checkout, where every Claude run there keeps its conversations and\n * memory): only this session's conversation goes — the newest transcript and its folder per folder —, never the rest.\n * Throws an AccountMoveError after putting back what was moved.\n */\nexport function moveConversations(\n session: Pick<WorktreeSession, 'paths' | 'isGroup'>,\n fromDir: string,\n toDir: string,\n tag = 'old',\n opts: { onlyLatest?: boolean } = {},\n): MoveResult {\n const steps: Step[] = [];\n const moved: string[] = [];\n if (path.resolve(fromDir) === path.resolve(toDir)) return { moved };\n const emptied: string[] = [];\n let at = '';\n try {\n for (const cwd of sessionRunFolders(session, false)) {\n const name = encodeProjectDir(cwd);\n const src = path.join(projectsRootOf(fromDir), name);\n if (!isDir(src)) continue;\n at = src;\n const dst = path.join(projectsRootOf(toDir), name);\n if (opts.onlyLatest) {\n // Not the folder: its own conversation alone, into the target's folder of that name (made when missing).\n for (const entry of latestConversation(src)) {\n at = path.join(src, entry);\n mergeInto(path.join(src, entry), path.join(dst, entry), tag, steps, moved);\n }\n continue;\n }\n mergeInto(src, dst, tag, steps, moved);\n emptied.push(src);\n }\n } catch (err) {\n const { restored, stuck } = undo(steps);\n const why = err instanceof Error ? err.message : String(err);\n throw new AccountMoveError(\n `couldn't move its conversations (${at}): ${why}. ` +\n (stuck.length\n ? `${restored.length} put back, ${stuck.length} could not be: ${stuck.join(', ')}`\n : steps.length\n ? 'what was moved is back where it was'\n : 'nothing was moved'),\n at,\n restored,\n stuck,\n );\n }\n // A folder whose entries all went across: gone (never recursive: a leftover keeps it).\n for (const src of emptied) {\n try {\n fs.rmdirSync(src);\n } catch {\n /* something is left in it, or it is already gone */\n }\n }\n return { moved };\n}\n\n/** Claude's account part of the adapter (types.ts): which accounts there are, and a switch's file move. */\nexport const claudeAccountSwitch: AgentAccounts = {\n list(): AccountInfo[] {\n return claudeAccounts().map((a) => ({ name: a.name, dir: a.dir, isDefault: a.isDefault, loggedIn: isLoggedIn(a.dir) }));\n },\n defaultName: () => defaultAccountName(),\n has: (name) => accountDir(name) !== null,\n current: (session) => sessionAccount(session),\n async switchFiles(session, to) {\n const from = sessionAccount(session);\n const fromDir = accountDir(from);\n const toDir = accountDir(to);\n if (!fromDir) throw new Error(`its account “${from}” is not in your config any more`);\n if (!toDir) throw new Error(`no account “${to}”`);\n // A repo's own checkout is everyone's folder (other sessions, your own Claude there): only this session's conversation.\n const onlyLatest = isOwnCheckout(session, loadConfig()?.repos ?? {});\n return moveConversations(session, fromDir, toDir, from, { onlyLatest });\n },\n folders: (session) => sessionRunFolders(session, false),\n admin: claudeAccountAdmin,\n};\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { getAiTool, type AiToolSpec } from '../../platform/ai-launcher.js';\nimport { DEFAULT_ACCOUNT, getConfigPath, loadConfig } from '../../platform/config.js';\nimport { applyEnvDelta, type EnvDelta } from '../../platform/env-delta.js';\nimport { atomicWriteFile, withFileLock } from '../../platform/fs-safe.js';\nimport spawn from '../../platform/spawn.js';\nimport { AccountAdminError, type AccountUsers, type AgentAccountAdmin } from '../types.js';\nimport { accountDir, accountEnv, accountForbiddenRoots, accountProblem, expandAccountDir, validateClaudeAccounts } from './accounts.js';\nimport { withoutParentSession } from './env.js';\nimport { installClaudeSkillsFor } from './skills.js';\nimport { applySetupCopy, planSetupCopy, type SetupAccount } from './setup-copy.js';\n\n/**\n * Changes to the Claude accounts in config.json, as raw JSON under the config's lock (repo-admin.ts does the same), so a\n * setting this code doesn't know is never lost. Never deletes a folder: an account's login and conversations are the user's.\n */\n\ntype RawConfig = Record<string, unknown> & { claudeAccounts?: Record<string, string>; claudeAccount?: string };\n\nasync function editConfig<T>(fn: (raw: RawConfig, accounts: Record<string, string>) => T): Promise<T> {\n const file = getConfigPath();\n if (!fs.existsSync(file)) throw new AccountAdminError('No configuration yet: run `work init` first.');\n return withFileLock(file, () => {\n const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) as RawConfig;\n const existing = raw.claudeAccounts;\n const accounts = existing && typeof existing === 'object' && !Array.isArray(existing) ? { ...existing } : {};\n const out = fn(raw, accounts);\n raw.claudeAccounts = accounts;\n if (!Object.keys(accounts).length) delete raw.claudeAccounts;\n atomicWriteFile(file, JSON.stringify(raw, null, 2));\n return out;\n });\n}\n\n/** The accounts the config has by the rules (accounts.ts): a written entry that isn't one doesn't count as one here either. */\nconst validIn = (raw: RawConfig): Record<string, string> =>\n validateClaudeAccounts(raw.claudeAccounts, undefined, accountForbiddenRoots(raw)).accounts ?? {};\n\n/** Add an account: its folder (default `~/.claude-<name>`) is made, the name and folder must be free. Returns the folder. */\nexport async function addAccount(name: string, dir?: string): Promise<string> {\n const folder = expandAccountDir(dir?.trim() || path.join(os.homedir(), `.claude-${name}`));\n if (!folder) throw new AccountAdminError(`${dir} is not an absolute folder`);\n return editConfig((raw, accounts) => {\n if (name in accounts) throw new AccountAdminError(`there is already an account “${name}”`);\n const problem = accountProblem(name, folder, Object.values(validIn(raw)), accountForbiddenRoots(raw));\n if (problem) throw new AccountAdminError(problem);\n try {\n fs.mkdirSync(folder, { recursive: true });\n } catch (e) {\n throw new AccountAdminError(`couldn't make ${folder}: ${e instanceof Error ? e.message : String(e)}`);\n }\n accounts[name] = folder;\n return folder;\n });\n}\n\n/** New sessions use this account (`default` or a configured one). */\nexport async function setDefaultAccount(name: string): Promise<void> {\n await editConfig((raw) => {\n if (name !== DEFAULT_ACCOUNT && !(name in validIn(raw))) throw new AccountAdminError(`no account “${name}”`);\n raw.claudeAccount = name;\n });\n}\n\nconst sessionsText = (n: number, what: string) => `${n} ${what} session${n === 1 ? '' : 's'}`;\n\n/**\n * Forget an account (its folder stays). `usedBy` is asked under the config's lock, right before the write: refused,\n * naming them, while live sessions run on it, or archived ones would need it to be restored; the default falls back to\n * `default`.\n */\nexport async function removeAccount(name: string, usedBy: () => AccountUsers): Promise<void> {\n if (name === DEFAULT_ACCOUNT) throw new AccountAdminError('the default account (~/.claude) can not be removed');\n await editConfig((raw, accounts) => {\n if (!(name in accounts)) throw new AccountAdminError(`no account “${name}”`);\n const { live, archived } = usedBy();\n if (live.length) throw new AccountAdminError(`${sessionsText(live.length, 'live')} on ${name}`, live, 'live');\n if (archived.length)\n throw new AccountAdminError(\n `${sessionsText(archived.length, 'archived')} on ${name} (a Restore would start it on the default account instead)`,\n archived,\n 'archived',\n );\n delete accounts[name];\n if (raw.claudeAccount === name) raw.claudeAccount = DEFAULT_ACCOUNT;\n });\n}\n\n/**\n * Claude Code on the account, so you `/login` once: the configured command when it is Claude (`claude --model …`, config\n * `aiCommand`), else plain `claude`, with the account's folder in its environment (`accountEnv`: set for a configured\n * account, taken out for the default one while accounts exist). What `loginOn` runs here and the dashboard's login\n * terminal runs in the PTY host.\n */\nexport function loginLaunch(name: string): { tool: AiToolSpec; agentEnv: EnvDelta } {\n if (!accountDir(name)) throw new AccountAdminError(`no account “${name}”`);\n const config = loadConfig();\n const tool = getAiTool(config && getAiTool(config).cmd === 'claude' ? config : {});\n return { tool, agentEnv: accountEnv(name) };\n}\n\n/**\n * Claude Code in this terminal on the account (`loginLaunch`). The login is the user's, in this terminal (stdio\n * inherited): nothing to hide. Blocks until it exits.\n */\nexport function loginOn(name: string, run: typeof spawn.sync = spawn.sync): void {\n const { tool, agentEnv } = loginLaunch(name);\n const env = applyEnvDelta(withoutParentSession(process.env), agentEnv) as NodeJS.ProcessEnv;\n run(tool.cmd, tool.baseArgs, { stdio: 'inherit', windowsHide: false, env });\n}\n\n/** Claude's account administration (types.ts `AgentAccountAdmin`). */\nexport const claudeAccountAdmin: AgentAccountAdmin = {\n add: addAccount,\n setDefault: setDefaultAccount,\n remove: removeAccount,\n login: (name) => loginOn(name),\n loginLaunch,\n installSkills: (name) => {\n const dir = accountDir(name);\n if (!dir) return { ok: false, message: `no account “${name}”` };\n return installClaudeSkillsFor(dir);\n },\n setupPlan: (from, to) => planSetupCopy(...setupPair(from, to)),\n copySetup: (from, to) => applySetupCopy(...setupPair(from, to)),\n};\n\n/** The two accounts of a setup copy, with their folders; refused when either is unknown or they are one account. */\nexport function setupPair(from: string, to: string): [SetupAccount, SetupAccount] {\n const [a, b] = [from, to].map((name) => {\n const dir = accountDir(name);\n if (!dir) throw new AccountAdminError(`no account “${name}”`);\n return { name, dir };\n });\n if (a.name === b.name) throw new AccountAdminError('an account’s setup can’t be copied to itself');\n return [a, b];\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * The folder of work's own package.json — the installed package, or this\n * repo in dev. Found by walking up from this module, so it holds wherever\n * the code sits: bundled into dist/ (a chunk next to bin.js) or a source\n * file several folders under src/. Files shipped beside dist/ (dist/web, the\n * skills under plugins/) are found from here, never by counting `..`.\n */\nlet cached: string | null | undefined;\nexport function packageRoot(): string | null {\n if (cached !== undefined) return cached;\n let dir = path.dirname(fileURLToPath(import.meta.url));\n for (;;) {\n try {\n const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')) as { name?: unknown };\n if (pkg.name === '@moberg_hr/work-tree') return (cached = dir);\n } catch {\n /* none here */\n }\n const up = path.dirname(dir);\n if (up === dir) return (cached = null);\n dir = up;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AAoCR,IAAM,kBAOT;AAAA,EACF,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,QAAQ;AAAA;AAAA,EACV;AAAA,EACA,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,YAAY;AAAA;AAAA,IACZ,QAAQ;AAAA,EACV;AACF;AAGO,IAAM,cAAc;AAAA,EACzB,EAAE,MAAM,wBAAwB,OAAO,SAAS;AAAA,EAChD,EAAE,MAAM,uBAAuB,OAAO,WAAW;AACnD;AAMO,SAAS,UAAU,QAAsE;AAC9F,QAAM,WAAW,OAAO,aAAa,UAAU,KAAK;AACpD,QAAM,QAAQ,QAAQ,MAAM,KAAK,EAAE,OAAO,OAAO;AACjD,QAAM,MAAM,MAAM,CAAC,KAAK;AACxB,QAAM,WAAW,MAAM,MAAM,CAAC;AAC9B,QAAM,SAAS,gBAAgB,GAAG,KAAK,gBAAgB;AACvD,QAAM,YAAY,OAAO,kBAAkB,CAAC;AAC5C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,YAAY,UAAU,UAAU,OAAO;AAAA,IACvC,gBAAgB,UAAU,cAAc,OAAO;AAAA,IAC/C,YAAY,UAAU,UAAU,OAAO;AAAA,EACzC;AACF;AAGO,SAAS,kBAAkB,MAAkB,OAAqB,CAAC,GAAoC;AAC5G,QAAM,OAAO,C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K,MAAMD,KAAG,aAAaC,OAAK,KAAK,KAAK,cAAc,GAAG,MAAM,CAAC;AAC9E,UAAI,IAAI,SAAS,uBAAwB,QAAQ,SAAS;AAAA,IAC5D,QAAQ;AAAA,IAER;AACA,UAAM,KAAKA,OAAK,QAAQ,GAAG;AAC3B,QAAI,OAAO,IAAK,QAAQ,SAAS;AACjC,UAAM;AAAA,EACR;AACF;","names":["path","fs","path","path","fs","fs","os","path","fs","os","path","path","fs","os","key","os","path","fs","fs","path","fs","os","path","os","path","key","n","fs","fs","path","path","fs","path","path","fs","key","kept","path","fs","fs","whatOf","TAIL_BYTES","key","path","path","path","str","path","workCommand","kept","fs","path","path","fs","fs","os","path","path","os","fs","key","cached","fs","path","fs","path","runClaude","lastLine","installer","loadInstaller","fs","path","fs","os","path","fs","path","os","fs","path","kept","TAIL_BYTES","path","path","fs","path"]}