@moberg_hr/work-tree 2.23.0 → 2.23.2
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.
- package/dist/{account-FKQZQP3W.js → account-6ZQ3VFA2.js} +23 -21
- package/dist/{account-FKQZQP3W.js.map → account-6ZQ3VFA2.js.map} +1 -1
- package/dist/{add-repo-VJ2OPGRB.js → add-repo-WXDEKZRX.js} +13 -13
- package/dist/{answer-HQGVCGOF.js → answer-L55DWMR5.js} +11 -11
- package/dist/{attach-M46SZYRL.js → attach-KLVI7BHS.js} +16 -16
- package/dist/bin.js +4 -4
- package/dist/{block-B2WNCH52.js → block-BRNRP226.js} +12 -12
- package/dist/{broadcast-JD755S3I.js → broadcast-GQE7H3MF.js} +8 -8
- package/dist/{catchup-PTV2VTWT.js → catchup-ZMG4OWF2.js} +13 -13
- package/dist/{child-XFLJLJ6I.js → child-MPXXJ2QX.js} +11 -11
- package/dist/{chunk-ZIZ5ZTEN.js → chunk-2JLG65GB.js} +2 -2
- package/dist/{chunk-BTGPUOF7.js → chunk-6S3DYLGH.js} +5 -5
- package/dist/{chunk-26BZGPFZ.js → chunk-773UJC5C.js} +4 -4
- package/dist/{chunk-FEI73IPX.js → chunk-7BH2PUYY.js} +5 -5
- package/dist/{chunk-R7IENU76.js → chunk-7HQSILMM.js} +4 -4
- package/dist/{chunk-W4GDPHIF.js → chunk-7ZATXG5F.js} +2 -2
- package/dist/{chunk-V6FD76AQ.js → chunk-A53OR6P5.js} +4 -4
- package/dist/{chunk-UGDTSOPX.js → chunk-APHVSSLI.js} +2 -2
- package/dist/{chunk-HTV7366A.js → chunk-BBI4YQTS.js} +8 -8
- package/dist/{chunk-ETRKZHM5.js → chunk-BGQ6NUU7.js} +4 -4
- package/dist/{chunk-KUYEYPO4.js → chunk-BMPTUIP4.js} +2 -2
- package/dist/{chunk-AZF7HIDT.js → chunk-BZOYUBK4.js} +3 -3
- package/dist/{chunk-4FOC35LW.js → chunk-C5BBVVHW.js} +2 -2
- package/dist/{chunk-EJZMCAM2.js → chunk-CRAGAIOS.js} +7 -7
- package/dist/{chunk-AEH72XTU.js → chunk-DK3UMOX7.js} +2 -2
- package/dist/{chunk-6RFDASKQ.js → chunk-DNC2ZJOF.js} +4 -4
- package/dist/chunk-DYKA3LO3.js +9 -0
- package/dist/{chunk-ASGJ3MCL.js → chunk-ETWP7MDS.js} +2 -1
- package/dist/chunk-ETWP7MDS.js.map +1 -0
- package/dist/{chunk-R7JIKEIL.js → chunk-G4VKMMIC.js} +10 -10
- package/dist/{chunk-AUIHERJ7.js → chunk-GF7RAQFD.js} +2 -2
- package/dist/{chunk-L5U47Q63.js → chunk-HBYXSFLN.js} +5 -5
- package/dist/{chunk-5THKIWZU.js → chunk-HO5KESIB.js} +3 -3
- package/dist/{chunk-V56WW2LA.js → chunk-HUGHF45U.js} +3 -3
- package/dist/{chunk-TVIM5VV5.js → chunk-IUVMVNIO.js} +5 -5
- package/dist/chunk-JVOQSU6R.js +151 -0
- package/dist/chunk-JVOQSU6R.js.map +1 -0
- package/dist/{chunk-6ISLCEBR.js → chunk-K6FD5WDW.js} +5 -5
- package/dist/{chunk-4LZLVHZE.js → chunk-KJAE7WO5.js} +22 -11
- package/dist/chunk-KJAE7WO5.js.map +1 -0
- package/dist/{chunk-WYCGV5Z7.js → chunk-KWJ6S4NZ.js} +4 -4
- package/dist/{chunk-SZAD5U3J.js → chunk-LB2GAU7E.js} +2 -2
- package/dist/{chunk-WLYWO6JH.js → chunk-LCYYJFSZ.js} +4 -4
- package/dist/{chunk-DP6YMZUL.js → chunk-LOFGDH5B.js} +17 -7
- package/dist/chunk-LOFGDH5B.js.map +1 -0
- package/dist/{chunk-Z3JSYKOS.js → chunk-LW6VCL6S.js} +6 -6
- package/dist/{chunk-PCJVBGRS.js → chunk-M2P722BR.js} +3 -3
- package/dist/{chunk-VHENFC2S.js → chunk-M2X6OHHR.js} +14 -1
- package/dist/chunk-M2X6OHHR.js.map +1 -0
- package/dist/{chunk-DSDPJATB.js → chunk-MMEFW2PI.js} +3 -3
- package/dist/{chunk-4GIAERRK.js → chunk-MYASALCU.js} +5 -5
- package/dist/{chunk-DHZ5DF6Y.js → chunk-MYXEX6BB.js} +2 -1
- package/dist/{chunk-7I2UHJJF.js → chunk-NLU6MBYT.js} +10 -8
- package/dist/chunk-NLU6MBYT.js.map +1 -0
- package/dist/{chunk-ZDTFAMD2.js → chunk-NREZVTBP.js} +2 -2
- package/dist/{chunk-BS6GTKF2.js → chunk-NWKVTUTN.js} +9 -9
- package/dist/{chunk-4VTRRZWZ.js → chunk-P53UYZZ4.js} +2 -2
- package/dist/{chunk-6HVDHGNE.js → chunk-PSALWCBD.js} +3 -3
- package/dist/{chunk-O7BXNXU2.js → chunk-QAIG5FSQ.js} +3 -3
- package/dist/{chunk-ETO7CUIS.js → chunk-QMWV4UKB.js} +3 -3
- package/dist/{chunk-5IZMEAKN.js → chunk-QSSCVTFG.js} +4 -4
- package/dist/{chunk-LZJ5VDUD.js → chunk-RGKGJOES.js} +138 -7
- package/dist/chunk-RGKGJOES.js.map +1 -0
- package/dist/{chunk-OETBYJFV.js → chunk-SF3DIIKN.js} +3 -3
- package/dist/{chunk-EOXYDFBB.js → chunk-SUHANL3G.js} +4 -4
- package/dist/{chunk-FRFS6JC4.js → chunk-VNZBFVGY.js} +3 -3
- package/dist/{chunk-EEMPMVCP.js → chunk-VPZ5ILKT.js} +4 -4
- package/dist/{chunk-EE744F4B.js → chunk-VQEMPGJL.js} +2 -2
- package/dist/{chunk-ULI54QYZ.js → chunk-WH6DAD6D.js} +2 -2
- package/dist/{chunk-JIMD77FI.js → chunk-XB4SCJWD.js} +83 -21
- package/dist/chunk-XB4SCJWD.js.map +1 -0
- package/dist/{chunk-EVGYDJI2.js → chunk-XIN6XUFL.js} +2 -2
- package/dist/{chunk-XJQ7XJJC.js → chunk-XL4YNA3L.js} +4 -4
- package/dist/chunk-XL4YNA3L.js.map +1 -0
- package/dist/{chunk-K76NOSEX.js → chunk-XT3FON6A.js} +2 -2
- package/dist/{chunk-ZBVM57LO.js → chunk-XWUX474Q.js} +4 -150
- package/dist/chunk-XWUX474Q.js.map +1 -0
- package/dist/{chunk-QPQV3IU2.js → chunk-ZG6HB4BO.js} +2 -2
- package/dist/{chunk-336YLJ5L.js → chunk-ZHK5XOV5.js} +60 -60
- package/dist/{chunk-VVJY6IKW.js → chunk-ZPDCVDE2.js} +2 -2
- package/dist/{cleanup-RVQ2PPCC.js → cleanup-DRELB6UC.js} +29 -29
- package/dist/{cli-RQ7LQXRX.js → cli-C3U2BC44.js} +4 -4
- package/dist/{color-37SJ7NPH.js → color-T75ANAWG.js} +11 -11
- package/dist/{config-QMNCPBT7.js → config-KI6JOXKW.js} +10 -10
- package/dist/{coordinate-22N2UBE4.js → coordinate-4PPZN4U4.js} +11 -11
- package/dist/{diff-VSM47DNB.js → diff-NDZPRQV7.js} +12 -12
- package/dist/{digest-H5YMEW54.js → digest-H5YFX5WR.js} +11 -11
- package/dist/{fork-Q2AEFG5M.js → fork-HHHATXVI.js} +25 -25
- package/dist/{history-E34WUNZO.js → history-3Z7AS2AC.js} +8 -8
- package/dist/{hook-IMBHXXH2.js → hook-KOK7NKCO.js} +16 -16
- package/dist/{hydrate-IPNTSEDA.js → hydrate-VI3XSZQH.js} +8 -8
- package/dist/{init-V7Z3RVHQ.js → init-7NOKRHNJ.js} +12 -12
- package/dist/{install-skills-PP7WYASM.js → install-skills-TL5D7HZU.js} +8 -8
- package/dist/install-skills-bin.js +7 -7
- package/dist/{keep-JZBFDYC5.js → keep-G62GSDOQ.js} +10 -10
- package/dist/{list-D6GWBNUI.js → list-CEVAZQ4V.js} +8 -8
- package/dist/{move-T6IVLRRI.js → move-ISAW6RDM.js} +15 -15
- package/dist/{note-L4YF6DYN.js → note-YIVFXTGM.js} +10 -10
- package/dist/{overlaps-33U2T7IV.js → overlaps-YBEHBRRK.js} +13 -13
- package/dist/{pin-BVNCXHQI.js → pin-J4IDSHRG.js} +11 -11
- package/dist/{pr-DBTWVMRE.js → pr-Z7CPBBGT.js} +20 -20
- package/dist/{prune-HUYBTMZM.js → prune-UA3UDZSM.js} +26 -26
- package/dist/{pty-host-IJFDGRA4.js → pty-host-JIQUP62K.js} +63 -16
- package/dist/pty-host-JIQUP62K.js.map +1 -0
- package/dist/{read-4OUYRSKS.js → read-DG4PCLFH.js} +10 -10
- package/dist/{recent-PB233FPD.js → recent-PGD6QYAH.js} +14 -14
- package/dist/{remove-YCQLIDTS.js → remove-TPLA64HP.js} +27 -27
- package/dist/{report-XMESBL7C.js → report-K3OTT2ED.js} +11 -11
- package/dist/{restart-NQ5DJ3TN.js → restart-477IX2JX.js} +11 -11
- package/dist/{resume-KL5JCKVD.js → resume-OYBAJCYE.js} +14 -14
- package/dist/{review-MIKB545E.js → review-6PWFSBAO.js} +10 -10
- package/dist/{review-now-VF6X6M64.js → review-now-AT2SPPRO.js} +2 -2
- package/dist/{run-Y255ESUN.js → run-XEHF2N4A.js} +8 -8
- package/dist/{screen-AZFHPOCB.js → screen-SFU6TCDV.js} +11 -11
- package/dist/{search-DAFKJTLY.js → search-VJ3BGWPX.js} +8 -8
- package/dist/{section-WCC35C44.js → section-ZLINSTGS.js} +11 -11
- package/dist/{send-MYEMZU7Z.js → send-NBP2WYBG.js} +12 -12
- package/dist/{sessions-P3D46QLP.js → sessions-UT4I7A43.js} +23 -23
- package/dist/{show-JOO5OT2F.js → show-RK2EWOR6.js} +10 -10
- package/dist/{snooze-7KLABMIG.js → snooze-T2WWIKZN.js} +10 -10
- package/dist/{start-PGVZZJQT.js → start-AWHOIA3Q.js} +11 -11
- package/dist/{state-XHTOESKK.js → state-HK67C4UA.js} +2 -2
- package/dist/{status-CXIRNRMP.js → status-QE2DA6RR.js} +11 -11
- package/dist/{statusline-HPH2ORNT.js → statusline-Z5HLKDIA.js} +5 -5
- package/dist/{statusline-hook-Q645N4XF.js → statusline-hook-VPPS3PFO.js} +3 -3
- package/dist/{stop-IJNUSRIG.js → stop-YOU3P3ZR.js} +11 -11
- package/dist/{sync-3HMCC55V.js → sync-74EFTPBJ.js} +26 -26
- package/dist/{time-DUDNSHM3.js → time-ZGMZZ5OY.js} +11 -11
- package/dist/{time-actions-M4QTTH4M.js → time-actions-VAGRSY5B.js} +3 -3
- package/dist/{timesheet-BMKDX5KZ.js → timesheet-N74LPF5M.js} +18 -17
- package/dist/timesheet-N74LPF5M.js.map +1 -0
- package/dist/{todo-QMXJ5R3E.js → todo-UVKGOG7D.js} +2 -2
- package/dist/{tree-TL4GISI5.js → tree-FXTCWC6D.js} +26 -26
- package/dist/{update-3TODL7J3.js → update-5QSRHIWH.js} +15 -15
- package/dist/{usage-YFTN2IS7.js → usage-CW7CDFU3.js} +10 -10
- package/dist/{usage-ask-EZR3W3UW.js → usage-ask-V2SIRW4F.js} +3 -3
- package/dist/{version-LNHKXZBP.js → version-RJ4PCHPB.js} +5 -5
- package/dist/{wait-B37BTCVG.js → wait-XXC3I6DK.js} +11 -11
- package/dist/wd-bin.js +3 -3
- package/dist/web/assets/{PtyView-C8yW4SST.js → PtyView-BLTE5F3E.js} +26 -26
- package/dist/web/assets/PtyView-BLTE5F3E.js.map +1 -0
- package/dist/web/assets/{index-DDZCgbD-.js → index-BiadbzE6.js} +59 -59
- package/dist/web/assets/index-BiadbzE6.js.map +1 -0
- package/dist/web/assets/{index-yBTfBzDm.css → index-CfTmdABt.css} +1 -1
- package/dist/web/index.html +2 -2
- package/dist/{web-JAAXINIU.js → web-SUSR4IAK.js} +245 -97
- package/dist/web-SUSR4IAK.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/chunk-4LZLVHZE.js.map +0 -1
- package/dist/chunk-7I2UHJJF.js.map +0 -1
- package/dist/chunk-ASGJ3MCL.js.map +0 -1
- package/dist/chunk-CJFAJV2K.js +0 -9
- package/dist/chunk-DP6YMZUL.js.map +0 -1
- package/dist/chunk-JIMD77FI.js.map +0 -1
- package/dist/chunk-LZJ5VDUD.js.map +0 -1
- package/dist/chunk-VHENFC2S.js.map +0 -1
- package/dist/chunk-XJQ7XJJC.js.map +0 -1
- package/dist/chunk-ZBVM57LO.js.map +0 -1
- package/dist/pty-host-IJFDGRA4.js.map +0 -1
- package/dist/timesheet-BMKDX5KZ.js.map +0 -1
- package/dist/web/assets/PtyView-C8yW4SST.js.map +0 -1
- package/dist/web/assets/index-DDZCgbD-.js.map +0 -1
- package/dist/web-JAAXINIU.js.map +0 -1
- /package/dist/{add-repo-VJ2OPGRB.js.map → add-repo-WXDEKZRX.js.map} +0 -0
- /package/dist/{answer-HQGVCGOF.js.map → answer-L55DWMR5.js.map} +0 -0
- /package/dist/{attach-M46SZYRL.js.map → attach-KLVI7BHS.js.map} +0 -0
- /package/dist/{block-B2WNCH52.js.map → block-BRNRP226.js.map} +0 -0
- /package/dist/{broadcast-JD755S3I.js.map → broadcast-GQE7H3MF.js.map} +0 -0
- /package/dist/{catchup-PTV2VTWT.js.map → catchup-ZMG4OWF2.js.map} +0 -0
- /package/dist/{child-XFLJLJ6I.js.map → child-MPXXJ2QX.js.map} +0 -0
- /package/dist/{chunk-ZIZ5ZTEN.js.map → chunk-2JLG65GB.js.map} +0 -0
- /package/dist/{chunk-BTGPUOF7.js.map → chunk-6S3DYLGH.js.map} +0 -0
- /package/dist/{chunk-26BZGPFZ.js.map → chunk-773UJC5C.js.map} +0 -0
- /package/dist/{chunk-FEI73IPX.js.map → chunk-7BH2PUYY.js.map} +0 -0
- /package/dist/{chunk-R7IENU76.js.map → chunk-7HQSILMM.js.map} +0 -0
- /package/dist/{chunk-W4GDPHIF.js.map → chunk-7ZATXG5F.js.map} +0 -0
- /package/dist/{chunk-V6FD76AQ.js.map → chunk-A53OR6P5.js.map} +0 -0
- /package/dist/{chunk-UGDTSOPX.js.map → chunk-APHVSSLI.js.map} +0 -0
- /package/dist/{chunk-HTV7366A.js.map → chunk-BBI4YQTS.js.map} +0 -0
- /package/dist/{chunk-ETRKZHM5.js.map → chunk-BGQ6NUU7.js.map} +0 -0
- /package/dist/{chunk-KUYEYPO4.js.map → chunk-BMPTUIP4.js.map} +0 -0
- /package/dist/{chunk-AZF7HIDT.js.map → chunk-BZOYUBK4.js.map} +0 -0
- /package/dist/{chunk-4FOC35LW.js.map → chunk-C5BBVVHW.js.map} +0 -0
- /package/dist/{chunk-EJZMCAM2.js.map → chunk-CRAGAIOS.js.map} +0 -0
- /package/dist/{chunk-AEH72XTU.js.map → chunk-DK3UMOX7.js.map} +0 -0
- /package/dist/{chunk-6RFDASKQ.js.map → chunk-DNC2ZJOF.js.map} +0 -0
- /package/dist/{chunk-CJFAJV2K.js.map → chunk-DYKA3LO3.js.map} +0 -0
- /package/dist/{chunk-R7JIKEIL.js.map → chunk-G4VKMMIC.js.map} +0 -0
- /package/dist/{chunk-AUIHERJ7.js.map → chunk-GF7RAQFD.js.map} +0 -0
- /package/dist/{chunk-L5U47Q63.js.map → chunk-HBYXSFLN.js.map} +0 -0
- /package/dist/{chunk-5THKIWZU.js.map → chunk-HO5KESIB.js.map} +0 -0
- /package/dist/{chunk-V56WW2LA.js.map → chunk-HUGHF45U.js.map} +0 -0
- /package/dist/{chunk-TVIM5VV5.js.map → chunk-IUVMVNIO.js.map} +0 -0
- /package/dist/{chunk-6ISLCEBR.js.map → chunk-K6FD5WDW.js.map} +0 -0
- /package/dist/{chunk-WYCGV5Z7.js.map → chunk-KWJ6S4NZ.js.map} +0 -0
- /package/dist/{chunk-SZAD5U3J.js.map → chunk-LB2GAU7E.js.map} +0 -0
- /package/dist/{chunk-WLYWO6JH.js.map → chunk-LCYYJFSZ.js.map} +0 -0
- /package/dist/{chunk-Z3JSYKOS.js.map → chunk-LW6VCL6S.js.map} +0 -0
- /package/dist/{chunk-PCJVBGRS.js.map → chunk-M2P722BR.js.map} +0 -0
- /package/dist/{chunk-DSDPJATB.js.map → chunk-MMEFW2PI.js.map} +0 -0
- /package/dist/{chunk-4GIAERRK.js.map → chunk-MYASALCU.js.map} +0 -0
- /package/dist/{chunk-DHZ5DF6Y.js.map → chunk-MYXEX6BB.js.map} +0 -0
- /package/dist/{chunk-ZDTFAMD2.js.map → chunk-NREZVTBP.js.map} +0 -0
- /package/dist/{chunk-BS6GTKF2.js.map → chunk-NWKVTUTN.js.map} +0 -0
- /package/dist/{chunk-4VTRRZWZ.js.map → chunk-P53UYZZ4.js.map} +0 -0
- /package/dist/{chunk-6HVDHGNE.js.map → chunk-PSALWCBD.js.map} +0 -0
- /package/dist/{chunk-O7BXNXU2.js.map → chunk-QAIG5FSQ.js.map} +0 -0
- /package/dist/{chunk-ETO7CUIS.js.map → chunk-QMWV4UKB.js.map} +0 -0
- /package/dist/{chunk-5IZMEAKN.js.map → chunk-QSSCVTFG.js.map} +0 -0
- /package/dist/{chunk-OETBYJFV.js.map → chunk-SF3DIIKN.js.map} +0 -0
- /package/dist/{chunk-EOXYDFBB.js.map → chunk-SUHANL3G.js.map} +0 -0
- /package/dist/{chunk-FRFS6JC4.js.map → chunk-VNZBFVGY.js.map} +0 -0
- /package/dist/{chunk-EEMPMVCP.js.map → chunk-VPZ5ILKT.js.map} +0 -0
- /package/dist/{chunk-EE744F4B.js.map → chunk-VQEMPGJL.js.map} +0 -0
- /package/dist/{chunk-ULI54QYZ.js.map → chunk-WH6DAD6D.js.map} +0 -0
- /package/dist/{chunk-EVGYDJI2.js.map → chunk-XIN6XUFL.js.map} +0 -0
- /package/dist/{chunk-K76NOSEX.js.map → chunk-XT3FON6A.js.map} +0 -0
- /package/dist/{chunk-QPQV3IU2.js.map → chunk-ZG6HB4BO.js.map} +0 -0
- /package/dist/{chunk-336YLJ5L.js.map → chunk-ZHK5XOV5.js.map} +0 -0
- /package/dist/{chunk-VVJY6IKW.js.map → chunk-ZPDCVDE2.js.map} +0 -0
- /package/dist/{cleanup-RVQ2PPCC.js.map → cleanup-DRELB6UC.js.map} +0 -0
- /package/dist/{cli-RQ7LQXRX.js.map → cli-C3U2BC44.js.map} +0 -0
- /package/dist/{color-37SJ7NPH.js.map → color-T75ANAWG.js.map} +0 -0
- /package/dist/{config-QMNCPBT7.js.map → config-KI6JOXKW.js.map} +0 -0
- /package/dist/{coordinate-22N2UBE4.js.map → coordinate-4PPZN4U4.js.map} +0 -0
- /package/dist/{diff-VSM47DNB.js.map → diff-NDZPRQV7.js.map} +0 -0
- /package/dist/{digest-H5YMEW54.js.map → digest-H5YFX5WR.js.map} +0 -0
- /package/dist/{fork-Q2AEFG5M.js.map → fork-HHHATXVI.js.map} +0 -0
- /package/dist/{history-E34WUNZO.js.map → history-3Z7AS2AC.js.map} +0 -0
- /package/dist/{hook-IMBHXXH2.js.map → hook-KOK7NKCO.js.map} +0 -0
- /package/dist/{hydrate-IPNTSEDA.js.map → hydrate-VI3XSZQH.js.map} +0 -0
- /package/dist/{init-V7Z3RVHQ.js.map → init-7NOKRHNJ.js.map} +0 -0
- /package/dist/{install-skills-PP7WYASM.js.map → install-skills-TL5D7HZU.js.map} +0 -0
- /package/dist/{keep-JZBFDYC5.js.map → keep-G62GSDOQ.js.map} +0 -0
- /package/dist/{list-D6GWBNUI.js.map → list-CEVAZQ4V.js.map} +0 -0
- /package/dist/{move-T6IVLRRI.js.map → move-ISAW6RDM.js.map} +0 -0
- /package/dist/{note-L4YF6DYN.js.map → note-YIVFXTGM.js.map} +0 -0
- /package/dist/{overlaps-33U2T7IV.js.map → overlaps-YBEHBRRK.js.map} +0 -0
- /package/dist/{pin-BVNCXHQI.js.map → pin-J4IDSHRG.js.map} +0 -0
- /package/dist/{pr-DBTWVMRE.js.map → pr-Z7CPBBGT.js.map} +0 -0
- /package/dist/{prune-HUYBTMZM.js.map → prune-UA3UDZSM.js.map} +0 -0
- /package/dist/{read-4OUYRSKS.js.map → read-DG4PCLFH.js.map} +0 -0
- /package/dist/{recent-PB233FPD.js.map → recent-PGD6QYAH.js.map} +0 -0
- /package/dist/{remove-YCQLIDTS.js.map → remove-TPLA64HP.js.map} +0 -0
- /package/dist/{report-XMESBL7C.js.map → report-K3OTT2ED.js.map} +0 -0
- /package/dist/{restart-NQ5DJ3TN.js.map → restart-477IX2JX.js.map} +0 -0
- /package/dist/{resume-KL5JCKVD.js.map → resume-OYBAJCYE.js.map} +0 -0
- /package/dist/{review-MIKB545E.js.map → review-6PWFSBAO.js.map} +0 -0
- /package/dist/{review-now-VF6X6M64.js.map → review-now-AT2SPPRO.js.map} +0 -0
- /package/dist/{run-Y255ESUN.js.map → run-XEHF2N4A.js.map} +0 -0
- /package/dist/{screen-AZFHPOCB.js.map → screen-SFU6TCDV.js.map} +0 -0
- /package/dist/{search-DAFKJTLY.js.map → search-VJ3BGWPX.js.map} +0 -0
- /package/dist/{section-WCC35C44.js.map → section-ZLINSTGS.js.map} +0 -0
- /package/dist/{send-MYEMZU7Z.js.map → send-NBP2WYBG.js.map} +0 -0
- /package/dist/{sessions-P3D46QLP.js.map → sessions-UT4I7A43.js.map} +0 -0
- /package/dist/{show-JOO5OT2F.js.map → show-RK2EWOR6.js.map} +0 -0
- /package/dist/{snooze-7KLABMIG.js.map → snooze-T2WWIKZN.js.map} +0 -0
- /package/dist/{start-PGVZZJQT.js.map → start-AWHOIA3Q.js.map} +0 -0
- /package/dist/{state-XHTOESKK.js.map → state-HK67C4UA.js.map} +0 -0
- /package/dist/{status-CXIRNRMP.js.map → status-QE2DA6RR.js.map} +0 -0
- /package/dist/{statusline-HPH2ORNT.js.map → statusline-Z5HLKDIA.js.map} +0 -0
- /package/dist/{statusline-hook-Q645N4XF.js.map → statusline-hook-VPPS3PFO.js.map} +0 -0
- /package/dist/{stop-IJNUSRIG.js.map → stop-YOU3P3ZR.js.map} +0 -0
- /package/dist/{sync-3HMCC55V.js.map → sync-74EFTPBJ.js.map} +0 -0
- /package/dist/{time-DUDNSHM3.js.map → time-ZGMZZ5OY.js.map} +0 -0
- /package/dist/{time-actions-M4QTTH4M.js.map → time-actions-VAGRSY5B.js.map} +0 -0
- /package/dist/{todo-QMXJ5R3E.js.map → todo-UVKGOG7D.js.map} +0 -0
- /package/dist/{tree-TL4GISI5.js.map → tree-FXTCWC6D.js.map} +0 -0
- /package/dist/{update-3TODL7J3.js.map → update-5QSRHIWH.js.map} +0 -0
- /package/dist/{usage-YFTN2IS7.js.map → usage-CW7CDFU3.js.map} +0 -0
- /package/dist/{usage-ask-EZR3W3UW.js.map → usage-ask-V2SIRW4F.js.map} +0 -0
- /package/dist/{version-LNHKXZBP.js.map → version-RJ4PCHPB.js.map} +0 -0
- /package/dist/{wait-B37BTCVG.js.map → wait-XXC3I6DK.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/comments/pending-delivery.ts"],"sourcesContent":["/**\n * Bridge between `work web` review comments and any live Claude session\n * running in the same worktree. Storage (state.db, see db.ts):\n *\n * comments the comment stores (comment-file-store.ts)\n * comment_deliveries (session, comment id) pairs surfaced to Claude\n *\n * \"Pending\" = published, user-authored, not in the delivered list. Replies\n * authored by Claude (author === 'claude') are excluded — Claude wrote\n * them; we don't need to echo them back.\n *\n * Delivery is lazy: when a Claude in the matching worktree submits a\n * prompt, the hook reads pending comments via this module, prints them as\n * a system-reminder block to stdout (which Claude Code injects into the\n * conversation), and marks them delivered.\n */\n\nimport { checkedOutBranch } from '../git/git-head.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { loadHistory, type WorktreeSession } from '../sessions/history.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { getCommentFileStore, readStoreComments, readStoresComments } from './comment-file-store.js';\nimport { scopeHashFor } from '../diff/repo-spec.js';\nimport { tx, withDb, type Db } from '../platform/db.js';\nimport type { Comment } from './comment-types.js';\n\nfunction deliveredIds(d: Db, sessionId: string): Set<string> {\n return new Set(\n (d.prepare('SELECT comment_id FROM comment_deliveries WHERE session_id = ?').all(sessionId) as Array<{ comment_id: string }>).map(\n (r) => r.comment_id,\n ),\n );\n}\n\n/** Norm-path comparison that mirrors what we do server-side. */\nfunction normalize(p: string): string {\n return path.resolve(p).replace(/\\\\/g, '/').toLowerCase();\n}\n\n/** Map a Claude cwd back to a session. Tries direct-match against any\n * session's path first, then ancestor match (so cwd inside a subdir of a\n * worktree still resolves to the worktree's session). */\n/**\n * Two sessions on one folder (an old entry and a newer one, a typo'd target\n * re-added): which of them a Claude there is. Not an archived one when the\n * other isn't; then the one whose branch is checked out there; then the one\n * entered last. The oldest used to win, so status and comments went to an\n * entry nobody looks at.\n */\nfunction owns(candidate: WorktreeSession, current: WorktreeSession, root: string): boolean {\n if (!!candidate.archivedAt !== !!current.archivedAt) return !candidate.archivedAt;\n const onBranch = checkedOutBranch(root);\n const a = candidate.branch === onBranch;\n const b = current.branch === onBranch;\n if (a !== b) return a;\n return (Date.parse(candidate.lastAccessedAt) || 0) > (Date.parse(current.lastAccessedAt) || 0);\n}\n\nexport function findSessionForCwd(cwd: string, sessions: WorktreeSession[] = loadHistory()): WorktreeSession | null {\n const here = normalize(cwd);\n // Deepest root containing cwd wins, so nested worktrees disambiguate. A\n // group's roots include the group root (the sub-repos' parent) — that's\n // where `work tree` launches Claude for a group, so hooks fire from there.\n let best: { session: WorktreeSession; root: string; len: number } | null = null;\n for (const s of sessions) {\n const roots = s.isGroup && s.paths[0] ? [...s.paths, path.dirname(s.paths[0])] : s.paths;\n for (const root of roots) {\n const r = normalize(root);\n if (!(here === r || here.startsWith(r + '/'))) continue;\n if (!best || r.length > best.len || (r.length === best.len && owns(s, best.session, root))) {\n best = { session: s, root, len: r.length };\n }\n }\n }\n if (!best) return null;\n // A separate checkout nested INSIDE the session's tree (a git worktree at\n // <repo>/.claude/worktrees/x, a vendored repo) is not this session: its\n // Claude must not report status, take checkpoints or receive comments as\n // if it were the parent. Any `.git` between cwd and the matched root —\n // other than the session's own repos — marks a different checkout.\n // (Plain fs checks: this runs on every hook.)\n const own = new Set(best.session.paths.map(normalize));\n const top = normalize(best.root);\n for (let dir = path.resolve(cwd); normalize(dir) !== top && normalize(dir).startsWith(top + '/'); dir = path.dirname(dir)) {\n if (!own.has(normalize(dir)) && fs.existsSync(path.join(dir, '.git'))) return null;\n if (path.dirname(dir) === dir) break;\n }\n return best.session;\n}\n\nfunction isPendingFor(delivered: Set<string>) {\n return (c: Comment) => c.status === 'published' && c.author === 'user' && !delivered.has(c.id);\n}\n\n/** Returns published user comments that haven't been delivered yet.\n * Reads through the file-store cache so we see in-flight writes\n * (`session-meta.ts` and other readers couldn't, when they re-read the\n * disk directly). */\n/**\n * The line typed into an idle Claude (or given as the first prompt of one\n * work starts) so its UserPromptSubmit hook attaches the pending comments.\n * Short on purpose: a long typed note got mangled by Claude Code's paste\n * handling. It says where the content is, so it reads right in the\n * transcript.\n */\nexport const NOTE_NUDGE =\n 'work has new notes for you (review feedback, CI results or comments); they are attached to this message. Work through them now.';\n\nexport function readPendingForSession(sessionId: string): Comment[] {\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n return readStoreComments(sessionId).filter(isPendingFor(delivered));\n}\n\n/** Comment-store ids for every `wd` scope that could cover this worktree.\n * A scope is keyed by `sha1` of its sorted repo roots (see\n * `repo-spec.scopeHashFor`), so from a session's paths we can rebuild the\n * exact ids without consulting `work web`'s in-memory scope registry:\n * - the whole-set hash → a group `wd` opened at the group root, or the\n * single-repo `wd` (one path);\n * - each individual path's hash → a `wd` opened inside one sub-repo of a\n * group worktree.\n * `registerScope` hashes `path.resolve()`d roots, so we resolve here too or\n * the hashes won't line up. Mirrors `scope-manager.commentStoreIdForScope`\n * (`scope-<hash>`). */\nexport function scopeStoreIdsForPaths(paths: string[]): string[] {\n const resolved = paths.map((p) => path.resolve(p));\n const ids = new Set<string>();\n ids.add(`scope-${scopeHashFor(resolved)}`);\n for (const p of resolved) ids.add(`scope-${scopeHashFor([p])}`);\n return [...ids];\n}\n\n/**\n * Pending comments for a whole worktree: the session's own comment store\n * PLUS any `wd` / `wd -c` scope review store covering the same paths.\n *\n * `wd` registers its review under a scope-hash comment store, not the\n * session store the hook reads — without this merge, comments left in the\n * `wd` review UI would never reach the Claude running in that worktree.\n * Delivered-tracking stays per-session (one `<sessionId>.delivered.json`),\n * so a comment surfaced here won't be re-delivered regardless of which\n * store it came from.\n */\nexport function readPendingForWorktree(session: WorktreeSession, sessionId: string = sessionIdFor(session)): Comment[] {\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n const pending = isPendingFor(delivered);\n const storeIds = [sessionId, ...scopeStoreIdsForPaths(session.paths)];\n const rows = readStoresComments(storeIds); // one query: this runs for every row of /api/sessions\n const seen = new Set<string>();\n const out: Comment[] = [];\n for (const storeId of storeIds) {\n for (const c of rows.get(storeId) ?? []) {\n if (seen.has(c.id) || !pending(c)) continue;\n seen.add(c.id);\n out.push(c);\n }\n }\n return out;\n}\n\n/**\n * What was handed to Claude is done once its turn really ends: your review\n * comments and work's notes to it (PR feedback, CI, a prompt you sent) —\n * every top-level comment of yours it was given, in the session's store and\n * any `wd` scope store over its paths — are marked resolved. Left open, they\n * piled up on the Diff tab's badge (three PR-watch notes read as \"3\"), to\n * resolve or delete by hand. Resolved threads stay listed (dimmed) and can\n * be reopened. Claude's own replies are left as they are. Returns the ids\n * resolved.\n */\nexport function resolveAddressed(session: WorktreeSession): string[] {\n const sessionId = sessionIdFor(session);\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n if (delivered.size === 0) return [];\n const done: string[] = [];\n for (const storeId of [sessionId, ...scopeStoreIdsForPaths(session.paths)]) {\n const open = readStoreComments(storeId).filter(\n (c) => delivered.has(c.id) && c.author === 'user' && c.status === 'published' && !c.parentId && !c.resolved,\n );\n if (open.length === 0) continue;\n const store = getCommentFileStore(storeId);\n for (const c of open) if (store.setResolved(c.id, true)) done.push(c.id);\n }\n return done;\n}\n\n/** Persist a delivery batch, so these ids are never surfaced again. */\nexport function markDelivered(sessionId: string, ids: string[]): void {\n if (ids.length === 0) return;\n tx((d) => {\n const ins = d.prepare('INSERT OR IGNORE INTO comment_deliveries (session_id, comment_id) VALUES (?, ?)');\n for (const id of ids) ins.run(sessionId, id);\n });\n}\n\n/**\n * Claim comments for delivery: of `ids`, return the ones nobody has\n * delivered yet, and mark them delivered — atomically. Two deliverers\n * racing (a Stop hook and the PTY push for the same comment) then can't\n * both send it: only the one that claimed it does. A deliverer whose send\n * fails gives the ids back with `releaseClaim`.\n */\nexport function claimForDelivery(sessionId: string, ids: string[]): string[] {\n if (ids.length === 0) return [];\n // INSERT OR IGNORE in one write transaction: a row inserted here is our\n // claim; one that already existed was someone else's.\n return tx((d) => {\n const ins = d.prepare('INSERT OR IGNORE INTO comment_deliveries (session_id, comment_id) VALUES (?, ?)');\n return ids.filter((id) => ins.run(sessionId, id).changes > 0);\n });\n}\n\n/** Undo a claim whose delivery failed, so the next hook picks them up. */\nexport function releaseClaim(sessionId: string, ids: string[]): void {\n if (ids.length === 0) return;\n tx((d) => {\n const del = d.prepare('DELETE FROM comment_deliveries WHERE session_id = ? AND comment_id = ?');\n for (const id of ids) del.run(sessionId, id);\n });\n}\n\n/** Cap the size of one comment body we surface to Claude. A pathologically\n * long comment shouldn't blow out Claude's context — we truncate, then\n * hint at the rest via \"(truncated)\". 4 KB is generous for a code-review\n * note while leaving headroom for batches. */\nconst MAX_BODY_BYTES = 4 * 1024;\n/** A general note: a prompt, or work's own note (a PR review round quotes\n * every thread, then a bot's overview). 4 KB once cut such a note before\n * the line telling Claude how to draft its replies. */\nconst MAX_NOTE_BYTES = 16 * 1024;\n/** Overall cap on the whole system-reminder payload. Multiple long\n * comments at once still get bounded — but room for four whole notes, since\n * the cut falls on the newest one's end: its instructions. */\nconst MAX_TOTAL_BYTES = 4 * MAX_NOTE_BYTES;\n\n/**\n * Format pending comments as a system-reminder block suitable for stdout.\n * Returns empty string when there's nothing pending — the caller (the\n * `work hook` CLI) just exits silently in that case.\n *\n * Truncates pathologically long bodies and caps the overall payload so\n * one runaway comment can't displace the rest of Claude's context.\n */\nexport function formatPendingForPrompt(pending: Comment[]): string {\n if (pending.length === 0) return '';\n\n const sorted = [...pending].sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n\n const general = sorted.filter((c) => c.side === 'general' && !c.parentId);\n const inline = sorted.filter((c) => c.side !== 'general' && !c.parentId);\n const replies = sorted.filter((c) => c.parentId);\n\n const lines: string[] = [];\n lines.push('<system-reminder>');\n lines.push(`New review comments from \\`work web\\` (${pending.length} item${pending.length === 1 ? '' : 's'}):`);\n lines.push('');\n\n if (general.length > 0) {\n lines.push('## General notes');\n for (const c of general) {\n // General notes (this is where `work broadcast` lands) may be multi-line\n // prompts — deliver the whole body, not just line 1. Only the byte cap\n // applies. Inline/reply comments still use the one-line `formatBody`.\n lines.push(formatFullBody('-', c));\n }\n lines.push('');\n }\n\n if (inline.length > 0) {\n lines.push('## Inline comments');\n for (const c of inline) {\n const where = `${c.repo}/${c.file}:${c.line} (${c.side})`;\n lines.push(formatBody(`- ${where}`, c));\n }\n lines.push('');\n }\n\n if (replies.length > 0) {\n lines.push('## Replies');\n for (const c of replies) {\n lines.push(formatBody(`- (reply to ${c.parentId})`, c));\n }\n lines.push('');\n }\n\n lines.push(\n 'Address them as part of your next response. You can reply via the same review UI by posting back to the latest review URL at `~/.work/web.url` + `/api/sessions/<id>/comments` with `author: \"claude\"`.',\n );\n lines.push('</system-reminder>');\n const out = lines.join('\\n');\n if (out.length <= MAX_TOTAL_BYTES) return out;\n const trimmed = out.slice(0, MAX_TOTAL_BYTES - 200);\n return (\n trimmed +\n '\\n\\n(…review payload truncated for context-window safety; ' +\n `${pending.length} comment(s) total — open work web for the full list.)\\n` +\n '</system-reminder>'\n );\n}\n\nfunction formatBody(prefix: string, c: Comment): string {\n const lead = c.body.split('\\n')[0].trim();\n const capped = lead.length > MAX_BODY_BYTES ? `${lead.slice(0, MAX_BODY_BYTES)}…` : lead;\n return `${prefix}: ${capped}${c.body.includes('\\n') ? ' …' : ''}`;\n}\n\n/** Like `formatBody` but preserves the full multi-line body (only the note\n * cap applies). Multi-line bodies are emitted under the bullet, indented, so\n * a broadcast prompt arrives intact rather than truncated to its first line. */\nfunction formatFullBody(prefix: string, c: Comment): string {\n const body = c.body.trim();\n const capped = body.length > MAX_NOTE_BYTES ? `${body.slice(0, MAX_NOTE_BYTES)}…` : body;\n const bodyLines = capped.split('\\n');\n if (bodyLines.length === 1) return `${prefix}: ${bodyLines[0]}`;\n const [first, ...rest] = bodyLines;\n return [`${prefix}: ${first}`, ...rest.map((l) => ` ${l}`)].join('\\n');\n}\n\n/** Re-export so consumers don't have to know which module owns it. */\nexport { sessionIdFor };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,OAAO,QAAQ;AACf,OAAO,UAAU;AAQjB,SAAS,aAAa,GAAO,WAAgC;AAC3D,SAAO,IAAI;AAAA,IACR,EAAE,QAAQ,gEAAgE,EAAE,IAAI,SAAS,EAAoC;AAAA,MAC5H,CAAC,MAAM,EAAE;AAAA,IACX;AAAA,EACF;AACF;AAGA,SAAS,UAAU,GAAmB;AACpC,SAAO,KAAK,QAAQ,CAAC,EAAE,QAAQ,OAAO,GAAG,EAAE,YAAY;AACzD;AAYA,SAAS,KAAK,WAA4B,SAA0B,MAAuB;AACzF,MAAI,CAAC,CAAC,UAAU,eAAe,CAAC,CAAC,QAAQ,WAAY,QAAO,CAAC,UAAU;AACvE,QAAM,WAAW,iBAAiB,IAAI;AACtC,QAAM,IAAI,UAAU,WAAW;AAC/B,QAAM,IAAI,QAAQ,WAAW;AAC7B,MAAI,MAAM,EAAG,QAAO;AACpB,UAAQ,KAAK,MAAM,UAAU,cAAc,KAAK,MAAM,KAAK,MAAM,QAAQ,cAAc,KAAK;AAC9F;AAEO,SAAS,kBAAkB,KAAa,WAA8B,YAAY,GAA2B;AAClH,QAAM,OAAO,UAAU,GAAG;AAI1B,MAAI,OAAuE;AAC3E,aAAW,KAAK,UAAU;AACxB,UAAM,QAAQ,EAAE,WAAW,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,KAAK,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE;AACnF,eAAW,QAAQ,OAAO;AACxB,YAAM,IAAI,UAAU,IAAI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|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/time/month-gather.ts","../src/core/time/time-deps.ts","../src/core/jira/jira.ts","../src/core/time/graph.ts"],"sourcesContent":["import { buildDay, type TimeDeps } from './time-days.js';\nimport { readDays } from './time-store.js';\nimport { daysBetween, localDay } from './time-view.js';\nimport { monthRange, needsBuild } from './time-month.js';\n\n/**\n * Gather these days (the Month view of a past month): every day of it the\n * keeper didn't reach — never gathered, or gathered before it ended — built\n * one after another in the background, the tab told after each. One gather\n * of a month at a time; how the last one failed is kept for the view.\n */\n\nexport interface MonthGather {\n /** Start gathering `month`; false when there's nothing to gather or it's under way already. */\n start: (month: string) => boolean;\n state: (month: string) => { gathering: boolean; error: string | null };\n /** Resolves when the month's gather under way (if any) is done. */\n done: (month: string) => Promise<void>;\n}\n\nexport function createMonthGather(deps: TimeDeps, opts: { changed: (day: string) => void; now?: () => number }): MonthGather {\n const now = opts.now ?? (() => Date.now());\n const running = new Map<string, Promise<void>>();\n const errors = new Map<string, string>();\n return {\n start: (month) => {\n if (running.has(month)) return false;\n const today = localDay(now());\n const range = monthRange(month, today);\n if (!range) return false;\n const built = new Map(readDays(range.from, range.to).map((r) => [r.day, r.builtAt]));\n const days = daysBetween(range.from, range.to).filter((d) => d < today && needsBuild(d, built.get(d)));\n if (!days.length) return false;\n errors.delete(month);\n const p = (async () => {\n const failed: string[] = [];\n for (const d of days) {\n try {\n await buildDay(d, deps);\n opts.changed(d);\n } catch (err) {\n failed.push(`${d}: ${(err as Error).message}`);\n }\n }\n if (failed.length) errors.set(month, `${failed.length} of ${days.length} days not gathered — ${failed.join('; ')}`);\n })().finally(() => {\n running.delete(month);\n // The view's \"gathering…\" ends even when the last day failed.\n opts.changed(days[days.length - 1]);\n });\n running.set(month, p);\n return true;\n },\n state: (month) => ({ gathering: running.has(month), error: errors.get(month) ?? null }),\n done: (month) => running.get(month) ?? Promise.resolve(),\n };\n}\n","import fs from 'node:fs';\nimport { knownHosts } from '../hosts/index.js';\nimport { loadConfig } from '../platform/config.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\nimport { loadHistory } from '../sessions/history.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { sessionWorkTime } from '../conversations/work-time-source.js';\nimport { runGitAsync } from '../diff/git-tree-snapshot.js';\nimport { fetchMyIssuesOrThrow, issueIdOf, issueNumberField, myAccountId, searchIssuesOrThrow } from '../jira/jira.js';\nimport { runInternal } from '../diff/checkpoint-summary.js';\nimport { chatsOf, chatsSince, graphApp, graphToken, meetingsOn, type ChatsRead } from './graph.js';\nimport type { TimeJiraEvidence } from '../api-types.js';\nimport { readIssueIds, rememberIssueId } from './time-store.js';\nimport { isIssueKey } from './allocate.js';\nimport type { TimeDeps } from './time-days.js';\nimport { addDays, daysBetween, DEFAULT_CATCH_UP_DAYS, listFrom, localDay, MAX_RANGE_DAYS, timeSettings } from './time-view.js';\n\n/**\n * The Time tab's real I/O: the sessions in state.db and their transcripts,\n * `git log` in every enrolled repo (your commits, by each repo's\n * `user.email`), and Jira through `acli` (what you moved; titles).\n */\nasync function graphTokenNow(): Promise<string | null> {\n const app = graphApp(loadConfig()?.time?.graph, process.env);\n return 'why' in app ? null : graphToken(app);\n}\n\n/**\n * The commits of a `git log --format=%H%x09%aI%x09%ce%x09%s` written on the\n * day: by author date, so a rebase, an amend or a cherry-pick counts on the\n * day of the work, not of the rewrite; and none a git host committed (a squash\n * merge: the work is already counted by its own commits), nor a stash's own\n * commits. Pure.\n */\nexport function commitsWrittenOn(stdout: string, day: string): Array<{ sha: string; subject: string }> {\n const out: Array<{ sha: string; subject: string }> = [];\n for (const line of stdout.split('\\n').filter(Boolean)) {\n const [sha, authored, committer, ...rest] = line.split('\\t');\n if (knownHosts().some((h) => h.hostCommit(committer ?? ''))) continue;\n // A stash's helper commits, should something other than refs/stash (left out of the log) still reach them.\n if (/^(index|untracked files) on /.test(rest.join('\\t'))) continue;\n const at = Date.parse(authored ?? '');\n if (Number.isNaN(at) || localDay(at) !== day) continue;\n out.push({ sha, subject: rest.join('\\t') });\n }\n return out;\n}\n\n/**\n * How long one read (a session's working time, a repo's commits, the Teams\n * chats, your assigned issues) serves the days after it, at most: a run of the\n * keeper starts fresh (`fresh`), and a catch-up of slow days (the AI step can\n * take a minute) reads each once, not once per day.\n */\nconst READ_FRESH_MS = 30 * 60_000;\n\n/** Issues one day's Jira search returns at most (the default 50 would cut a sprint's close or a triage short). */\nexport const JIRA_DAY_LIMIT = 500;\n\n/** What you did in Jira that day: status changes, and anything else you updated (a comment, an edit) — `updatedBy()`, by account id. */\nexport async function jiraOn(day: string): Promise<TimeJiraEvidence[]> {\n const d = day.replace(/-/g, '/');\n // To the next day's start, not 23:59: a change in a day's last minute would be on no day at all.\n const end = addDays(day, 1).replace(/-/g, '/');\n // Throws when acli can't answer: the day keeps what it had (time-days.ts), rather than \"did nothing\".\n const moved = await searchIssuesOrThrow(`status CHANGED BY currentUser() DURING (\"${d} 00:00\", \"${end} 00:00\")`, JIRA_DAY_LIMIT);\n const out: TimeJiraEvidence[] = moved.map((i) => ({ key: i.key, summary: i.summary, what: `moved (now ${i.status || 'changed'})` }));\n const account = loadConfig()?.time?.tempo?.accountId || process.env.JIRA_ACCOUNT_ID || (await myAccountId());\n if (account && /^[\\w:-]+$/.test(account)) {\n // The same bounds, with times (a bare end date may mean the whole of that day, or its start).\n // A failure throws too: half the answer would drop the day's commented-on issues.\n const updated = await searchIssuesOrThrow(`issuekey IN updatedBy(\"${account}\", \"${d} 00:00\", \"${end} 00:00\")`, JIRA_DAY_LIMIT);\n for (const i of updated)\n if (!out.some((o) => o.key === i.key)) out.push({ key: i.key, summary: i.summary, what: 'updated by you (a comment or an edit)' });\n }\n return out;\n}\n\n/**\n * Titles of these keys and whether each is done, in one search; when that is\n * refused (one key that doesn't exist fails the whole JQL — a branch's\n * `FOO-12`), each key alone, keeping the ones found. Throws when none could be\n * asked about (acli down): the day keeps what it had.\n */\nexport async function titlesOf(\n keys: string[],\n search: (jql: string, limit: number) => Promise<Array<{ key: string; summary: string; statusCategory?: string }>>,\n now = Date.now(),\n): Promise<Record<string, { title: string; done: boolean }>> {\n // Keys Jira said it doesn't have stay out of the search for an hour: one such key would send every rebuild\n // of the day down the one-key-at-a-time path.\n for (const [k, at] of refused) if (now - at > REFUSED_FOR_MS) refused.delete(k);\n const valid = keys.filter((k) => isIssueKey(k) && !refused.has(k));\n if (!valid.length) return {};\n const of = (issues: Array<{ key: string; summary: string; statusCategory?: string }>) =>\n issues.map((i) => [i.key, { title: i.summary, done: i.statusCategory === 'done' }] as const);\n try {\n return Object.fromEntries(of(await search(`key in (${valid.join(', ')})`, valid.length)));\n } catch (err) {\n if (valid.length === 1) throw err;\n // A few at a time (each is an acli process).\n const one: Array<ReturnType<typeof of> | null> = [];\n for (let i = 0; i < valid.length; i += TITLES_AT_ONCE)\n one.push(...(await Promise.all(valid.slice(i, i + TITLES_AT_ONCE).map((k) => search(`key = ${k}`, 1).then(of, () => null)))));\n if (one.every((r) => r === null)) throw err;\n // Asked alone and still refused, while others answered: Jira doesn't have it.\n one.forEach((r, i) => r === null && refused.set(valid[i], now));\n return Object.fromEntries(one.flatMap((r) => r ?? []));\n }\n}\n\n/**\n * Story points of these tasks: one acli view each (a search can't return a custom field), a few at a time.\n * A task with none, or one Jira refuses, is left out; throws when none could be asked about (acli down).\n */\nexport async function pointsOf(keys: string[], read: (key: string) => Promise<number | null>): Promise<Record<string, number>> {\n const out: Record<string, number> = {};\n let answered = 0;\n for (let i = 0; i < keys.length; i += TITLES_AT_ONCE)\n await Promise.all(\n keys.slice(i, i + TITLES_AT_ONCE).map((k) =>\n read(k).then(\n (p) => {\n answered++;\n if (p !== null && p > 0) out[k] = p;\n },\n () => {},\n ),\n ),\n );\n if (keys.length && !answered) throw new Error('Jira could not be asked about story points');\n return out;\n}\n\nconst TITLES_AT_ONCE = 3;\nconst REFUSED_FOR_MS = 60 * 60_000;\nconst refused = new Map<string, number>();\n\n/** Forget the keys Jira refused (tests). */\nexport function resetRefusedKeys(): void {\n refused.clear();\n}\n\n/** What `defaultTimeDeps` reads with (tests pass their own). */\nexport interface TimeIo {\n git: (cwd: string, args: string[]) => Promise<{ status: number | null; stdout: string }>;\n workTime: (s: WorktreeSession, now: number, days: number) => Promise<{ byDay: Array<{ day: string; ms: number }> }>;\n /** Enrolled repos: alias → folder. */\n repos: () => Record<string, string>;\n exists: (folder: string) => boolean;\n}\n\nconst realIo: TimeIo = {\n git: (cwd, args) => runGitAsync(cwd, { args }),\n workTime: (s, now, days) => sessionWorkTime(s, now, days),\n repos: () => loadConfig()?.repos ?? {},\n exists: (folder) => fs.existsSync(folder),\n};\n\n/**\n * Your commits in one repo since a day, read once (a catch-up asks day by day,\n * oldest first: one `git log` from the oldest serves the rest).\n * `--exclude=refs/stash` keeps a stash's commits out; `--since` is the\n * committer date, never before the author date, so every commit written\n * since is in (and more, which `commitsWrittenOn` drops); `--fixed-strings`:\n * the email as it is (`jane+work@corp.com` isn't a pattern), whole (`<…>`). No email set:\n * none of yours to find (''). A git that fails throws: the day keeps the\n * commits it had.\n */\nasync function commitLog(git: TimeIo['git'], repo: string, from: string): Promise<string> {\n const email = (await git(repo, ['config', 'user.email'])).stdout.trim();\n if (!email) return '';\n const log = await git(repo, [\n 'log',\n '--exclude=refs/stash',\n '--all',\n '--no-merges',\n '--fixed-strings',\n `--since=${from} 00:00:00`,\n // The address in its angle brackets: --author matches anywhere in \"Name <email>\", and `an@corp` is in `ivan@corp`.\n `--author=<${email}>`,\n '--format=%H%x09%aI%x09%ce%x09%s',\n ]);\n if (log.status !== 0) throw new Error(`git log failed in ${repo}`);\n return log.stdout;\n}\n\nexport function defaultTimeDeps(io: TimeIo = realIo): TimeDeps {\n const catchUpDays = () => timeSettings(loadConfig()?.time).catchUpDays ?? DEFAULT_CATCH_UP_DAYS;\n // How many days the work-time reader goes back: as far as the list (the whole month at least), or to an older\n // day being gathered (a past month's Gather these days) — never more than a quarter.\n const reachFor = (day: string) => {\n const today = localDay();\n const from = listFrom(today, catchUpDays());\n return Math.min(MAX_RANGE_DAYS, daysBetween(day < from ? day : from, today).length);\n };\n // A session's working time, read once for every day a run builds (each read goes through all its transcripts).\n const workTime = new Map<string, { at: number; reach: number; byDay: Promise<Map<string, number>> }>();\n const logs = new Map<string, { from: string; at: number; out: Promise<string> }>();\n // One read of the chats serves every day after its first: a 14-day catch-up is one read, not fourteen.\n let chats: { from: string; at: number; read: Promise<ChatsRead> } | null = null;\n let assigned: { at: number; list: Promise<Array<{ key: string; title: string }>> } | null = null;\n // What a turn doesn't move, read once until the next full run: a day's meetings, its Jira, its tickets' titles\n // (network: Graph and acli, every two minutes while Claude works otherwise).\n const slow = new Map<string, { at: number; read: Promise<unknown> }>();\n const once = <T>(key: string, read: () => Promise<T>): Promise<T> => {\n const c = slow.get(key);\n if (c && Date.now() - c.at <= READ_FRESH_MS) return c.read as Promise<T>;\n const p = read();\n slow.set(key, { at: Date.now(), read: p });\n p.catch(() => slow.delete(key)); // a failed read isn't kept\n return p;\n };\n return {\n fresh: (what = 'all') => {\n workTime.clear();\n logs.clear();\n if (what === 'local') return;\n chats = null;\n slow.clear();\n assigned = null;\n },\n sessions: () => loadHistory(),\n minutesOn: async (s, day) => {\n const id = sessionIdFor(s);\n let w = workTime.get(id);\n const reach = reachFor(day);\n if (!w || Date.now() - w.at > READ_FRESH_MS || w.reach < reach) {\n const byDay = io.workTime(s, Date.now(), reach).then((t) => new Map(t.byDay.map((d) => [d.day, d.ms])));\n w = { at: Date.now(), reach, byDay };\n workTime.set(id, w);\n byDay.catch(() => workTime.delete(id)); // a failed read isn't kept\n }\n return ((await w.byDay).get(day) ?? 0) / 60_000;\n },\n minutesFrom: () => listFrom(localDay(), catchUpDays()),\n commits: async (day) => {\n const repos = io.repos();\n const aliasOf = new Map<string, string>();\n for (const [alias, folder] of Object.entries(repos)) if (!aliasOf.has(folder)) aliasOf.set(folder, alias);\n const seen = new Set<string>();\n const out: Array<{ repo: string; sha: string; subject: string }> = [];\n // Every repo's read started at once (each a git process), then taken in order.\n const reads = [...aliasOf.keys()]\n .filter((repo) => io.exists(repo)) // a folder gone: nothing to read there (not a failure)\n .map((repo) => {\n let l = logs.get(repo);\n if (!l || day < l.from || Date.now() - l.at > READ_FRESH_MS) {\n const read = commitLog(io.git, repo, day);\n l = { from: day, at: Date.now(), out: read };\n logs.set(repo, l);\n read.catch(() => logs.delete(repo)); // a failed read isn't kept\n }\n return { repo, out: l.out };\n });\n for (const { repo, out: log } of reads) {\n for (const c of commitsWrittenOn(await log, day)) {\n if (seen.has(c.sha)) continue;\n seen.add(c.sha);\n out.push({ repo: aliasOf.get(repo) ?? repo, ...c });\n }\n }\n return out;\n },\n jiraMoved: (day) => once(`jira:${day}`, () => jiraOn(day)),\n titles: (keys) => once(`titles:${[...keys].sort().join(',')}`, () => titlesOf(keys, searchIssuesOrThrow)),\n points: async (keys) => {\n const field = timeSettings(loadConfig()?.time).storyPointsField;\n return field ? once(`points:${field}:${[...keys].sort().join(',')}`, () => pointsOf(keys, (k) => issueNumberField(k, field))) : {};\n },\n settings: () => timeSettings(loadConfig()?.time),\n // Outlook and Teams only once you signed in (the Time tab's Connect): none otherwise. A sign-in that stopped\n // working, or no network, throws (graphToken): the day keeps the meetings and chats it had.\n meetings: async (day) => {\n const token = await graphTokenNow();\n return token ? once(`meetings:${day}`, () => meetingsOn(day, token)) : undefined;\n },\n chats: async (day) => {\n const token = await graphTokenNow();\n if (!token) return undefined;\n if (!chats || day < chats.from || Date.now() - chats.at > READ_FRESH_MS) {\n const read = chatsSince(day, token);\n chats = { from: day, at: Date.now(), read };\n read.catch(() => (chats = null)); // a failed read isn't kept\n }\n // A chat busier than was read reached back only so far: a day before that isn't known, and keeps what it had.\n return chatsOf(await chats.read, day);\n },\n // Throws when acli can't list them: the day keeps its AI answer and the projects it knew (time-days.ts).\n candidates: () => {\n if (!assigned || Date.now() - assigned.at > READ_FRESH_MS) {\n const list = fetchMyIssuesOrThrow().then((is) => is.map((i) => ({ key: i.key, title: i.summary })));\n assigned = { at: Date.now(), list };\n list.catch(() => (assigned = null)); // a failed read isn't kept\n }\n return assigned.list;\n },\n classify: (prompt) => runInternal(prompt, 60_000, { small: true }),\n issueId: async (key) => {\n const known = readIssueIds()[key];\n if (known !== undefined) return known;\n const id = await issueIdOf(key);\n if (id !== null) rememberIssueId(key, id);\n return id;\n },\n };\n}\n","import { execFile } from 'node:child_process';\nimport { explainNotOnPath, programPath } from '../platform/program-path.js';\n\nexport interface JiraIssue {\n key: string;\n summary: string;\n status: string;\n /** Jira's category for the status: new (to do), indeterminate (in progress, review…), done. Orders the board's columns. */\n statusCategory?: 'new' | 'indeterminate' | 'done';\n issuetype: string;\n priority: string;\n url: string;\n /** The project your issue rules start it in (`issues.rules`), when they say: Start opens with it filled in. */\n startsIn?: string;\n}\n\nfunction execAsync(cmd: string, args: string[], timeout: number): Promise<string> {\n return new Promise((resolve, reject) => {\n // `windowsHide: true` prevents a console window from flashing on\n // Windows whenever the Jira pane refreshes (every 120 s when open).\n // Without it, opening the Jira pane in `work web` triggers a\n // visible terminal popup.\n execFile(programPath(cmd), args, { encoding: 'utf-8', timeout, windowsHide: true }, (err, stdout) => {\n if (err) reject(explainNotOnPath(err));\n else resolve(stdout ?? '');\n });\n });\n}\n\n/** Run `acli jira auth status` once and parse it for both availability\n * AND the site URL. Replaces the previous two-call pattern where\n * `isAcliAvailable` and `getJiraSiteUrl` each shelled out independently. */\nasync function probeAcli(): Promise<{ available: boolean; siteUrl: string }> {\n try {\n const stdout = await execAsync('acli', ['jira', 'auth', 'status'], 5000);\n const match = stdout.match(/Site:\\s+(\\S+)/);\n return {\n available: true,\n siteUrl: match ? `https://${match[1]}` : '',\n };\n } catch {\n return { available: false, siteUrl: '' };\n }\n}\n\n/** The fields of `acli jira workitem search --json` this reads; all optional — it is someone else's output. */\ninterface AcliIssue {\n key?: string;\n fields?: {\n summary?: string;\n status?: { name?: string; statusCategory?: { key?: string } };\n issuetype?: { name?: string };\n priority?: { name?: string };\n };\n}\n\n/** Jira's three status categories (the board's column order); anything else isn't one. */\nfunction isStatusCategory(k: unknown): k is NonNullable<JiraIssue['statusCategory']> {\n return k === 'new' || k === 'indeterminate' || k === 'done';\n}\n\nfunction parseIssuesJson(stdout: string, siteUrl: string): JiraIssue[] {\n const parsed = JSON.parse(stdout) as { issues?: AcliIssue[] } | AcliIssue[] | null;\n const issues: AcliIssue[] = (Array.isArray(parsed) ? parsed : parsed?.issues) ?? [];\n\n return issues.map((issue) => {\n const fields = issue.fields ?? {};\n return {\n key: issue.key ?? '',\n summary: fields.summary ?? '',\n status: fields.status?.name ?? '',\n ...(isStatusCategory(fields.status?.statusCategory?.key) ? { statusCategory: fields.status.statusCategory.key } : {}),\n issuetype: fields.issuetype?.name ?? '',\n priority: fields.priority?.name ?? '',\n url: siteUrl ? `${siteUrl}/browse/${issue.key}` : '',\n };\n });\n}\n\n/**\n * Your open issues: by the status's category, not `resolution = Unresolved` — service-desk workflows set a\n * resolution on issues still open (\"Waiting for feedback\", a Review), which hid them from the Jira tab.\n */\nexport const MY_ISSUES_JQL = 'assignee = currentUser() AND statusCategory != Done AND status NOT IN (Archived) ORDER BY updated DESC';\n\nasync function searchMyIssues(siteUrl: string): Promise<JiraIssue[]> {\n try {\n const stdout = await execAsync('acli', ['jira', 'workitem', 'search', '--jql', MY_ISSUES_JQL, '--json', '--limit', '50'], 15000);\n if (!stdout) return [];\n return parseIssuesJson(stdout, siteUrl);\n } catch {\n return [];\n }\n}\n\n/**\n * Your open issues, or a throw when acli can't list them (not there, signed\n * out, offline) — for the Jira watch, where \"none\" and \"couldn't ask\" must\n * differ: an empty list taken for the truth would use up the one-time\n * adoption of issues the list newly shows (`adoptListChange`).\n */\nexport async function fetchMyIssuesOrThrow(): Promise<JiraIssue[]> {\n const probe = await probeAcli();\n if (!probe.available) throw new Error('acli is not available (installed and signed in?)');\n // All of them, not the 50 most recently updated: one the watch never saw would look newly assigned once it's updated.\n const stdout = await execAsync('acli', ['jira', 'workitem', 'search', '--jql', MY_ISSUES_JQL, '--json', '--paginate'], 60_000);\n return stdout ? parseIssuesJson(stdout, probe.siteUrl) : [];\n}\n\n/** An issue's numeric id (Tempo wants it); null when acli can't say. */\nexport async function issueIdOf(key: string): Promise<number | null> {\n try {\n const stdout = await execAsync('acli', ['jira', 'workitem', 'view', key, '--json'], 15000);\n const j = JSON.parse(stdout) as { id?: unknown };\n const id = typeof j.id === 'string' ? Number(j.id) : j.id;\n return typeof id === 'number' && Number.isFinite(id) ? id : null;\n } catch {\n return null;\n }\n}\n\n/** A numeric field of an issue (story points: a `customfield_…`); null when it has none. Throws when acli can't say. */\nexport async function issueNumberField(key: string, field: string): Promise<number | null> {\n const stdout = await execAsync('acli', ['jira', 'workitem', 'view', key, '--fields', field, '--json'], 15000);\n const v = (JSON.parse(stdout) as { fields?: Record<string, unknown> }).fields?.[field];\n return typeof v === 'number' && Number.isFinite(v) ? v : null;\n}\n\nlet accountIdCache: string | null = null;\n/** When it last couldn't tell: not asked again for a while (each ask is an acli process, and every Jira lookup asks). */\nlet accountIdMissedAt = 0;\nconst ACCOUNT_RETRY_MS = 10 * 60_000;\n\n/**\n * Your Jira account id (what `updatedBy()` wants: acli refuses `currentUser()`\n * inside it), from an issue assigned to you; cached for the process. Null\n * when it can't tell.\n */\nexport async function myAccountId(): Promise<string | null> {\n if (accountIdCache) return accountIdCache;\n if (Date.now() - accountIdMissedAt < ACCOUNT_RETRY_MS) return null;\n try {\n const stdout = await execAsync(\n 'acli',\n [\n 'jira',\n 'workitem',\n 'search',\n '--jql',\n 'assignee = currentUser() ORDER BY updated DESC',\n '--fields',\n 'assignee',\n '--json',\n '--limit',\n '1',\n ],\n 15000,\n );\n const parsed = JSON.parse(stdout) as unknown;\n const list = (Array.isArray(parsed) ? parsed : (parsed as { issues?: unknown[] } | null)?.issues) ?? [];\n const id = (list[0] as { fields?: { assignee?: { accountId?: unknown } } } | undefined)?.fields?.assignee?.accountId;\n accountIdCache = typeof id === 'string' && id ? id : null;\n } catch {\n accountIdCache = null;\n }\n if (!accountIdCache) accountIdMissedAt = Date.now();\n return accountIdCache;\n}\n\n/** The same, but a failure (no acli, signed out, no network) throws: for callers that must tell \"none\" from \"couldn't ask\". */\nexport async function searchIssuesOrThrow(jql: string, limit = 50): Promise<JiraIssue[]> {\n const stdout = await execAsync('acli', ['jira', 'workitem', 'search', '--jql', jql, '--json', '--limit', String(limit)], 15000);\n return stdout ? parseIssuesJson(stdout, '') : [];\n}\n\n/**\n * Combined availability check + issue fetch in one acli probe. Used by\n * the dashboard's Jira pane so a refresh only spawns `acli jira auth\n * status` once instead of twice. The pane needs `available` separately\n * from `issues` so it can render the \"acli not configured\" hint.\n */\nexport async function fetchJiraPane(): Promise<{\n available: boolean;\n issues: JiraIssue[];\n}> {\n const probe = await probeAcli();\n if (!probe.available) return { available: false, issues: [] };\n const issues = await searchMyIssues(probe.siteUrl);\n return { available: true, issues };\n}\n\n/** What the Jira watch reads to decide where an issue belongs. */\nexport interface JiraIssueDetail {\n project: { key: string; name: string } | null;\n components: string[];\n labels: string[];\n /** The description as plain text (from Jira's document format), cut to a few thousand characters. */\n description: string;\n created: string | null;\n}\n\n/** Jira's document format (ADF) as plain text: paragraphs and list items on their own lines. Pure. */\nexport function adfText(node: unknown, max = 4000): string {\n const out: string[] = [];\n const walk = (n: unknown): void => {\n if (!n || typeof n !== 'object') return;\n const o = n as { type?: unknown; text?: unknown; content?: unknown };\n if (o.type === 'text' && typeof o.text === 'string') out.push(o.text);\n if (Array.isArray(o.content)) for (const c of o.content) walk(c);\n if (o.type === 'paragraph' || o.type === 'heading' || o.type === 'listItem' || o.type === 'codeBlock') out.push('\\n');\n };\n walk(node);\n const text = out\n .join('')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n return text.length > max ? text.slice(0, max) + '…' : text;\n}\n\n/** One issue's project, components, labels and description (`acli jira workitem view`). Null when acli can't say. */\nexport async function fetchIssueDetail(key: string): Promise<JiraIssueDetail | null> {\n if (!/^[A-Z][A-Z0-9_]*-\\d+$/.test(key)) return null;\n try {\n const stdout = await execAsync(\n 'acli',\n ['jira', 'workitem', 'view', key, '--json', '--fields', 'summary,description,project,components,labels,created'],\n 15000,\n );\n const f = (JSON.parse(stdout) as { fields?: Record<string, unknown> }).fields ?? {};\n const p = f.project as { key?: unknown; name?: unknown } | undefined;\n const names = (v: unknown) =>\n Array.isArray(v)\n ? v.map((c) => (typeof c === 'string' ? c : (c as { name?: unknown })?.name)).filter((s): s is string => typeof s === 'string')\n : [];\n return {\n project: p && typeof p.key === 'string' ? { key: p.key, name: typeof p.name === 'string' ? p.name : p.key } : null,\n components: names(f.components),\n labels: names(f.labels),\n description: adfText(f.description),\n created: typeof f.created === 'string' ? f.created : null,\n };\n } catch {\n return null;\n }\n}\n\n/** Your assigned, unresolved issues (the Jira tab's list); [] when acli isn't there or fails. */\nexport async function fetchMyIssues(): Promise<JiraIssue[]> {\n const r = await fetchJiraPane();\n return r.issues;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from '../platform/config.js';\nimport { atomicWriteFile, ensureFile, withFileLockSync } from '../platform/fs-safe.js';\nimport { issueKeys } from './allocate.js';\nimport { localDay } from './time-view.js';\nimport type { TimeChatEvidence, TimeMeetingEvidence } from '../api-types.js';\n\n/**\n * Outlook meetings and Teams chats for the Time tab, from Microsoft Graph\n * as you (delegated): the device-code sign-in the timesheet tool uses — a\n * code you enter at microsoft.com — with its app registration (config\n * `time.graph.clientId` / `tenantId`, else GRAPH_CLIENT_ID / GRAPH_TENANT_ID).\n * The refresh token is kept in ~/.work/graph-token.json (only your user can\n * read it) and never reaches the browser. Read only: Calendars.Read,\n * Chat.Read. Chats are your own messages that day, shortened: what the\n * Time tab's AI step reads to place them on a ticket (classify.ts).\n */\n\nexport const GRAPH_SCOPES = 'offline_access User.Read Calendars.Read Chat.Read';\nconst GRAPH = 'https://graph.microsoft.com/v1.0';\nconst loginUrl = (tenant: string, what: string) => `https://login.microsoftonline.com/${encodeURIComponent(tenant)}/oauth2/v2.0/${what}`;\n\nexport interface GraphApp {\n clientId: string;\n tenantId: string;\n}\n\n/** The app registration to sign in with, or why there's none. Pure over config and env. */\nexport function graphApp(\n cfg: { clientId?: string; tenantId?: string } | undefined,\n env: Record<string, string | undefined>,\n): GraphApp | { why: string } {\n const clientId = cfg?.clientId?.trim() || env.GRAPH_CLIENT_ID?.trim();\n if (!clientId) return { why: 'No app to sign in to Microsoft with: set time.graph.clientId (and tenantId) in config.json.' };\n return { clientId, tenantId: cfg?.tenantId?.trim() || env.GRAPH_TENANT_ID?.trim() || 'organizations' };\n}\n\ninterface TokenFile {\n refreshToken: string;\n accessToken: string;\n expiresAt: number;\n account: string;\n clientId: string;\n /** Why the sign-in stopped working (a refused refresh): connect again. */\n problem?: string;\n}\n\nconst tokenPath = () => path.join(getConfigDir(), 'graph-token.json');\n\nfunction readTokens(): TokenFile | null {\n try {\n const v = JSON.parse(fs.readFileSync(tokenPath(), 'utf8')) as Partial<TokenFile>;\n return typeof v.refreshToken === 'string' && typeof v.accessToken === 'string' && typeof v.expiresAt === 'number'\n ? {\n refreshToken: v.refreshToken,\n accessToken: v.accessToken,\n expiresAt: v.expiresAt,\n account: v.account ?? '',\n clientId: v.clientId ?? '',\n ...(typeof v.problem === 'string' ? { problem: v.problem } : {}),\n }\n : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Under the file's lock, atomically (work web and a `work timesheet` may\n * refresh at once). Only you can read it: the file is made 0600 before\n * anything is in it, and the atomic write keeps the mode it finds.\n */\nfunction writeTokens(t: TokenFile): void {\n const file = tokenPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n ensureFile(file, '{}');\n fs.chmodSync(file, 0o600);\n withFileLockSync(file, () => atomicWriteFile(file, JSON.stringify(t)));\n}\n\n/**\n * Change the tokens as they are now, under the lock (a read-modify-write: the\n * keeper and a `work timesheet` may refresh at once). `change` gets what's\n * there and returns what to write, or null to leave it. Not signed in (the\n * file gone — Disconnect): nothing is written, so a refresh that was under way\n * can't sign you back in.\n */\nfunction updateTokens(change: (cur: TokenFile) => TokenFile | null): void {\n const file = tokenPath();\n if (!fs.existsSync(file)) return;\n withFileLockSync(file, () => {\n const cur = readTokens();\n const next = cur && change(cur);\n if (next) atomicWriteFile(file, JSON.stringify(next));\n });\n}\n\n/** Signed in as whom, if at all. */\nexport function graphAccount(): string | null {\n return readTokens()?.account || null;\n}\n\nexport const EXPIRED = 'The Microsoft sign-in stopped working (expired or revoked): connect again.';\nexport const OTHER_APP = 'Signed in with another app registration than time.graph names now: connect again.';\n\n/** Signed in, but it no longer works, and why (a refused refresh, another app registration); null when fine or not signed in. */\nexport function graphProblem(app: GraphApp | { why: string }): string | null {\n const t = readTokens();\n if (!t) return null;\n if (t.problem) return t.problem;\n if (!('why' in app) && t.clientId && t.clientId !== app.clientId) return OTHER_APP;\n return null;\n}\n\nexport function signOutGraph(): void {\n const file = tokenPath();\n if (!fs.existsSync(file)) return;\n // Under the lock, so a refresh writing at that moment finishes first (and then finds no file).\n withFileLockSync(file, () => fs.rmSync(file, { force: true }));\n}\n\ntype Fetch = typeof fetch;\n\n/** The code to enter at microsoft.com, and what to poll with. */\nexport interface DeviceLogin {\n userCode: string;\n verificationUri: string;\n deviceCode: string;\n expiresAt: number;\n intervalMs: number;\n}\n\n/** Every call to Microsoft gives up after this: a hung connection must not hold a day's build (and the keeper) for ever. */\nexport const TIMEOUT_MS = 30_000;\n\n/** Token-endpoint errors that mean the sign-in itself is gone (expired, revoked, a changed password). Others (throttling, a server error) pass. */\nconst SIGN_IN_GONE = new Set(['invalid_grant', 'interaction_required', 'invalid_client', 'unauthorized_client', 'consent_required']);\n\n/** A form POST to the sign-in endpoints, with the timeout. */\nconst postForm = (fetchImpl: Fetch, url: string, form: Record<string, string>) =>\n fetchImpl(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form).toString(),\n signal: AbortSignal.timeout(TIMEOUT_MS),\n });\n\nexport async function startDeviceLogin(app: GraphApp, fetchImpl: Fetch = fetch, now = Date.now()): Promise<DeviceLogin> {\n const res = await postForm(fetchImpl, loginUrl(app.tenantId, 'devicecode'), { client_id: app.clientId, scope: GRAPH_SCOPES });\n const j = (await res.json().catch(() => ({}))) as {\n user_code?: string;\n device_code?: string;\n verification_uri?: string;\n expires_in?: number;\n interval?: number;\n error_description?: string;\n };\n if (!res.ok || !j.user_code || !j.device_code) throw new Error(`Microsoft sign-in: ${j.error_description?.split('\\n')[0] ?? res.status}`);\n return {\n userCode: j.user_code,\n verificationUri: j.verification_uri ?? 'https://microsoft.com/devicelogin',\n deviceCode: j.device_code,\n expiresAt: now + (j.expires_in ?? 900) * 1000,\n intervalMs: (j.interval ?? 5) * 1000,\n };\n}\n\nexport const CANCELLED = 'The sign-in was cancelled.';\n/** Who a new sign-in is, until Microsoft says (`/me`). */\nexport const NEW_ACCOUNT = 'your Microsoft account';\n\n/** Wait for the code to be entered (polling as Microsoft asks); keeps the tokens. Resolves with the account, or throws why not. */\nexport async function finishDeviceLogin(\n app: GraphApp,\n login: DeviceLogin,\n opts: { fetchImpl?: Fetch; sleep?: (ms: number) => Promise<void>; now?: () => number; cancelled?: () => boolean } = {},\n): Promise<string> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const sleep = opts.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));\n const now = opts.now ?? (() => Date.now());\n let interval = login.intervalMs;\n while (now() < login.expiresAt) {\n await sleep(interval);\n // Disconnected, or another sign-in started: this one keeps nothing.\n if (opts.cancelled?.()) throw new Error(CANCELLED);\n const res = await postForm(fetchImpl, loginUrl(app.tenantId, 'token'), {\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n client_id: app.clientId,\n device_code: login.deviceCode,\n });\n const j = (await res.json().catch(() => ({}))) as TokenAnswer & { error?: string; error_description?: string };\n if (res.ok && j.access_token) {\n if (opts.cancelled?.()) throw new Error(CANCELLED);\n return keep(app, j, now(), fetchImpl);\n }\n if (j.error === 'authorization_pending') continue;\n if (j.error === 'slow_down') {\n interval += 5000;\n continue;\n }\n throw new Error(\n j.error === 'expired_token'\n ? 'The sign-in code expired: connect again.'\n : `Microsoft sign-in: ${j.error_description?.split('\\n')[0] ?? j.error ?? res.status}`,\n );\n }\n throw new Error('The sign-in code expired: connect again.');\n}\n\ninterface TokenAnswer {\n access_token?: string;\n refresh_token?: string;\n expires_in?: number;\n}\n\n/**\n * Keep the tokens Microsoft just gave — first, before anything else can fail:\n * a refresh rotates the refresh token, and losing the new one would leave the\n * old. Then who you are (`/me`), best effort: a failure keeps the account\n * known before.\n */\nasync function keep(app: GraphApp, j: TokenAnswer, now: number, fetchImpl: Fetch, opts: { refresh?: boolean } = {}): Promise<string> {\n const before = readTokens();\n const tokens: TokenFile = {\n refreshToken: j.refresh_token ?? before?.refreshToken ?? '',\n accessToken: j.access_token!,\n expiresAt: now + ((j.expires_in ?? 3600) - 60) * 1000,\n // A refresh keeps who it was; a new sign-in may be another account: not the old one's name (until /me says).\n account: opts.refresh ? (before?.account ?? '') : NEW_ACCOUNT,\n clientId: app.clientId,\n };\n // A refresh only updates a sign-in that's still there (Disconnect meanwhile wins); a new sign-in writes it.\n if (opts.refresh) updateTokens(() => tokens);\n else writeTokens(tokens);\n const who = await fetchImpl(`${GRAPH}/me?$select=userPrincipalName,id`, {\n headers: { Authorization: `Bearer ${j.access_token}` },\n signal: AbortSignal.timeout(TIMEOUT_MS),\n })\n .then((me) => me.json() as Promise<{ userPrincipalName?: string }>)\n .catch(() => ({}) as { userPrincipalName?: string });\n if (who.userPrincipalName && who.userPrincipalName !== tokens.account)\n updateTokens((cur) => (cur.accessToken === tokens.accessToken ? { ...cur, account: who.userPrincipalName! } : null));\n return who.userPrincipalName ?? tokens.account;\n}\n\n/**\n * An access token, refreshed when it ran out; null when not signed in.\n * Signed in but not working (a refused refresh — recorded, so the tab says\n * \"connect again\" —, another app registration, no network) throws: the day\n * then keeps the meetings and chats it had, rather than losing them.\n */\nexport async function graphToken(app: GraphApp, fetchImpl: Fetch = fetch, now = Date.now()): Promise<string | null> {\n const t = readTokens();\n if (!t) return null;\n if (t.problem) throw new Error(t.problem);\n if (t.clientId && t.clientId !== app.clientId) throw new Error(OTHER_APP);\n if (t.expiresAt > now) return t.accessToken;\n const res = await postForm(fetchImpl, loginUrl(app.tenantId, 'token'), {\n grant_type: 'refresh_token',\n client_id: app.clientId,\n refresh_token: t.refreshToken,\n scope: GRAPH_SCOPES,\n });\n const j = (await res.json().catch(() => ({}))) as TokenAnswer & { error?: string };\n if (!res.ok || !j.access_token) {\n // The sign-in itself refused: said until you connect again. Throttling (429) or a server error may pass: tried again next time.\n const gone = !!j.error && SIGN_IN_GONE.has(j.error);\n if (gone) {\n // Another refresh may have just rotated it (the keeper and a Gather at once): its new tokens stand.\n let renewed: string | null = null;\n updateTokens((cur) => {\n if (cur.refreshToken !== t.refreshToken) {\n renewed = cur.expiresAt > now ? cur.accessToken : null;\n return null;\n }\n return { ...cur, problem: EXPIRED };\n });\n if (renewed) return renewed;\n }\n throw new Error(gone ? EXPIRED : `Microsoft sign-in: ${res.status}${j.error ? ` ${j.error}` : ''}`);\n }\n await keep(app, j, now, fetchImpl, { refresh: true });\n return j.access_token;\n}\n\nasync function getJson<T>(url: string, token: string, fetchImpl: Fetch, headers: Record<string, string> = {}): Promise<T> {\n const res = await fetchImpl(url, { headers: { Authorization: `Bearer ${token}`, ...headers }, signal: AbortSignal.timeout(TIMEOUT_MS) });\n if (!res.ok) throw new Error(`Microsoft Graph: ${res.status} ${(await res.text().catch(() => '')).slice(0, 200)}`);\n return (await res.json()) as T;\n}\n\n/** A local day's bounds as instants. */\nconst dayBounds = (day: string) => {\n const from = new Date(`${day}T00:00:00`);\n const to = new Date(from);\n to.setDate(to.getDate() + 1);\n return { from, to };\n};\n\n/** Meetings you had that day: not cancelled, not declined, not free, not all day. */\nexport async function meetingsOn(day: string, token: string, fetchImpl: Fetch = fetch): Promise<TimeMeetingEvidence[]> {\n const { from, to } = dayBounds(day);\n const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;\n type Event = {\n id?: string;\n subject?: string;\n start?: { dateTime?: string; timeZone?: string };\n end?: { dateTime?: string; timeZone?: string };\n isAllDay?: boolean;\n isCancelled?: boolean;\n showAs?: string;\n responseStatus?: { response?: string };\n };\n // Page by page: a day with shared calendars and holds can have more than a page.\n const all: Event[] = [];\n let next: string | undefined =\n `${GRAPH}/me/calendarView?startDateTime=${from.toISOString()}&endDateTime=${to.toISOString()}` +\n '&$select=id,subject,start,end,isAllDay,isCancelled,showAs,responseStatus&$top=100';\n for (let page = 0; next && page < MAX_PAGES; page++) {\n const p: Paged<Event> = await getJson(next, token, fetchImpl, { Prefer: `outlook.timezone=\"${tz}\"` });\n all.push(...(p.value ?? []));\n next = p['@odata.nextLink'];\n }\n // Cut at the page limit: not the whole day — a failed read, so the day keeps the meetings it had.\n if (next) throw new Error(`more calendar items than ${MAX_PAGES} pages`);\n // Each meeting within the day (a three-day offsite is this day's part of it), in order; time two meetings\n // share counts once (the later one gets only what the earlier didn't cover), so a day never holds more than it has.\n const events = all\n .filter((e) => !(e.isAllDay || e.isCancelled || e.showAs === 'free' || e.responseStatus?.response === 'declined'))\n .map((e) => ({\n e,\n start: Math.max(graphTime(e.start), from.getTime()),\n end: Math.min(graphTime(e.end), to.getTime()),\n }))\n .filter((x) => x.end > x.start)\n .sort((a, b) => a.start - b.start);\n const out: TimeMeetingEvidence[] = [];\n let covered = -Infinity;\n for (const { e, start, end } of events) {\n const minutes = Math.round((end - Math.max(start, Math.min(covered, end))) / 60_000);\n covered = Math.max(covered, end);\n if (!(minutes > 0)) continue;\n out.push({\n ...(e.id ? { id: e.id } : {}),\n subject: e.subject?.trim() || '(no subject)',\n start: hhmm(start),\n end: end >= to.getTime() ? '24:00' : hhmm(end),\n minutes,\n });\n }\n return out;\n}\n\n/** A local time as `HH:MM`. */\nconst hhmm = (ms: number) => {\n const d = new Date(ms);\n return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;\n};\n\n/**\n * A calendar time as Graph gives it: a `dateTime` with no offset, in the zone\n * `timeZone` names — local when it honoured our `Prefer: outlook.timezone`,\n * UTC when it didn't (it falls back to UTC): read as such, not as local,\n * which would shift every meeting by the offset. NaN when unreadable.\n */\nexport function graphTime(t: { dateTime?: string; timeZone?: string } | undefined): number {\n const dt = t?.dateTime ?? '';\n if (!dt) return NaN;\n if (/[zZ]|[+-]\\d\\d:?\\d\\d$/.test(dt.slice(19))) return Date.parse(dt); // carries its own offset\n return /^(utc|etc\\/utc|coordinated universal time|gmt)$/i.test(t?.timeZone ?? '') ? Date.parse(`${dt}Z`) : Date.parse(dt);\n}\n\n/** How many pages of chats, and of one chat's messages, are read at most (50 each). */\nexport const MAX_PAGES = 10;\n\ntype Paged<T> = { value?: T[]; '@odata.nextLink'?: string };\ntype Chat = { id?: string; topic?: string | null; chatType?: string; lastMessagePreview?: { createdDateTime?: string } | null };\ntype Msg = {\n createdDateTime?: string;\n lastModifiedDateTime?: string;\n from?: { user?: { id?: string } } | null;\n body?: { content?: string };\n};\n\n/** The earliest of these times (none: -Infinity, so no further page). */\nconst oldestAt = (times: Array<string | undefined>) => {\n const ms = times.map((t) => Date.parse(t ?? '')).filter((n) => !Number.isNaN(n));\n return ms.length ? Math.min(...ms) : -Infinity;\n};\n\n/** Teams chats where you wrote that day: who with, how many messages, a few of yours, shortened. */\nexport async function chatsOn(day: string, token: string, fetchImpl: Fetch = fetch): Promise<TimeChatEvidence[]> {\n return chatsOf(await chatsSince(day, token, fetchImpl), day);\n}\n\n/** A day's chats from a read; throws for a day the read may have missed messages of (it keeps what it had). */\nexport function chatsOf(r: ChatsRead, day: string): TimeChatEvidence[] {\n if (r.incompleteThrough && day <= r.incompleteThrough) throw new Error('more Teams messages than were read for that day');\n return r.byDay.get(day) ?? [];\n}\n\n/** A read of the chats: per day, and the last day it may have missed messages of (a chat busier than MAX_PAGES), if any. */\nexport interface ChatsRead {\n byDay: Map<string, TimeChatEvidence[]>;\n /** Days up to this one may lack messages: not to be taken as the day's chats (it keeps what it had). */\n incompleteThrough: string | null;\n}\n\n/**\n * Every day's Teams chats from `firstDay` to now, read once: the chats with\n * a message since, each paged back to that day (newest first). Per day, the\n * chats you wrote in — how many of your messages, a few of them shortened —\n * and the issue keys anyone there named that day (`mentions`: only the keys\n * are taken from others' messages; their text is neither kept nor given to\n * the AI step). A whole catch-up costs one read, not one per day.\n */\nexport async function chatsSince(firstDay: string, token: string, fetchImpl: Fetch = fetch): Promise<ChatsRead> {\n const from = dayBounds(firstDay).from.getTime();\n const me = await getJson<{ id?: string }>(`${GRAPH}/me?$select=id`, token, fetchImpl);\n // Without your id nothing can be told yours (a bot's message has no user either: undefined === undefined).\n if (!me.id) throw new Error('Microsoft Graph: no id for you');\n const active: Chat[] = [];\n let next: string | undefined = `${GRAPH}/me/chats?$top=50&$expand=lastMessagePreview&$orderby=lastMessagePreview/createdDateTime desc`;\n for (let page = 0; next && page < MAX_PAGES; page++) {\n const j: Paged<Chat> = await getJson(next, token, fetchImpl);\n const value = j.value ?? [];\n active.push(...value.filter((c) => Date.parse(c.lastMessagePreview?.createdDateTime ?? '') >= from));\n next = oldestAt(value.map((c) => c.lastMessagePreview?.createdDateTime)) >= from ? j['@odata.nextLink'] : undefined;\n }\n const out = new Map<string, TimeChatEvidence[]>();\n let incompleteThrough: string | null = null;\n for (const c of active) {\n if (!c.id) continue;\n const msgs: Msg[] = [];\n let more: string | undefined = `${GRAPH}/me/chats/${encodeURIComponent(c.id)}/messages?$top=50`;\n for (let page = 0; more && page < MAX_PAGES; page++) {\n const j: Paged<Msg> = await getJson(more, token, fetchImpl);\n const value = j.value ?? [];\n msgs.push(...value);\n // Graph lists them by last change, newest first: an old message edited today sits on the first page, so\n // the stop is by that order's own time — nothing changed before the day's start can be from it.\n more = oldestAt(value.map((m) => m.lastModifiedDateTime ?? m.createdDateTime)) >= from ? j['@odata.nextLink'] : undefined;\n }\n // Stopped at the page limit with more to go: the days back to the oldest message read may be missing some.\n if (more) {\n const reached = localDay(oldestAt(msgs.map((m) => m.lastModifiedDateTime ?? m.createdDateTime)));\n if (!incompleteThrough || reached > incompleteThrough) incompleteThrough = reached;\n }\n const byDay = new Map<string, Msg[]>();\n for (const m of msgs) {\n const at = Date.parse(m.createdDateTime ?? '');\n if (!(at >= from)) continue;\n const d = localDay(at);\n byDay.set(d, [...(byDay.get(d) ?? []), m]);\n }\n for (const [d, dayMsgs] of byDay) {\n const mine = dayMsgs.filter((m) => m.from?.user?.id === me.id);\n if (!mine.length) continue;\n const list = out.get(d) ?? [];\n if (list.length >= 20) continue;\n const mentions = [...new Set(dayMsgs.flatMap((m) => issueKeys(plain(m.body?.content ?? ''))))];\n list.push({\n id: c.id,\n chat: c.topic?.trim() || (c.chatType === 'oneOnOne' ? 'a one-on-one chat' : 'a group chat'),\n messages: mine.length,\n sample: mine.slice(0, 5).map((m) => plain(m.body?.content ?? '').slice(0, 200)),\n ...(mentions.length ? { mentions } : {}),\n });\n out.set(d, list);\n }\n }\n return { byDay: out, incompleteThrough };\n}\n\n/** A message's HTML as plain text. */\nexport function plain(html: string): string {\n return html\n .replace(/<[^>]+>/g, ' ')\n .replace(/ /g, ' ')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/&/g, '&') // last: `&lt;` is the text \"<\", not \"<\"\n .replace(/\\s+/g, ' ')\n .trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,SAAS,kBAAkB,MAAgB,MAA2E;AAC3H,QAAM,MAAM,KAAK,QAAQ,MAAM,KAAK,IAAI;AACxC,QAAM,UAAU,oBAAI,IAA2B;AAC/C,QAAM,SAAS,oBAAI,IAAoB;AACvC,SAAO;AAAA,IACL,OAAO,CAAC,UAAU;AAChB,UAAI,QAAQ,IAAI,KAAK,EAAG,QAAO;AAC/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/agents/agent-path.ts","../src/core/pty/resume.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { execFile } from 'node:child_process';\nimport { programPath } from '../platform/program-path.js';\nimport { ensureHost, probeHostDetailed } from './pty-host-client.js';\nimport { hostInfoPath, readHostInfo } from './pty-host-protocol.js';\nimport { isPidAlive, killTree } from '../platform/process.js';\n\n/**\n * Stopping and restarting the PTY host — the CLI's `work pty-host\n * --stop/--restart` and the dashboard's Restart share it. The persisted\n * session list stays, so the next host restores them with --continue.\n */\n\nexport type StopOutcome = 'stopped' | 'not-running' | 'stale-file' | 'unresponsive' | 'failed';\n\n/** A process's command line, or null when it isn't running or can't be read (Windows: CIM; elsewhere: ps). */\nexport function commandLineOf(pid: number): Promise<string | null> {\n return new Promise((resolve) => {\n const done = (err: Error | null, out: string) => resolve(err ? null : out.trim() || null);\n if (process.platform === 'win32')\n execFile(\n programPath('powershell'),\n ['-NoProfile', '-Command', `(Get-CimInstance Win32_Process -Filter 'ProcessId=${Math.trunc(pid)}').CommandLine`],\n { windowsHide: true, timeout: 15_000 },\n (err, out) => done(err, String(out)),\n );\n else\n execFile(programPath('ps'), ['-o', 'args=', '-p', String(Math.trunc(pid))], { windowsHide: true, timeout: 5000 }, (err, out) =>\n done(err, String(out)),\n );\n });\n}\n\n/**\n * The recorded pid really is a running PTY host of work's: alive, and its command line runs `pty-host` (not a\n * `--stop`/`--restart`/`--status` call). Pids get reused — on Windows fast — so a host that doesn't answer is only\n * force-stopped after this: blind, it could take down any process that took its number. Pure over its inputs.\n */\nexport function looksLikeHost(commandLine: string | null): boolean {\n return (\n !!commandLine && /(^|\\s|[\"'\\\\/])pty-host(\\s|$|[\"'])/.test(commandLine) && !/\\bpty-host\\b.*--(stop|restart|status)\\b/.test(commandLine)\n );\n}\n\n/**\n * Kill the running host and its PTYs. Only a PID that proves it's our host gets killed: it answers /health with the\n * discovery file's token and that same PID — or, with `force`, it doesn't answer at all (hung: a ConPTY start that\n * blocked its event loop) but its process is alive and runs `work pty-host` (`looksLikeHost`). The file survives\n * crashes and reboots (TerminateProcess skips cleanup), and Windows reuses PIDs. A stale file is just removed.\n */\nexport async function stopHost(\n kill: (pid: number) => boolean = killTree,\n probeTimeoutMs = 5000,\n opts: { force?: boolean; isOurHost?: (pid: number) => Promise<boolean> } = {},\n): Promise<StopOutcome> {\n const hostInfo = readHostInfo();\n if (!hostInfo) return 'not-running';\n // A busy host (restoring many sessions) can miss a short probe; give it\n // longer before concluding anything.\n const probe = await probeHostDetailed(hostInfo, probeTimeoutMs);\n if (probe.kind === 'timeout') {\n // Alive-but-slow must NOT be treated as stale: deleting the file would\n // orphan a live host, and --restart would then start a second one that\n // restores every session again. Keep the file, kill nothing — unless\n // asked to stop a hung one, and it proves to be ours.\n const ours = opts.isOurHost ?? (async (pid: number) => isPidAlive(pid) && looksLikeHost(await commandLineOf(pid)));\n if (!opts.force || !(await ours(hostInfo.pid))) return 'unresponsive';\n return killAndForget(kill, hostInfo.pid);\n }\n if (probe.kind !== 'host' || probe.pid !== hostInfo.pid) {\n // Nothing listening, or someone else on that port: the file is stale\n // (reboot, crash, PID/port reused). Remove it; kill nothing.\n removeInfo();\n return 'stale-file';\n }\n return killAndForget(kill, hostInfo.pid);\n}\n\nfunction killAndForget(kill: (pid: number) => boolean, pid: number): StopOutcome {\n const ok = kill(pid);\n // TerminateProcess means the host never runs its own cleanup.\n removeInfo();\n return ok ? 'stopped' : 'failed';\n}\n\nfunction removeInfo(): void {\n try {\n fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n}\n\n/**\n * Stop the host and start a new one, which restores every saved session with --continue. `force`: a host that\n * doesn't answer is stopped too (see stopHost). Never starts a second host beside one it couldn't stop.\n */\nexport async function restartHost(\n workBin: string,\n opts: { force?: boolean } = {},\n steps: { stop?: (force: boolean) => Promise<StopOutcome>; start?: (workBin: string) => Promise<{ pid: number }>; pauseMs?: number } = {},\n): Promise<{ outcome: StopOutcome; pid: number | null }> {\n const outcome = await (steps.stop ?? ((force) => stopHost(killTree, 5000, { force })))(!!opts.force);\n if (outcome === 'failed' || outcome === 'unresponsive') return { outcome, pid: null };\n // The old one's port and lock let go before the new one takes them.\n await new Promise((r) => setTimeout(r, steps.pauseMs ?? 500));\n const host = await (steps.start ?? ensureHost)(workBin);\n return { outcome, pid: host.pid };\n}\n","import { spawnSync, type SpawnSyncOptionsWithStringEncoding } from 'node:child_process';\nimport path from 'node:path';\nimport { findOnPath } from './find-on-path.js';\nimport { report } from './report.js';\nimport { debugLog } from './logger.js';\nimport { detachHere } from './process.js';\n\n/**\n * The PATH of the user's login shell, for a work started without one.\n *\n * Reported from a Mac: every session ended at once with \"session exited with code 1\", and Enter\n * gave the same. The desktop app started from the Dock or Finder gets the system's minimal PATH\n * (/usr/bin:/bin:/usr/sbin:/sbin), not the one the user's shell sets up, and passes it on to work\n * web, the PTY host and every Claude: `claude` (in ~/.local/bin, /opt/homebrew/bin, an nvm folder…)\n * isn't found, and node-pty's child exits with 1 when its exec fails. So when work web or the PTY\n * host starts on macOS or Linux and the agent's command isn't on its PATH, it asks the login shell\n * for its PATH (`$SHELL -ilc`, as a terminal would set it up) and puts it first. Started from a\n * terminal, the command is found and nothing is asked.\n */\n\nconst MARK = '__WORK_SHELL_PATH__';\n\n/** The shell's PATH first, then what we had that it lacks (e.g. the app's ~/.work/bin). */\nexport function mergePath(current: string | undefined, shellPath: string, sep = path.delimiter): string {\n const out: string[] = [];\n for (const d of [...shellPath.split(sep), ...(current ?? '').split(sep)]) if (d && !out.includes(d)) out.push(d);\n return out.join(sep);\n}\n\n/** The PATH between the markers of the shell's output (an interactive shell may print a greeting around it). */\nexport function parseShellPath(stdout: string): string | null {\n const m = new RegExp(`${MARK}(.*?)${MARK}`, 's').exec(stdout);\n const p = m?.[1].trim();\n return p ? p : null;\n}\n\n/** How long the login shell may take to say its PATH. */\nexport const SHELL_PATH_TIMEOUT_MS = 5_000;\n\n/** The shell's arguments: a login, interactive shell (what a terminal runs) printing its PATH between markers. */\nexport const shellPathArgs = (): string[] => ['-ilc', `printf '%s%s%s' '${MARK}' \"$PATH\" '${MARK}'`];\n\n/**\n * How it's started. `killSignal: SIGKILL`: an interactive bash or zsh ignores SIGTERM (spawnSync's\n * default at the timeout), and Node then waits for it — a stuck profile held work web up for as long as\n * it hung (reproduced: a 2 s timeout returned after 8 s). `detached` (POSIX): its own session, so it\n * never takes this terminal's foreground group — killed while holding it, it left `work web` in the\n * background, where Ctrl+C no longer reached it (reproduced).\n */\nexport const shellPathSpawnOptions = (timeoutMs = SHELL_PATH_TIMEOUT_MS): SpawnSyncOptionsWithStringEncoding =>\n // `detached` isn't in @types/node's spawnSync options, but spawnSync honors it (spawn_sync reads it).\n ({\n encoding: 'utf8',\n timeout: timeoutMs,\n killSignal: 'SIGKILL',\n detached: detachHere(),\n stdio: ['ignore', 'pipe', 'ignore'],\n windowsHide: true,\n }) as SpawnSyncOptionsWithStringEncoding;\n\ntype ShellRun = (cmd: string, args: string[]) => { stdout?: string | null; status?: number | null; signal?: string | null; error?: Error };\n\n/** Ask the login shell for its PATH: its PATH, or why it couldn't say (a timeout, no such shell, no markers). */\nexport function readShellPath(\n shell = process.env.SHELL || '/bin/zsh',\n run: ShellRun = (cmd, args) => spawnSync(cmd, args, shellPathSpawnOptions()),\n): { path: string } | { why: string } {\n try {\n const r = run(shell, shellPathArgs());\n const p = parseShellPath(r.stdout ?? '');\n if (p) return { path: p };\n const how = r.error\n ? r.error.message\n : r.signal\n ? `stopped by ${r.signal} (over ${SHELL_PATH_TIMEOUT_MS / 1000} s?)`\n : `exit ${r.status ?? '?'}, no PATH printed`;\n return { why: `${shell} -ilc: ${how}` };\n } catch (err) {\n return { why: `${shell} -ilc: ${(err as Error).message}` };\n }\n}\n\n/**\n * Make sure the commands in `need` (the agent's binary) can be found: on macOS and Linux, when one\n * isn't on PATH, the login shell's PATH is merged into this process's (which everything it starts\n * inherits). Says what it did; never throws.\n */\nexport function ensureShellPath(\n need: string[],\n opts: {\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n readPath?: () => { path: string } | { why: string };\n find?: (cmd: string, env: NodeJS.ProcessEnv) => string | null;\n } = {},\n): 'found' | 'added' | 'unavailable' {\n const platform = opts.platform ?? process.platform;\n const env = opts.env ?? process.env;\n if (platform === 'win32') return 'found';\n const find = opts.find ?? ((c: string, e: NodeJS.ProcessEnv) => findOnPath(c, e, platform));\n const missing = need.filter((c) => !find(c, env));\n if (!missing.length) return 'found';\n // Said in the debug log too: started by the desktop app, nothing shows what a reporter prints.\n const say = (level: 'info' | 'warn', text: string) => {\n report(level, text);\n debugLog(level === 'warn' ? 'WARN' : 'INFO', text);\n };\n const read = (opts.readPath ?? (() => readShellPath(env.SHELL)))();\n if ('why' in read) {\n say('warn', `${missing.join(', ')} isn't on PATH (${env.PATH ?? ''}), and the login shell's PATH couldn't be read: ${read.why}`);\n return 'unavailable';\n }\n env.PATH = mergePath(env.PATH, read.path);\n const still = missing.filter((c) => !find(c, env));\n say(\n still.length ? 'warn' : 'info',\n still.length\n ? `${still.join(', ')} isn't on PATH, even with the login shell's (${env.PATH})`\n : `${missing.join(', ')} found with the login shell's PATH: using it (${env.PATH})`,\n );\n return 'added';\n}\n","import { agentFor, agentSettings, assistantAgent, internalAgent } from './index.js';\nimport type { AgentSettings } from './index.js';\nimport { ensureShellPath } from '../platform/shell-path.js';\nimport { debugLog } from '../platform/logger.js';\n\n/**\n * The agents' commands, found on PATH before work web or the PTY host starts any of them\n * (`core/platform/shell-path.ts` says why: the Mac app from the Dock gets the system's PATH).\n */\n\n/** The commands work starts agents with, from the registry: new sessions', the Ctrl+K assistant's, the summaries'. */\nexport function agentCommands(settings: AgentSettings = agentSettings()): string[] {\n return [...new Set([agentFor(settings), assistantAgent(settings), internalAgent(settings)].map((a) => a.launch.tool(settings).cmd))];\n}\n\n/** For `work web` and the PTY host as they start (not wd's lean server: it starts no agent). Never throws. */\nexport function ensureAgentPath(\n deps: { commands?: () => string[]; ensure?: (need: string[]) => ReturnType<typeof ensureShellPath> } = {},\n): ReturnType<typeof ensureShellPath> | 'failed' {\n try {\n return (deps.ensure ?? ensureShellPath)((deps.commands ?? agentCommands)());\n } catch (err) {\n debugLog('WARN', 'finding the agents on PATH failed:', err);\n return 'failed';\n }\n}\n","import { validGrid } from './terminal-size.js';\n\n/**\n * Reattach where a client left off (terminal-rendering.md, \"Reattach where you left off\"). Pure; the Terminal tab and\n * the PTY host share it.\n *\n * Every screen the host sends (the `replay` frame) says which output stream it belongs to (`stream`: one per PTY entry\n * in one host, so a new spawn under the same id after the entry ended, or a host started again, is another stream) and\n * the offset it stands at (`offset`: characters of output since the entry was spawned, the pacer's unit, UTF-16 code\n * units). A restart or halt of its agent in place keeps the entry, and so the stream and the count: the clients attached\n * through it are sent the new process's output as it continues the old one's, with no screen in between, and a client\n * resuming across it is sent the same characters from its offset (pty-registry.test.ts, \"across a restart\"). Live\n * output follows in frames that are contiguous slices of that output, so a client knows its offset without any stamp\n * on them: the screen's offset plus what it was sent since (`utf16Length` of each binary frame, flow-control.ts).\n *\n * Reconnecting, a client that kept its screen states `?resume=<stream>-<offset>-<cols>x<rows>`: it has drawn\n * everything of that stream up to that offset, and its terminal is that grid. If the host can prove that sending what\n * came since is all it needs, it sends that (`replay` with `resumed: true`) and no screen; otherwise a screen as on\n * any attach. Absent, or from an older host or client, nothing changes: a screen.\n */\n\n/** The attach address's parameter a reconnecting client states its position in. An older host ignores it. */\nexport const RESUME_PARAM = 'resume';\n\n/** Where a client stands in a PTY's output: it has drawn all of `stream` up to `offset`, at this grid. */\nexport interface ResumePoint {\n stream: string;\n offset: number;\n cols: number;\n rows: number;\n}\n\n/** A stream id: what the host makes (pty-registry.ts), hex. */\nconst STREAM = /^[0-9a-f]{8,64}$/;\nconst FORMAT = /^([0-9a-f]{8,64})-(\\d{1,15})-(\\d{1,4})x(\\d{1,4})$/;\n\nexport function isStreamId(s: unknown): s is string {\n return typeof s === 'string' && STREAM.test(s);\n}\n\n/** `url` with the client's position added (`?resume=…`). */\nexport function withResume(url: string, at: ResumePoint | null | undefined): string {\n if (!at) return url;\n const value = `${at.stream}-${at.offset}-${at.cols}x${at.rows}`;\n return `${url}${url.includes('?') ? '&' : '?'}${RESUME_PARAM}=${value}`;\n}\n\n/** The position stated on an attach address, or null when there is none or it isn't one (then: a screen). */\nexport function resumeFromParams(params: URLSearchParams): ResumePoint | null {\n const m = FORMAT.exec(params.get(RESUME_PARAM) ?? '');\n if (!m) return null;\n const offset = Number(m[2]);\n const grid = validGrid(Number(m[3]), Number(m[4]));\n if (!Number.isSafeInteger(offset) || !grid) return null;\n return { stream: m[1], offset, cols: grid.cols, rows: grid.rows };\n}\n\n/** What a `replay` frame says about the stream (fields a host from before sends none of). */\nexport interface ReplayPosition {\n stream?: unknown;\n offset?: unknown;\n resumed?: unknown;\n}\n\n/**\n * A client's position in the PTY's output, as it receives it: set by each `replay` frame (a screen, or what it missed),\n * moved on by each binary frame. Unknown (null) when the host said nothing of it (an older host): then the client\n * never asks to resume.\n */\nexport class StreamPosition {\n private stream: string | null = null;\n private at = 0;\n\n /** A `replay` frame: it stands at its offset now (a screen replaces what was drawn; what was missed continues it). */\n replay(msg: ReplayPosition): void {\n const ok = isStreamId(msg.stream) && typeof msg.offset === 'number' && Number.isSafeInteger(msg.offset) && msg.offset >= 0;\n this.stream = ok ? (msg.stream as string) : null;\n this.at = ok ? (msg.offset as number) : 0;\n }\n\n /** A frame of live output, `chars` long in the host's unit (`utf16Length` of its bytes). */\n output(chars: number): void {\n if (this.stream !== null && chars > 0) this.at += chars;\n }\n\n /** Where it stands, at its terminal's grid; null when unknown. */\n point(cols: number, rows: number): ResumePoint | null {\n if (this.stream === null) return null;\n const grid = validGrid(cols, rows);\n return grid ? { stream: this.stream, offset: this.at, cols: grid.cols, rows: grid.rows } : null;\n }\n\n /** Forget it (the screen will be replaced whatever the host says: a fresh terminal). */\n forget(): void {\n this.stream = null;\n this.at = 0;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,GAAG,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,GAAG,YAAY,IAAI,KAAK;AACvE;AAGO,SAAS,iBAAiB,QAA6C;AAC5E,QAAM,IAAI,OAAO,KAAK,OAAO,IAAI,YAAY,KAAK,EAAE;AACpD,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,SAAS,OAAO,EAAE,CAAC,CAAC;AAC1B,QAAM,OAAO,UAAU,OAAO,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC;AACjD,MAAI,CAAC,OAAO,cAAc,MAAM,KAAK,CAAC,KAAM,QAAO;AACnD,SAAO,EAAE,QAAQ,EAAE,CAAC,GAAG,QAAQ,MAAM,KAAK,MAAM,MAAM,KAAK,KAAK;AAClE;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/platform/process.ts"],"sourcesContent":["import fs from 'node:fs';\nimport os from 'node:os';\nimport { execFile, spawn, spawnSync } from 'node:child_process';\nimport { programPath } from './program-path.js';\nimport { timedSync } from './sync-work.js';\n\n/**\n * Process lifecycle rules for the long-lived pieces (work web, the PTY\n * host), in one place — they differ on Windows in ways that bit us:\n *\n * - Killing: process.kill on Windows is TerminateProcess of that one\n * process — its ConPTY children (Claudes) survive, orphaned. Kill the\n * tree with taskkill /T /F. Elsewhere SIGTERM lets the process clean up\n * its own children.\n * - Liveness: `process.kill(pid, 0)` works on both, but a live PID is not\n * proof it's OURS (Windows reuses PIDs fast) — callers that act on it\n * must also verify identity (e.g. the host's /health token check).\n * - Detached `work` children: `detached` + `windowsHide` so no console\n * window flashes and the child outlives the parent's terminal; output\n * goes to a log file, never the parent's stdio.\n * - Anything else started in the background (an editor, a URL, a toast, a\n * status hook): `detached` on POSIX only (`detachHere`). On Windows a\n * detached process has no console at all, so every console program it\n * starts — cmd.exe running code.cmd, PowerShell — opens a window of its\n * own, and `windowsHide` can't stop that (measured: detached flashed a\n * Windows Terminal window every time, hidden alone never). A child there\n * outlives its parent anyway.\n */\n\n/** Start a background program detached? POSIX yes (its own process group); Windows no — see above. */\nexport function detachHere(platform: NodeJS.Platform = process.platform): boolean {\n return platform !== 'win32';\n}\n\nexport function isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n } catch {\n return false;\n }\n return !isZombie(pid);\n}\n\n/**\n * Exited, but not yet collected by its parent (a zombie): `kill(pid, 0)` still\n * succeeds, though nothing runs. A server started by a parent that never\n * waits for it — the desktop app's work web, or a test's child while the test\n * blocks in spawnSync — is one once it stops, and `work web --dev --stop`\n * waited for it to go, then said it didn't. Linux only (/proc/<pid>/stat: the\n * state letter after the command's closing parenthesis); elsewhere false.\n */\nexport function isZombie(pid: number, read: Pick<ProcReader, 'file'> = procFs, platform: NodeJS.Platform = process.platform): boolean {\n if (platform !== 'linux') return false;\n const stat = read.file(`/proc/${pid}/stat`) ?? '';\n // The state follows the command name, which is in parentheses and may hold some.\n const close = stat.lastIndexOf(')');\n return close >= 0 && stat[close + 2] === 'Z';\n}\n\n/** How /proc is read (tests pass a fake one). */\nexport interface ProcReader {\n link: (p: string) => string | null;\n file: (p: string) => string | null;\n pids: () => number[];\n}\n\nconst procFs: ProcReader = {\n link: (p) => {\n try {\n return fs.readlinkSync(p);\n } catch {\n return null;\n }\n },\n file: (p) => {\n try {\n return fs.readFileSync(p, 'utf-8');\n } catch {\n return null;\n }\n },\n pids: () => {\n try {\n return fs\n .readdirSync('/proc')\n .filter((n) => /^\\d+$/.test(n))\n .map(Number);\n } catch {\n return [];\n }\n },\n};\n\nconst baseName = (p: string) => p.split('/').pop() || p;\n\n/**\n * On Linux, the program a process runs, from /proc: its executable when it\n * can be read (our own processes), else its command line's first word, else\n * its `comm`. Not `ps -o comm` alone: that is its main thread's name, which\n * Node 24 sets to \"MainThread\" — every node process, Claude Code's included,\n * read as that, and no Claude was ever found running.\n */\nexport function linuxProcessName(pid: number, read: ProcReader = procFs): string | null {\n const exe = read.link(`/proc/${pid}/exe`);\n if (exe) return baseName(exe.replace(/ \\(deleted\\)$/, ''));\n const argv0 = (read.file(`/proc/${pid}/cmdline`) ?? '').split('\\0')[0];\n if (argv0) return baseName(argv0.split(' ')[0]);\n const comm = (read.file(`/proc/${pid}/comm`) ?? '').trim();\n return comm || null;\n}\n\n/** On Linux, every process's program by pid (linuxProcessName), from /proc: no `ps` to run. */\nexport function linuxProcessTable(read: ProcReader = procFs): Map<number, string> {\n const out = new Map<number, string>();\n for (const pid of read.pids()) {\n const name = linuxProcessName(pid, read);\n if (name) out.set(pid, name);\n }\n return out;\n}\n\n/**\n * The executable name of a live process (\"cmd.exe\", \"sh\"), or null if it\n * isn't running or can't be read. For checking a remembered pid is still\n * the process we started before acting on it — pids get reused.\n */\nexport function processName(pid: number): string | null {\n try {\n if (process.platform === 'win32') {\n const r = spawnSync(programPath('tasklist'), ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], {\n encoding: 'utf-8',\n windowsHide: true,\n timeout: 5000,\n });\n const m = /^\"([^\"]+)\",\"(\\d+)\"/.exec((r.stdout ?? '').trim());\n return m && Number(m[2]) === pid ? m[1] : null;\n }\n if (process.platform === 'linux') return isPidAlive(pid) ? linuxProcessName(pid) : null;\n const r = spawnSync(programPath('ps'), ['-o', 'comm=', '-p', String(pid)], { encoding: 'utf-8', timeout: 5000, windowsHide: true });\n const name = (r.stdout ?? '').trim();\n return r.status === 0 && name ? name.split('/').pop()! : null;\n } catch {\n return null;\n }\n}\n\nlet recentTable: { at: number; table: Map<number, string> } | null = null;\nlet refreshingTable: Promise<void> | null = null;\n\n/**\n * The process table as of at most `maxAgeMs` ago, without waiting: a stale\n * or missing one starts a background refresh (one at a time) and the last\n * one is returned — null before the first is in. For views that refresh\n * often (the session list); a decision that must be right now (is a Claude\n * already running, before starting one?) uses processTable().\n */\nexport function recentProcessTable(maxAgeMs: number, now = Date.now()): Map<number, string> | null {\n if (!recentTable || now - recentTable.at >= maxAgeMs) {\n refreshingTable ??= processTableAsync()\n // An empty table is a failed or timed-out listing (there is always at\n // least this process): keep the last good one, and try again next time.\n .then((table) => void (table.size > 0 && (recentTable = { at: Date.now(), table })))\n .finally(() => void (refreshingTable = null));\n }\n return recentTable?.table ?? null;\n}\n\n/** processTable(), without blocking the event loop. */\nexport function processTableAsync(): Promise<Map<number, string>> {\n if (process.platform === 'linux') return Promise.resolve(linuxProcessTable());\n return new Promise((resolve) => {\n const win = process.platform === 'win32';\n const [cmd, args] = win ? ['tasklist', ['/FO', 'CSV', '/NH']] : ['ps', ['-A', '-o', 'pid=,comm=']];\n execFile(\n programPath(cmd as string),\n args as string[],\n { encoding: 'utf-8', windowsHide: true, timeout: 8000, maxBuffer: 16 * 1024 * 1024 },\n (_err, stdout) => {\n resolve(parseProcessTable(stdout ?? '', win));\n },\n );\n });\n}\n\nfunction parseProcessTable(stdout: string, win: boolean): Map<number, string> {\n const out = new Map<number, string>();\n for (const line of stdout.split(/\\r?\\n/)) {\n if (win) {\n const m = /^\"([^\"]+)\",\"(\\d+)\"/.exec(line);\n if (m) out.set(Number(m[2]), m[1]);\n } else {\n const m = /^\\s*(\\d+)\\s+(.+)$/.exec(line);\n if (m) out.set(Number(m[1]), m[2].trim().split('/').pop()!);\n }\n }\n return out;\n}\n\n/**\n * Every running process's executable name, by pid, in ONE call (tasklist /\n * ps) — for checking many remembered pids at once. Empty if it can't be read.\n */\nexport function processTable(): Map<number, string> {\n if (process.platform === 'linux') return linuxProcessTable();\n // Named when slow (on Windows it takes a second or more): a blocked server says what it waited on (sync-work.ts).\n return timedSync(() => 'listing every process (tasklist / ps)', readProcessTable);\n}\n\nfunction readProcessTable(): Map<number, string> {\n try {\n const win = process.platform === 'win32';\n const r = win\n ? spawnSync(programPath('tasklist'), ['/FO', 'CSV', '/NH'], {\n encoding: 'utf-8',\n windowsHide: true,\n timeout: 8000,\n maxBuffer: 16 * 1024 * 1024,\n })\n : spawnSync(programPath('ps'), ['-A', '-o', 'pid=,comm='], {\n encoding: 'utf-8',\n timeout: 8000,\n windowsHide: true,\n maxBuffer: 16 * 1024 * 1024,\n });\n return parseProcessTable(r.stdout ?? '', win);\n } catch {\n return new Map(); // unreadable: nothing is known to be alive\n }\n}\n\n/** When this machine last booted (ms since epoch, ±1 s). */\nexport function bootTime(): number {\n return Date.now() - os.uptime() * 1000;\n}\n\n/** Kill a process AND its children. True if the kill was delivered. */\nexport function killTree(pid: number): boolean {\n if (process.platform === 'win32') {\n return spawnSync(programPath('taskkill'), ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).status === 0;\n }\n try {\n process.kill(pid);\n return true;\n } catch {\n return false;\n }\n}\n\n/** killTree, not blocking the event loop (taskkill takes a few hundred ms): for a server killing several at once. */\nexport function killTreeAsync(pid: number): Promise<boolean> {\n // Already gone counts as stopped, as with taskkill below: it's what the caller wanted.\n if (process.platform !== 'win32') return Promise.resolve(killTree(pid) || !isPidAlive(pid));\n return new Promise((resolve) =>\n // taskkill fails the whole call when one child had already exited or won't go; the top gone is what counts.\n execFile(programPath('taskkill'), ['/PID', String(pid), '/T', '/F'], { windowsHide: true, timeout: 10_000 }, (err) =>\n resolve(!err || !isPidAlive(pid)),\n ),\n );\n}\n\n/**\n * Start `node <workBin> ...args` detached, appending its output to\n * `logFile`. Returns immediately; the caller polls for readiness (a\n * discovery file / health check), because a detached child can't report\n * back directly.\n */\nexport function spawnDetachedWork(workBin: string, args: string[], logFile: string): void {\n const log = fs.openSync(logFile, 'a');\n try {\n const child = spawn(process.execPath, [workBin, ...args], {\n detached: true,\n stdio: ['ignore', log, log],\n windowsHide: true,\n // Not the caller's folder: a long-lived server working from it keeps it\n // in use on Windows — a worktree then can't be removed, the desktop\n // app's install folder can't be updated.\n cwd: os.homedir(),\n });\n child.unref();\n } finally {\n fs.closeSync(log);\n }\n}\n"],"mappings":";;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,SAAS,UAAU,OAAO,iBAAiB;AA4BpC,SAAS,WAAW,WAA4B,QAAQ,UAAmB;AAChF,SA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