@moberg_hr/work-tree 2.7.0 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account-FKNMH5IT.js +245 -0
- package/dist/account-FKNMH5IT.js.map +1 -0
- package/dist/{add-repo-E7KWNJJV.js → add-repo-SG4D3C76.js} +26 -22
- package/dist/{add-repo-E7KWNJJV.js.map → add-repo-SG4D3C76.js.map} +1 -1
- package/dist/{answer-2CBOWCL5.js → answer-M4YETVGV.js} +15 -12
- package/dist/{answer-2CBOWCL5.js.map → answer-M4YETVGV.js.map} +1 -1
- package/dist/{attach-AWRY4LSI.js → attach-3P3WQJKZ.js} +19 -16
- package/dist/{attach-AWRY4LSI.js.map → attach-3P3WQJKZ.js.map} +1 -1
- package/dist/bin.js +7 -5
- package/dist/bin.js.map +1 -1
- package/dist/{block-JTJX5QIO.js → block-2C3GZYAP.js} +15 -12
- package/dist/{block-JTJX5QIO.js.map → block-2C3GZYAP.js.map} +1 -1
- package/dist/{broadcast-3SF55HA6.js → broadcast-BH2H7UTU.js} +12 -9
- package/dist/{broadcast-3SF55HA6.js.map → broadcast-BH2H7UTU.js.map} +1 -1
- package/dist/{catchup-2WNHEMLD.js → catchup-PENTMANK.js} +18 -15
- package/dist/{catchup-2WNHEMLD.js.map → catchup-PENTMANK.js.map} +1 -1
- package/dist/{chunk-C5HPSURF.js → chunk-3JFRM4IY.js} +12 -12
- package/dist/{chunk-O34CKSE4.js → chunk-3N3UQEC4.js} +2 -2
- package/dist/{chunk-EPNYZJMM.js → chunk-3TN77GOI.js} +9 -6
- package/dist/chunk-3TN77GOI.js.map +1 -0
- package/dist/{chunk-YJ4CAD3X.js → chunk-44AU2STD.js} +5 -5
- package/dist/{chunk-TPPTL7LA.js → chunk-4M5TIZDC.js} +113 -6
- package/dist/chunk-4M5TIZDC.js.map +1 -0
- package/dist/chunk-4NITDMDH.js +372 -0
- package/dist/chunk-4NITDMDH.js.map +1 -0
- package/dist/{chunk-SNRP2MC3.js → chunk-5QGCF3PS.js} +2 -2
- package/dist/{chunk-ZS6F6JLC.js → chunk-6MJ6BDHL.js} +88 -12
- package/dist/chunk-6MJ6BDHL.js.map +1 -0
- package/dist/chunk-6THUVP6T.js +118 -0
- package/dist/chunk-6THUVP6T.js.map +1 -0
- package/dist/{chunk-BHU26CNH.js → chunk-6XMH3WFY.js} +6 -4
- package/dist/{chunk-BHU26CNH.js.map → chunk-6XMH3WFY.js.map} +1 -1
- package/dist/{chunk-DYJ4VJJD.js → chunk-A42MFPMC.js} +8 -33
- package/dist/chunk-A42MFPMC.js.map +1 -0
- package/dist/{chunk-JIYGGN2N.js → chunk-AU27USPZ.js} +2 -2
- package/dist/chunk-BBZ2DK6W.js +9 -0
- package/dist/{chunk-B2HUKRWX.js → chunk-BT7SZQQL.js} +4 -4
- package/dist/{chunk-MGQK6BWH.js → chunk-CNE5SWFH.js} +35 -18
- package/dist/chunk-CNE5SWFH.js.map +1 -0
- package/dist/chunk-D675JTUZ.js +442 -0
- package/dist/chunk-D675JTUZ.js.map +1 -0
- package/dist/{chunk-FUNZ7TOS.js → chunk-F6M255O5.js} +534 -121
- package/dist/chunk-F6M255O5.js.map +1 -0
- package/dist/chunk-FDKJFIUU.js +169 -0
- package/dist/chunk-FDKJFIUU.js.map +1 -0
- package/dist/{chunk-YNHIMOE7.js → chunk-GNGXYXBC.js} +2 -2
- package/dist/{chunk-KU63EHZO.js → chunk-ICJPVSRY.js} +2 -2
- package/dist/{chunk-VEKEA3ER.js → chunk-J36ULZBO.js} +2 -2
- package/dist/{chunk-UHYIB6AV.js → chunk-JEET43KM.js} +2 -2
- package/dist/{chunk-2IKWNRMV.js → chunk-K5QBU5CY.js} +3 -3
- package/dist/{chunk-LDFICXOZ.js → chunk-KC66FLGZ.js} +10 -6
- package/dist/{chunk-LDFICXOZ.js.map → chunk-KC66FLGZ.js.map} +1 -1
- package/dist/{chunk-TBY6ZFAV.js → chunk-KNRGVUW7.js} +3 -3
- package/dist/{chunk-AFW7HREX.js → chunk-KUO5ATYX.js} +9 -41
- package/dist/chunk-KUO5ATYX.js.map +1 -0
- package/dist/{chunk-WIWO3YWP.js → chunk-LCV62KMO.js} +2 -2
- package/dist/{chunk-3JY3QT4J.js → chunk-LZUFHLBF.js} +5 -5
- package/dist/{chunk-CFLMBFBO.js → chunk-M6LJ3GE3.js} +76 -10
- package/dist/chunk-M6LJ3GE3.js.map +1 -0
- package/dist/{chunk-3PLWNCRM.js → chunk-MMFXUIQQ.js} +2 -2
- package/dist/{chunk-J5CMORVD.js → chunk-NMSJJCOD.js} +28 -15
- package/dist/chunk-NMSJJCOD.js.map +1 -0
- package/dist/{chunk-46UTKL5L.js → chunk-OMIMK3LB.js} +2 -2
- package/dist/chunk-P2HOLCBF.js +34 -0
- package/dist/chunk-P2HOLCBF.js.map +1 -0
- package/dist/{chunk-PUTZR6F5.js → chunk-P4EQWC5W.js} +2 -2
- package/dist/{chunk-4PRPDACI.js → chunk-PC67UHUW.js} +10 -7
- package/dist/chunk-PC67UHUW.js.map +1 -0
- package/dist/{chunk-OFCY7RCM.js → chunk-QJLJH5DC.js} +4 -4
- package/dist/{chunk-ZMCU2PZN.js → chunk-RCGFHJM7.js} +5 -3
- package/dist/chunk-RCGFHJM7.js.map +1 -0
- package/dist/{chunk-G2FE7HUB.js → chunk-RGUSVBGN.js} +2 -2
- package/dist/{chunk-R3DASZQF.js → chunk-S3BAD4IR.js} +2 -2
- package/dist/{chunk-B7C3RYSJ.js → chunk-SG5LUMGE.js} +3 -3
- package/dist/{chunk-KUVL75PL.js → chunk-SVSRQ3R2.js} +8 -8
- package/dist/{chunk-QGKJXCEJ.js → chunk-T2ZB6I3Y.js} +19 -13
- package/dist/chunk-T2ZB6I3Y.js.map +1 -0
- package/dist/{chunk-5GA3PFK5.js → chunk-TGWUOZJL.js} +13 -9
- package/dist/chunk-TGWUOZJL.js.map +1 -0
- package/dist/{chunk-5XSY3C6E.js → chunk-UBOKRHNV.js} +13 -13
- package/dist/chunk-UBOKRHNV.js.map +1 -0
- package/dist/{chunk-TTTIKTNR.js → chunk-UMYB6DZX.js} +2 -2
- package/dist/{chunk-W4YWFAYC.js → chunk-VEWSK3FG.js} +4 -4
- package/dist/{chunk-BVJ2ZE7B.js → chunk-VQGHVXGL.js} +34 -13
- package/dist/chunk-VQGHVXGL.js.map +1 -0
- package/dist/{chunk-W7WC7UA2.js → chunk-VRHQMUPB.js} +5 -5
- package/dist/{chunk-LQXGNO5X.js → chunk-W7NCZ3VU.js} +3 -3
- package/dist/{chunk-3UHKPHTB.js → chunk-WM4JWBKJ.js} +4 -4
- package/dist/{chunk-MCSEYS2J.js → chunk-WPZTIF5C.js} +5 -5
- package/dist/{chunk-USUQYM6V.js → chunk-WVJASLMV.js} +58 -54
- package/dist/chunk-WVJASLMV.js.map +1 -0
- package/dist/{chunk-ZNXACRZ5.js → chunk-WZ4QXVCC.js} +9 -5
- package/dist/{chunk-ZNXACRZ5.js.map → chunk-WZ4QXVCC.js.map} +1 -1
- package/dist/{chunk-DO5NW46X.js → chunk-X4AXKO3A.js} +2 -2
- package/dist/{chunk-LWKFZOCJ.js → chunk-X63DS7BW.js} +3 -3
- package/dist/{chunk-5WEDCEZG.js → chunk-X7TWBG4X.js} +5 -5
- package/dist/{chunk-KE2TFF7B.js → chunk-XNLQSW6J.js} +23 -212
- package/dist/chunk-XNLQSW6J.js.map +1 -0
- package/dist/{chunk-5BNNPXID.js → chunk-YA3WCQ2A.js} +4 -4
- package/dist/{chunk-ZGPWIBSZ.js → chunk-YEXW2OCN.js} +9 -34
- package/dist/chunk-YEXW2OCN.js.map +1 -0
- package/dist/chunk-YEY2WKOE.js +43 -0
- package/dist/chunk-YEY2WKOE.js.map +1 -0
- package/dist/{chunk-COKQPFLB.js → chunk-YYBXQBW2.js} +3 -3
- package/dist/chunk-ZDMJPEBO.js +31 -0
- package/dist/chunk-ZDMJPEBO.js.map +1 -0
- package/dist/{chunk-PIKOCEWX.js → chunk-ZOGGTAOK.js} +5 -5
- package/dist/chunk-ZXHMC7UO.js +106 -0
- package/dist/chunk-ZXHMC7UO.js.map +1 -0
- package/dist/{cleanup-PWN4XZ2F.js → cleanup-HEUCA22O.js} +31 -27
- package/dist/{cleanup-PWN4XZ2F.js.map → cleanup-HEUCA22O.js.map} +1 -1
- package/dist/cli-Y4JSWLZ2.js +19 -0
- package/dist/{command-hook-installer-RJH5QLCD.js → command-hook-installer-7Q7UD7AU.js} +9 -8
- package/dist/command-hook-installer-7Q7UD7AU.js.map +1 -0
- package/dist/{config-KGDVJKQN.js → config-TPK3PXW6.js} +19 -15
- package/dist/{config-KGDVJKQN.js.map → config-TPK3PXW6.js.map} +1 -1
- package/dist/{diff-ZORXBJDI.js → diff-XGPISLYB.js} +16 -13
- package/dist/{diff-ZORXBJDI.js.map → diff-XGPISLYB.js.map} +1 -1
- package/dist/{digest-PUUBJTD3.js → digest-4IF376QE.js} +14 -11
- package/dist/{digest-PUUBJTD3.js.map → digest-4IF376QE.js.map} +1 -1
- package/dist/{fork-7L76HZAS.js → fork-DQMXZEQM.js} +27 -24
- package/dist/{fork-7L76HZAS.js.map → fork-DQMXZEQM.js.map} +1 -1
- package/dist/{history-YX74IRQY.js → history-OXEG6SOK.js} +13 -8
- package/dist/{hook-JCD6SDB3.js → hook-Z3THJRUB.js} +20 -19
- package/dist/{hook-JCD6SDB3.js.map → hook-Z3THJRUB.js.map} +1 -1
- package/dist/{hydrate-W4V5RJYU.js → hydrate-47IPPOYB.js} +14 -11
- package/dist/{hydrate-W4V5RJYU.js.map → hydrate-47IPPOYB.js.map} +1 -1
- package/dist/{init-5MMV2UF5.js → init-OZ6ARQJB.js} +14 -11
- package/dist/{init-5MMV2UF5.js.map → init-OZ6ARQJB.js.map} +1 -1
- package/dist/install-skills-QTWYVAOZ.js +20 -0
- package/dist/install-skills-bin.js +9 -5
- package/dist/install-skills-bin.js.map +1 -1
- package/dist/{list-ZS3UWOGJ.js → list-22MUAA6K.js} +14 -11
- package/dist/{list-ZS3UWOGJ.js.map → list-22MUAA6K.js.map} +1 -1
- package/dist/{move-ZTL7HAIU.js → move-7QGWP7FG.js} +42 -18
- package/dist/move-7QGWP7FG.js.map +1 -0
- package/dist/{note-B4FVZGJJ.js → note-PA7HHBXX.js} +15 -12
- package/dist/{note-B4FVZGJJ.js.map → note-PA7HHBXX.js.map} +1 -1
- package/dist/{overlaps-W3BLUG53.js → overlaps-FE36QGVQ.js} +13 -10
- package/dist/{overlaps-W3BLUG53.js.map → overlaps-FE36QGVQ.js.map} +1 -1
- package/dist/{pin-YYQV5OPS.js → pin-AD43POUY.js} +15 -12
- package/dist/{pin-YYQV5OPS.js.map → pin-AD43POUY.js.map} +1 -1
- package/dist/{pr-HQTMQOF5.js → pr-MCPGZ44W.js} +15 -12
- package/dist/{pr-HQTMQOF5.js.map → pr-MCPGZ44W.js.map} +1 -1
- package/dist/{prune-6BYOFOUR.js → prune-M4BMLYDQ.js} +29 -26
- package/dist/{prune-6BYOFOUR.js.map → prune-M4BMLYDQ.js.map} +1 -1
- package/dist/{pty-host-KSS45FVH.js → pty-host-BMQOW67M.js} +142 -37
- package/dist/pty-host-BMQOW67M.js.map +1 -0
- package/dist/{read-I5TGSBPC.js → read-VALY2SX6.js} +14 -11
- package/dist/{read-I5TGSBPC.js.map → read-VALY2SX6.js.map} +1 -1
- package/dist/{recent-GRKJEEKT.js → recent-SCQJX6DJ.js} +22 -12
- package/dist/recent-SCQJX6DJ.js.map +1 -0
- package/dist/{remove-64T6TMOE.js → remove-24KP2GMZ.js} +28 -25
- package/dist/{remove-64T6TMOE.js.map → remove-24KP2GMZ.js.map} +1 -1
- package/dist/{report-KAS2UEXO.js → report-J7TUQRJS.js} +3 -3
- package/dist/{restart-WJROWFMU.js → restart-SSOENWTH.js} +15 -12
- package/dist/{restart-WJROWFMU.js.map → restart-SSOENWTH.js.map} +1 -1
- package/dist/{resume-634R6KNE.js → resume-GM66FDEP.js} +16 -12
- package/dist/resume-GM66FDEP.js.map +1 -0
- package/dist/{run-57LGOBXQ.js → run-OATO7NBV.js} +11 -8
- package/dist/{run-57LGOBXQ.js.map → run-OATO7NBV.js.map} +1 -1
- package/dist/{screen-CX7WUVXM.js → screen-RV2SJGJP.js} +15 -12
- package/dist/{screen-CX7WUVXM.js.map → screen-RV2SJGJP.js.map} +1 -1
- package/dist/{search-JYAQWT6A.js → search-UHYMBMA7.js} +11 -8
- package/dist/{search-JYAQWT6A.js.map → search-UHYMBMA7.js.map} +1 -1
- package/dist/{section-4FICXE46.js → section-24WUAJKW.js} +15 -12
- package/dist/{section-4FICXE46.js.map → section-24WUAJKW.js.map} +1 -1
- package/dist/{send-RRTPY47A.js → send-GRTDUQIN.js} +16 -13
- package/dist/{send-RRTPY47A.js.map → send-GRTDUQIN.js.map} +1 -1
- package/dist/{sessions-UJNUCYND.js → sessions-FAYRQHXJ.js} +21 -18
- package/dist/{sessions-UJNUCYND.js.map → sessions-FAYRQHXJ.js.map} +1 -1
- package/dist/{snooze-DJEPOBT5.js → snooze-WPUVDSBY.js} +14 -11
- package/dist/{snooze-DJEPOBT5.js.map → snooze-WPUVDSBY.js.map} +1 -1
- package/dist/{start-YPEN5QI3.js → start-EDY2RTZ3.js} +15 -12
- package/dist/{start-YPEN5QI3.js.map → start-EDY2RTZ3.js.map} +1 -1
- package/dist/{state-UAW6DWWU.js → state-DC73V5TS.js} +6 -4
- package/dist/{state-UAW6DWWU.js.map → state-DC73V5TS.js.map} +1 -1
- package/dist/{status-4EOTN33T.js → status-KISVX264.js} +13 -10
- package/dist/{status-4EOTN33T.js.map → status-KISVX264.js.map} +1 -1
- package/dist/{statusline-EUT6VZLP.js → statusline-A2DTGLK5.js} +40 -28
- package/dist/statusline-A2DTGLK5.js.map +1 -0
- package/dist/statusline-hook-OVWHHFBV.js +63 -0
- package/dist/statusline-hook-OVWHHFBV.js.map +1 -0
- package/dist/{stop-3UNZ22YA.js → stop-YJCB5IOT.js} +15 -12
- package/dist/{stop-3UNZ22YA.js.map → stop-YJCB5IOT.js.map} +1 -1
- package/dist/{sync-XXZBP6PK.js → sync-GD6LFFCX.js} +29 -26
- package/dist/{sync-XXZBP6PK.js.map → sync-GD6LFFCX.js.map} +1 -1
- package/dist/{time-G5Z57AE5.js → time-YUSOOTR5.js} +17 -14
- package/dist/{time-G5Z57AE5.js.map → time-YUSOOTR5.js.map} +1 -1
- package/dist/time-actions-4XNIRNMH.js +16 -0
- package/dist/{timesheet-NA7NQUVR.js → timesheet-W6RIHJE7.js} +19 -16
- package/dist/{timesheet-NA7NQUVR.js.map → timesheet-W6RIHJE7.js.map} +1 -1
- package/dist/{todo-V7EVWHF2.js → todo-4VTGOCKH.js} +7 -5
- package/dist/{todo-V7EVWHF2.js.map → todo-4VTGOCKH.js.map} +1 -1
- package/dist/{tree-R5YXQTP7.js → tree-UVJP5XF4.js} +41 -30
- package/dist/tree-UVJP5XF4.js.map +1 -0
- package/dist/{update-B3MQXQJ6.js → update-2A4JGE3U.js} +16 -13
- package/dist/{update-B3MQXQJ6.js.map → update-2A4JGE3U.js.map} +1 -1
- package/dist/{usage-2HE4RSVM.js → usage-KJZAMQW5.js} +18 -13
- package/dist/usage-KJZAMQW5.js.map +1 -0
- package/dist/{wait-2OPYJO3K.js → wait-XA3ZS2WF.js} +15 -12
- package/dist/{wait-2OPYJO3K.js.map → wait-XA3ZS2WF.js.map} +1 -1
- package/dist/wd-bin.js +8 -6
- package/dist/wd-bin.js.map +1 -1
- package/dist/web/assets/{PtyView-DgdSx6WG.js → PtyView-BPk8N9xQ.js} +2 -2
- package/dist/web/assets/{PtyView-DgdSx6WG.js.map → PtyView-BPk8N9xQ.js.map} +1 -1
- package/dist/web/assets/{index-C5JNhi3-.css → index-CZwdUbxG.css} +1 -1
- package/dist/web/assets/index-vXchs7b4.js +119 -0
- package/dist/web/assets/index-vXchs7b4.js.map +1 -0
- package/dist/web/index.html +2 -2
- package/dist/{web-QXQ4NGCJ.js → web-QCHECDRD.js} +407 -262
- package/dist/web-QCHECDRD.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/chunk-3Q5RZCQW.js +0 -9
- package/dist/chunk-3ZGZNZTY.js +0 -134
- package/dist/chunk-3ZGZNZTY.js.map +0 -1
- package/dist/chunk-4PRPDACI.js.map +0 -1
- package/dist/chunk-5GA3PFK5.js.map +0 -1
- package/dist/chunk-5XSY3C6E.js.map +0 -1
- package/dist/chunk-AFW7HREX.js.map +0 -1
- package/dist/chunk-BVJ2ZE7B.js.map +0 -1
- package/dist/chunk-CFLMBFBO.js.map +0 -1
- package/dist/chunk-DYJ4VJJD.js.map +0 -1
- package/dist/chunk-EPNYZJMM.js.map +0 -1
- package/dist/chunk-FUNZ7TOS.js.map +0 -1
- package/dist/chunk-J5CMORVD.js.map +0 -1
- package/dist/chunk-KE2TFF7B.js.map +0 -1
- package/dist/chunk-MGQK6BWH.js.map +0 -1
- package/dist/chunk-QGKJXCEJ.js.map +0 -1
- package/dist/chunk-TPPTL7LA.js.map +0 -1
- package/dist/chunk-TUFQJXXO.js +0 -19
- package/dist/chunk-TUFQJXXO.js.map +0 -1
- package/dist/chunk-USUQYM6V.js.map +0 -1
- package/dist/chunk-VMBWCDBA.js +0 -186
- package/dist/chunk-VMBWCDBA.js.map +0 -1
- package/dist/chunk-ZGPWIBSZ.js.map +0 -1
- package/dist/chunk-ZMCU2PZN.js.map +0 -1
- package/dist/chunk-ZS6F6JLC.js.map +0 -1
- package/dist/cli-UTID323G.js +0 -17
- package/dist/command-hook-installer-RJH5QLCD.js.map +0 -1
- package/dist/install-skills-7EHZBANC.js +0 -16
- package/dist/move-ZTL7HAIU.js.map +0 -1
- package/dist/pty-host-KSS45FVH.js.map +0 -1
- package/dist/recent-GRKJEEKT.js.map +0 -1
- package/dist/resume-634R6KNE.js.map +0 -1
- package/dist/statusline-EUT6VZLP.js.map +0 -1
- package/dist/statusline-hook-TZ7M762P.js +0 -118
- package/dist/statusline-hook-TZ7M762P.js.map +0 -1
- package/dist/time-actions-H5WCOYZG.js +0 -14
- package/dist/tree-R5YXQTP7.js.map +0 -1
- package/dist/usage-2HE4RSVM.js.map +0 -1
- package/dist/web/assets/index-O8yTaaWX.js +0 -119
- package/dist/web/assets/index-O8yTaaWX.js.map +0 -1
- package/dist/web-QXQ4NGCJ.js.map +0 -1
- /package/dist/{chunk-C5HPSURF.js.map → chunk-3JFRM4IY.js.map} +0 -0
- /package/dist/{chunk-O34CKSE4.js.map → chunk-3N3UQEC4.js.map} +0 -0
- /package/dist/{chunk-YJ4CAD3X.js.map → chunk-44AU2STD.js.map} +0 -0
- /package/dist/{chunk-SNRP2MC3.js.map → chunk-5QGCF3PS.js.map} +0 -0
- /package/dist/{chunk-JIYGGN2N.js.map → chunk-AU27USPZ.js.map} +0 -0
- /package/dist/{chunk-3Q5RZCQW.js.map → chunk-BBZ2DK6W.js.map} +0 -0
- /package/dist/{chunk-B2HUKRWX.js.map → chunk-BT7SZQQL.js.map} +0 -0
- /package/dist/{chunk-YNHIMOE7.js.map → chunk-GNGXYXBC.js.map} +0 -0
- /package/dist/{chunk-KU63EHZO.js.map → chunk-ICJPVSRY.js.map} +0 -0
- /package/dist/{chunk-VEKEA3ER.js.map → chunk-J36ULZBO.js.map} +0 -0
- /package/dist/{chunk-UHYIB6AV.js.map → chunk-JEET43KM.js.map} +0 -0
- /package/dist/{chunk-2IKWNRMV.js.map → chunk-K5QBU5CY.js.map} +0 -0
- /package/dist/{chunk-TBY6ZFAV.js.map → chunk-KNRGVUW7.js.map} +0 -0
- /package/dist/{chunk-WIWO3YWP.js.map → chunk-LCV62KMO.js.map} +0 -0
- /package/dist/{chunk-3JY3QT4J.js.map → chunk-LZUFHLBF.js.map} +0 -0
- /package/dist/{chunk-3PLWNCRM.js.map → chunk-MMFXUIQQ.js.map} +0 -0
- /package/dist/{chunk-46UTKL5L.js.map → chunk-OMIMK3LB.js.map} +0 -0
- /package/dist/{chunk-PUTZR6F5.js.map → chunk-P4EQWC5W.js.map} +0 -0
- /package/dist/{chunk-OFCY7RCM.js.map → chunk-QJLJH5DC.js.map} +0 -0
- /package/dist/{chunk-G2FE7HUB.js.map → chunk-RGUSVBGN.js.map} +0 -0
- /package/dist/{chunk-R3DASZQF.js.map → chunk-S3BAD4IR.js.map} +0 -0
- /package/dist/{chunk-B7C3RYSJ.js.map → chunk-SG5LUMGE.js.map} +0 -0
- /package/dist/{chunk-KUVL75PL.js.map → chunk-SVSRQ3R2.js.map} +0 -0
- /package/dist/{chunk-TTTIKTNR.js.map → chunk-UMYB6DZX.js.map} +0 -0
- /package/dist/{chunk-W4YWFAYC.js.map → chunk-VEWSK3FG.js.map} +0 -0
- /package/dist/{chunk-W7WC7UA2.js.map → chunk-VRHQMUPB.js.map} +0 -0
- /package/dist/{chunk-LQXGNO5X.js.map → chunk-W7NCZ3VU.js.map} +0 -0
- /package/dist/{chunk-3UHKPHTB.js.map → chunk-WM4JWBKJ.js.map} +0 -0
- /package/dist/{chunk-MCSEYS2J.js.map → chunk-WPZTIF5C.js.map} +0 -0
- /package/dist/{chunk-DO5NW46X.js.map → chunk-X4AXKO3A.js.map} +0 -0
- /package/dist/{chunk-LWKFZOCJ.js.map → chunk-X63DS7BW.js.map} +0 -0
- /package/dist/{chunk-5WEDCEZG.js.map → chunk-X7TWBG4X.js.map} +0 -0
- /package/dist/{chunk-5BNNPXID.js.map → chunk-YA3WCQ2A.js.map} +0 -0
- /package/dist/{chunk-COKQPFLB.js.map → chunk-YYBXQBW2.js.map} +0 -0
- /package/dist/{chunk-PIKOCEWX.js.map → chunk-ZOGGTAOK.js.map} +0 -0
- /package/dist/{cli-UTID323G.js.map → cli-Y4JSWLZ2.js.map} +0 -0
- /package/dist/{history-YX74IRQY.js.map → history-OXEG6SOK.js.map} +0 -0
- /package/dist/{install-skills-7EHZBANC.js.map → install-skills-QTWYVAOZ.js.map} +0 -0
- /package/dist/{report-KAS2UEXO.js.map → report-J7TUQRJS.js.map} +0 -0
- /package/dist/{time-actions-H5WCOYZG.js.map → time-actions-4XNIRNMH.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/platform/shell-path.ts","../src/core/platform/find-on-path.ts","../src/core/agents/agent-path.ts"],"sourcesContent":["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 fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * The file a command name runs, as a shell finds it: a path is itself, else the\n * first match in PATH. On Windows a name without one of PATHEXT's extensions is\n * tried with each (`claude` is `claude.exe` or `claude.cmd`; npm's extension-less\n * `claude` sh shim beside them is never run); elsewhere only an executable file\n * counts. Null when there's none.\n */\nexport function findOnPath(cmd: string, env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string | null {\n const win = platform === 'win32';\n const isFile = (p: string) => {\n try {\n const st = fs.statSync(p);\n return st.isFile() && (win || (st.mode & 0o111) !== 0);\n } catch {\n return false;\n }\n };\n const pathExt = (env.PATHEXT ?? env.Pathext ?? '.COM;.EXE;.BAT;.CMD')\n .split(';')\n .filter(Boolean)\n .map((e) => e.toLowerCase());\n const hasExt = pathExt.includes(path.extname(cmd).toLowerCase());\n const candidates = (base: string) => (!win || hasExt ? [base] : pathExt.map((e) => base + e));\n if (cmd.includes('/') || (win && cmd.includes('\\\\'))) return candidates(cmd).find(isFile) ?? null;\n const dirs = (env.PATH ?? env.Path ?? '').split(win ? ';' : path.delimiter).filter(Boolean);\n for (const dir of dirs) {\n const hit = candidates(path.join(dir, cmd)).find(isFile);\n if (hit) return hit;\n }\n return null;\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"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAA0D;AACnE,OAAOA,WAAU;;;ACDjB,OAAO,QAAQ;AACf,OAAO,UAAU;AASV,SAAS,WAAW,KAAa,MAAyB,QAAQ,KAAK,WAA4B,QAAQ,UAAyB;AACzI,QAAM,MAAM,aAAa;AACzB,QAAM,SAAS,CAAC,MAAc;AAC5B,QAAI;AACF,YAAM,KAAK,GAAG,SAAS,CAAC;AACxB,aAAO,GAAG,OAAO,MAAM,QAAQ,GAAG,OAAO,QAAW;AAAA,IACtD,QAAQ;AACN,aAA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,KAAK,aAAa,MAAM,cAAc,IAAI,KAAK,IAAI;AACjE,MAAI,SAAS,MAAM;AACjB,QAAI,QAAQ,GAAG,QAAQ,KAAK,IAAI,CAAC,mBAAmB,IAAI,QAAQ,EAAE,mDAAmD,KAAK,GAAG,EAAE;AAC/H,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,IAAI,MAAM,KAAK,IAAI;AACxC,QAAM,QAAQ,QAAQ,OAAO,CAAC,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC;AACjD;AAAA,IACE,MAAM,SAAS,SAAS;AAAA,IACxB,MAAM,SACF,GAAG,MAAM,KAAK,IAAI,CAAC,gDAAgD,IAAI,IAAI,MAC3E,GAAG,QAAQ,KAAK,IAAI,CAAC,iDAAiD,IAAI,IAAI;AAAA,EACpF;AACA,SAAO;AACT;;;AE9GO,SAAS,cAAc,WAA0B,cAAc,GAAa;AACjF,SAAO,CAAC,GAAG,IAAI,IAAI,CAAC,SAAS,QAAQ,GAAG,eAAe,QAAQ,GAAG,cAAc,QAAQ,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,KAAK,QAAQ,EAAE,GAAG,CAAC,CAAC;AACrI;AAGO,SAAS,gBACd,OAAuG,CAAC,GACzD;AAC/C,MAAI;AACF,YAAQ,KAAK,UAAU,kBAAkB,KAAK,YAAY,eAAe,CAAC;AAAA,EAC5E,SAAS,KAAK;AACZ,aAAS,QAAQ,sCAAsC,GAAG;AAC1D,WAAO;AAAA,EACT;AACF;","names":["path","path"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/usage/usage-store.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from '../platform/config.js';\nimport { atomicWriteFile } from '../platform/fs-safe.js';\nimport { debugLog } from '../platform/logger.js';\nimport type { UsageAccount, UsageWindow } from './usage.js';\n\n// Readings the agents' hooks leave behind, one file per agent and account. The status-line hook calls recordReading on every refresh, so it stays cheap.\n\n/** A reading that hasn't changed is rewritten only when its time is this old: the age stays honest without a write per refresh. */\nconst REFRESH_MS = 60_000;\n\ntype Stored = Omit<UsageAccount, 'account'>;\n\nexport const usageDir = () => path.join(getConfigDir(), 'usage');\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\nfunction isWindow(v: unknown): v is UsageWindow {\n return (\n isRecord(v) &&\n typeof v.id === 'string' &&\n typeof v.label === 'string' &&\n typeof v.usedPercent === 'number' &&\n (v.resetsAt === null || typeof v.resetsAt === 'string') &&\n (v.reset === undefined || v.reset === true)\n );\n}\n\nfunction parseStored(text: string): Stored | null {\n let v: unknown;\n try {\n v = JSON.parse(text);\n } catch {\n return null;\n }\n if (!isRecord(v) || typeof v.at !== 'string' || !Array.isArray(v.windows) || !v.windows.every(isWindow)) return null;\n return { at: v.at, windows: v.windows };\n}\n\nconst fileFor = (agent: string, account: string) => path.join(usageDir(), `${agent}-${account}.json`);\n\n/**\n * Within one window (same id, same known reset) usage only grows: an idle agent's redraw can carry an older, lower figure\n * than another session just reported, and it mustn't win.\n */\nfunction keepHigher(stored: UsageWindow[], fresh: UsageWindow[]): UsageWindow[] {\n return fresh.map((w) => {\n const was = w.resetsAt === null ? undefined : stored.find((s) => s.id === w.id && s.resetsAt === w.resetsAt);\n return was && was.usedPercent > w.usedPercent ? { ...w, usedPercent: was.usedPercent } : w;\n });\n}\n\n/** Keep a reading. Writes only when it changed (or the stored time is over a minute old); returns whether it wrote. Never throws. */\nexport function recordReading(agent: string, account: string, windows: UsageWindow[], now = Date.now()): boolean {\n if (windows.length === 0) return false;\n try {\n const file = fileFor(agent, account);\n let stored: Stored | null = null;\n try {\n stored = parseStored(fs.readFileSync(file, 'utf-8'));\n } catch {\n /* nothing stored yet */\n }\n const kept = stored ? keepHigher(stored.windows, windows) : windows;\n if (stored && JSON.stringify(stored.windows) === JSON.stringify(kept) && now - Date.parse(stored.at) < REFRESH_MS) return false;\n fs.mkdirSync(usageDir(), { recursive: true });\n atomicWriteFile(file, JSON.stringify({ at: new Date(now).toISOString(), windows: kept }));\n return true;\n } catch (e) {\n // Only the log: this runs in an agent's hook (Claude's status line), which shows nothing of ours.\n const err = e as NodeJS.ErrnoException;\n debugLog('WARN', `[usage] reading not kept: ${err.code ? `${err.code} ` : ''}${err.message ?? String(e)}`);\n return false;\n }\n}\n\n/** Every account's last reading for an agent, by account name. A file that isn't a reading is skipped. */\nexport function readReadings(agent: string): UsageAccount[] {\n let names: string[];\n try {\n names = fs.readdirSync(usageDir());\n } catch {\n return [];\n }\n const prefix = `${agent}-`;\n const out: UsageAccount[] = [];\n for (const name of names) {\n if (!name.startsWith(prefix) || !name.endsWith('.json')) continue;\n try {\n const stored = parseStored(fs.readFileSync(path.join(usageDir(), name), 'utf-8'));\n if (stored) out.push({ account: name.slice(prefix.length, -'.json'.length), ...stored });\n } catch {\n /* unreadable: skipped */\n }\n }\n return out.sort((a, b) => a.account.localeCompare(b.account));\n}\n"],"mappings":";;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AASjB,IAAM,aAAa;AAIZ,IAAM,WAAW,MAAM,KAAK,KAAK,aAAa,GAAG,OAAO;AAE/D,IAAM,WAAW,CAAC,MAA6C,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAEtH,SAAS,SAAS,GAA8B;AAC9C,SACE,SAAS,CAAC,KACV,OAAO,EAAE,OAAO,YAChB,OAAO,EAAE,UAAU,YACnB,OAAO,EAAE,gBAAgB,aACxB,EAAE,aAAa,QAAQ,OAAO,EAAE,aAAa,cAC7C,EAAE,UAAU,UAAa,EAAE,UAAU;AAE1C;AAEA,SAAS,YAAY,MAA6B;AAChD,MAAI;AACJ,MAAI;AACF,QAAI,KAAK,MAAM,IAAI;AAAA,EACrB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,SAAS,CAAC,KAAK,OAAO,EAAE,OAAO,YAAY,CAAC,MAA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EAAE,GAAG,IAAI,WAAW,OAAO,CAAC,CAAC,EAAE;AACzG,WAAO;AAAA,EACT;AACF;AAGO,SAAS,aAAa,OAA+B;AAC1D,MAAI;AACJ,MAAI;AACF,YAAQ,GAAG,YAAY,SAAS,CAAC;AAAA,EACnC,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACA,QAAM,SAAS,GAAG,KAAK;AACvB,QAAM,MAAsB,CAAC;AAC7B,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,KAAK,WAAW,MAAM,KAAK,CAAC,KAAK,SAAS,OAAO,EAAG;AACzD,QAAI;AACF,YAAM,SAAS,YAAY,GAAG,aAAa,KAAK,KAAK,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC;AAChF,UAAI,OAAQ,KAAI,KAAK,EAAE,SAAS,KAAK,MAAM,OAAO,QAAQ,CAAC,QAAQ,MAAM,GAAG,GAAG,OAAO,CAAC;AAAA,IACzF,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO,IAAI,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,cAAc,EAAE,OAAO,CAAC;AAC9D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/pty/output-status.ts","../src/core/pty/pty-pool.ts","../src/core/sessions/web-state.ts"],"sourcesContent":["import type { SessionAttention } from '../api-types.js';\n\n/**\n * A status for a session whose tool isn't Claude Code (config `aiCommand`,\n * e.g. opencode): no hooks report its turns, so the PTY host's \"last printed\n * anything\" stands in — a working agent redraws its spinner, an idle one\n * prints nothing. Working while it printed in the last `OUTPUT_WORKING_MS`,\n * idle after; never \"done, unseen\" or \"needs input\" (output can't tell a\n * finished turn from a question). Pure.\n */\n\nexport const OUTPUT_WORKING_MS = 10_000;\n\nexport interface PtyOutput {\n /** The tool's binary (the host's spawn spec). */\n tool?: string;\n /** When it last printed (ISO). */\n lastOutputAt?: string;\n startedAt: string;\n}\n\nexport function statusFromOutput(p: PtyOutput, now: number): SessionAttention | null {\n if (!p.tool || p.tool === 'claude' || !p.lastOutputAt) return null;\n const at = Date.parse(p.lastOutputAt);\n if (!Number.isFinite(at)) return null;\n const working = now - at < OUTPUT_WORKING_MS;\n return {\n state: working ? 'working' : 'idle',\n seen: true,\n since: p.lastOutputAt,\n updatedAt: p.lastOutputAt,\n stale: false,\n summary: `${working ? 'Printing' : 'Quiet'} — from its terminal output (${p.tool} has no status hooks)`,\n };\n}\n","import path from 'node:path';\nimport type { AgentAdapter } from '../agents/types.js';\nimport { agentFor, agentSettings, assistantAgent } from '../agents/index.js';\nimport { statusFromOutput, type PtyOutput } from './output-status.js';\nimport type { SessionAttention } from '../api-types.js';\nimport type { HostBeat } from './host-health.js';\nimport { PtyHostBusyError } from './pty-host-client.js';\nimport { noClaudeBecause } from '../archive/archiving.js';\nimport { findSession, sessionIdFor } from '../sessions/web-state.js';\nimport type { WorktreeSession } from '../sessions/history.js';\nimport { hostStartLockPath, type SpawnSpec, type HostInfo, type PtyInfo } from './pty-host-protocol.js';\nimport { dbPtySessions } from './pty-sessions-file.js';\nimport { ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { forgetPersistedSession } from './pty-sessions-file.js';\nimport { loadConfig } from '../platform/config.js';\nimport { ensureHost, findHost, PtyHostClient, findHostPatient, PtyHostVersionError } from './pty-host-client.js';\nimport { logSwallowed, swallow } from '../platform/best-effort.js';\nimport { ASSISTANT_ID, prepareAssistantDir } from '../agents/assistant.js';\n\n/**\n * `work web`'s view of the Claude PTYs. The PTYs themselves live in the\n * PTY host (`work pty-host`, see core/pty-host.ts), a separate long-lived\n * process — so restarting or rebuilding `work web` never kills an agent,\n * and a real terminal (`work attach`) can share the same session.\n *\n * This module resolves a dashboard session to a spawn spec, asks the host\n * to spawn it on first attach, and keeps a small cache of which sessions\n * have a live PTY for the synchronous badge path (`peekPty`).\n */\n\nlet workBin = process.argv[1] ?? '';\n/** Whether this server may start the PTY host when none runs (not the dev server: see configurePtyPool). */\nlet mayStartHost = true;\nlet client: PtyHostClient | null = null;\nlet live = new Set<string>();\n/** The pids of those PTYs' processes (the Claudes the app runs). */\nlet livePids = new Set<number>();\n/** Each live PTY's tool and last output (for output-status.ts). */\nlet outputs = new Map<string, PtyOutput & { pid: number }>();\nlet refreshTimer: NodeJS.Timeout | null = null;\n/** The heartbeat (host-health.ts): each list request is one. */\nconst beat: HostBeat = { known: false, lastOkAt: null, latencyMs: null, lastError: null };\n\n/** How the host answered lately (for GET /api/pty-host/health). */\nexport function hostBeat(): HostBeat {\n return { ...beat };\n}\nconst REFRESH_MS = 2000;\n\n/** Called by `work web` at startup with the resolved `work` binary path,\n * which is what the host is spawned from. */\nexport function configurePtyPool(opts: { workBin: string; startHost?: boolean }): void {\n workBin = opts.workBin;\n // The dev server (`work web --dev`) uses the host that runs and never starts one: started\n // from a checkout's build, the long-lived host that owns every Claude would outlive it,\n // and the installed work would become a client of the checkout's code.\n mayStartHost = opts.startHost ?? true;\n}\n\n/** The `work` binary path, for routes that launch `work attach`. */\nexport function getWorkBin(): string {\n return workBin;\n}\n\nasync function getClient(spawnIfMissing: boolean): Promise<PtyHostClient | null> {\n if (client) {\n // Cheap liveness re-check happens in refresh(); a dead host surfaces\n // as a failed call, which resets `client` below.\n return client;\n }\n const info = spawnIfMissing && mayStartHost ? await ensureHost(workBin) : await findHost();\n if (!info && spawnIfMissing && !mayStartHost)\n throw new Error(\n \"No PTY host is running, and the dev server doesn't start one: start the installed work (its app or `work web`) first.\",\n );\n if (!info) return null;\n client = new PtyHostClient(info);\n startRefresh();\n return client;\n}\n\nasync function refresh(): Promise<void> {\n const t0 = Date.now();\n try {\n const c = await getClient(false);\n if (!c) {\n beat.known = false;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n return;\n }\n beat.known = true;\n const ptys = await c.list();\n beat.lastOkAt = Date.now();\n beat.latencyMs = beat.lastOkAt - t0;\n beat.lastError = null;\n live = new Set(ptys.filter((p) => !p.exited).map((p) => p.id));\n livePids = new Set(ptys.filter((p) => !p.exited).map((p) => p.pid));\n outputs = new Map(\n ptys.filter((p) => !p.exited).map((p) => [p.id, { tool: p.tool, lastOutputAt: p.lastOutputAt, startedAt: p.startedAt, pid: p.pid }]),\n );\n } catch (err) {\n // Host went away (or was restarted on a new port) — rediscover next tick.\n // A busy host is still a host (it is there, just not answering).\n beat.known = beat.known || err instanceof PtyHostBusyError;\n beat.lastError = (err as Error).message;\n client = null;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n }\n}\n\nfunction startRefresh(): void {\n if (refreshTimer) return;\n refreshTimer = setInterval(() => void refresh(), REFRESH_MS);\n refreshTimer.unref?.();\n}\n\n/** Connect to an already-running host at `work web` startup so badges for\n * PTYs that survived a web restart show immediately. Never spawns. */\n/** Re-read the host's PTY list now (the periodic refresh can be seconds old,\n * or not have run at all right after `work web` started). */\nexport async function syncPtyPool(): Promise<void> {\n await refresh();\n}\n\nexport async function initPtyPool(): Promise<void> {\n await refresh().catch(() => {});\n startRefresh();\n}\n\n/**\n * After a reboot (or a host crash) nothing is running but\n * `pty-sessions.json` still lists the sessions that were live. Starting the\n * host restores them; do that when there's something to restore, so\n * reopening `work web` picks up where you left off. Returns how many\n * sessions the host will bring back (0 = nothing to do).\n */\nexport async function resumePersistedSessions(): Promise<number> {\n let count: number;\n try {\n count = Object.keys(dbPtySessions.read()).length;\n } catch {\n return 0;\n }\n if (count === 0) return 0;\n if (await findHost().catch(() => true)) return 0; // already running\n await getClient(true);\n await refresh();\n return count;\n}\n\n/**\n * Where Claude runs for a session — the same directory `work tree` launches\n * in: the worktree for a single repo, the group root (parent of the\n * sub-repos) for a group.\n */\nexport { ASSISTANT_ID };\n\n/** The assistant runs config `assistantAgent` (Claude Code by default), in its folder written for that agent. */\nexport function assistantSpec(): { cwd: string; tool: ReturnType<AgentAdapter['launch']['tool']> } {\n const settings = agentSettings();\n const agent = assistantAgent(settings);\n return { cwd: prepareAssistantDir(agent), tool: agent.launch.tool(settings) };\n}\n\nexport function spawnSpecFor(session: WorktreeSession): SpawnSpec | null {\n const first = session.paths[0];\n if (!first) return null;\n const cwd = session.isGroup ? path.dirname(first) : first;\n const config = loadConfig();\n return { cwd, tool: agentFor(config, session).launch.tool(config), port: session.port };\n}\n\n/**\n * Ensure a live PTY exists for the session (spawning Claude in the host if\n * needed) and return the host WebSocket URL to attach to. Null for an\n * unknown session.\n */\nexport async function ensurePty(sessionId: string, extra: { initialPrompt?: string } = {}): Promise<string | null> {\n // The dashboard assistant (Ctrl+K) is not a worktree: it runs in its own\n // folder, which is (re)written first (assistant.ts).\n const session = sessionId === ASSISTANT_ID ? null : findSession(sessionId);\n // Not for a session being archived, or archived: its Claude was stopped on\n // purpose (a Terminal tab still open on it reconnects and would start it).\n const refused = sessionId === ASSISTANT_ID ? null : noClaudeBecause(session, sessionId);\n if (refused) throw new Error(refused);\n const base = sessionId === ASSISTANT_ID ? assistantSpec() : session ? spawnSpecFor(session) : null;\n if (!base) return null;\n // The first prompt only applies to a fresh spawn (the host ignores the\n // spec when the session's PTY is already running).\n const spec = extra.initialPrompt ? { ...base, initialPrompt: extra.initialPrompt } : base;\n\n let c = await getClient(true);\n if (!c) return null;\n try {\n await c.spawn(sessionId, spec);\n } catch (err) {\n // Stale client (host restarted on a new port) — retry once, fresh.\n client = null;\n c = await getClient(true);\n if (!c) throw err;\n await c.spawn(sessionId, spec);\n }\n live.add(sessionId);\n return c.attachUrl(sessionId);\n}\n\n/** Side-effect-free check: does an active (non-exited) PTY exist for this\n * session? Served from the refresh cache — used by session-meta for the\n * \"running/idle\" badge, which must stay synchronous. */\n/** Every PTY in the host, fresh (never starts a host; [] without one). */\nexport async function listHostPtys(): Promise<PtyInfo[]> {\n const c = await getClient(false);\n return c ? c.list() : [];\n}\n\n/** Pids of the Claudes running in the PTY host (from the refresh cache). */\nexport function ptyPids(): ReadonlySet<number> {\n return livePids;\n}\n\n/** A status from its terminal output, for a session whose tool has no hooks (output-status.ts); null for Claude or no PTY. */\nexport function outputStatus(sessionId: string, now = Date.now()): SessionAttention | null {\n const o = outputs.get(sessionId);\n return o ? statusFromOutput(o, now) : null;\n}\n\n/** When a session's terminal last printed (ms, from the refresh cache); null with no PTY or a host that doesn't say. */\nexport function ptyLastOutputMs(sessionId: string): number | null {\n const at = outputs.get(sessionId)?.lastOutputAt;\n const ms = at ? Date.parse(at) : NaN;\n return Number.isFinite(ms) ? ms : null;\n}\n\n/** Its agent's process id in the host (from the refresh cache); null with no PTY. */\nexport function ptyPid(sessionId: string): number | null {\n return outputs.get(sessionId)?.pid ?? null;\n}\n\nexport function peekPty(sessionId: string): boolean {\n return live.has(sessionId);\n}\n\n/** A session's live PTY screen as text; null when there is none (never spawns). */\nexport async function readPtyScreen(sessionId: string): Promise<string | null> {\n if (!live.has(sessionId)) return null;\n const c = await getClient(false);\n return c ? c.screen(sessionId) : null;\n}\n\n/** Write to a session's live PTY. False when there is none (never spawns). */\nexport async function writeToPty(sessionId: string, data: string): Promise<boolean> {\n if (!live.has(sessionId)) return false;\n const c = await getClient(false);\n return c ? c.write(sessionId, data) : false;\n}\n\n/**\n * Restart a session's agent in the host, resuming its conversation, its terminals\n * kept attached (agent-restart.ts). A host from before that call: stopped and\n * started again (an open Terminal tab then offers Enter, as after a stop).\n */\nexport async function restartPty(sessionId: string): Promise<string | void> {\n let c = await getClient(false);\n if (!c) throw new Error('the PTY host is not running');\n let how: Awaited<ReturnType<PtyHostClient['restart']>>;\n try {\n how = await c.restart(sessionId);\n } catch (err) {\n // A stale client (the host restarted on a new port before the refresh noticed): once more, fresh.\n client = null;\n c = await getClient(false);\n if (!c) throw err;\n how = await c.restart(sessionId);\n }\n if (how === 'not-running') throw new Error('its agent is not running in the PTY host');\n if (how === 'unsupported') {\n await disposePty(sessionId);\n if (!(await ensurePty(sessionId))) throw new Error('its agent could not be started again');\n return OLD_HOST_RESTART;\n }\n}\n\n/** How a restart on a PTY host from before restart-in-place went: what differs, and the way to the real thing. */\nexport const OLD_HOST_RESTART =\n 'stopped and started again (an older PTY host: open terminals show it ended, and it runs with only the variables `hostEnv` keeps; `work pty-host --restart` gets restarts in place)';\n\n/** Kill one session's PTY (if any). Called before removing a worktree so\n * the Claude process doesn't hold its cwd open (Windows refuses to delete\n * a directory that is some process's working directory). */\nexport async function disposePty(sessionId: string): Promise<void> {\n live.delete(sessionId);\n let c = client;\n if (!c) {\n // A busy host (mid-restore) is waited for, not skipped: skipping left\n // Claude running inside the worktree about to be deleted. A host from\n // another build can't be talked to — nothing to do but proceed.\n let info: HostInfo | null;\n try {\n info = await findHostPatient();\n } catch (err) {\n if (err instanceof PtyHostVersionError) return;\n throw err; // still busy after waiting: let the caller report it\n }\n if (!info) return;\n c = new PtyHostClient(info);\n }\n await c.kill(sessionId).catch(swallow(`stop session ${sessionId} in the PTY host`));\n}\n\n/**\n * Stop a session's Claude in the PTY host before its worktree is deleted —\n * from any caller, including the CLI (`work remove` / prune / sync), which\n * doesn't run a pool. Never starts a host; waits for the process to exit\n * (the host's kill does) so Windows can then delete the directory.\n * Best-effort: no host, or a host that can't be reached, is a no-op.\n */\nexport async function stopSessionPty(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch } as WorktreeSession);\n live.delete(id);\n // Under the host START lock: a host that's starting holds it until it has\n // restored, so we either see it running (and kill the session) or know\n // none is — and then drop the session from the saved list so a later\n // start doesn't restore Claude into a worktree that's being deleted.\n const lock = hostStartLockPath();\n ensureFile(lock, '');\n await withFileLock(lock, async () => {\n let info;\n try {\n info = await findHostPatient();\n } catch (err) {\n // A host from another build can't be talked to; one still busy after\n // waiting is running and owns the session — leave both alone (and\n // never drop the saved entry: the host is what it belongs to).\n logSwallowed(`stop session ${id}: PTY host`, err);\n return;\n }\n if (info) await new PtyHostClient(info).kill(id).catch(swallow(`stop session ${id} in the PTY host`));\n else await forgetPersistedSession(id).catch(swallow(`forget saved session ${id}`));\n }).catch(swallow(`stop session ${id}: host start lock`));\n}\n\n/** `work web` shutdown. Deliberately does NOT kill anything: the PTYs belong\n * to the host and outlive the dashboard. Just stops polling. */\nexport function detachPtyPool(): void {\n if (refreshTimer) clearInterval(refreshTimer);\n refreshTimer = null;\n client = null;\n live = new Set();\n livePids = new Set();\n}\n","import { createFsWatcher, type FsWatcher } from '../platform/fs-watcher.js';\nimport { findSessionById, type WorktreeSession } from './history.js';\n\nexport { sessionIdFor } from './session-id.js';\n\n/** A session by id — a primary-key lookup (every /api/sessions/:id/*\n * request does one; it used to load and hash every row). */\nexport function findSession(sessionId: string): WorktreeSession | null {\n return findSessionById(sessionId);\n}\n\ninterface WatcherEntry {\n watcher: FsWatcher;\n subscribers: Set<() => void>;\n}\n\nconst sessionWatchers = new Map<string, WatcherEntry>();\nconst DEBOUNCE_MS = 150;\n\n/**\n * Subscribe to filesystem changes for a session's worktree(s). The watch is\n * started on first subscriber and stopped when the last one leaves —\n * reference-counted so the cost stays proportional to what's actually being\n * viewed in the browser. It is the shared fs-watcher: dependency and build\n * folders (node_modules, bin/obj, dist, …) are left out, and on Windows and\n * macOS it is one recursive OS watch per root. A chokidar watch over the\n * whole worktree used to open one watch per folder, node_modules included.\n *\n * Returns an unsubscribe function. Safe to call multiple times.\n */\nexport function subscribeSession(sessionId: string, onChange: () => void): () => void {\n const session = findSession(sessionId);\n if (!session)\n return () => {\n /* unknown session */\n };\n\n let entry = sessionWatchers.get(sessionId);\n if (!entry) {\n const subscribers = new Set<() => void>();\n const newEntry: WatcherEntry = {\n subscribers,\n watcher: createFsWatcher({\n roots: session.paths,\n debounceMs: DEBOUNCE_MS,\n onChange: () => {\n for (const cb of subscribers) {\n try {\n cb();\n } catch {\n /* swallow */\n }\n }\n },\n }),\n };\n sessionWatchers.set(sessionId, newEntry);\n entry = newEntry;\n }\n\n entry.subscribers.add(onChange);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n entry!.subscribers.delete(onChange);\n if (entry!.subscribers.size === 0) {\n entry!.watcher.stop();\n if (sessionWatchers.get(sessionId) === entry) {\n sessionWatchers.delete(sessionId);\n }\n }\n };\n}\n\n/**\n * Force-stop one session's watcher regardless of subscribers. Used before\n * removing a worktree: on Windows an open directory watch keeps a handle\n * on the tree and makes `git worktree remove` fail. Late unsubscribes from\n * the orphaned entry are harmless (see the identity check above).\n */\nexport async function disposeSessionWatcher(sessionId: string): Promise<void> {\n const entry = sessionWatchers.get(sessionId);\n if (!entry) return;\n sessionWatchers.delete(sessionId);\n entry.subscribers.clear();\n entry.watcher.stop();\n}\n\n/** Stop every active session watcher. Called on server shutdown. */\nexport function disposeAllWatchers(): void {\n for (const [, entry] of sessionWatchers) entry.watcher.stop();\n sessionWatchers.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,oBAAoB;AAU1B,SAAS,iBAAiB,GAAc,KAAsC;AACnF,MAAI,CAAC,EAAE,QAAQ,EAAE,SAAS,YAAY,CAAC,EAAE,aAAc,QAAO;AAC9D,QAAM,KAAK,KAAK,MAAM,EAAE,YAAY;AACpC,MAAI,CAAC,OAAO,SAAS,EAAE,EAAG,QAAO;AACjC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO;AAAA,IACL,OAAO,UAAU,YAAY;AAAA,IAC7B,MAAM;AAAA,IACN,OAAO,EAAE;AAAA,IACT,WAAW,EAAE;AAAA,IACb,OAAO;AAAA,IACP,SAAS,GAAG,UAAU,aAAa,OAAO,qCAAgC,EAAE,IAAI;AAAA,EAClF;AACF;;;AClCA,OAAO,UAAU;;;ACOV,SAAS,YAAY,WAA2C;AACrE,SAAO,gBAAgB,SAAS;AAClC;AAOA,IAAM,kBAAkB,oBAAI,IAA0B;AACtD,IAAM,cAAc;AAab,SAAS,iBAAiB,WAAmB,UAAkC;AACpF,QAAM,UAAU,YAAY,SAAS;AACrC,MAAI,CAAC;AACH,WAAO,MAAM;AAAA,IAEb;AAEF,MAAI,QAAQ,gBAAgB,IAAI,SAAS;AACzC,MAAI,CAAC,OAAO;AACV,UAAM,cAAc,oBAAI,IAAgB;AACxC,UAAM,WAAyB;A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A+B;AAClF,QAAM,KAAK,aAAa,EAAE,QAAQ,OAAO,CAAoB;AAC7D,OAAK,OAAO,EAAE;AAKd,QAAM,OAAO,kBAAkB;AAC/B,aAAW,MAAM,EAAE;AACnB,QAAM,aAAa,MAAM,YAAY;AACnC,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,gBAAgB;AAAA,IAC/B,SAAS,KAAK;AAIZ,mBAAa,gBAAgB,EAAE,cAAc,GAAG;AAChD;AAAA,IACF;AACA,QAAI,KAAM,OAAM,IAAI,cAAc,IAAI,EAAE,KAAK,EAAE,EAAE,MAAM,QAAQ,gBAAgB,EAAE,kBAAkB,CAAC;AAAA,QAC/F,OAAM,uBAAuB,EAAE,EAAE,MAAM,QAAQ,wBAAwB,EAAE,EAAE,CAAC;AAAA,EACnF,CAAC,EAAE,MAAM,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC;AACzD;AAIO,SAAS,gBAAsB;AACpC,MAAI,aAAc,eAAc,YAAY;AAC5C,iBAAe;AACf,WAAS;AACT,SAAO,oBAAI,IAAI;AACf,aAAW,oBAAI,IAAI;AACrB;","names":[]}
|
package/dist/cli-UTID323G.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
COMMANDS,
|
|
4
|
-
commandsFor,
|
|
5
|
-
run
|
|
6
|
-
} from "./chunk-USUQYM6V.js";
|
|
7
|
-
import "./chunk-3Q5RZCQW.js";
|
|
8
|
-
import "./chunk-VEKEA3ER.js";
|
|
9
|
-
import "./chunk-O34CKSE4.js";
|
|
10
|
-
import "./chunk-RCYI7SRA.js";
|
|
11
|
-
import "./chunk-KE2TFF7B.js";
|
|
12
|
-
export {
|
|
13
|
-
COMMANDS,
|
|
14
|
-
commandsFor,
|
|
15
|
-
run
|
|
16
|
-
};
|
|
17
|
-
//# sourceMappingURL=cli-UTID323G.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/platform/command-hook-installer.ts"],"sourcesContent":["/**\n * Installs a `command`-type entry in `~/.claude/settings.json` so Claude\n * Code spawns our hook subcommand and injects its stdout into the\n * conversation — command hooks let us return text that becomes part of\n * Claude's context (and record status for the attention inbox).\n *\n * Each install is tagged via the shared `settings-editor` (owner + PID)\n * so stale entries from a crashed previous run get pruned automatically\n * and writes are atomic.\n *\n * SECURITY NOTE: the `command` we register is resolved against the user's\n * PATH at hook-fire time (not install time). If an attacker can shadow\n * `work` earlier in PATH between install and fire, they intercept review\n * comments. We accept this for V1 — the tool is local-only — but a future\n * hardening pass should resolve the absolute path of the running `work`\n * binary at install time and embed that instead.\n */\n\nimport { editSettings, editSettingsSync, isOwnerEntry, isStaleEntry, HOOK_TAGS, tag, type HookEntry } from './settings-editor.js';\n\nexport interface CommandHookOptions {\n owner: string;\n /** Claude Code hook event to register under (e.g. UserPromptSubmit). */\n event: string;\n /** Shell command to execute. Receives the hook payload on stdin. */\n command: string;\n /** Hook timeout in seconds. Default 5. */\n timeoutSec?: number;\n}\n\nconst HOOK_TYPE = 'command';\n\nexport function installCommandHook(opts: CommandHookOptions): Promise<void> {\n return editSettings((s) => {\n if (!s.hooks) s.hooks = {};\n const list = (s.hooks[opts.event] ?? []) as HookEntry[];\n const cleaned = list.filter((h) => !isStaleEntry(h) && !isOwnerEntry(h, opts.owner));\n cleaned.push(\n tag(\n {\n hooks: [\n {\n type: HOOK_TYPE,\n command: opts.command,\n timeout: opts.timeoutSec ?? 5,\n },\n ],\n },\n opts.owner,\n ),\n );\n s.hooks[opts.event] = cleaned;\n });\n}\n\n/** The hook commands work web installs in ~/.claude/settings.json. */\nexport const MANAGED_HOOK_COMMANDS: ReadonlySet<string> = new Set(\n ['prompt-submit', 'stop', 'checkpoint', 'checkpoint-seal', 'status-prompt', 'status-stop', 'status-notify', 'turn-start', 'turn-end'].map(\n (e) => `work hook ${e}`,\n ),\n);\n\n/**\n * An entry of only work's own hook commands that lost its tags. Whatever\n * else rewrites settings.json — Claude Code saving a setting, a Claude\n * editing the file — may drop the `_workHook*` keys it doesn't know. Work\n * then no longer saw the entry as its own and installed a new one beside\n * it on every start: copies piled up, and each ran on every turn.\n */\nexport function isUntaggedWorkEntry(h: HookEntry): boolean {\n if (typeof h[HOOK_TAGS.OWNER_TAG] === 'string') return false;\n const cmds = (h.hooks ?? []).map((x) => (typeof x.command === 'string' ? x.command.trim() : ''));\n return cmds.length > 0 && cmds.every((c) => MANAGED_HOOK_COMMANDS.has(c));\n}\n\n/** Drop untagged copies of work's own hooks from these events. */\nfunction removeUntaggedWorkEntries(s: { hooks?: Record<string, HookEntry[] | undefined> }, events: Iterable<string>): void {\n if (!s.hooks) return;\n for (const event of events) {\n const list = s.hooks[event];\n if (!Array.isArray(list)) continue;\n s.hooks[event] = list.filter((h) => !isUntaggedWorkEntry(h));\n if (s.hooks[event]!.length === 0) delete s.hooks[event];\n }\n}\n\n/**\n * Install `install` and remove every `remove` (owner + event) in ONE write\n * of settings.json — one install per hook used to be one atomic rename\n * each, a burst Windows sometimes refused (EPERM while a Claude reads the\n * file). Stale entries (their process gone) and untagged copies of work's\n * own hooks are pruned on the way.\n */\nexport function syncCommandHooks(install: CommandHookOptions[], remove: Array<{ owner: string; event: string }> = []): Promise<void> {\n return editSettings((s) => {\n if (!s.hooks) s.hooks = {};\n removeUntaggedWorkEntries(s, new Set([...install, ...remove].map((x) => x.event)));\n for (const r of remove) removeOwnerEntries(s, r.owner, r.event);\n for (const opts of install) {\n const list = (s.hooks[opts.event] ?? []) as HookEntry[];\n const cleaned = list.filter((h) => !isStaleEntry(h) && !isOwnerEntry(h, opts.owner));\n cleaned.push(tag({ hooks: [{ type: HOOK_TYPE, command: opts.command, timeout: opts.timeoutSec ?? 5 }] }, opts.owner));\n s.hooks[opts.event] = cleaned;\n }\n });\n}\n\n/** Remove several owner + event entries in one write (signal handlers: synchronous). */\nexport function removeCommandHooksSync(remove: Array<{ owner: string; event: string }>): void {\n editSettingsSync((s) => {\n removeUntaggedWorkEntries(s, new Set(remove.map((r) => r.event)));\n for (const r of remove) removeOwnerEntries(s, r.owner, r.event);\n });\n}\n\nexport function removeCommandHook(owner: string, event: string): Promise<void> {\n return editSettings((s) => removeOwnerEntries(s, owner, event));\n}\n\n/** Synchronous variant for signal handlers. */\nexport function removeCommandHookSync(owner: string, event: string): void {\n editSettingsSync((s) => removeOwnerEntries(s, owner, event));\n}\n\nfunction removeOwnerEntries(s: { hooks?: Record<string, HookEntry[] | undefined> }, owner: string, event: string): void {\n if (!s.hooks) return;\n const list = s.hooks[event];\n if (!Array.isArray(list)) return;\n s.hooks[event] = list.filter((h) => !isStaleEntry(h) && !isOwnerEntry(h, owner));\n if (s.hooks[event]!.length === 0) delete s.hooks[event];\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,IAAM,YAAY;AAEX,SAAS,mBAAmB,MAAyC;AAC1E,SAAO,aAAa,CAAC,MAAM;AACzB,QAAI,CAAC,EAAE,MAAO,GAAE,QAAQ,CAAC;AACzB,UAAM,OAAQ,EAAE,MAAM,KAAK,KAAK,KAAK,CAAC;AACtC,UAAM,UAAU,KAAK,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,aAAa,GAAG,KAAK,KAAK,CAAC;AACnF,YAAQ;AAAA,MACN;AAAA,QACE;AAAA,UACE,OAAO;AAAA,YACL;AAAA,cACE,MAAM;AAAA,cACN,SAAS,KAAK;AAAA,cACd,SAAS,KAAK,cAAc;AAAA,YAC9B;AAAA,UACF;AAAA,QACF;AAAA,QACA,KAAK;AAAA,MACP;AAAA,IACF;AACA,MAAE,MAAM,KAAK,KAAK,IAAI;AAAA,EACxB,CAAC;AACH;AAGO,IAAM,wBAA6C,IAAI;AAAA,EAC5D,CAAC,iBAAiB,QAAQ,cAAc,mBAAmB,iBAAiB,eAAe,iBAAiB,cAAc,UAAU,EAAE;AAAA,IACpI,CAAC,MAAM,aAAa,CAAC;AAAA,EACvB;AACF;AASO,SAAS,oBAAoB,GAAuB;AACzD,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E,MAAM,KAAK,KAAK,IAAI;AAAA,IACxB;AAAA,EACF,CAAC;AACH;AAGO,SAAS,uBAAuB,QAAuD;AAC5F,mBAAiB,CAAC,MAAM;AACtB,8BAA0B,GAAG,IAAI,IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAChE,eAAW,KAAK,OAAQ,oBAAmB,GAAG,EAAE,OAAO,EAAE,KAAK;AAAA,EAChE,CAAC;AACH;AAEO,SAAS,kBAAkB,OAAe,OAA8B;AAC7E,SAAO,aAAa,CAAC,MAAM,mBAAmB,GAAG,OAAO,KAAK,CAAC;AAChE;AAGO,SAAS,sBAAsB,OAAe,OAAqB;AACxE,mBAAiB,CAAC,MAAM,mBAAmB,GAAG,OAAO,KAAK,CAAC;AAC7D;AAEA,SAAS,mBAAmB,GAAwD,OAAe,OAAqB;AACtH,MAAI,CAAC,EAAE,MAAO;AACd,QAAM,OAAO,EAAE,MAAM,KAAK;AAC1B,MAAI,CAAC,MAAM,QAAQ,IAAI,EAAG;AAC1B,IAAE,MAAM,KAAK,IAAI,KAAK,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC;AAC/E,MAAI,EAAE,MAAM,KAAK,EAAG,WAAW,EAAG,QAAO,EAAE,MAAM,KAAK;AACxD;","names":[]}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
installSkillsCommand,
|
|
4
|
-
runInstallSkills
|
|
5
|
-
} from "./chunk-3PLWNCRM.js";
|
|
6
|
-
import "./chunk-LNHSBM4L.js";
|
|
7
|
-
import "./chunk-FUNZ7TOS.js";
|
|
8
|
-
import "./chunk-ZMCU2PZN.js";
|
|
9
|
-
import "./chunk-VMBWCDBA.js";
|
|
10
|
-
import "./chunk-RCYI7SRA.js";
|
|
11
|
-
import "./chunk-KE2TFF7B.js";
|
|
12
|
-
export {
|
|
13
|
-
installSkillsCommand,
|
|
14
|
-
runInstallSkills
|
|
15
|
-
};
|
|
16
|
-
//# sourceMappingURL=install-skills-7EHZBANC.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/move.ts","../src/core/move/move.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { exportBundle, importBundle, MoveError, runningHere, unsavedWork } from '../core/move/move.js';\nimport { loadHistory } from '../core/sessions/history.js';\n\n/**\n * `work move export <dir>` / `work move import <dir>` — take your sessions,\n * conversations and setup to another computer (core/move/move.ts).\n */\nexport const moveCommand: CommandModule = {\n command: 'move <action> <dir>',\n describe: 'Move work to another computer: export a bundle here, import it there',\n builder: (y) =>\n y\n .positional('action', { choices: ['export', 'import'] as const, describe: 'export a bundle here, or import one' })\n .positional('dir', { type: 'string', describe: 'The bundle folder (new for export)' })\n .option('force', { type: 'boolean', describe: 'export: even with work not pushed; import: replace the sessions here' })\n .option('repos-root', { type: 'string', describe: 'import: where the repos are on this computer (each in its folder name)' })\n .option('worktrees-root', { type: 'string', describe: 'import: where worktrees go on this computer' })\n .option('clone', { type: 'boolean', describe: \"import: clone repos that aren't here from their origin\" }),\n handler: async (argv) => {\n const dir = path.resolve(argv.dir as string);\n try {\n if (argv.action === 'export') {\n const unsaved = await unsavedWork(loadHistory());\n if (unsaved.length) {\n console.log(chalk.yellow(\"Work that's only on this computer (the other one gets worktrees from origin):\"));\n for (const u of unsaved) console.log(` ${u.session}: ${u.what} ${chalk.gray(u.path)}`);\n if (!argv.force) {\n console.log(chalk.gray('Commit and push it (or ask its Claude), then export again — or --force to leave it behind.'));\n process.exitCode = 1;\n return;\n }\n }\n const r = exportBundle(dir);\n console.log(chalk.green(`Exported ${r.sessions} session(s) and ${r.transcripts} conversation file(s) to ${r.dir}`));\n console.log(chalk.gray('Copy the folder to the other computer and run `work move import <folder>` there (with work web stopped).'));\n return;\n }\n const running = await runningHere();\n if (running.length) {\n console.error(chalk.red(`Stop ${running.join(' and ')} first: an import replaces the database they hold.`));\n process.exitCode = 1;\n return;\n }\n const r = await importBundle(dir, {\n force: argv.force === true,\n clone: argv.clone === true,\n reposRoot: typeof argv['repos-root'] === 'string' ? path.resolve(argv['repos-root']) : undefined,\n worktreesRoot: typeof argv['worktrees-root'] === 'string' ? path.resolve(argv['worktrees-root']) : undefined,\n });\n console.log(chalk.green(`Imported ${r.sessions} session(s); ${r.transcripts} conversation file(s) put back for Claude.`));\n if (r.repos.cloned.length) console.log(`Cloned: ${r.repos.cloned.join(', ')}`);\n if (r.repos.missing.length)\n console.log(chalk.yellow(`Not on this computer: ${r.repos.missing.join(', ')} — clone them (or run again with --clone).`));\n if (r.worktrees.created.length) console.log(`Worktrees recreated: ${r.worktrees.created.join(', ')}`);\n for (const f of r.worktrees.failed) console.log(chalk.yellow(` ${f.session}: ${f.error}`));\n console.log(chalk.gray('Start `work web`: sessions resume their conversations when you open them.'));\n } catch (err) {\n if (!(err instanceof MoveError)) throw err;\n console.error(chalk.red(err.message));\n process.exitCode = 1;\n }\n },\n};\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { getConfigDir, getConfigPath, loadConfig } from '../platform/config.js';\nimport { replaceDb, snapshotDb, withDb } from '../platform/db.js';\nimport { atomicWriteFile } from '../platform/fs-safe.js';\nimport { loadHistory, saveHistory, type WorktreeSession } from '../sessions/history.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { sessionAliases } from '../sessions/session-repos.js';\nimport { agentOf } from '../agents/index.js';\nimport { originUrl, readGitConfig } from '../worktree/repo-scan.js';\nimport { defaultRunner, type CommandRunner } from '../pr/ship.js';\nimport { createInProcess, type CreateWorktree } from '../worktree/setup-child.js';\nimport { readWebUrl, webServerResponds } from '../platform/web-discovery.js';\nimport { findHost } from '../pty/pty-host-client.js';\n\n/**\n * Moving work to another computer (`work move export` / `import`). A bundle\n * is a folder you carry over (OneDrive, a USB stick): a snapshot of\n * state.db, config.json, work's own conversation copies and archives, the\n * groups' instruction files, every live session's agent transcripts, and a\n * manifest with each repo's origin. Never `~/.work` itself live in a synced\n * folder: syncing a database corrupts it, and two computers would both run\n * the PR and Jira watches.\n *\n * Import writes it all back with paths moved to the new computer (another\n * home folder, or other repo / worktree roots), clones repos that aren't\n * there (`--clone`), recreates live sessions' worktrees from their branches\n * on origin — so export first checks nothing is uncommitted or unpushed —\n * and puts the transcripts back where the agent looks, so conversations\n * resume. Checkpoint refs and wd's own review scopes stay behind (they live\n * in the old repos, keyed by old paths).\n */\n\nexport const BUNDLE_VERSION = 1;\n\nexport interface MoveManifest {\n version: number;\n exportedAt: string;\n from: { home: string; platform: string; worktreesRoot: string };\n /** Each repo's folder and origin URL, so a missing one can be cloned. */\n repos: Record<string, { path: string; origin: string | null }>;\n sessions: Array<{ id: string; target: string; branch: string; archived: boolean; transcripts: number }>;\n}\n\n/** A refusal, in words for the CLI. */\nexport class MoveError extends Error {}\n\nconst exists = (p: string) => fs.existsSync(p);\n\n// ---- before export: what wouldn't survive the move -------------------------------\n\nexport interface Unsaved {\n session: string;\n repo: string;\n path: string;\n what: string;\n}\n\n/**\n * Work only this computer has, per live session's repo: uncommitted files,\n * commits not on origin. Import recreates worktrees from origin, so these\n * would stay behind.\n */\nexport async function unsavedWork(sessions: WorktreeSession[], run: CommandRunner = defaultRunner): Promise<Unsaved[]> {\n const out: Unsaved[] = [];\n for (const s of sessions) {\n if (s.archivedAt) continue;\n for (const p of s.paths) {\n if (!exists(p)) continue;\n const at = { session: `${s.target} · ${s.branch || '(its checkout)'}`, repo: s.isGroup ? path.basename(p) : s.target, path: p };\n const status = await run('git', ['status', '--porcelain'], p);\n const dirty = status.code === 0 ? status.stdout.split('\\n').filter((l) => l.trim()).length : 0;\n if (dirty) out.push({ ...at, what: `${dirty} uncommitted file${dirty === 1 ? '' : 's'}` });\n const branch = (await run('git', ['rev-parse', '--abbrev-ref', 'HEAD'], p)).stdout.trim();\n if (!branch || branch === 'HEAD') continue;\n const onOrigin = (await run('git', ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`], p)).code === 0;\n const against = onOrigin ? `origin/${branch}` : 'origin/HEAD';\n const ahead = Number((await run('git', ['rev-list', '--count', `${against}..HEAD`], p)).stdout.trim()) || 0;\n if (ahead)\n out.push({ ...at, what: `${ahead} commit${ahead === 1 ? '' : 's'} not pushed${onOrigin ? '' : ` (${branch} isn't on origin)`}` });\n }\n }\n return out;\n}\n\n// ---- export ------------------------------------------------------------------------\n\nexport interface ExportResult {\n dir: string;\n sessions: number;\n transcripts: number;\n}\n\n/** Write the bundle into `dest` (a new or empty folder). */\nexport function exportBundle(dest: string, now = new Date()): ExportResult {\n if (exists(dest) && fs.readdirSync(dest).length) throw new MoveError(`${dest} isn't empty: give a new folder`);\n const home = getConfigDir();\n const config = loadConfig();\n if (!config) throw new MoveError('nothing to move: work has no config here');\n fs.mkdirSync(dest, { recursive: true });\n snapshotDb(path.join(dest, 'state.db'));\n fs.copyFileSync(getConfigPath(), path.join(dest, 'config.json'));\n for (const dir of ['conversations', 'archive']) {\n const from = path.join(home, dir);\n // An archive's copied git-ignored files (archive-ignored.ts) can hold secrets: they stay\n // on this computer, not in a bundle meant for a stick or a synced folder.\n const notIgnored = (src: string) => dir !== 'archive' || path.relative(from, src).split(path.sep)[1] !== 'ignored';\n if (exists(from)) fs.cpSync(from, path.join(dest, dir), { recursive: true, filter: notIgnored });\n }\n for (const f of fs.readdirSync(home).filter((n) => n.endsWith('.claude.md'))) {\n fs.mkdirSync(path.join(dest, 'instructions'), { recursive: true });\n fs.copyFileSync(path.join(home, f), path.join(dest, 'instructions', f));\n }\n\n const history = loadHistory();\n let transcripts = 0;\n const sessions: MoveManifest['sessions'] = [];\n for (const s of history) {\n const id = sessionIdFor(s);\n // An archived session's conversation is in its archive already.\n const files = s.archivedAt ? [] : (agentOf(s).conversation?.files(s) ?? []);\n for (const f of files) {\n fs.mkdirSync(path.join(dest, 'transcripts', id), { recursive: true });\n fs.copyFileSync(f.file, path.join(dest, 'transcripts', id, path.basename(f.file)));\n }\n transcripts += files.length;\n sessions.push({ id, target: s.target, branch: s.branch, archived: !!s.archivedAt, transcripts: files.length });\n }\n const repos: MoveManifest['repos'] = {};\n for (const [alias, p] of Object.entries(config.repos)) {\n repos[alias] = { path: p, origin: originUrl(readGitConfig(p) ?? '') };\n }\n const manifest: MoveManifest = {\n version: BUNDLE_VERSION,\n exportedAt: now.toISOString(),\n from: { home: os.homedir(), platform: process.platform, worktreesRoot: config.worktreesRoot },\n repos,\n sessions,\n };\n fs.writeFileSync(path.join(dest, 'manifest.json'), JSON.stringify(manifest, null, 2));\n return { dir: dest, sessions: history.length, transcripts };\n}\n\n// ---- paths on the new computer (pure) ---------------------------------------------\n\nexport interface PathRule {\n from: string;\n to: string;\n}\n\nconst norm = (p: string, caseless: boolean) => {\n const n = p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n return caseless ? n.toLowerCase() : n;\n};\n\n/**\n * Where things go: the worktrees root and each repo to the folders given\n * (`--worktrees-root`, `--repos-root` + its folder name), else the same\n * place under the new home folder; anything else under the old home moves\n * with it. Longest first, so the most specific rule wins. Pure.\n */\nexport function remapRules(\n m: Pick<MoveManifest, 'from' | 'repos'>,\n opts: { reposRoot?: string; worktreesRoot?: string },\n newHome: string,\n join: (...parts: string[]) => string = path.join,\n): PathRule[] {\n const caseless = m.from.platform === 'win32';\n const homeSwap = (p: string) => remapPath(p, [{ from: m.from.home, to: newHome }], caseless, join);\n const base = (p: string) =>\n p\n .replace(/[\\\\/]+$/, '')\n .split(/[\\\\/]/)\n .pop() ?? p;\n const rules: PathRule[] = [\n { from: m.from.worktreesRoot, to: opts.worktreesRoot ?? homeSwap(m.from.worktreesRoot) },\n ...Object.values(m.repos).map((r) => ({ from: r.path, to: opts.reposRoot ? join(opts.reposRoot, base(r.path)) : homeSwap(r.path) })),\n { from: m.from.home, to: newHome },\n ];\n return rules.sort((a, b) => b.from.length - a.from.length);\n}\n\n/** `p` under the first rule whose folder holds it, written for this computer; unchanged when none does. Pure. */\nexport function remapPath(p: string, rules: PathRule[], caseless: boolean, join: (...parts: string[]) => string = path.join): string {\n const key = norm(p, caseless);\n for (const r of rules) {\n const from = norm(r.from, caseless);\n if (key !== from && !key.startsWith(`${from}/`)) continue;\n const rest = p.replace(/\\\\/g, '/').slice(from.length).split('/').filter(Boolean);\n return rest.length ? join(r.to, ...rest) : r.to;\n }\n return p;\n}\n\n/** A session with its paths (and per-repo bases, keyed by path) moved. Pure. */\nexport function remapSession(s: WorktreeSession, move: (p: string) => string): WorktreeSession {\n const out: WorktreeSession = { ...s, paths: s.paths.map(move) };\n if (s.baseBranches) out.baseBranches = Object.fromEntries(Object.entries(s.baseBranches).map(([p, b]) => [move(p), b]));\n return out;\n}\n\n// ---- import ------------------------------------------------------------------------\n\n/**\n * What holds the database open here and must stop before an import replaces\n * it: work web, the PTY host. A host that doesn't answer counts as running.\n */\nexport async function runningHere(): Promise<string[]> {\n const out: string[] = [];\n const url = readWebUrl();\n if (url && (await webServerResponds(url))) out.push('work web (`work web --stop`)');\n try {\n if (await findHost()) out.push('the PTY host (`work pty-host --stop`)');\n } catch {\n out.push('the PTY host (`work pty-host --stop`)');\n }\n return out;\n}\n\nexport function readManifest(dir: string): MoveManifest {\n let raw: unknown;\n try {\n raw = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf-8'));\n } catch {\n throw new MoveError(`${dir} isn't a work bundle (no manifest.json): make one with \\`work move export\\``);\n }\n const m = raw as MoveManifest;\n if (!m || typeof m !== 'object' || typeof m.from?.home !== 'string' || typeof m.repos !== 'object')\n throw new MoveError(`${dir}/manifest.json isn't one work can read`);\n if (m.version > BUNDLE_VERSION) throw new MoveError(`this bundle is from a newer work (v${m.version}): update work first`);\n if (!exists(path.join(dir, 'state.db')) || !exists(path.join(dir, 'config.json')))\n throw new MoveError(`${dir} is missing state.db or config.json`);\n return m;\n}\n\nexport interface ImportOptions {\n reposRoot?: string;\n worktreesRoot?: string;\n /** Clone repos that aren't on this computer, from their origin. */\n clone?: boolean;\n /** Replace what this computer has already. */\n force?: boolean;\n}\n\nexport interface ImportReport {\n sessions: number;\n repos: { cloned: string[]; missing: string[] };\n worktrees: { created: string[]; failed: Array<{ session: string; error: string }> };\n transcripts: number;\n}\n\nexport interface ImportDeps {\n run: CommandRunner;\n create: CreateWorktree;\n /** Where a session's agent looks for its conversations (null: it starts fresh). */\n restoreDir: (s: WorktreeSession) => string | null;\n}\n\nconst defaultImportDeps = (): ImportDeps => ({\n run: defaultRunner,\n create: createInProcess,\n restoreDir: (s) => agentOf(s).conversation?.restoreDir?.(s) ?? null,\n});\n\n/** Bring a bundle in. The caller makes sure no work web or PTY host runs (they hold the database). */\nexport async function importBundle(dir: string, opts: ImportOptions = {}, deps: ImportDeps = defaultImportDeps()): Promise<ImportReport> {\n const m = readManifest(dir);\n if (!opts.force && exists(getConfigPath()) && loadHistory().length)\n throw new MoveError('work here has sessions already; importing replaces them (--force to do it anyway)');\n const caseless = m.from.platform === 'win32';\n const rules = remapRules(m, opts, os.homedir());\n const move = (p: string) => remapPath(p, rules, caseless);\n\n // config.json, as JSON: keys this version doesn't know come along.\n const raw = JSON.parse(fs.readFileSync(path.join(dir, 'config.json'), 'utf-8')) as Record<string, unknown>;\n if (typeof raw.worktreesRoot === 'string') raw.worktreesRoot = move(raw.worktreesRoot);\n if (raw.repos && typeof raw.repos === 'object')\n raw.repos = Object.fromEntries(\n Object.entries(raw.repos as Record<string, unknown>).map(([a, p]) => [a, typeof p === 'string' ? move(p) : p]),\n );\n for (const key of ['scanRoots', 'ignoredRepos'])\n if (Array.isArray(raw[key])) raw[key] = (raw[key] as unknown[]).map((p) => (typeof p === 'string' ? move(p) : p));\n fs.mkdirSync(getConfigDir(), { recursive: true });\n atomicWriteFile(getConfigPath(), JSON.stringify(raw, null, 2));\n\n // The database, then its sessions' paths. Its Claudes start when you open them here.\n replaceDb(path.join(dir, 'state.db'));\n const history = loadHistory().map((s) => remapSession(s, move));\n saveHistory(history);\n withDb((d) => d.prepare('DELETE FROM pty_sessions').run());\n\n // work's own files.\n for (const sub of ['conversations', 'archive'])\n if (exists(path.join(dir, sub))) fs.cpSync(path.join(dir, sub), path.join(getConfigDir(), sub), { recursive: true, force: false });\n if (exists(path.join(dir, 'instructions')))\n for (const f of fs.readdirSync(path.join(dir, 'instructions')))\n fs.copyFileSync(path.join(dir, 'instructions', f), path.join(getConfigDir(), f));\n\n const report: ImportReport = {\n sessions: history.length,\n repos: { cloned: [], missing: [] },\n worktrees: { created: [], failed: [] },\n transcripts: 0,\n };\n const config = loadConfig()!;\n for (const [alias, p] of Object.entries(config.repos)) {\n if (exists(p)) continue;\n const origin = m.repos[alias]?.origin;\n if (opts.clone && origin) {\n fs.mkdirSync(path.dirname(p), { recursive: true });\n const r = await deps.run('git', ['clone', origin, p], path.dirname(p));\n if (r.code === 0) {\n report.repos.cloned.push(alias);\n continue;\n }\n }\n report.repos.missing.push(alias);\n }\n\n // Live sessions get their worktrees back, from their branches on origin.\n const missing = new Set(report.repos.missing);\n for (const s of history) {\n if (s.archivedAt || !s.branch || s.paths.every(exists)) continue;\n const label = `${s.target} · ${s.branch}`;\n const repos = sessionAliases(s, config);\n if (repos.some((r) => missing.has(r))) {\n report.worktrees.failed.push({ session: label, error: `its repo isn't here (${repos.filter((r) => missing.has(r)).join(', ')})` });\n continue;\n }\n // A repo's own checkout (`work tree <repo>`) comes with the repo.\n if (!s.isGroup && config.repos[s.target] && s.paths[0] === config.repos[s.target]) continue;\n const r = await deps.create({ target: s.target, branch: s.branch }, config);\n if (r.ok) report.worktrees.created.push(label);\n else report.worktrees.failed.push({ session: label, error: r.error });\n }\n\n // Conversations back where the agent looks, so they resume.\n for (const s of loadHistory()) {\n const from = path.join(dir, 'transcripts', sessionIdFor(s));\n const to = exists(from) ? deps.restoreDir(s) : null;\n if (!to) continue;\n fs.mkdirSync(to, { recursive: true });\n for (const f of fs.readdirSync(from)) {\n if (exists(path.join(to, f)))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ty/pty-registry.ts","../src/core/pty/pty-session.ts","../src/core/pty/spawn-helper.ts"],"sourcesContent":["import fs from 'node:fs';\nimport chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { startPtyHost } from '../core/pty/pty-host.js';\nimport {\n ensureHost,\n findHost,\n probeHostDetailed,\n PtyHostBusyError,\n PtyHostClient,\n PtyHostVersionError,\n} from '../core/pty/pty-host-client.js';\nimport { ensureFile, withFileLock } from '../core/platform/fs-safe.js';\nimport { killTree } from '../core/platform/process.js';\nimport { hostInfoPath, hostStartLockPath, readHostInfo } from '../core/pty/pty-host-protocol.js';\nimport { loadHistory } from '../core/sessions/history.js';\nimport { sessionIdFor } from '../core/sessions/session-id.js';\nimport { resolveWorkBinPath } from '../core/platform/work-bin.js';\nimport { ensureAgentPath } from '../core/agents/agent-path.js';\n\nfunction info(message: string): void {\n process.stderr.write(message + '\\n');\n}\n\nexport type StopOutcome = 'stopped' | 'not-running' | 'stale-file' | 'unresponsive' | 'failed';\n\n/**\n * Kill the running host and its PTYs. The persisted session list stays, so\n * the next host start restores them with --continue.\n *\n * Only a PID that proves it's our host gets killed: it must answer /health\n * with the discovery file's token and report that same PID. The file\n * survives crashes and reboots (TerminateProcess skips cleanup), and\n * Windows reuses PIDs — force-killing the recorded PID and its tree blind\n * could take down an unrelated process. A stale file is just removed.\n */\nexport async function stopHost(kill: (pid: number) => boolean = killTree, probeTimeoutMs = 5000): 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.\n return 'unresponsive';\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 try {\n fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n return 'stale-file';\n }\n const ok = kill(hostInfo.pid);\n // TerminateProcess means the host never runs its own cleanup.\n try {\n fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n return ok ? 'stopped' : 'failed';\n}\n\nasync function printStatus(): Promise<void> {\n let host;\n try {\n host = await findHost();\n } catch (err) {\n if (err instanceof PtyHostVersionError || err instanceof PtyHostBusyError) {\n info(chalk.yellow(err.message));\n return;\n }\n throw err;\n }\n if (!host) {\n info(chalk.gray('No PTY host running.'));\n return;\n }\n const ptys = await new PtyHostClient(host).list();\n const names = new Map(loadHistory().map((s) => [sessionIdFor(s), `${s.target} · ${s.branch}`]));\n info(chalk.gray(`PTY host PID ${host.pid}, port ${host.port} — ${ptys.length} session(s)`));\n for (const p of ptys) {\n const state = p.exited ? chalk.red('exited') : chalk.green('live');\n const tag = p.restored ? chalk.gray(' (restored)') : '';\n info(` ${state} ${names.get(p.id) ?? p.id}${tag} ${chalk.gray(p.cwd)}`);\n }\n}\n\nexport const ptyHostCommand: CommandModule = {\n command: 'pty-host',\n describe: false, // internal — started on demand by `work web` / `work attach`\n builder: (yargs) =>\n yargs\n .option('stop', { type: 'boolean', default: false, describe: 'Stop the PTY host (sessions restore on next start).' })\n .option('restart', { type: 'boolean', default: false, describe: 'Restart the PTY host, e.g. after upgrading work.' })\n .option('status', { type: 'boolean', default: false, describe: 'List the sessions the PTY host owns.' }),\n handler: async (argv) => {\n if (argv.status) {\n await printStatus();\n return;\n }\n if (argv.stop || argv.restart) {\n const outcome = await stopHost();\n info(\n chalk.gray(\n {\n stopped: 'Stopped the PTY host.',\n 'not-running': 'No PTY host running.',\n 'stale-file': 'No PTY host running (removed a stale discovery file; nothing was killed).',\n unresponsive: 'The PTY host is not responding (busy?). Nothing was stopped — try again in a moment.',\n failed: 'Could not stop the PTY host.',\n }[outcome],\n ),\n );\n if (outcome === 'failed' || outcome === 'unresponsive') {\n process.exitCode = 1;\n return; // never --restart on top of a host we couldn't stop\n }\n if (argv.stop) return;\n await new Promise((r) => setTimeout(r, 500));\n const host = await ensureHost(resolveWorkBinPath(process.argv[1]));\n info(chalk.gray(`PTY host restarted (PID ${host.pid}); sessions are being restored.`));\n return;\n }\n\n // Singleton: a second host would restore every saved session a second\n // time (two Claudes per conversation). Check-and-start under a lock; a\n // version-mismatched or busy (not answering in time) host still counts\n // as running.\n const lock = hostStartLockPath();\n ensureFile(lock, '');\n const handle = await withFileLock(lock, async () => {\n const running = await findHost().catch((err) =>\n err instanceof PtyHostVersionError || err instanceof PtyHostBusyError ? true : null,\n );\n if (running) return null;\n // Started by the Mac app from the Dock, the PATH is the system's: `claude` wouldn't be found and\n // every session would end at once (\"exited with code 1\"). The login shell's, before the restore\n // below starts any (shell-path.ts); only once we know we're the host.\n ensureAgentPath();\n // Restore INSIDE the lock, as part of starting: startPtyHost writes\n // the discovery file and reads the saved list in the same tick,\n // before any request is served — so a client spawning a session\n // can't overwrite the list first (which lost every other saved\n // session), and a racing `work remove` waits for the restore.\n return startPtyHost();\n });\n if (!handle) {\n info(chalk.gray('PTY host already running.'));\n return;\n }\n info(chalk.gray(`PTY host listening on 127.0.0.1:${handle.info.port} (PID ${process.pid})`));\n const shutdown = () => {\n void handle.stop().finally(() => process.exit(0));\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n await new Promise(() => {});\n },\n};\n","import http from 'node:http';\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport { WebSocketServer } from 'ws';\nimport { atomicWriteFile } from '../platform/fs-safe.js';\nimport { PtyRegistry } from './pty-registry.js';\nimport { adoptLegacyRestoreList } from './pty-sessions-file.js';\nimport { bestEffort } from '../platform/best-effort.js';\nimport { PROTOCOL_VERSION, hostInfoPath, type ClientFrame, type HostInfo, type SpawnSpec } from './pty-host-protocol.js';\nimport { report } from '../platform/report.js';\n\nconst ATTACH_PATH = /^\\/ptys\\/([^/?]+)\\/attach(?:\\?|$)/;\nconst PTY_PATH = /^\\/ptys\\/([^/?]+)(\\/write|\\/screen|\\/restart)?$/;\nconst MAX_BODY = 1024 * 1024;\n\n/**\n * Input a terminal sends on its own, with nobody typing: focus in/out, answers to the agent's queries (device\n * attributes, cursor position, status, mode and keyboard-flag reports, window size), OSC / DCS / APC replies — and\n * the mouse moving with no button down (SGR motion reports, codes 35 + modifiers), which hovering over a terminal\n * sends. Every attached client answers a query, and a hidden one still reports focus, so these must not count as\n * using a client — only typing (keys, a paste, a click, a drag) does. A cursor-position report at row 1 and columns\n * 2–8 looks just like Shift/Alt/Ctrl+F3 (`ESC[1;2R` …), so it is taken for the key. Pure.\n */\nconst REPLY =\n /^(?:\\x1b\\[[IO]|\\x1b\\[[?>=][\\d;]*c|\\x1b\\[(?!1;[2-8]R)\\d+;\\d+R|\\x1b\\[\\??\\d*n|\\x1b\\[\\?\\d*u|\\x1b\\[\\??[\\d;]*\\$y|\\x1b\\[\\d+(?:;\\d+)*t|\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|\\x1b[P_][\\s\\S]*?\\x1b\\\\|\\x1b\\[<(?:35|39|43|47|51|55|59|63);\\d+;\\d+M)+$/;\nexport function isTerminalReply(data: string): boolean {\n return REPLY.test(data);\n}\n\nexport interface PtyHostHandle {\n info: HostInfo;\n registry: PtyRegistry;\n /** Kill every PTY (state file kept for the next restore) and stop. */\n stop(): Promise<void>;\n}\n\nfunction readBody(req: http.IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0;\n const chunks: Buffer[] = [];\n req.on('data', (c: Buffer) => {\n size += c.length;\n if (size > MAX_BODY) {\n reject(new Error('body too large'));\n req.destroy();\n return;\n }\n chunks.push(c);\n });\n req.on('end', () => {\n try {\n const text = Buffer.concat(chunks).toString('utf-8');\n resolve(text ? JSON.parse(text) : {});\n } catch (err) {\n reject(err);\n }\n });\n req.on('error', reject);\n });\n}\n\nfunction send(res: http.ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(body));\n}\n\nfunction isSpawnSpec(v: unknown): v is SpawnSpec {\n if (!v || typeof v !== 'object') return false;\n const s = v as Partial<SpawnSpec>;\n return typeof s.cwd === 'string' && s.cwd.length > 0 && !!s.tool && typeof s.tool.cmd === 'string' && Array.isArray(s.tool.baseArgs);\n}\n\n/**\n * The PTY host: a small localhost-only server that owns every Claude PTY\n * so they survive `work web` restarts and rebuilds, and so any number of\n * clients (browser terminal via `work web`, a real terminal via\n * `work attach`) can attach to the same session.\n *\n * Auth: a random token written to `~/.work/pty-host.json` (user-only\n * readable location) must accompany every request — `x-work-token` header\n * for HTTP, `?token=` for the WebSocket upgrade. Plus a Host-header check\n * against DNS rebinding, same as the other local servers (§1.3).\n */\nexport async function startPtyHost(opts: { registry?: PtyRegistry; restore?: boolean; writeInfo?: boolean } = {}): Promise<PtyHostHandle> {\n const registry = opts.registry ?? new PtyRegistry();\n const token = crypto.randomBytes(24).toString('hex');\n let allowedHosts = new Set<string>();\n\n const authorized = (req: http.IncomingMessage, url: URL): boolean => {\n if (!req.headers.host || !allowedHosts.has(req.headers.host)) return false;\n const given = (req.headers['x-work-token'] as string | undefined) ?? url.searchParams.get('token') ?? '';\n const a = Buffer.from(given);\n const b = Buffer.from(token);\n return a.length === b.length && crypto.timingSafeEqual(a, b);\n };\n\n const server = http.createServer(async (req, res) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (!authorized(req, url)) return send(res, 403, { error: 'forbidden' });\n\n try {\n if (req.method === 'GET' && url.pathname === '/health') {\n return send(res, 200, { version: PROTOCOL_VERSION, pid: process.pid });\n }\n if (req.method === 'GET' && url.pathname === '/ptys') {\n return send(res, 200, registry.list());\n }\n const m = url.pathname.match(PTY_PATH);\n if (m) {\n const id = decodeURIComponent(m[1]);\n if (m[2] === '/screen' && req.method === 'GET') {\n const text = registry.screen(id);\n return text === null ? send(res, 404, { error: 'not found' }) : send(res, 200, { text });\n }\n // Additive (no protocol bump): an older host answers 404 \"not found\", and the pool stops and starts it instead.\n if (m[2] === '/restart' && req.method === 'POST') {\n const info = await registry.restart(id);\n return info ? send(res, 200, info) : send(res, 409, { error: 'not running' });\n }\n if (m[2] === '/write' && req.method === 'POST') {\n const body = (await readBody(req)) as { data?: unknown };\n if (typeof body.data !== 'string') return send(res, 400, { error: 'data required' });\n return send(res, registry.write(id, body.data) ? 200 : 404, {});\n }\n if (!m[2] && req.method === 'POST') {\n const spec = await readBody(req);\n if (!isSpawnSpec(spec)) return send(res, 400, { error: 'invalid spawn spec' });\n if (!fs.existsSync(spec.cwd)) return send(res, 400, { error: 'cwd does not exist' });\n return send(res, 200, registry.spawn(id, spec));\n }\n if (!m[2] && req.method === 'GET') {\n const info = registry.get(id);\n return info ? send(res, 200, info) : send(res, 404, { error: 'not found' });\n }\n if (!m[2] && req.method === 'DELETE') {\n await registry.kill(id);\n return send(res, 200, {});\n }\n }\n return send(res, 404, { error: 'not found' });\n } catch (err) {\n return send(res, 500, { error: (err as Error).message });\n }\n });\n\n const wss = new WebSocketServer({ noServer: true });\n server.on('upgrade', (req, socket, head) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n const m = (req.url ?? '').match(ATTACH_PATH);\n if (!m || !authorized(req, url)) {\n socket.destroy();\n return;\n }\n const id = decodeURIComponent(m[1]);\n wss.handleUpgrade(req, socket, head, (ws) => {\n const attached = registry.attach(\n id,\n (data) => {\n try {\n ws.send(Buffer.from(data, 'utf-8'), { binary: true });\n } catch {\n /* */\n }\n },\n (code) => {\n try {\n ws.send(JSON.stringify({ type: 'exit', code }));\n ws.close(1000);\n } catch {\n /* */\n }\n },\n );\n if (!attached) {\n try {\n ws.send(JSON.stringify({ type: 'error', message: 'no such pty' }));\n ws.close(1011);\n } catch {\n /* */\n }\n return;\n }\n // Always first, even when empty: clients hold input and their own\n // resize until they've drawn it (see HostControlFrame 'replay'). The\n // screen as of the attach, then what came since (registry.attach).\n void attached.ready.then((replay) => {\n try {\n ws.send(JSON.stringify({ type: 'replay', ...replay }));\n } catch {\n /* */\n }\n if (attached.exitedWith !== null) {\n try {\n ws.send(JSON.stringify({ type: 'exit', code: attached.exitedWith }));\n ws.close(1000);\n } catch {\n /* */\n }\n return;\n }\n attached.start();\n });\n if (attached.exitedWith !== null) return;\n // This client's own grid. The PTY has one size for all its clients: the one used last sets it — resized OR typed\n // in (tmux's `window-size latest` counts both). With \"last resize\" alone, opening the session in the app shrank\n // the PTY to the app's grid, and a terminal attached to it stayed drawn for that size while you typed in it.\n let size: { cols: number; rows: number } | null = null;\n ws.on('message', (raw, isBinary) => {\n if (isBinary) return;\n let msg: ClientFrame;\n try {\n msg = JSON.parse(raw.toString('utf-8')) as ClientFrame;\n } catch {\n return;\n }\n if (msg.type === 'input' && typeof msg.data === 'string') {\n // Back to this client's grid first (a no-op when it is) — when someone typed in it, not for its own replies.\n if (size && !isTerminalReply(msg.data)) registry.resize(id, size.cols, size.rows);\n registry.write(id, msg.data);\n } else if (msg.type === 'resize' && Number.isInteger(msg.cols) && Number.isInteger(msg.rows)) {\n size = { cols: msg.cols, rows: msg.rows };\n registry.resize(id, msg.cols, msg.rows);\n }\n });\n ws.on('close', () => attached.detach());\n ws.on('error', () => attached.detach());\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', () => resolve());\n });\n const port = (server.address() as { port: number }).port;\n allowedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);\n\n const info: HostInfo = { pid: process.pid, port, token, version: PROTOCOL_VERSION };\n if (opts.writeInfo !== false) {\n atomicWriteFile(hostInfoPath(), JSON.stringify(info));\n }\n if (opts.restore !== false) {\n // An older host that outlived the upgrade kept its list in the old\n // file: take it over before restoring (see adoptLegacyRestoreList).\n if (!opts.registry) {\n const adopted = bestEffort('adopt the old pty-sessions.json', () => adoptLegacyRestoreList(), null);\n if (adopted !== null && adopted !== undefined)\n report('info', `[pty-host] adopted ${adopted} session(s) from an older host's pty-sessions.json`);\n }\n await registry.restore();\n }\n\n return {\n info,\n registry,\n async stop() {\n registry.disposeAllKeepingState();\n wss.close();\n await new Promise<void>((r) => server.close(() => r()));\n if (opts.writeInfo !== false) {\n try {\n const cur = JSON.parse(fs.readFileSync(hostInfoPath(), 'utf-8')) as HostInfo;\n if (cur.pid === process.pid) fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n }\n },\n };\n}\n","import fs from 'node:fs';\nimport { agentById } from '../agents/index.js';\nimport { ASSISTANT_ID } from '../agents/assistant.js';\nimport { loadConfig } from '../platform/config.js';\nimport { PtySession } from './pty-session.js';\nimport { atomicWriteFile, ensureFile, withFileLockSync } from '../platform/fs-safe.js';\nimport { dbPtySessions, type PtySessionsStore } from './pty-sessions-file.js';\nimport { isPersistedPty, keepEnv, type PersistedPty, type PersistedPtys, type PtyInfo, type SpawnSpec } from './pty-host-protocol.js';\nimport { logSwallowed, swallow } from '../platform/best-effort.js';\n\nconst REPLAY_MAX = 256 * 1024;\n\n/** How long an exited PTY lingers before it's dropped from the persisted\n * list. During a Windows shutdown/logoff the child Claudes are often killed\n * a moment BEFORE the host; dropping them immediately would erase exactly\n * the list we need to restore after the reboot. A host that's itself about\n * to die never reaches the timer. */\nconst FORGET_EXITED_MS = 5_000;\n\n/** Minimal PTY surface the registry needs — `PtySession` in production, a\n * fake in tests. */\nexport interface PtyLike {\n readonly pty: { pid: number };\n readonly exited: boolean;\n onExit?: (code: number) => void;\n setOutputHandler(h?: (data: string) => void): void;\n write(data: string): void;\n resize(cols: number, rows: number): void;\n dispose(): void;\n /** Serialized screen state (see PtySession.serialize). Optional so test\n * fakes can fall back to the raw replay buffer. */\n serialize?(): string;\n /** The serialized screen once everything written so far is parsed (see\n * PtySession.serializeSettled). Optional: a fake's screen is its raw buffer. */\n serializeSettled?(): Promise<string>;\n /** Visible screen as plain text (PtySession.screenText). */\n screenText?(): string;\n}\n\n/** What a newly attached client is sent first: the screen as it stands,\n * plus the grid it was drawn for. */\nexport interface ReplaySnapshot {\n data: string;\n cols: number;\n rows: number;\n}\n\nexport type PtySpawner = (spec: SpawnSpec & { resume: boolean }) => PtyLike;\n\nexport const defaultSpawner: PtySpawner = (spec) =>\n new PtySession(spec.cwd, spec.cols ?? 120, spec.rows ?? 32, undefined, {\n tool: spec.tool,\n resume: spec.resume,\n port: spec.port,\n unsafe: spec.unsafe,\n initialPrompt: spec.initialPrompt,\n env: spec.env,\n });\n\ninterface Entry {\n id: string;\n spec: Omit<PersistedPty, 'startedAt'>;\n pty: PtyLike;\n cols: number;\n rows: number;\n startedAt: string;\n restored: boolean;\n replay: string;\n subscribers: Set<(data: string) => void>;\n exitSubscribers: Set<(code: number) => void>;\n /** Set once the process exited (the entry lingers FORGET_EXITED_MS). */\n exitCode: number | null;\n /** When it last printed anything (ms): an idle Claude at its prompt prints nothing. */\n lastOutputAt: number;\n /** Its agent is being restarted (restart): the old process's end isn't the session's, a spawn starts no\n * second one, and a second restart gets this one's outcome. */\n restarting?: Promise<PtyInfo | null>;\n /** The environment it was started with, in memory only (never in the restore list: it can hold secrets), so a\n * restart runs as the session did; a restore after the host restarts has only what `hostEnv` kept. */\n env?: Record<string, string>;\n}\n\nexport interface RegistryDeps {\n /** The env variable names to keep for a restore (default: config `hostEnv`). */\n keepEnvNames?: () => string[];\n spawner?: PtySpawner;\n /** Its agent can resume a conversation in this folder (default: the agent's own check, agents/). */\n hasConversation?: (cwd: string, tool: string) => boolean;\n /** Where the restore list lives. Default: state.db. */\n sessions?: PtySessionsStore;\n /** Keep the restore list in this JSON file instead (tests, which must\n * never touch the user's state.db). */\n sessionsPath?: string;\n cwdExists?: (cwd: string) => boolean;\n}\n\n/** A restore list in a plain JSON file, written under the file lock. */\nexport function fileSessionsStore(file: string): PtySessionsStore {\n return {\n read() {\n const out: PersistedPtys = {};\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown;\n if (raw && typeof raw === 'object') {\n for (const [id, entry] of Object.entries(raw)) if (isPersistedPty(entry)) out[id] = entry;\n }\n } catch {\n /* missing or unreadable: nothing to restore */\n }\n return out;\n },\n write(all) {\n ensureFile(file, '{}');\n withFileLockSync(file, () => atomicWriteFile(file, JSON.stringify(all, null, 2)));\n },\n };\n}\n\n/**\n * Owns every live PTY in the host process and mirrors the set to the\n * restore list (state.db `pty_sessions`, see pty-sessions-file.ts) so a\n * host restart (crash, `--restart`, reboot) can respawn them with\n * `--continue`. Writes replace the list in one transaction, so two hosts\n * racing at startup can't interleave.\n */\nexport class PtyRegistry {\n private readonly entries = new Map<string, Entry>();\n private readonly spawner: PtySpawner;\n private readonly hasConversation: (cwd: string, tool: string) => boolean;\n private readonly store: PtySessionsStore;\n private readonly cwdExists: (cwd: string) => boolean;\n private readonly keepEnvNames: () => string[];\n /** Serializes persistence writes inside this process. */\n private writeChain: Promise<void> = Promise.resolve();\n\n constructor(deps: RegistryDeps = {}) {\n this.spawner = deps.spawner ?? defaultSpawner;\n this.hasConversation = deps.hasConversation ?? ((cwd, tool) => agentById(tool).launch.canResume(cwd));\n this.store = deps.sessions ?? (deps.sessionsPath ? fileSessionsStore(deps.sessionsPath) : dbPtySessions);\n this.cwdExists = deps.cwdExists ?? ((p) => fs.existsSync(p));\n this.keepEnvNames = deps.keepEnvNames ?? (() => loadConfig()?.hostEnv ?? []);\n }\n\n list(): PtyInfo[] {\n return [...this.entries.values()].map((e) => this.info(e));\n }\n\n get(id: string): PtyInfo | null {\n const e = this.entries.get(id);\n return e ? this.info(e) : null;\n }\n\n /** Spawn unless a live PTY already exists for `id` (idempotent). */\n spawn(id: string, spec: SpawnSpec & { keptEnv?: Record<string, string> }, restored = false): PtyInfo {\n const existing = this.entries.get(id);\n if (existing && (!existing.pty.exited || existing.restarting)) return this.info(existing);\n\n // A spawn from a shell keeps the variables config `hostEnv` names; a\n // restore — or a respawn without a shell (the Terminal tab) — runs with\n // the host's environment plus what its session kept.\n const kept = spec.env ? keepEnv(spec.env, this.keepEnvNames()) : (spec.keptEnv ?? existing?.spec.keptEnv);\n if (!spec.env && kept) spec = { ...spec, env: this.respawnEnv(kept) };\n\n const cols = spec.cols ?? 120;\n const rows = spec.rows ?? 32;\n const pty = this.spawner({\n ...spec,\n cols,\n rows,\n // `--continue` hard-errors in a directory Claude never ran in;\n // `--fresh` opts out even when one exists.\n resume: !spec.fresh && this.hasConversation(spec.cwd, spec.tool.cmd),\n });\n const entry: Entry = {\n id,\n // Only what a restore may reuse: env/prompt/fresh are one-shot (and\n // env can hold secrets), so they never reach pty-sessions.json — but\n // the variables config `hostEnv` names do (keepEnv), so a restore after\n // a reboot gets the JAVA_HOME / PATH it was started with.\n spec: { cwd: spec.cwd, tool: spec.tool, port: spec.port, unsafe: spec.unsafe, ...(kept ? { keptEnv: kept } : {}) },\n env: spec.env as Record<string, string> | undefined,\n pty,\n cols,\n rows,\n startedAt: new Date().toISOString(),\n restored,\n replay: '',\n subscribers: new Set(),\n exitSubscribers: new Set(),\n exitCode: null,\n lastOutputAt: Date.now(),\n };\n this.wire(entry, pty);\n this.entries.set(id, entry);\n void this.persist();\n return this.info(entry);\n }\n\n /** The env a spawn without a shell runs with: the host's, plus what its session kept (spawn). */\n private respawnEnv(kept: Record<string, string> | undefined): Record<string, string> | undefined {\n return kept ? { ...(process.env as Record<string, string>), ...kept } : undefined;\n }\n\n /** `pty` becomes the entry's process: its output to the entry's clients, its exit told to them (then forgotten). */\n private wire(entry: Entry, pty: PtyLike): void {\n const id = entry.id;\n entry.pty = pty;\n // Raw history is only a fallback for PTYs that can't serialize their\n // screen (test fakes) — real sessions replay PtySession.serialize().\n const keepRaw = !pty.serialize;\n pty.setOutputHandler((data) => {\n entry.lastOutputAt = Date.now();\n if (keepRaw) {\n entry.replay += data;\n if (entry.replay.length > REPLAY_MAX) {\n entry.replay = entry.replay.slice(entry.replay.length - REPLAY_MAX);\n }\n }\n for (const cb of entry.subscribers) {\n try {\n cb(data);\n } catch {\n /* subscriber gone */\n }\n }\n });\n pty.onExit = (code) => {\n entry.exitCode = code;\n for (const cb of entry.exitSubscribers) {\n try {\n cb(code);\n } catch {\n /* */\n }\n }\n setTimeout(() => {\n // Only forget it if nothing respawned under the same id meanwhile.\n if (this.entries.get(id) === entry) {\n this.entries.delete(id);\n void this.persist();\n }\n }, FORGET_EXITED_MS).unref?.();\n };\n }\n\n /** The live PTY's visible screen as text; null when there is none (or\n * it can't render one — test fakes). */\n screen(id: string): string | null {\n const e = this.entries.get(id);\n if (!e || e.pty.exited || !e.pty.screenText) return null;\n return e.pty.screenText();\n }\n\n write(id: string, data: string): boolean {\n const e = this.entries.get(id);\n if (!e || e.pty.exited) return false;\n e.pty.write(data);\n return true;\n }\n\n /** Last writer wins — with several clients attached (browser + a real\n * terminal) the host calls this when one resizes AND when one is typed in\n * (its own grid again), so the client used last sets the grid, like\n * tmux's `window-size latest` (pty-host.ts). */\n resize(id: string, cols: number, rows: number): void {\n const e = this.entries.get(id);\n if (!e || e.pty.exited) return;\n if (cols < 2 || rows < 2 || (cols === e.cols && rows === e.rows)) return;\n e.cols = cols;\n e.rows = rows;\n e.pty.resize(cols, rows);\n }\n\n /**\n * Attach a client: the screen snapshot, a disposer, and — for a real\n * session — `ready`, the snapshot once the screen has parsed everything\n * that arrived before this attach, then `start()` once it was sent.\n *\n * Output reaches clients the moment it arrives, but the screen parses it a\n * moment later (xterm's write is queued). A client attaching in between got\n * a snapshot without that output and subscribed too late to be sent it: it\n * was lost (a Linux PTY answers fast enough to land there). So output\n * arriving from the attach on is held for this client until `start()`, and\n * `ready` is the screen exactly as of the attach — nothing lost, nothing\n * twice. `replay` (taken at once) is for screens with no parsing step.\n */\n attach(\n id: string,\n onData: (data: string) => void,\n onExit: (code: number) => void,\n ): {\n replay: ReplaySnapshot;\n ready: Promise<ReplaySnapshot>;\n start: () => void;\n detach: () => void;\n exitedWith: number | null;\n } | null {\n const e = this.entries.get(id);\n if (!e) return null;\n // Attaching to one that already exited (inside the linger window): its\n // exit subscribers have fired, so tell this client now — otherwise it\n // would sit on a dead screen, its input silently dropped.\n const exitedWith = e.pty.exited && !e.restarting ? (e.exitCode ?? 0) : null;\n // Mid-restart the process in the entry is the old one, already disposed (its screen with it): nothing of it to\n // send or wait on — the new one draws from scratch, straight to this client.\n const restarting = !!e.restarting;\n const settled = restarting ? undefined : e.pty.serializeSettled;\n // Held output while the settled snapshot is taken; null = passed straight on.\n let held: string[] | null = settled ? [] : null;\n const sub = (d: string) => (held ? held.push(d) : onData(d));\n if (exitedWith === null) {\n e.subscribers.add(sub);\n e.exitSubscribers.add(onExit);\n }\n const snapshot = (data: string): ReplaySnapshot => ({ data, cols: e.cols, rows: e.rows });\n const replay = snapshot(restarting ? '' : e.pty.serialize?.() || e.replay);\n return {\n exitedWith,\n replay,\n ready: settled ? settled.call(e.pty).then((d) => snapshot(d || e.replay)) : Promise.resolve(replay),\n start: () => {\n const q = held;\n held = null;\n for (const d of q ?? []) onData(d);\n },\n detach: () => {\n e.subscribers.delete(sub);\n e.exitSubscribers.delete(onExit);\n },\n };\n }\n\n /**\n * Explicit kill (worktree removal, user closed the session). Removed\n * from the persisted list so it is NOT restored.\n *\n * Resolves once the process has actually exited (or after `timeoutMs`):\n * on Windows a just-killed process still holds its cwd for a moment, and\n * the caller's next step is usually deleting that very directory.\n */\n async kill(id: string, timeoutMs = 3000): Promise<void> {\n const e = this.entries.get(id);\n if (!e) return;\n this.entries.delete(id);\n // The terminals attached to it are told it ended (and so offer Enter to start it again):\n // dropped silently, a dashboard tab kept a connection to nothing and took no input.\n const attached = [...e.exitSubscribers];\n e.subscribers.clear();\n e.exitSubscribers.clear();\n const exited = e.pty.exited\n ? Promise.resolve(e.exitCode ?? 0)\n : new Promise<number>((resolve) => {\n const timer = setTimeout(() => resolve(0), timeoutMs);\n e.pty.onExit = (code) => {\n clearTimeout(timer);\n resolve(code);\n };\n });\n e.pty.dispose();\n const [code] = await Promise.all([exited, this.persist()]);\n for (const cb of attached) {\n try {\n cb(code);\n } catch {\n /* that client is gone */\n }\n }\n }\n\n /**\n * Its agent stopped and started again in place, resuming its conversation (a\n * tool that updated runs its new version). The new process goes into the same\n * entry, so the terminals attached stay attached (and a detach still finds them),\n * see the new one draw, and one that attaches meanwhile joins it; the restore\n * list keeps it. Null when there's no live PTY of that id.\n *\n * Never two agents on one conversation: an old one that hasn't exited within\n * `timeoutMs` is left running and tracked, and the restart fails. A new one that\n * can't start (its tool gone mid-update) ends the session as a kill does, its\n * terminals told so.\n */\n restart(id: string, timeoutMs = 3000): Promise<PtyInfo | null> {\n const e = this.entries.get(id);\n if (!e) return Promise.resolve(null);\n // Asked twice (two windows, the CLI): both get the one restart's outcome, failure included.\n if (e.restarting) return e.restarting;\n if (e.pty.exited) return Promise.resolve(null);\n const running = this.restartEntry(e, timeoutMs).finally(() => {\n e.restarting = undefined;\n });\n e.restarting = running;\n return running;\n }\n\n private async restartEntry(e: Entry, timeoutMs: number): Promise<PtyInfo | null> {\n const id = e.id;\n const old = e.pty;\n const stopped = await new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), timeoutMs);\n old.onExit = () => {\n clearTimeout(timer);\n resolve(true);\n };\n old.dispose();\n });\n if (this.entries.get(id) !== e) return this.get(id); // killed meanwhile\n if (!stopped) {\n // Its screen is gone with the dispose and the kill is on its way: not a session to keep showing (frozen\n // terminals, input into a dying process). Ended as a stop is, and no second agent is started on its\n // conversation while the old one may still be going.\n await this.endEntry(e);\n throw new Error(\n `its agent didn't stop within ${Math.round(timeoutMs / 1000)} s; its session was stopped (open it to start it again)`,\n );\n }\n let pty: PtyLike;\n try {\n pty = this.spawner({\n ...e.spec,\n env: e.env ?? this.respawnEnv(e.spec.keptEnv),\n cols: e.cols,\n rows: e.rows,\n resume: this.hasConversation(e.spec.cwd, e.spec.tool.cmd),\n });\n } catch (err) {\n await this.endEntry(e); // nothing runs now\n throw err;\n }\n e.exitCode = null;\n e.replay = '';\n e.startedAt = new Date().toISOString();\n e.restored = false;\n e.lastOutputAt = Date.now();\n this.wire(e, pty);\n void this.persist();\n return this.info(e);\n }\n\n /** A restart that can't go on ends the session as a kill does: its terminals told (they offer Enter to start it again), forgotten. */\n private async endEntry(e: Entry): Promise<void> {\n if (this.entries.get(e.id) === e) this.entries.delete(e.id);\n const attached = [...e.exitSubscribers];\n e.subscribers.clear();\n e.exitSubscribers.clear();\n await this.persist();\n for (const cb of attached) {\n try {\n cb(1);\n } catch {\n /* that client is gone */\n }\n }\n }\n\n /**\n * Respawn everything in the persisted list. Called once at host startup.\n * Worktrees that no longer exist are dropped, and so is the Ctrl+K\n * assistant: it starts when you open it (its conversation resumes then) —\n * restored, one opened once ran for good, a Claude nobody used.\n */\n async restore(): Promise<string[]> {\n const saved = this.readPersisted();\n const restored: string[] = [];\n for (const [id, entry] of Object.entries(saved)) {\n if (id === ASSISTANT_ID || !this.cwdExists(entry.cwd)) continue;\n try {\n this.spawn(id, entry, true);\n restored.push(id);\n } catch (err) {\n // One bad entry (tool missing, cwd unreadable) mustn't block the rest.\n logSwallowed(`restore session ${id} in ${entry.cwd}`, err);\n }\n }\n await this.persist();\n return restored;\n }\n\n /** Host shutdown: kill every PTY but KEEP the persisted list, so the next\n * host start restores them. */\n disposeAllKeepingState(): void {\n for (const e of this.entries.values()) {\n e.pty.onExit = undefined;\n e.subscribers.clear();\n e.exitSubscribers.clear();\n e.pty.dispose();\n }\n this.entries.clear();\n }\n\n /** Resolves once every queued persistence write has landed. */\n flush(): Promise<void> {\n return this.writeChain;\n }\n\n private info(e: Entry): PtyInfo {\n return {\n id: e.id,\n cwd: e.spec.cwd,\n pid: e.pty.pty.pid,\n exited: e.pty.exited,\n cols: e.cols,\n rows: e.rows,\n startedAt: e.startedAt,\n restored: e.restored,\n clients: e.subscribers.size,\n lastOutputAt: new Date(e.lastOutputAt).toISOString(),\n tool: e.spec.tool.cmd,\n };\n }\n\n private readPersisted(): PersistedPtys {\n try {\n return this.store.read();\n } catch (err) {\n logSwallowed('read the PTY restore list', err);\n return {};\n }\n }\n\n private persist(): Promise<void> {\n const snapshot: PersistedPtys = {};\n // Exited entries still lingering (see FORGET_EXITED_MS) are kept on\n // purpose — dropping them on an unrelated write would defeat the delay.\n for (const e of this.entries.values()) {\n snapshot[e.id] = { ...e.spec, startedAt: e.startedAt };\n }\n this.writeChain = this.writeChain\n .then(() => this.store.write(snapshot))\n .catch(swallow('persist the PTY restore list (next change retries)'));\n return this.writeChain;\n }\n}\n","import pty, { type IPty } from 'node-pty';\nimport { agentById } from '../agents/index.js';\nimport crossSpawn from 'cross-spawn';\nimport xtermHeadless from '@xterm/headless';\nimport xtermSerialize from '@xterm/addon-serialize';\nimport { debug } from '../platform/logger.js';\nimport { buildAiLaunchArgs, type AiToolSpec } from '../platform/ai-launcher.js';\nimport childProcess from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { makeSpawnHelperExecutable } from './spawn-helper.js';\nimport { report } from '../platform/report.js';\n\ntype Fork = typeof childProcess.fork;\nconst HIDDEN = Symbol.for('work.forkHidesConsole');\n\n/**\n * Make `fork()` hide the child's console window unless the caller says\n * otherwise. node-pty kills a Windows PTY by forking a helper\n * (conpty_console_list_agent) without `windowsHide`; from the PTY host —\n * detached, so it has no console of its own — Windows gave every such helper\n * a new, visible console: a window flashed on each Archive or stop.\n */\nexport function hideForkConsoles(cp: { fork: Fork }): void {\n if ((cp.fork as { [HIDDEN]?: true })[HIDDEN]) return;\n // windowsHide isn't in @types/node's ForkOptions, but fork passes its\n // options on to spawn, which honours it.\n const orig = cp.fork as unknown as (modulePath: string | URL, args: readonly string[], options: object) => ReturnType<Fork>;\n const wrapped = function (modulePath: string | URL, a?: unknown, b?: unknown) {\n const args = Array.isArray(a) ? (a as readonly string[]) : [];\n const options = (Array.isArray(a) || a == null ? b : a) ?? {};\n return orig.call(cp, modulePath, args, { windowsHide: true, ...(options as object) });\n } as unknown as Fork & { [HIDDEN]?: true };\n wrapped[HIDDEN] = true;\n cp.fork = wrapped;\n}\nif (process.platform === 'win32') hideForkConsoles(childProcess);\n\nlet spawnHelperChecked = false;\n/**\n * Once per process, before the first terminal: node-pty's spawn-helper must\n * be executable on macOS and Linux, or every terminal fails with\n * \"posix_spawnp failed\" (spawn-helper.ts). Fixes an install that has it\n * wrong; says so when it can't.\n */\nfunction ensureSpawnHelper(): void {\n if (spawnHelperChecked) return;\n spawnHelperChecked = true;\n try {\n const dir = path.dirname(createRequire(import.meta.url).resolve('node-pty/package.json'));\n const { fixed, failed } = makeSpawnHelperExecutable(dir);\n for (const file of fixed) debug('made node-pty spawn-helper executable', file);\n for (const { file, error } of failed)\n report(\n 'warn',\n `node-pty's spawn-helper isn't executable and couldn't be made so (${error}): terminals can't start. Run: chmod +x \"${file}\"`,\n );\n } catch (err) {\n debug('spawn-helper check failed', (err as Error).message);\n }\n}\n\nconst { Terminal } = xtermHeadless;\nconst { SerializeAddon } = xtermSerialize;\n\nexport interface PtyAiOptions {\n /** Resolved AI tool spec (from `getAiTool(config)`). */\n tool: AiToolSpec;\n unsafe?: boolean;\n resume?: boolean;\n promptFile?: string;\n /** Initial prompt passed on the command line (escaped — see\n * resolvePtyCommand). */\n initialPrompt?: string;\n /** Dev-server port exposed to the launched process as $PORT. */\n port?: number;\n /** Environment for the process instead of this process's own — the PTY\n * host passes the launching shell's env so PATH, AWS_PROFILE, venvs,\n * WT_SESSION etc. match where the user ran `work tree`. */\n env?: Record<string, string>;\n}\n\ntype CrossSpawnParse = (\n command: string,\n args: string[],\n options: { env?: NodeJS.ProcessEnv; cwd?: string },\n) => { command: string; args: string[]; file?: string; options: { windowsVerbatimArguments?: boolean } };\n\n/**\n * Turn `cmd args` into what node-pty should spawn, safely.\n *\n * Windows: resolved the way cross-spawn (used by `work tree`'s direct\n * launch) resolves it — a real .exe is spawned directly with normal argv\n * quoting; a .cmd/.bat shim goes through `cmd.exe /d /s /c \"…\"` with\n * cmd-metacharacters caret-escaped, handed to node-pty as a verbatim\n * command line. Never a bare `cmd.exe /c cmd args`: that lets `&`, `|`, `%`\n * in an argument (a prompt, a path) run as commands (§1.1).\n */\nexport function resolvePtyCommand(\n cmd: string,\n args: string[],\n opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {},\n): { file: string; args: string[] | string } {\n if (process.platform !== 'win32') return { file: cmd, args };\n const parse = (crossSpawn as unknown as { _parse: CrossSpawnParse })._parse;\n const parsed = parse(cmd, args, opts);\n if (parsed.options.windowsVerbatimArguments) {\n return { file: parsed.command, args: parsed.args.join(' ') };\n }\n return { file: parsed.file ?? parsed.command, args: parsed.args };\n}\n\nexport class PtySession {\n readonly pty: IPty;\n readonly terminal: InstanceType<typeof Terminal>;\n private readonly serializer = new SerializeAddon();\n readonly cwd: string;\n private outputHandler?: (data: string) => void;\n private _exited = false;\n private _outputBuffer = '';\n private _loggedOutput = false;\n onExit?: (code: number) => void;\n\n constructor(cwd: string, cols: number, rows: number, command?: { cmd: string; args: string[] }, aiOptions?: PtyAiOptions) {\n this.cwd = cwd;\n this.terminal = new Terminal({\n cols,\n rows,\n scrollback: 200,\n allowProposedApi: true,\n });\n this.terminal.loadAddon(this.serializer);\n\n let rawCmd: string;\n let rawArgs: string[];\n\n if (command) {\n // Custom command (e.g. work tree)\n rawCmd = command.cmd;\n rawArgs = command.args;\n } else if (aiOptions) {\n // Launch configured AI tool (default: claude)\n ({ cmd: rawCmd, args: rawArgs } = buildAiLaunchArgs(aiOptions.tool, {\n unsafe: aiOptions.unsafe,\n resume: aiOptions.resume,\n promptFile: aiOptions.promptFile,\n initialPrompt: aiOptions.initialPrompt,\n }));\n } else {\n throw new Error('PtySession requires either a custom command or aiOptions');\n }\n\n // A session of its own: never another agent's child (its adapter knows what a parent sets).\n const env: Record<string, string> = Object.fromEntries(\n Object.entries(agentById(aiOptions?.tool.cmd ?? 'claude').launch.cleanEnv(aiOptions?.env ?? process.env)).filter(\n (e): e is [string, string] => e[1] != null,\n ),\n );\n if (aiOptions?.port !== undefined) {\n env.PORT = String(aiOptions.port);\n }\n const { file: spawnCmd, args: spawnArgs } = resolvePtyCommand(rawCmd, rawArgs, { env, cwd });\n\n debug('PtySession spawn', { spawnCmd, spawnArgs, cwd, cols, rows });\n ensureSpawnHelper();\n this.pty = pty.spawn(spawnCmd, spawnArgs, {\n name: 'xterm-256color',\n cwd,\n cols,\n rows,\n env,\n });\n debug('PtySession spawned pid=', this.pty.pid);\n\n this.pty.onData((data) => {\n this.terminal.write(data);\n this.outputHandler?.(data);\n // Log first 500 chars of PTY output for debugging early exits\n if (!this._loggedOutput) {\n this._outputBuffer = (this._outputBuffer || '') + data;\n if (this._outputBuffer.length > 500) {\n debug('PtySession first output', { cwd, output: this._outputBuffer.slice(0, 500) });\n this._loggedOutput = true;\n this._outputBuffer = '';\n }\n }\n });\n\n this.pty.onExit(({ exitCode }) => {\n if (!this._loggedOutput && this._outputBuffer) {\n debug('PtySession output before exit', { cwd, output: this._outputBuffer.slice(0, 500) });\n }\n this._outputBuffer = '';\n debug('PtySession exited', { cwd, exitCode });\n this._exited = true;\n this.onExit?.(exitCode);\n });\n }\n\n get exited() {\n return this._exited;\n }\n\n write(data: string) {\n if (!this._exited) {\n try {\n this.pty.write(data);\n } catch {\n /* PTY already exited */\n }\n }\n }\n\n resize(cols: number, rows: number) {\n if (!this._exited) {\n try {\n this.pty.resize(cols, rows);\n } catch {\n // PTY already exited natively before our flag was set — ignore\n }\n this.terminal.resize(cols, rows);\n }\n }\n\n /**\n * The current screen + scrollback as escape sequences that redraw it\n * exactly (colors, cursor, modes, alt screen). What a late attacher is\n * sent instead of raw output history — raw bytes can start mid-sequence\n * and were drawn for another client's grid (VS Code does the same).\n */\n serialize(): string {\n try {\n return this.serializer.serialize();\n } catch {\n return '';\n }\n }\n\n /**\n * serialize(), once the screen has parsed everything written to it so far:\n * xterm queues writes, and a write's callback runs right after that write\n * is parsed — before any written later. What a new client is sent first.\n */\n serializeSettled(): Promise<string> {\n return new Promise((resolve) => {\n try {\n this.terminal.write('', () => resolve(this.serialize()));\n } catch {\n resolve(this.serialize());\n }\n });\n }\n\n /** The visible screen as plain text, one line per row (no colors).\n * What the dashboard checks before answering a prompt by keystroke. */\n screenText(): string {\n try {\n const buf = this.terminal.buffer.active;\n const lines: string[] = [];\n for (let y = buf.viewportY; y < buf.viewportY + this.terminal.rows; y++) {\n lines.push(buf.getLine(y)?.translateToString(true) ?? '');\n }\n return lines.join('\\n');\n } catch {\n return '';\n }\n }\n\n setOutputHandler(handler?: (data: string) => void) {\n this.outputHandler = handler;\n }\n\n dispose() {\n this.setOutputHandler(undefined);\n if (!this._exited) {\n try {\n this.pty.kill();\n } catch {\n /* PTY already exited */\n }\n }\n this.terminal.dispose();\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** The file system calls this needs (tests pass a fake one). */\nexport interface ModeFs {\n statSync(p: string): { mode: number };\n chmodSync(p: string, mode: number): void;\n}\n\nexport interface SpawnHelperCheck {\n /** Made executable. */\n fixed: string[];\n /** Not executable, and chmod failed (a root-owned global install): terminals can't start. */\n failed: Array<{ file: string; error: string }>;\n}\n\n/**\n * node-pty starts every terminal on macOS and Linux through its\n * `spawn-helper`. Its npm package ships the prebuilt one without the\n * executable bit, and its install script — which would fix that — doesn't\n * always run (npm skipping dependency install scripts; the desktop app's\n * 2.0.2 shipped it 0644): every terminal then fails with \"posix_spawnp\n * failed\". Make it executable where it lies: the prebuild for this\n * platform, and a locally built one. Nothing on Windows.\n */\nexport function makeSpawnHelperExecutable(\n ptyDir: string,\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n f: ModeFs = fs,\n): SpawnHelperCheck {\n const out: SpawnHelperCheck = { fixed: [], failed: [] };\n if (platform === 'win32') return out;\n for (const file of [\n path.join(ptyDir, 'prebuilds', `${platform}-${arch}`, 'spawn-helper'),\n path.join(ptyDir, 'build', 'Release', 'spawn-helper'),\n ]) {\n let mode: number;\n try {\n mode = f.statSync(file).mode;\n } catch {\n continue; // not there: the other one is used\n }\n if ((mode & 0o111) === 0o111) continue;\n try {\n f.chmodSync(file, (mode & 0o777) | 0o755);\n out.fixed.push(file);\n } catch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AA,UACV,EAAE,OAAO;AAAA,QACX;AAAA,MACF;AACA,UAAI,YAAY,YAAY,YAAY,gBAAgB;AACtD,gBAAQ,WAAW;AACnB;AAAA,MACF;AACA,UAAI,KAAK,KAAM;AACf,YAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,GAAG,CAAC;AAC3C,YAAM,OAAO,MAAM,WAAW,mBAAmB,QAAQ,KAAK,CAAC,CAAC,CAAC;AACjE,WAAK,MAAM,KAAK,2BAA2B,KAAK,GAAG,iCAAiC,CAAC;AACrF;AAAA,IACF;AAMA,UAAM,OAAO,kBAAkB;AAC/B,eAAW,MAAM,EAAE;AACnB,UAAM,SAAS,MAAM,aAAa,MAAM,YAAY;AAClD,YAAM,UAAU,MAAM,SAAS,EAAE;AAAA,QAAM,CAAC,QACtC,eAAe,uBAAuB,eAAe,mBAAmB,OAAO;AAAA,MACjF;AACA,UAAI,QAAS,QAAO;AAIpB,sBAAgB;AAMhB,aAAO,aAAa;AAAA,IACtB,CAAC;AACD,QAAI,CAAC,QAAQ;AACX,WAAK,MAAM,KAAK,2BAA2B,CAAC;AAC5C;AAAA,IACF;AACA,SAAK,MAAM,KAAK,mCAAmC,OAAO,KAAK,IAAI,SAAS,QAAQ,GAAG,GAAG,CAAC;AAC3F,UAAM,WAAW,MAAM;AACrB,WAAK,OAAO,KAAK,EAAE,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC;AAAA,IAClD;AACA,YAAQ,GAAG,UAAU,QAAQ;AAC7B,YAAQ,GAAG,WAAW,QAAQ;AAC9B,UAAM,IAAI,QAAQ,MAAM;AAAA,IAAC,CAAC;AAAA,EAC5B;AACF;","names":["fs","fs","fs","path","path","fs","pty","code","info","fs","fs"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/recent.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { agentFor } from '../core/agents/index.js';\nimport chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { select } from '@inquirer/prompts';\nimport { ensureConfig } from '../core/platform/config.js';\nimport { loadHistory, getRecentSessions, recordLaunch, touchSession } from '../core/sessions/history.js';\nimport { effectiveLastAccessedAt } from '../core/sessions/session-activity.js';\nimport { launchAi } from '../core/platform/launch.js';\nimport { timeAgo } from '../core/platform/format.js';\n\nexport const recentCommand: CommandModule = {\n command: 'recent [count]',\n describe: 'List recent worktree sessions',\n builder: (yargs) =>\n yargs\n .positional('count', {\n describe: 'Number of recent sessions to show',\n type: 'number',\n default: 10,\n })\n .option('resume', {\n describe: 'Interactively pick a session and launch the configured AI tool',\n type: 'boolean',\n default: false,\n })\n .option('unsafe', {\n describe: 'Launch the AI tool with its skip-permissions flag (used with --resume)',\n type: 'boolean',\n default: false,\n }),\n handler: async (argv) => {\n const count = argv.count as number;\n const resume = argv.resume as boolean;\n const unsafe = argv.unsafe as boolean;\n\n const config = ensureConfig();\n\n const sessions = loadHistory();\n const recent = getRecentSessions(sessions, count);\n\n if (recent.length === 0) {\n console.log(chalk.yellow('No recent worktree sessions found.'));\n return;\n }\n\n if (resume) {\n // Filter to sessions that still exist on disk\n const valid = recent.filter((s) => s.paths.some((p) => fs.existsSync(p)));\n\n if (valid.length === 0) {\n console.log(chalk.yellow('No resumable sessions (all paths removed from disk).'));\n return;\n }\n\n const choices = valid.map((s) => {\n const typeTag = s.isGroup ? '[group]' : '[repo]';\n return {\n name: `${typeTag} ${s.target} ${s.branch} (${timeAgo(effectiveLastAccessedAt(s))})`,\n value: s,\n };\n });\n\n const choice = await select({\n message: 'Select a session to resume:',\n choices,\n pageSize: 15,\n });\n\n // Find first existing path\n const firstExisting = choice.paths.find((p) => fs.existsSync(p));\n if (!firstExisting) {\n console.error('Session path no longer exists.');\n process.exitCode = 1;\n return;\n }\n\n // Resume where Claude actually has a transcript (group root or the\n // sub-repo the user worked in); start fresh when none exists so\n // `--continue` doesn't error out. Mirrors `work resume`.\n const { launchPath, hasConversation } = agentFor(config, choice).launch.resumeLaunch(choice);\n\n // Only its last access: the list was read before the picker waited on you, and a repo may have been added since.\n touchSession(choice.target, choice.branch);\n\n const tool = agentFor(config, choice).launch.tool(config);\n console.log(chalk.cyan(`Resuming in: ${launchPath}`));\n if (!hasConversation) {\n console.log(chalk.yellow(`No prior ${tool.cmd} conversation found for this worktree — starting a fresh session.`));\n }\n console.log(`Starting ${tool.cmd}...`);\n recordLaunch(choice.target, choice.branch, { unsafe: !!unsafe });\n launchAi(launchPath, tool, { unsafe, resume: hasConversation }, choice.port);\n return;\n }\n\n // Just list recent sessions\n console.log('');\n console.log(chalk.cyan('Recent Sessions'));\n console.log(chalk.cyan('==============='));\n console.log('');\n\n for (const session of recent) {\n const typeLabel = session.isGroup ? chalk.magenta('[group]') : chalk.blue('[repo]');\n const exists = session.paths.some((p) => fs.existsSync(p));\n const existsTag = exists ? '' : chalk.red(' [removed]');\n\n console.log(`${typeLabel} ${chalk.green(session.target)} ${chalk.white(session.branch)}${existsTag}`);\n console.log(chalk.gray(` Last used: ${timeAgo(effectiveLastAccessedAt(session))}`));\n }\n\n console.log('');\n console.log(chalk.gray('Use work resume to interactively resume a session.'));\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AAEf,OAAO,WAAW;AAElB,SAAS,cAAc;AAOhB,IAAM,gBAA+B;AAAA,EAC1C,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,CAAC,UACR,MACG,WAAW,SAAS;AAAA,IACnB,UAAU;AAAA,IACV,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC,EACA,OAAO,UAAU;AAAA,IAChB,UAAU;AAAA,IACV,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC,EACA,OAAO,UAAU;AAAA,IAChB,UAAU;AAAA,IACV,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AAAA,EACL,SAAS,OAAO,SAAS;AACvB,UAAM,QAAQ,KAAK;AACnB,UAAM,SAAS,KAAK;AACpB,UAAM,S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G,wEAAmE,CAAC;AAAA,MACnH;AACA,cAAQ,IAAI,YAAY,KAAK,GAAG,KAAK;AACrC,mBAAa,OAAO,QAAQ,OAAO,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC;AAC/D,eAAS,YAAY,MAAM,EAAE,QAAQ,QAAQ,gBAAgB,GAAG,OAAO,IAAI;AAC3E;AAAA,IACF;AAGA,YAAQ,IAAI,EAAE;AACd,YAAQ,IAAI,MAAM,KAAK,iBAAiB,CAAC;AACzC,YAAQ,IAAI,MAAM,KAAK,iBAAiB,CAAC;AACzC,YAAQ,IAAI,EAAE;AAEd,eAAW,WAAW,QAAQ;AAC5B,YAAM,YAAY,QAAQ,UAAU,MAAM,QAAQ,SAAS,IAAI,MAAM,KAAK,QAAQ;AAClF,YAAM,SAAS,QAAQ,MAAM,KAAK,CAAC,MAAM,GAAG,WAAW,CAAC,CAAC;AACzD,YAAM,YAAY,SAAS,KAAK,MAAM,IAAI,YAAY;AAEtD,cAAQ,IAAI,GAAG,SAAS,IAAI,MAAM,MAAM,QAAQ,MAAM,CAAC,IAAI,MAAM,MAAM,QAAQ,MAAM,CAAC,GAAG,SAAS,EAAE;AACpG,cAAQ,IAAI,MAAM,KAAK,gBAAgB,QAAQ,wBAAwB,OAAO,CAAC,CAAC,EAAE,CAAC;AAAA,IACrF;AAEA,YAAQ,IAAI,EAAE;AACd,YAAQ,IAAI,MAAM,KAAK,oDAAoD,CAAC;AAAA,EAC9E;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/resume.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { agentFor } from '../core/agents/index.js';\nimport chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { select } from '@inquirer/prompts';\nimport { ensureConfig } from '../core/platform/config.js';\nimport { loadHistory, getRecentSessions, recordLaunch, touchSession } from '../core/sessions/history.js';\nimport { effectiveLastAccessedAt } from '../core/sessions/session-activity.js';\nimport { launchAi } from '../core/platform/launch.js';\nimport { timeAgo } from '../core/platform/format.js';\n\nexport const resumeCommand: CommandModule = {\n command: 'resume',\n describe: 'Resume a recent worktree session',\n builder: (yargs) =>\n yargs.option('unsafe', {\n describe: 'Launch the AI tool with its skip-permissions flag',\n type: 'boolean',\n default: false,\n }),\n handler: async (argv) => {\n const unsafe = argv.unsafe as boolean;\n\n const config = ensureConfig();\n\n const sessions = loadHistory();\n const recent = getRecentSessions(sessions, sessions.length);\n\n // Filter to sessions that still exist on disk\n const valid = recent.filter((s) => s.paths.some((p) => fs.existsSync(p)));\n\n if (valid.length === 0) {\n console.log(chalk.yellow('No resumable sessions found.'));\n return;\n }\n\n const choices = valid.map((s) => {\n const typeTag = s.isGroup ? '[group]' : '[repo]';\n return {\n name: `${typeTag} ${s.target} ${s.branch} (${timeAgo(effectiveLastAccessedAt(s))})`,\n value: s,\n };\n });\n\n const choice = await select({\n message: 'Select a session to resume:',\n choices,\n pageSize: 15,\n });\n\n // Find first existing path\n const firstExisting = choice.paths.find((p) => fs.existsSync(p));\n if (!firstExisting) {\n console.error('Session path no longer exists.');\n process.exitCode = 1;\n return;\n }\n\n // Resume in the directory that actually holds a Claude transcript — the\n // group root, or a sub-repo the user worked in. `--continue` errors out\n // (\"No conversation found to continue\") when launched somewhere with no\n // transcript, so fall back to a fresh session in that case.\n const { launchPath, hasConversation } = agentFor(config, choice).launch.resumeLaunch(choice);\n\n // Only its last access: the list was read before the picker waited on you, and a repo may have been added since.\n touchSession(choice.target, choice.branch);\n\n const tool = agentFor(config, choice).launch.tool(config);\n console.log(chalk.cyan(`Resuming in: ${launchPath}`));\n if (!hasConversation) {\n console.log(chalk.yellow(`No prior ${tool.cmd} conversation found for this worktree — starting a fresh session.`));\n }\n console.log(`Starting ${tool.cmd}...`);\n recordLaunch(choice.target, choice.branch, { unsafe: !!unsafe });\n launchAi(launchPath, tool, { unsafe, resume: hasConversation }, choice.port);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;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AQ,MAAM,EAAE,OAAO,KAAK,MAAM;AACxD,YAAQ,IAAI,MAAM,KAAK,gBAAgB,UAAU,EAAE,CAAC;AACpD,QAAI,CAAC,iBAAiB;AACpB,cAAQ,IAAI,MAAM,OAAO,YAAY,KAAK,GAAG,wEAAmE,CAAC;AAAA,IACnH;AACA,YAAQ,IAAI,YAAY,KAAK,GAAG,KAAK;AACrC,iBAAa,OAAO,QAAQ,OAAO,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC;AAC/D,aAAS,YAAY,MAAM,EAAE,QAAQ,QAAQ,gBAAgB,GAAG,OAAO,IAAI;AAAA,EAC7E;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/agents/claude/statusline.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteFile } from '../../platform/fs-safe.js';\nimport { editSettings, readSettingsFile, type SettingsFile } from '../../platform/settings-editor.js';\nimport { report } from '../../platform/report.js';\nimport { WORK_STATUSLINE, isOurs, isRecord, readSaved, savedPath, type StatusLine } from './statusline-run.js';\n\n// Claude hands its rate limits only to the status line command. work puts itself in front of the user's own: it records\n// the reading, then runs theirs and passes its output on (statusline-run.ts, the hook's half). This half installs and\n// removes it; work web loads it lazily through the adapter (usage.ts), never the hook.\n\nfunction save(original: StatusLine | null): void {\n fs.mkdirSync(path.dirname(savedPath()), { recursive: true });\n atomicWriteFile(savedPath(), JSON.stringify({ original }));\n}\n\n/**\n * The command work puts in Claude's settings: its hook, then — when the user had a line — theirs as the fallback\n * (`work hook statusline || (<theirs>)`). The hook always exits 0 and runs theirs itself (from statusline.json), so the\n * right side runs only when `work` is gone (uninstalled, not on PATH): the user's status line then still shows.\n */\nexport function wrapperCommand(original: StatusLine | null): string {\n const cmd = original && typeof original.command === 'string' ? original.command.trim() : '';\n if (!cmd) return WORK_STATUSLINE;\n // A `# comment` in it would swallow the closing parenthesis: the parenthesis goes on a line of its own then.\n return /[#\\n]/.test(cmd) ? `${WORK_STATUSLINE} || (${cmd}\\n)` : `${WORK_STATUSLINE} || (${cmd})`;\n}\n\n/** Put work's status line in front of the user's. The original is saved inside the edit, so a change made meanwhile isn't lost. */\nexport async function wrapStatusLine(): Promise<void> {\n await editSettings((s: SettingsFile) => {\n if (isOurs(s.statusLine)) {\n // Ours already (perhaps under another path, or from before): the fallback follows the saved original. Nothing\n // readable saved: left as it is — its fallback may be the only copy of the user's line.\n const saved = readSaved();\n if (saved.kind === 'ok') s.statusLine = { ...(s.statusLine as StatusLine), command: wrapperCommand(saved.original) };\n return;\n }\n // Not ours: the user's line, perhaps set again with /statusline since — saved fresh, with a new fallback.\n const original = isRecord(s.statusLine) ? s.statusLine : null;\n save(original);\n const { command: _c, type: _t, ...keep } = original ?? {};\n s.statusLine = { ...keep, type: 'command', command: wrapperCommand(original) };\n });\n}\n\n/** The statusLine entry of Claude's settings as it is now; `unreadable` when the file doesn't parse. */\nexport function readStatusLineSetting(): { kind: 'ok'; statusLine: unknown } | { kind: 'unreadable' } {\n const s = readSettingsFile();\n return s ? { kind: 'ok', statusLine: s.statusLine } : { kind: 'unreadable' };\n}\n\n/**\n * What unwrapStatusLine did: put the original back, found a status line that isn't work's (left alone), kept work's\n * because the saved original is missing or damaged (putting nothing back would lose the user's), or couldn't edit the settings.\n */\nexport type UnwrapOutcome = 'restored' | 'not-ours' | 'kept' | 'failed';\n\n/** Give the user's status line back (settings left alone when it isn't ours, or when what was saved can't be read). */\nexport async function unwrapStatusLine(): Promise<UnwrapOutcome> {\n let outcome = 'failed' as UnwrapOutcome; // the mutate never runs when the settings can't be read (set inside it, hence the cast)\n await editSettings((s: SettingsFile) => {\n if (!isOurs(s.statusLine)) {\n outcome = 'not-ours';\n return;\n }\n const saved = readSaved();\n if (saved.kind !== 'ok') {\n outcome = 'kept';\n return;\n }\n if (saved.original) s.statusLine = saved.original;\n else delete s.statusLine;\n outcome = 'restored';\n });\n if (outcome === 'kept')\n report(\n 'warn',\n `[work] ${savedPath()} (your own status line, saved by work) is missing or damaged: Claude's status line left as it is.`,\n );\n // The saved original goes only once the settings no longer point at work: a failed write must not lose it.\n const now = readStatusLineSetting();\n if (outcome !== 'kept' && now.kind === 'ok' && !isOurs(now.statusLine)) fs.rmSync(savedPath(), { force: true });\n return outcome;\n}\n\n/**\n * The choice work web makes at start (a lean `wd` server never touches it): `enabled: false` (config\n * `usage.statusLine: false`) gives the user's status line back, anything else wraps it.\n */\nexport async function applyStatusLineSetting(o: { enabled: boolean; lean: boolean }): Promise<'wrapped' | 'restored' | 'skipped'> {\n if (o.lean) return 'skipped';\n if (!o.enabled) {\n await unwrapStatusLine();\n return 'restored';\n }\n await wrapStatusLine();\n return 'wrapped';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAUjB,SAAS,KAAK,UAAmC;AAC/C,KAAG,UAAU,KAAK,QAAQ,UAAU,CAAC,GAAG,EAAE,WAAW,KAAK,CAAC;AAC3D,kBAAgB,UAAU,GAAG,KAAK,UAAU,EAAE,SAAS,CAAC,CAAC;AAC3D;AAOO,SAAS,eAAe,UAAqC;AAClE,QAAM,MAAM,YAAY,OAAO,SAAS,YAAY,WAAW,SAAS,QAAQ,KAAK,IAAI;AACzF,MAAI,CAAC,IAAK,QAAO;AAEjB,SAAO,QAAQ,KAAK,GAAG,IAAI,GAAG,eAAe,QAAQ,GAAG;AAAA,KAAQ,GAAG,eAAe,QAAQ,GAAG;AAC/F;AAGA,eAAsB,iBAAgC;AACpD,QAAM,aAAa,CAAC,MAAoB;AACtC,QAAI,OAAO,EAAE,UAAU,GAAG;AAGxB,YAAM,QAAQ,UAAU;AACxB,UAAI,MAAM,SAAS,KAAM,GAAE,aAAa,EAAE,GAAI,EAAE,YAA2B,SAAS,eAAe,MAAM,QAAQ,EAAE;AACnH;AAAA,IACF;AAEA,UAAM,WAAW,SAAS,EAAE,UAAU,IAAI,EAAE,aAAa;AACzD,S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
import {
|
|
8
|
-
recordReading
|
|
9
|
-
} from "./chunk-ZMCU2PZN.js";
|
|
10
|
-
import "./chunk-VMBWCDBA.js";
|
|
11
|
-
import "./chunk-RCYI7SRA.js";
|
|
12
|
-
import {
|
|
13
|
-
debugLog
|
|
14
|
-
} from "./chunk-KE2TFF7B.js";
|
|
15
|
-
|
|
16
|
-
// src/core/agents/claude/statusline-hook.ts
|
|
17
|
-
import fs from "fs";
|
|
18
|
-
|
|
19
|
-
// src/core/agents/claude/rate-limits.ts
|
|
20
|
-
import os from "os";
|
|
21
|
-
import path from "path";
|
|
22
|
-
import { createHash } from "crypto";
|
|
23
|
-
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
24
|
-
var clampPercent = (n) => Math.round(Math.min(100, Math.max(0, n)) * 10) / 10;
|
|
25
|
-
function resetIso(v) {
|
|
26
|
-
let ms;
|
|
27
|
-
if (typeof v === "number" && Number.isFinite(v)) ms = v < 1e12 ? v * 1e3 : v;
|
|
28
|
-
else if (typeof v === "string" && v.trim() !== "") ms = Date.parse(v);
|
|
29
|
-
else return null;
|
|
30
|
-
return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
|
|
31
|
-
}
|
|
32
|
-
var capitalise = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
33
|
-
function labelOf(key) {
|
|
34
|
-
if (key === "five_hour") return "5-hour limit";
|
|
35
|
-
if (key === "seven_day") return "Weekly limit";
|
|
36
|
-
const named = /^seven_day_(.+)$/.exec(key);
|
|
37
|
-
if (named) return `Weekly ${capitalise(named[1].replace(/_/g, " "))} limit`;
|
|
38
|
-
const span = /^(\d+)_(hour|day)$/.exec(key);
|
|
39
|
-
if (span) return `${span[1]}-${span[2]} limit`;
|
|
40
|
-
return `${capitalise(key.replace(/_/g, " "))} limit`;
|
|
41
|
-
}
|
|
42
|
-
var rank = (key) => key === "five_hour" ? 0 : key === "seven_day" ? 1 : 2;
|
|
43
|
-
function parseClaudeRateLimits(raw) {
|
|
44
|
-
if (!isRecord(raw)) return [];
|
|
45
|
-
const windows = [];
|
|
46
|
-
const keys = Object.keys(raw).filter((k) => k !== "spend_limit").sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
|
|
47
|
-
for (const key of keys) {
|
|
48
|
-
const w = raw[key];
|
|
49
|
-
if (!isRecord(w) || typeof w.used_percentage !== "number" || !Number.isFinite(w.used_percentage)) continue;
|
|
50
|
-
windows.push({ id: key, label: labelOf(key), usedPercent: clampPercent(w.used_percentage), resetsAt: resetIso(w.resets_at) });
|
|
51
|
-
}
|
|
52
|
-
const spend = raw.spend_limit;
|
|
53
|
-
if (isRecord(spend)) {
|
|
54
|
-
const { used_percentage: pct, used_usd: used, limit_usd: limit } = spend;
|
|
55
|
-
let percent = null;
|
|
56
|
-
if (typeof pct === "number" && Number.isFinite(pct)) percent = pct;
|
|
57
|
-
else if (typeof used === "number" && typeof limit === "number" && Number.isFinite(used) && Number.isFinite(limit) && limit > 0)
|
|
58
|
-
percent = used / limit * 100;
|
|
59
|
-
if (percent !== null) {
|
|
60
|
-
windows.push({ id: "spend_limit", label: "Spend limit", usedPercent: clampPercent(percent), resetsAt: resetIso(spend.resets_at) });
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
return windows;
|
|
64
|
-
}
|
|
65
|
-
function accountOf(configDir) {
|
|
66
|
-
if (!configDir) return "default";
|
|
67
|
-
const norm = (p) => process.platform === "win32" ? path.resolve(p).toLowerCase() : path.resolve(p);
|
|
68
|
-
const resolved = norm(configDir);
|
|
69
|
-
if (resolved === norm(path.join(os.homedir(), ".claude"))) return "default";
|
|
70
|
-
const hash = createHash("sha1").update(resolved).digest("hex");
|
|
71
|
-
return `cfg-${hash.slice(0, 8)}`;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// src/core/agents/claude/statusline-hook.ts
|
|
75
|
-
var INPUT_CAP = 1e6;
|
|
76
|
-
async function runStatusLineHook(o = {}) {
|
|
77
|
-
const stdin = o.stdin ?? process.stdin;
|
|
78
|
-
const stdout = o.stdout ?? process.stdout;
|
|
79
|
-
const env = o.env ?? process.env;
|
|
80
|
-
stdout.on("error", () => {
|
|
81
|
-
});
|
|
82
|
-
try {
|
|
83
|
-
const chunks = [];
|
|
84
|
-
let size = 0;
|
|
85
|
-
for await (const chunk of stdin) {
|
|
86
|
-
const b = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
|
|
87
|
-
chunks.push(b);
|
|
88
|
-
size += b.length;
|
|
89
|
-
if (size > INPUT_CAP) break;
|
|
90
|
-
}
|
|
91
|
-
const raw = Buffer.concat(chunks).toString("utf-8");
|
|
92
|
-
let input = null;
|
|
93
|
-
try {
|
|
94
|
-
const v = JSON.parse(raw);
|
|
95
|
-
if (typeof v === "object" && v !== null && !Array.isArray(v)) input = v;
|
|
96
|
-
} catch {
|
|
97
|
-
}
|
|
98
|
-
if (input) {
|
|
99
|
-
const limits = parseClaudeRateLimits(input.rate_limits);
|
|
100
|
-
const given = input.rate_limits;
|
|
101
|
-
if (limits.length === 0 && typeof given === "object" && given !== null && Object.keys(given).length > 0)
|
|
102
|
-
debugLog("WARN", `[statusline] rate_limits not understood; keys: ${Object.keys(given).join(", ")}`);
|
|
103
|
-
recordReading("claude", accountOf(env.CLAUDE_CONFIG_DIR), limits);
|
|
104
|
-
}
|
|
105
|
-
if (env[NESTED_ENV]) return;
|
|
106
|
-
const orig = originalStatusLine((why) => debugLog("WARN", `[statusline] saved status line unreadable: ${why}`));
|
|
107
|
-
if (!orig) return;
|
|
108
|
-
const ws = input?.workspace;
|
|
109
|
-
const dir = [input?.cwd, ws?.current_dir].find((d) => typeof d === "string" && fs.existsSync(d));
|
|
110
|
-
stdout.write(await runStatusLineCommand(orig.command, raw, { cwd: dir }));
|
|
111
|
-
} catch (e) {
|
|
112
|
-
debugLog("WARN", `[statusline] ${e instanceof Error ? e.message : String(e)}`);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
export {
|
|
116
|
-
runStatusLineHook
|
|
117
|
-
};
|
|
118
|
-
//# sourceMappingURL=statusline-hook-TZ7M762P.js.map
|