sema-code-ui 0.0.0-stage → 2.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -2
- package/bin/sema-ui.js +2 -0
- package/dist/cli.js +4639 -0
- package/dist/public/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/dist/public/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/dist/public/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/dist/public/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/dist/public/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/dist/public/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/dist/public/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/dist/public/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/dist/public/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/dist/public/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/dist/public/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/dist/public/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/dist/public/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/dist/public/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/dist/public/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/dist/public/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/dist/public/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/dist/public/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/dist/public/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/dist/public/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/dist/public/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/dist/public/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/dist/public/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/dist/public/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/dist/public/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/dist/public/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/dist/public/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/dist/public/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/dist/public/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/dist/public/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/dist/public/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/dist/public/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/dist/public/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/dist/public/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/dist/public/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/dist/public/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/dist/public/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/dist/public/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/dist/public/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/dist/public/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/dist/public/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/dist/public/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/dist/public/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/dist/public/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/dist/public/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/dist/public/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/dist/public/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/dist/public/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/dist/public/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/dist/public/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/dist/public/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/dist/public/assets/_commonjs-dynamic-modules-TDtrdbi3.js +1 -0
- package/dist/public/assets/abnfDiagram-VCTEODGH-jerp7nR7.js +1 -0
- package/dist/public/assets/arc-BKtVw-5X.js +1 -0
- package/dist/public/assets/architectureDiagram-5GKGNRK7-CAQBfzNp.js +36 -0
- package/dist/public/assets/blockDiagram-I7D4REHJ-eT3AUuZb.js +129 -0
- package/dist/public/assets/c4Diagram-7LVT6UL2-DAAd027j.js +38 -0
- package/dist/public/assets/channel-COTmjPbb.js +1 -0
- package/dist/public/assets/chunk-2Q5K7J3B-D-9Y1d0N.js +1 -0
- package/dist/public/assets/chunk-5VM5RSS4-DwGFL19Q.js +15 -0
- package/dist/public/assets/chunk-F27PBJKO-BQ3tTrPF.js +1 -0
- package/dist/public/assets/chunk-IMKFNOWR-C1YkYZnB.js +231 -0
- package/dist/public/assets/chunk-JWPE2WC7-ddWKnZRa.js +1 -0
- package/dist/public/assets/chunk-POPQ4Y6H-fBnUAxGB.js +1 -0
- package/dist/public/assets/chunk-SVP7TREG-CMXiwsDR.js +88 -0
- package/dist/public/assets/chunk-TICWLB2K-DST453KD.js +206 -0
- package/dist/public/assets/chunk-XXDRQBXY-D5kNIT5P.js +1 -0
- package/dist/public/assets/classDiagram-ZZMXUADV-Lr4CIilS.js +1 -0
- package/dist/public/assets/classDiagram-v2-VYDZK3BY-Lr4CIilS.js +1 -0
- package/dist/public/assets/cose-bilkent-JH36ORCC-sc1yF5Gf.js +1 -0
- package/dist/public/assets/cynefin-OW5HDTMX-Dwe5aQpb.js +178 -0
- package/dist/public/assets/cynefinDiagram-5FMLGOSQ-W_SW62Ko.js +62 -0
- package/dist/public/assets/cytoscape.esm-Bch-eiPH.js +331 -0
- package/dist/public/assets/dagre-GXQ25YYZ-D99NrftV.js +4 -0
- package/dist/public/assets/defaultLocale-DX6XiGOO.js +1 -0
- package/dist/public/assets/diagram-S7CK7UJ4-DL3IhTh8.js +30 -0
- package/dist/public/assets/diagram-UQ7AKVKN-DSL_Joxa.js +41 -0
- package/dist/public/assets/diagram-VSXAHHWV-ge66Mn5n.js +3 -0
- package/dist/public/assets/diagram-VX7I27RA-BGeISp3y.js +24 -0
- package/dist/public/assets/diagram-Z3DM3KII-ClJeMRbb.js +24 -0
- package/dist/public/assets/docx-preview-BcbGRtLc.js +27 -0
- package/dist/public/assets/ebnfDiagram-PWID7BFC-Cn4t65pg.js +1 -0
- package/dist/public/assets/erDiagram-RLTQ6QDP-B1CfcDsm.js +99 -0
- package/dist/public/assets/exceljs.min-GkdcPpXr.js +57 -0
- package/dist/public/assets/flowDiagram-HODETNUW-BKAsEEya.js +168 -0
- package/dist/public/assets/ganttDiagram-EL5Y4UJY-wj_xV86l.js +292 -0
- package/dist/public/assets/gitGraphDiagram-WWUBYQGX-DcWUGLDO.js +106 -0
- package/dist/public/assets/index-2mLslaAC.js +931 -0
- package/dist/public/assets/index-BANUd07X.css +32 -0
- package/dist/public/assets/index-BP9qYm1I.js +1 -0
- package/dist/public/assets/index-B_RX2-hb.js +1 -0
- package/dist/public/assets/index-BeSy_WW1.js +198 -0
- package/dist/public/assets/index-C1rb1p6e.js +74 -0
- package/dist/public/assets/infoDiagram-27XIBGKW-DIKucIos.js +2 -0
- package/dist/public/assets/init-Gi6I4Gst.js +1 -0
- package/dist/public/assets/ishikawaDiagram-5VMMS53U-Bz_J0vOe.js +70 -0
- package/dist/public/assets/journeyDiagram-3NMN7TZE-CLkeMlCH.js +139 -0
- package/dist/public/assets/jstat-so0kbz-l.js +1 -0
- package/dist/public/assets/jszip.min-Cbc05ZIR.js +12 -0
- package/dist/public/assets/kanban-definition-UXKFOSKX-CwzN7MzX.js +89 -0
- package/dist/public/assets/layout-BcaUROCV.js +1 -0
- package/dist/public/assets/linear-Gq1n-w3C.js +1 -0
- package/dist/public/assets/mermaid.core-COBFmWjx.js +312 -0
- package/dist/public/assets/mindmap-definition-YA3MSWOX-DqRme-JA.js +96 -0
- package/dist/public/assets/ordinal-Cboi1Yqb.js +1 -0
- package/dist/public/assets/pdf-B5ZmZFk6.js +57 -0
- package/dist/public/assets/pdf.worker.min-BmVo14Nb.mjs +28 -0
- package/dist/public/assets/pdf.worker.min-LAOCk-LR.js +1 -0
- package/dist/public/assets/pegDiagram-XKGWAZYB-DaxTeHLN.js +1 -0
- package/dist/public/assets/pieDiagram-E7YTZNPT-D11GqVqw.js +39 -0
- package/dist/public/assets/pptx-preview.es-CaqkDSuh.js +28 -0
- package/dist/public/assets/quadrantDiagram-AXDQQJYC-fFb8l4El.js +7 -0
- package/dist/public/assets/railroadDiagram-O6MQD6OU-CIa-0P69.js +1 -0
- package/dist/public/assets/requirementDiagram-BXWQKSXE-BKzH5D9W.js +84 -0
- package/dist/public/assets/sankeyDiagram-P5KCCOFB-CtqHjl2H.js +40 -0
- package/dist/public/assets/sequenceDiagram-WJ2MYXX4-BpX3U60k.js +162 -0
- package/dist/public/assets/sizeCapture-INFHLROL-DsR9QL71.js +1 -0
- package/dist/public/assets/stateDiagram-D77RDMKH-0454rKey.js +1 -0
- package/dist/public/assets/stateDiagram-v2-MP3YSRHH-CYc0JDHV.js +1 -0
- package/dist/public/assets/swimlanes-42K2YHIH-BNRZBx_P.js +1 -0
- package/dist/public/assets/swimlanesDiagram-VR7AAH4N-DMo6Bf1N.js +8 -0
- package/dist/public/assets/timeline-definition-24CTP7MA-BNDN48o2.js +120 -0
- package/dist/public/assets/vennDiagram-4TSXK5OY-C2f8zI0e.js +34 -0
- package/dist/public/assets/wardleyDiagram-VM6X3IG4-CmfNgA4_.js +78 -0
- package/dist/public/assets/xychartDiagram-S5SC5T6Z-B2xKzCa7.js +7 -0
- package/dist/public/icon.svg +8 -0
- package/dist/public/index.html +14 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78-RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78ms-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/78ms-RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/83pv-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/90ms-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/90ms-RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/90msp-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/90msp-RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/90pv-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/90pv-RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Add-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Add-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Add-RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Add-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-0.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-1.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-3.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-4.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-5.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-6.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-CNS1-UCS2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-GB1-0.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-GB1-1.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-GB1-2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-GB1-3.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-GB1-4.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-GB1-5.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-GB1-UCS2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-0.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-1.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-3.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-4.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-5.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-6.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Japan1-UCS2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Korea1-0.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Korea1-1.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Korea1-2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Adobe-Korea1-UCS2.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/B5pc-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/B5pc-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/CNS-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/CNS-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/CNS1-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/CNS1-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/CNS2-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/CNS2-V.bcmap +3 -0
- package/dist/public/pdfjs-6.3.289/cmaps/ETHK-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/ETHK-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/ETen-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/ETen-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/ETenms-B5-H.bcmap +3 -0
- package/dist/public/pdfjs-6.3.289/cmaps/ETenms-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Ext-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Ext-RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Ext-RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Ext-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GB-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GB-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GB-H.bcmap +4 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GB-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBK-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBK-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBK2K-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBK2K-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBKp-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBKp-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBT-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBT-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBT-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBT-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBTpc-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBTpc-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBpc-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/GBpc-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKdla-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKdla-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKdlb-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKdlb-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKgccs-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKgccs-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKm314-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKm314-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKm471-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKm471-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKscs-B5-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/HKscs-B5-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Hankaku.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Hiragana.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSC-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSC-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSC-Johab-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSC-Johab-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSCms-UHC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSCms-UHC-HW-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSCms-UHC-HW-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSCms-UHC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSCpc-EUC-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/KSCpc-EUC-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Katakana.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/LICENSE +36 -0
- package/dist/public/pdfjs-6.3.289/cmaps/NWP-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/NWP-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/RKSJ-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/RKSJ-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/Roman.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UCS2-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UCS2-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UTF16-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UTF16-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UTF32-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UTF32-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UTF8-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniCNS-UTF8-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UCS2-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UCS2-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UTF16-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UTF16-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UTF32-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UTF32-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UTF8-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniGB-UTF8-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UCS2-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UCS2-HW-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UCS2-HW-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UCS2-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UTF16-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UTF16-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UTF32-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UTF32-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UTF8-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS-UTF8-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS2004-UTF16-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS2004-UTF16-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS2004-UTF32-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS2004-UTF32-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS2004-UTF8-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJIS2004-UTF8-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJISPro-UCS2-HW-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJISPro-UCS2-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJISPro-UTF8-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJISX0213-UTF32-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJISX0213-UTF32-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJISX02132004-UTF32-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniJISX02132004-UTF32-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UCS2-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UCS2-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UTF16-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UTF16-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UTF32-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UTF32-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UTF8-H.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/UniKS-UTF8-V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/V.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/cmaps/WP-Symbol.bcmap +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitDingbats.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitFixed.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitFixedBold.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitFixedBoldItalic.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitFixedItalic.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitSerif.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitSerifBold.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitSerifBoldItalic.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitSerifItalic.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/FoxitSymbol.pfb +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/LICENSE_FOXIT +27 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/LICENSE_LIBERATION +363 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/LiberationSans-Bold.ttf +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/LiberationSans-BoldItalic.ttf +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/LiberationSans-Italic.ttf +0 -0
- package/dist/public/pdfjs-6.3.289/standard_fonts/LiberationSans-Regular.ttf +0 -0
- package/dist/public/pdfjs-6.3.289/wasm/LICENSE_JBIG2 +196 -0
- package/dist/public/pdfjs-6.3.289/wasm/LICENSE_OPENJPEG +39 -0
- package/dist/public/pdfjs-6.3.289/wasm/LICENSE_PDFJS_JBIG2 +13 -0
- package/dist/public/pdfjs-6.3.289/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
- package/dist/public/pdfjs-6.3.289/wasm/LICENSE_PDFJS_QCMS +19 -0
- package/dist/public/pdfjs-6.3.289/wasm/LICENSE_QCMS +21 -0
- package/dist/public/pdfjs-6.3.289/wasm/jbig2.wasm +0 -0
- package/dist/public/pdfjs-6.3.289/wasm/jbig2_nowasm_fallback.js +15 -0
- package/dist/public/pdfjs-6.3.289/wasm/openjpeg.wasm +0 -0
- package/dist/public/pdfjs-6.3.289/wasm/openjpeg_nowasm_fallback.js +17 -0
- package/dist/public/pdfjs-6.3.289/wasm/qcms_bg.wasm +0 -0
- package/dist/public/pdfjs-6.3.289/wasm/quickjs-eval.js +16 -0
- package/dist/public/pdfjs-6.3.289/wasm/quickjs-eval.wasm +0 -0
- package/dist/public/viz-runtime.js +2 -0
- package/dist/resources/README.md +89 -0
- package/dist/resources/chrome/.mcp.json +9 -0
- package/dist/resources/chrome/skills/chrome-use/SKILL.md +78 -0
- package/dist/resources/mcp/fetch.json +14 -0
- package/dist/resources/mcp/playwright.json +14 -0
- package/dist/resources/skills/android-native-dev.json +13 -0
- package/dist/resources/skills/archify.json +13 -0
- package/dist/resources/skills/avoid-ai-writing.json +13 -0
- package/dist/resources/skills/brainstorming.json +13 -0
- package/dist/resources/skills/budget-variance-analysis.json +13 -0
- package/dist/resources/skills/code-review.json +13 -0
- package/dist/resources/skills/contract-review.json +13 -0
- package/dist/resources/skills/decision-memo.json +13 -0
- package/dist/resources/skills/deck-from-doc.json +13 -0
- package/dist/resources/skills/documentation-and-adrs.json +13 -0
- package/dist/resources/skills/flutter-dev.json +13 -0
- package/dist/resources/skills/frontend-dev.json +13 -0
- package/dist/resources/skills/ios-application-dev.json +13 -0
- package/dist/resources/skills/landing-page-generator.json +13 -0
- package/dist/resources/skills/minimax-docx.json +14 -0
- package/dist/resources/skills/minimax-pdf.json +14 -0
- package/dist/resources/skills/minimax-xlsx.json +14 -0
- package/dist/resources/skills/pptx-generator.json +14 -0
- package/dist/resources/skills/react-native-dev.json +13 -0
- package/dist/resources/skills/remotion-best-practices.json +12 -0
- package/dist/resources/skills/shader-dev.json +13 -0
- package/dist/resources/skills/systematic-debugging.json +13 -0
- package/dist/resources/skills/visualize/SKILL.md +413 -0
- package/dist/resources/skills/visualize/card.json +7 -0
- package/dist/resources/skills/visualize/scripts/check.mjs +539 -0
- package/dist/resources/skills/visualize/scripts/path.mjs +24 -0
- package/dist/resources/skills/wiki-page-writer.json +13 -0
- package/dist/resources/skills/writing-plans.json +13 -0
- package/dist/worker-entry.js +326 -0
- package/package.json +49 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4639 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
9
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
|
|
28
|
+
// package.json
|
|
29
|
+
var require_package = __commonJS({
|
|
30
|
+
"package.json"(exports2, module2) {
|
|
31
|
+
module2.exports = {
|
|
32
|
+
name: "sema-code-ui",
|
|
33
|
+
version: "2.1.4",
|
|
34
|
+
description: "SemaWork \u547D\u4EE4\u884C\u542F\u52A8\u5668\uFF1Asema-ui \u4E00\u6761\u547D\u4EE4\u5728\u6D4F\u89C8\u5668\u6253\u5F00\u57FA\u4E8E sema-core \u7684\u672C\u5730 Web \u754C\u9762",
|
|
35
|
+
author: "AIRC Sema Team",
|
|
36
|
+
license: "MIT",
|
|
37
|
+
repository: {
|
|
38
|
+
type: "git",
|
|
39
|
+
url: "https://github.com/midea-ai/sema-code-core.git",
|
|
40
|
+
directory: "webui/cli"
|
|
41
|
+
},
|
|
42
|
+
bin: {
|
|
43
|
+
"sema-ui": "bin/sema-ui.js"
|
|
44
|
+
},
|
|
45
|
+
files: [
|
|
46
|
+
"bin",
|
|
47
|
+
"dist",
|
|
48
|
+
"README.md"
|
|
49
|
+
],
|
|
50
|
+
engines: {
|
|
51
|
+
node: ">=20.18.1"
|
|
52
|
+
},
|
|
53
|
+
scripts: {
|
|
54
|
+
build: "node esbuild.mjs",
|
|
55
|
+
typecheck: "tsc --noEmit",
|
|
56
|
+
prepublishOnly: "npm run build"
|
|
57
|
+
},
|
|
58
|
+
keywords: [
|
|
59
|
+
"sema",
|
|
60
|
+
"ai",
|
|
61
|
+
"assistant",
|
|
62
|
+
"webui",
|
|
63
|
+
"cli"
|
|
64
|
+
],
|
|
65
|
+
dependencies: {
|
|
66
|
+
"@modelcontextprotocol/sdk": "^1.25.1",
|
|
67
|
+
"cron-parser": "^5.5.0",
|
|
68
|
+
diff: "7.0.0",
|
|
69
|
+
"node-pty": "^1.1.0",
|
|
70
|
+
"sema-core": "^2.1.4",
|
|
71
|
+
ws: "^8.18.0",
|
|
72
|
+
zod: "^3.25.76"
|
|
73
|
+
},
|
|
74
|
+
devDependencies: {
|
|
75
|
+
"@types/diff": "^7.0.2",
|
|
76
|
+
"@types/node": "^20.0.0",
|
|
77
|
+
"@types/ws": "^8.5.12",
|
|
78
|
+
esbuild: "^0.24.0",
|
|
79
|
+
typescript: "^5.4.0"
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// src/cli.ts
|
|
86
|
+
var import_fs18 = __toESM(require("fs"));
|
|
87
|
+
var import_http2 = __toESM(require("http"));
|
|
88
|
+
var import_path17 = __toESM(require("path"));
|
|
89
|
+
|
|
90
|
+
// ../server/src/registry/registry.ts
|
|
91
|
+
var import_fs = __toESM(require("fs"));
|
|
92
|
+
var import_path = __toESM(require("path"));
|
|
93
|
+
var import_os = __toESM(require("os"));
|
|
94
|
+
var import_crypto = require("crypto");
|
|
95
|
+
|
|
96
|
+
// ../shared/types.ts
|
|
97
|
+
var PERMISSION_LEVELS = ["AutoEdit", "AutoRun", "Bypass"];
|
|
98
|
+
var DEFAULT_PERMISSION_LEVEL = "Bypass";
|
|
99
|
+
function normalizeLevel(l) {
|
|
100
|
+
return PERMISSION_LEVELS.includes(l) ? l : "AutoEdit";
|
|
101
|
+
}
|
|
102
|
+
var DEFAULT_SYSTEM_PROMPT = "You are SemaWork, an Agent AI for work.";
|
|
103
|
+
var PREVENT_SLEEP_MODES = ["off", "ac", "always"];
|
|
104
|
+
|
|
105
|
+
// ../shared/lang.ts
|
|
106
|
+
var LANGS = {
|
|
107
|
+
zh: { label: "\u4E2D\u6587", htmlLang: "zh-CN", dateLocale: "zh-CN", customRules: "- \u4E2D\u6587\u56DE\u7B54" },
|
|
108
|
+
en: { label: "English", htmlLang: "en", dateLocale: "en-US", customRules: "- Answer in English" },
|
|
109
|
+
de: { label: "Deutsch", htmlLang: "de", dateLocale: "de-DE", customRules: "- Antworte auf Deutsch" },
|
|
110
|
+
fr: { label: "Fran\xE7ais", htmlLang: "fr", dateLocale: "fr-FR", customRules: "- R\xE9ponds en fran\xE7ais" },
|
|
111
|
+
it: { label: "Italiano", htmlLang: "it", dateLocale: "it-IT", customRules: "- Rispondi in italiano" }
|
|
112
|
+
};
|
|
113
|
+
var DEFAULT_LANG = "zh";
|
|
114
|
+
var LANGUAGES = Object.keys(LANGS);
|
|
115
|
+
function normalizeLang(value) {
|
|
116
|
+
const code = typeof value === "string" ? value.toLowerCase().split(/[-_]/)[0] : "";
|
|
117
|
+
return Object.prototype.hasOwnProperty.call(LANGS, code) ? code : DEFAULT_LANG;
|
|
118
|
+
}
|
|
119
|
+
function defaultCustomRules(lang) {
|
|
120
|
+
return LANGS[lang].customRules;
|
|
121
|
+
}
|
|
122
|
+
function isBuiltinCustomRules(rules) {
|
|
123
|
+
const current = String(rules ?? "").trim();
|
|
124
|
+
return LANGUAGES.some((l) => LANGS[l].customRules.trim() === current);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ../server/src/registry/registry.ts
|
|
128
|
+
var WEBUI_HOME = import_path.default.join(import_os.default.homedir(), ".sema", "webui");
|
|
129
|
+
var TRANSCRIPT_DIR = import_path.default.join(WEBUI_HOME, "transcripts");
|
|
130
|
+
var SEMA_DOCS_ROOT = import_path.default.join(import_os.default.homedir(), "Documents", "Sema");
|
|
131
|
+
var CONFIG_WORKSPACE = import_path.default.join(WEBUI_HOME, "workspace");
|
|
132
|
+
var INDEX_FILE = import_path.default.join(WEBUI_HOME, "index.json");
|
|
133
|
+
var SETTINGS_FILE = import_path.default.join(WEBUI_HOME, "settings.json");
|
|
134
|
+
var FIXED_CORE_CONFIG = { stream: true, thinking: true };
|
|
135
|
+
var DEFAULT_SETTINGS = {
|
|
136
|
+
coreConfig: {
|
|
137
|
+
lang: DEFAULT_LANG,
|
|
138
|
+
stream: true,
|
|
139
|
+
thinking: true,
|
|
140
|
+
systemPrompt: DEFAULT_SYSTEM_PROMPT,
|
|
141
|
+
customRules: defaultCustomRules(DEFAULT_LANG),
|
|
142
|
+
skipFileEditPermission: false,
|
|
143
|
+
skipShellExecPermission: false,
|
|
144
|
+
skipSkillPermission: false,
|
|
145
|
+
skipMCPToolPermission: false,
|
|
146
|
+
skipFetchUrlPermission: false,
|
|
147
|
+
skipExternalFileReadPermission: true,
|
|
148
|
+
disableBackgroundTasks: true,
|
|
149
|
+
enableToolSearch: true,
|
|
150
|
+
enableInputPrediction: true
|
|
151
|
+
},
|
|
152
|
+
defaultAgentMode: "Agent",
|
|
153
|
+
defaultPermissionLevel: DEFAULT_PERMISSION_LEVEL,
|
|
154
|
+
preventSleep: "off",
|
|
155
|
+
enableBrowserControl: false
|
|
156
|
+
};
|
|
157
|
+
function writeJsonAtomic(file, data) {
|
|
158
|
+
import_fs.default.mkdirSync(import_path.default.dirname(file), { recursive: true });
|
|
159
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
160
|
+
import_fs.default.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf8");
|
|
161
|
+
import_fs.default.renameSync(tmp, file);
|
|
162
|
+
}
|
|
163
|
+
function readJson(file, fallback) {
|
|
164
|
+
try {
|
|
165
|
+
if (!import_fs.default.existsSync(file)) return fallback;
|
|
166
|
+
return JSON.parse(import_fs.default.readFileSync(file, "utf8"));
|
|
167
|
+
} catch {
|
|
168
|
+
return fallback;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function dateFolder(d = /* @__PURE__ */ new Date()) {
|
|
172
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
173
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
|
174
|
+
}
|
|
175
|
+
function removeEmptyDateParent(workingDir) {
|
|
176
|
+
const parent = import_path.default.dirname(import_path.default.resolve(workingDir));
|
|
177
|
+
if (import_path.default.dirname(parent) !== import_path.default.resolve(SEMA_DOCS_ROOT)) return;
|
|
178
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(import_path.default.basename(parent))) return;
|
|
179
|
+
try {
|
|
180
|
+
const rest = import_fs.default.readdirSync(parent).filter((n) => n !== ".DS_Store");
|
|
181
|
+
if (rest.length === 0) import_fs.default.rmSync(parent, { recursive: true, force: true });
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function safeName(name) {
|
|
186
|
+
return name.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").trim() || "project";
|
|
187
|
+
}
|
|
188
|
+
var RegistryStore = class {
|
|
189
|
+
data;
|
|
190
|
+
settings;
|
|
191
|
+
constructor() {
|
|
192
|
+
import_fs.default.mkdirSync(WEBUI_HOME, { recursive: true });
|
|
193
|
+
import_fs.default.mkdirSync(TRANSCRIPT_DIR, { recursive: true });
|
|
194
|
+
this.data = readJson(INDEX_FILE, { schemaVersion: 1, projects: [], sessions: [] });
|
|
195
|
+
const s = readJson(SETTINGS_FILE, {});
|
|
196
|
+
this.settings = {
|
|
197
|
+
...DEFAULT_SETTINGS,
|
|
198
|
+
...s,
|
|
199
|
+
coreConfig: { ...DEFAULT_SETTINGS.coreConfig, ...s.coreConfig || {}, ...FIXED_CORE_CONFIG }
|
|
200
|
+
};
|
|
201
|
+
this.normalizeSystemPrompt();
|
|
202
|
+
this.settings.coreConfig.lang = normalizeLang(this.settings.coreConfig.lang);
|
|
203
|
+
if (s.defaultPermissionLevel) this.settings.defaultPermissionLevel = normalizeLevel(s.defaultPermissionLevel);
|
|
204
|
+
for (const sess of this.data.sessions) {
|
|
205
|
+
sess.permissionLevel = normalizeLevel(sess.permissionLevel);
|
|
206
|
+
if (sess.managedWorkingDir === void 0) sess.managedWorkingDir = !sess.projectId;
|
|
207
|
+
}
|
|
208
|
+
const managedRoot = import_path.default.resolve(SEMA_DOCS_ROOT) + import_path.default.sep;
|
|
209
|
+
for (const proj of this.data.projects) {
|
|
210
|
+
if (proj.managedWorkingDir === void 0) proj.managedWorkingDir = import_path.default.resolve(proj.workingDir).startsWith(managedRoot);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
// ---------- 读 ----------
|
|
214
|
+
snapshot() {
|
|
215
|
+
return JSON.parse(JSON.stringify(this.data));
|
|
216
|
+
}
|
|
217
|
+
getSettings() {
|
|
218
|
+
return JSON.parse(JSON.stringify(this.settings));
|
|
219
|
+
}
|
|
220
|
+
getProject(id) {
|
|
221
|
+
return this.data.projects.find((p) => p.id === id);
|
|
222
|
+
}
|
|
223
|
+
getSession(id) {
|
|
224
|
+
return this.data.sessions.find((s) => s.id === id);
|
|
225
|
+
}
|
|
226
|
+
listSessions() {
|
|
227
|
+
return this.data.sessions;
|
|
228
|
+
}
|
|
229
|
+
/** 是否还有会话或项目引用同一个物理工作目录 */
|
|
230
|
+
hasWorkingDirReference(workingDir, excludeSessionId) {
|
|
231
|
+
const dir = import_path.default.resolve(workingDir);
|
|
232
|
+
return this.data.sessions.some((s) => s.id !== excludeSessionId && import_path.default.resolve(s.workingDir) === dir) || this.data.projects.some((p) => import_path.default.resolve(p.workingDir) === dir);
|
|
233
|
+
}
|
|
234
|
+
/** 角色定位留空时回落默认值,避免误清空后丢失身份定义 */
|
|
235
|
+
normalizeSystemPrompt() {
|
|
236
|
+
if (!this.settings.coreConfig.systemPrompt?.trim()) this.settings.coreConfig.systemPrompt = DEFAULT_SETTINGS.coreConfig.systemPrompt;
|
|
237
|
+
}
|
|
238
|
+
save() {
|
|
239
|
+
writeJsonAtomic(INDEX_FILE, this.data);
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* 切换界面语言的规则集中在此(设置页与未配置模型面板都经 PUT /api/settings 到这里):
|
|
243
|
+
* 保存后的 customRules 仍是某个语言的内置默认值时,随语言换成目标语言默认值;用户改过的规则一律不动。
|
|
244
|
+
*/
|
|
245
|
+
updateSettings(patch) {
|
|
246
|
+
const prevLang = this.settings.coreConfig.lang;
|
|
247
|
+
const safePatch = { ...patch };
|
|
248
|
+
delete safePatch.enableBrowserControl;
|
|
249
|
+
delete safePatch.defaultSkillsInstalled;
|
|
250
|
+
this.settings = {
|
|
251
|
+
...this.settings,
|
|
252
|
+
...safePatch,
|
|
253
|
+
coreConfig: { ...this.settings.coreConfig, ...patch.coreConfig || {}, ...FIXED_CORE_CONFIG }
|
|
254
|
+
};
|
|
255
|
+
const cc = this.settings.coreConfig;
|
|
256
|
+
cc.lang = normalizeLang(cc.lang);
|
|
257
|
+
if (cc.lang !== prevLang && isBuiltinCustomRules(cc.customRules)) cc.customRules = defaultCustomRules(cc.lang);
|
|
258
|
+
this.normalizeSystemPrompt();
|
|
259
|
+
this.settings.defaultPermissionLevel = normalizeLevel(this.settings.defaultPermissionLevel);
|
|
260
|
+
if (!PREVENT_SLEEP_MODES.includes(this.settings.preventSleep)) this.settings.preventSleep = "off";
|
|
261
|
+
writeJsonAtomic(SETTINGS_FILE, this.settings);
|
|
262
|
+
return this.getSettings();
|
|
263
|
+
}
|
|
264
|
+
/** 浏览器控制配置键的唯一写入口(http/browserControl 在动作全部成功后调用) */
|
|
265
|
+
setBrowserControl(enabled) {
|
|
266
|
+
this.settings.enableBrowserControl = enabled;
|
|
267
|
+
writeJsonAtomic(SETTINGS_FILE, this.settings);
|
|
268
|
+
}
|
|
269
|
+
/** 默认技能已处理列表的唯一写入口(启动时默认安装完成后追加) */
|
|
270
|
+
addDefaultSkillsInstalled(ids) {
|
|
271
|
+
this.settings.defaultSkillsInstalled = [.../* @__PURE__ */ new Set([...this.settings.defaultSkillsInstalled || [], ...ids])];
|
|
272
|
+
writeJsonAtomic(SETTINGS_FILE, this.settings);
|
|
273
|
+
}
|
|
274
|
+
// ---------- 项目 ----------
|
|
275
|
+
createProject(name) {
|
|
276
|
+
const dir = import_path.default.join(SEMA_DOCS_ROOT, safeName(name));
|
|
277
|
+
if (import_fs.default.existsSync(dir) && this.data.projects.some((p) => p.workingDir === import_fs.default.realpathSync(dir))) {
|
|
278
|
+
throw new Error(`\u9879\u76EE\u5DF2\u5B58\u5728\uFF1A${name}`);
|
|
279
|
+
}
|
|
280
|
+
import_fs.default.mkdirSync(dir, { recursive: true });
|
|
281
|
+
const now = Date.now();
|
|
282
|
+
const rec = { id: (0, import_crypto.randomUUID)(), name, workingDir: import_fs.default.realpathSync(dir), managedWorkingDir: true, createdAt: now, lastActiveAt: now };
|
|
283
|
+
this.data.projects.push(rec);
|
|
284
|
+
this.save();
|
|
285
|
+
return rec;
|
|
286
|
+
}
|
|
287
|
+
importProject(dirPath, name) {
|
|
288
|
+
const expanded = dirPath.startsWith("~") ? import_path.default.join(import_os.default.homedir(), dirPath.slice(1)) : dirPath;
|
|
289
|
+
if (!import_fs.default.existsSync(expanded) || !import_fs.default.statSync(expanded).isDirectory()) throw new Error(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${dirPath}`);
|
|
290
|
+
const real = import_fs.default.realpathSync(expanded);
|
|
291
|
+
const exists = this.data.projects.find((p) => p.workingDir === real);
|
|
292
|
+
if (exists) return exists;
|
|
293
|
+
const now = Date.now();
|
|
294
|
+
const rec = { id: (0, import_crypto.randomUUID)(), name: name || import_path.default.basename(real), workingDir: real, managedWorkingDir: false, createdAt: now, lastActiveAt: now };
|
|
295
|
+
this.data.projects.push(rec);
|
|
296
|
+
this.save();
|
|
297
|
+
return rec;
|
|
298
|
+
}
|
|
299
|
+
renameProject(id, name) {
|
|
300
|
+
const p = this.getProject(id);
|
|
301
|
+
if (!p) throw new Error("\u9879\u76EE\u4E0D\u5B58\u5728");
|
|
302
|
+
p.name = name;
|
|
303
|
+
this.save();
|
|
304
|
+
return p;
|
|
305
|
+
}
|
|
306
|
+
/** 移除项目索引(不删磁盘);其下会话一并移除索引 */
|
|
307
|
+
removeProject(id) {
|
|
308
|
+
const removed = this.data.sessions.filter((s) => s.projectId === id);
|
|
309
|
+
this.data.projects = this.data.projects.filter((p) => p.id !== id);
|
|
310
|
+
this.data.sessions = this.data.sessions.filter((s) => s.projectId !== id);
|
|
311
|
+
this.save();
|
|
312
|
+
return removed;
|
|
313
|
+
}
|
|
314
|
+
// ---------- 会话 ----------
|
|
315
|
+
/** 预分配一个独立会话目录(~/Documents/Sema/<日期>/<会话id>):备用 worker 预热用,此时还没有会话记录 */
|
|
316
|
+
allocStandaloneDir(id) {
|
|
317
|
+
const dir = import_path.default.join(SEMA_DOCS_ROOT, dateFolder(), id);
|
|
318
|
+
import_fs.default.mkdirSync(dir, { recursive: true });
|
|
319
|
+
return import_fs.default.realpathSync(dir);
|
|
320
|
+
}
|
|
321
|
+
/** 创建会话记录:项目会话共享项目目录;独立会话独占 ~/Documents/Sema/<日期>/<会话id>。
|
|
322
|
+
* preallocated:复用预热备用 worker 已占的 id 与目录(仅独立会话) */
|
|
323
|
+
createSession(opts) {
|
|
324
|
+
const id = !opts.projectId && opts.preallocated?.id || (0, import_crypto.randomUUID)();
|
|
325
|
+
let workingDir;
|
|
326
|
+
if (opts.projectId) {
|
|
327
|
+
const p = this.getProject(opts.projectId);
|
|
328
|
+
if (!p) throw new Error("\u9879\u76EE\u4E0D\u5B58\u5728");
|
|
329
|
+
workingDir = p.workingDir;
|
|
330
|
+
p.lastActiveAt = Date.now();
|
|
331
|
+
} else if (opts.preallocated && import_fs.default.existsSync(opts.preallocated.workingDir)) {
|
|
332
|
+
workingDir = opts.preallocated.workingDir;
|
|
333
|
+
} else {
|
|
334
|
+
workingDir = this.allocStandaloneDir(id);
|
|
335
|
+
}
|
|
336
|
+
const now = Date.now();
|
|
337
|
+
const rec = {
|
|
338
|
+
id,
|
|
339
|
+
title: "",
|
|
340
|
+
projectId: opts.projectId,
|
|
341
|
+
workingDir,
|
|
342
|
+
createdAt: now,
|
|
343
|
+
lastActiveAt: now,
|
|
344
|
+
managedWorkingDir: !opts.projectId,
|
|
345
|
+
agentMode: opts.agentMode || this.settings.defaultAgentMode,
|
|
346
|
+
permissionLevel: normalizeLevel(opts.permissionLevel || this.settings.defaultPermissionLevel)
|
|
347
|
+
};
|
|
348
|
+
this.data.sessions.push(rec);
|
|
349
|
+
this.save();
|
|
350
|
+
return rec;
|
|
351
|
+
}
|
|
352
|
+
/** 注册 core 已创建的分支会话;目录与会话配置严格继承源会话。 */
|
|
353
|
+
createBranchedSession(sourceId, id) {
|
|
354
|
+
const source = this.getSession(sourceId);
|
|
355
|
+
if (!source) throw new Error("\u6E90\u4F1A\u8BDD\u4E0D\u5B58\u5728");
|
|
356
|
+
if (!id || this.getSession(id)) throw new Error("\u5206\u652F\u4F1A\u8BDD ID \u65E0\u6548\u6216\u5DF2\u5B58\u5728");
|
|
357
|
+
const now = Date.now();
|
|
358
|
+
const rec = {
|
|
359
|
+
id,
|
|
360
|
+
title: source.title ? `${source.title}\uFF08\u5206\u652F\uFF09` : "\u5206\u652F\u4F1A\u8BDD",
|
|
361
|
+
projectId: source.projectId,
|
|
362
|
+
workingDir: source.workingDir,
|
|
363
|
+
managedWorkingDir: source.managedWorkingDir ?? !source.projectId,
|
|
364
|
+
branchedFromSessionId: source.id,
|
|
365
|
+
createdAt: now,
|
|
366
|
+
lastActiveAt: now,
|
|
367
|
+
agentMode: source.agentMode,
|
|
368
|
+
permissionLevel: source.permissionLevel
|
|
369
|
+
};
|
|
370
|
+
this.data.sessions.push(rec);
|
|
371
|
+
if (source.projectId) {
|
|
372
|
+
const project = this.getProject(source.projectId);
|
|
373
|
+
if (project) project.lastActiveAt = now;
|
|
374
|
+
}
|
|
375
|
+
this.save();
|
|
376
|
+
return rec;
|
|
377
|
+
}
|
|
378
|
+
updateSession(id, patch) {
|
|
379
|
+
const s = this.getSession(id);
|
|
380
|
+
if (!s) return void 0;
|
|
381
|
+
Object.assign(s, patch);
|
|
382
|
+
this.save();
|
|
383
|
+
return s;
|
|
384
|
+
}
|
|
385
|
+
touchSession(id) {
|
|
386
|
+
const s = this.getSession(id);
|
|
387
|
+
if (!s) return;
|
|
388
|
+
s.lastActiveAt = Date.now();
|
|
389
|
+
if (s.projectId) {
|
|
390
|
+
const p = this.getProject(s.projectId);
|
|
391
|
+
if (p) p.lastActiveAt = s.lastActiveAt;
|
|
392
|
+
}
|
|
393
|
+
this.save();
|
|
394
|
+
}
|
|
395
|
+
removeSession(id) {
|
|
396
|
+
const s = this.getSession(id);
|
|
397
|
+
this.data.sessions = this.data.sessions.filter((x) => x.id !== id);
|
|
398
|
+
this.save();
|
|
399
|
+
return s;
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
// ../server/src/http/router.ts
|
|
404
|
+
var import_fs11 = __toESM(require("fs"));
|
|
405
|
+
var import_os6 = __toESM(require("os"));
|
|
406
|
+
var import_path11 = __toESM(require("path"));
|
|
407
|
+
var import_child_process5 = require("child_process");
|
|
408
|
+
var import_url = require("url");
|
|
409
|
+
|
|
410
|
+
// ../server/src/files/search.ts
|
|
411
|
+
var import_fs2 = __toESM(require("fs"));
|
|
412
|
+
var import_path2 = __toESM(require("path"));
|
|
413
|
+
var import_child_process = require("child_process");
|
|
414
|
+
var CACHE_TTL_MS = 1e4;
|
|
415
|
+
var MAX_ENTRIES = 2e4;
|
|
416
|
+
var WALK_EXCLUDES = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "build", "out", ".next", ".nuxt", "target", "__pycache__", ".venv", "venv", ".idea", ".vscode", ".DS_Store", "coverage", ".cache", ".gradle"]);
|
|
417
|
+
var cache = /* @__PURE__ */ new Map();
|
|
418
|
+
var inflight = /* @__PURE__ */ new Map();
|
|
419
|
+
var rgPath;
|
|
420
|
+
function resolveRg() {
|
|
421
|
+
if (rgPath !== void 0) return rgPath;
|
|
422
|
+
rgPath = null;
|
|
423
|
+
const exe = process.platform === "win32" ? "rg.exe" : "rg";
|
|
424
|
+
for (const dir of (process.env.PATH || "").split(import_path2.default.delimiter)) {
|
|
425
|
+
const p = import_path2.default.join(dir, exe);
|
|
426
|
+
if (dir && import_fs2.default.existsSync(p)) {
|
|
427
|
+
rgPath = p;
|
|
428
|
+
return rgPath;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
const coreMain = require.resolve("sema-core");
|
|
433
|
+
const mod = require.resolve("@vscode/ripgrep", { paths: [import_path2.default.dirname(coreMain)] });
|
|
434
|
+
const bin = import_path2.default.join(import_path2.default.dirname(mod), "..", "bin", exe);
|
|
435
|
+
if (import_fs2.default.existsSync(bin)) rgPath = bin;
|
|
436
|
+
} catch {
|
|
437
|
+
}
|
|
438
|
+
return rgPath;
|
|
439
|
+
}
|
|
440
|
+
function listWithRg(rg, root) {
|
|
441
|
+
return new Promise((resolve, reject) => {
|
|
442
|
+
(0, import_child_process.execFile)(rg, ["--files", "--hidden", "-g", "!.git", "-g", "!node_modules"], { cwd: root, maxBuffer: 64 * 1024 * 1024, timeout: 15e3 }, (err, stdout) => {
|
|
443
|
+
if (err && err.code !== 1) return reject(err);
|
|
444
|
+
const lines = String(stdout).split(/\r?\n/).filter(Boolean).map((l) => l.split(import_path2.default.sep).join("/"));
|
|
445
|
+
resolve(lines.length > MAX_ENTRIES ? lines.slice(0, MAX_ENTRIES) : lines);
|
|
446
|
+
});
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
function listWithWalk(root) {
|
|
450
|
+
const out = [];
|
|
451
|
+
const stack = [""];
|
|
452
|
+
while (stack.length && out.length < MAX_ENTRIES) {
|
|
453
|
+
const rel = stack.pop();
|
|
454
|
+
let ents = [];
|
|
455
|
+
try {
|
|
456
|
+
ents = import_fs2.default.readdirSync(import_path2.default.join(root, rel), { withFileTypes: true });
|
|
457
|
+
} catch {
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
for (const e of ents) {
|
|
461
|
+
if (WALK_EXCLUDES.has(e.name)) continue;
|
|
462
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
463
|
+
if (e.isDirectory()) stack.push(r);
|
|
464
|
+
else if (e.isFile()) out.push(r);
|
|
465
|
+
if (out.length >= MAX_ENTRIES) break;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return out;
|
|
469
|
+
}
|
|
470
|
+
async function listFiles(root) {
|
|
471
|
+
const hit = cache.get(root);
|
|
472
|
+
if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.files;
|
|
473
|
+
const running = inflight.get(root);
|
|
474
|
+
if (running) return running;
|
|
475
|
+
const p = (async () => {
|
|
476
|
+
let files;
|
|
477
|
+
const rg = resolveRg();
|
|
478
|
+
if (rg) {
|
|
479
|
+
try {
|
|
480
|
+
files = await listWithRg(rg, root);
|
|
481
|
+
} catch {
|
|
482
|
+
files = listWithWalk(root);
|
|
483
|
+
}
|
|
484
|
+
} else files = listWithWalk(root);
|
|
485
|
+
cache.set(root, { at: Date.now(), files });
|
|
486
|
+
return files;
|
|
487
|
+
})();
|
|
488
|
+
inflight.set(root, p);
|
|
489
|
+
try {
|
|
490
|
+
return await p;
|
|
491
|
+
} finally {
|
|
492
|
+
inflight.delete(root);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
function isSubsequence(query, text) {
|
|
496
|
+
let i = 0;
|
|
497
|
+
for (let j = 0; j < text.length && i < query.length; j++) if (text[j] === query[i]) i++;
|
|
498
|
+
return i === query.length;
|
|
499
|
+
}
|
|
500
|
+
function score(rel, isDir, q) {
|
|
501
|
+
const lower = rel.toLowerCase();
|
|
502
|
+
const base = (isDir ? rel : rel.slice(rel.lastIndexOf("/") + 1)).toLowerCase();
|
|
503
|
+
const baseName = isDir ? base.slice(base.lastIndexOf("/") + 1) : base;
|
|
504
|
+
let s;
|
|
505
|
+
if (baseName === q) s = 0;
|
|
506
|
+
else if (baseName.startsWith(q)) s = 1;
|
|
507
|
+
else if (baseName.includes(q)) s = 2;
|
|
508
|
+
else if (lower.includes(q)) s = 3;
|
|
509
|
+
else if (q.length >= 3 && isSubsequence(q, baseName)) s = 4;
|
|
510
|
+
else s = 5;
|
|
511
|
+
return s * 1e3 + (isDir ? 400 : 0) + Math.min(399, rel.split("/").length * 10 + Math.min(9, Math.floor(rel.length / 40)));
|
|
512
|
+
}
|
|
513
|
+
function insideRoot(root, rel) {
|
|
514
|
+
try {
|
|
515
|
+
const real = import_fs2.default.realpathSync(import_path2.default.join(root, rel));
|
|
516
|
+
return real === root || real.startsWith(root + import_path2.default.sep);
|
|
517
|
+
} catch {
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
async function searchFiles(workingDir, query, limit = 50) {
|
|
522
|
+
let root;
|
|
523
|
+
try {
|
|
524
|
+
root = import_fs2.default.realpathSync(workingDir);
|
|
525
|
+
} catch {
|
|
526
|
+
return [];
|
|
527
|
+
}
|
|
528
|
+
const files = await listFiles(root);
|
|
529
|
+
const q = query.trim().replace(/\/+$/, "").toLowerCase();
|
|
530
|
+
const max = Math.max(1, Math.min(200, limit));
|
|
531
|
+
const candidates = /* @__PURE__ */ new Map();
|
|
532
|
+
if (!q) {
|
|
533
|
+
for (const f of files) {
|
|
534
|
+
const s = f.split("/").length * 10 + Math.min(9, Math.floor(f.length / 40));
|
|
535
|
+
candidates.set(f, { path: f, isDirectory: false, score: s });
|
|
536
|
+
}
|
|
537
|
+
} else {
|
|
538
|
+
for (const f of files) {
|
|
539
|
+
const lower = f.toLowerCase();
|
|
540
|
+
const base = lower.slice(lower.lastIndexOf("/") + 1);
|
|
541
|
+
const baseHit = base.includes(q) || q.length >= 3 && isSubsequence(q, base);
|
|
542
|
+
const pathHit = lower.includes(q);
|
|
543
|
+
if (!baseHit && !pathHit) continue;
|
|
544
|
+
candidates.set(f, { path: f, isDirectory: false, score: score(f, false, q) });
|
|
545
|
+
if (pathHit) {
|
|
546
|
+
const parts = f.split("/");
|
|
547
|
+
for (let i = 1; i < parts.length; i++) {
|
|
548
|
+
const dir = parts.slice(0, i).join("/");
|
|
549
|
+
if (!parts[i - 1].toLowerCase().includes(q) && !(q.includes("/") && dir.toLowerCase().includes(q))) continue;
|
|
550
|
+
if (!candidates.has(dir)) candidates.set(dir, { path: dir, isDirectory: true, score: score(dir, true, q) });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
const sorted = [...candidates.values()].sort((a, b) => a.score - b.score || a.path.localeCompare(b.path));
|
|
556
|
+
const out = [];
|
|
557
|
+
for (const c of sorted) {
|
|
558
|
+
if (out.length >= max) break;
|
|
559
|
+
if (!insideRoot(root, c.path)) continue;
|
|
560
|
+
out.push({ path: c.path, isDirectory: c.isDirectory });
|
|
561
|
+
}
|
|
562
|
+
return out;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// ../server/src/files/read.ts
|
|
566
|
+
var import_fs3 = __toESM(require("fs"));
|
|
567
|
+
var import_path3 = __toESM(require("path"));
|
|
568
|
+
var MAX_TEXT = 1024 * 1024;
|
|
569
|
+
var MAX_RAW = 50 * 1024 * 1024;
|
|
570
|
+
var IMAGE_MIME = {
|
|
571
|
+
".png": "image/png",
|
|
572
|
+
".jpg": "image/jpeg",
|
|
573
|
+
".jpeg": "image/jpeg",
|
|
574
|
+
".gif": "image/gif",
|
|
575
|
+
".webp": "image/webp",
|
|
576
|
+
".svg": "image/svg+xml",
|
|
577
|
+
".bmp": "image/bmp",
|
|
578
|
+
".ico": "image/x-icon",
|
|
579
|
+
".avif": "image/avif"
|
|
580
|
+
};
|
|
581
|
+
var OFFICE_MIME = {
|
|
582
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
583
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
584
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
585
|
+
".csv": "text/csv",
|
|
586
|
+
".tsv": "text/tab-separated-values",
|
|
587
|
+
".pdf": "application/pdf"
|
|
588
|
+
};
|
|
589
|
+
function isAbsolutePath(p) {
|
|
590
|
+
return import_path3.default.isAbsolute(p) || /^[a-zA-Z]:[\\/]/.test(p);
|
|
591
|
+
}
|
|
592
|
+
function resolvePath(workingDir, p) {
|
|
593
|
+
const root = import_fs3.default.realpathSync(workingDir);
|
|
594
|
+
const abs = isAbsolutePath(p) ? import_path3.default.resolve(p) : import_path3.default.resolve(root, p || ".");
|
|
595
|
+
if (!import_fs3.default.existsSync(abs)) throw new Error("\u6587\u4EF6\u4E0D\u5B58\u5728");
|
|
596
|
+
const real = import_fs3.default.realpathSync(abs);
|
|
597
|
+
const inside = real === root || real.startsWith(root + import_path3.default.sep);
|
|
598
|
+
return { abs: real, inside };
|
|
599
|
+
}
|
|
600
|
+
function looksBinary(buf) {
|
|
601
|
+
const n = Math.min(buf.length, 8e3);
|
|
602
|
+
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
|
|
603
|
+
return false;
|
|
604
|
+
}
|
|
605
|
+
function readFileInDir(workingDir, rel) {
|
|
606
|
+
const { abs, inside } = resolvePath(workingDir, rel);
|
|
607
|
+
const st = import_fs3.default.statSync(abs);
|
|
608
|
+
if (st.isDirectory()) throw new Error("\u662F\u76EE\u5F55");
|
|
609
|
+
const fd = import_fs3.default.openSync(abs, "r");
|
|
610
|
+
try {
|
|
611
|
+
const len = Math.min(st.size, MAX_TEXT);
|
|
612
|
+
const buf = Buffer.alloc(len);
|
|
613
|
+
import_fs3.default.readSync(fd, buf, 0, len, 0);
|
|
614
|
+
const ext = import_path3.default.extname(abs).toLowerCase();
|
|
615
|
+
const binary = !!IMAGE_MIME[ext] && ext !== ".svg" ? true : looksBinary(buf);
|
|
616
|
+
return { path: rel, abs, inside, size: st.size, mtime: st.mtimeMs, truncated: st.size > MAX_TEXT, binary, image: !!IMAGE_MIME[ext], content: binary ? "" : buf.toString("utf8") };
|
|
617
|
+
} finally {
|
|
618
|
+
import_fs3.default.closeSync(fd);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
function statPaths(workingDir, paths) {
|
|
622
|
+
const out = {};
|
|
623
|
+
for (const p of paths.slice(0, 100)) {
|
|
624
|
+
try {
|
|
625
|
+
const { abs, inside } = resolvePath(workingDir, p);
|
|
626
|
+
const st = import_fs3.default.statSync(abs);
|
|
627
|
+
const isDir = st.isDirectory();
|
|
628
|
+
out[p] = { exists: true, isDir, inside, image: !isDir && !!IMAGE_MIME[import_path3.default.extname(abs).toLowerCase()], abs, mtime: st.mtimeMs };
|
|
629
|
+
} catch {
|
|
630
|
+
out[p] = { exists: false, isDir: false, inside: false, image: false };
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return out;
|
|
634
|
+
}
|
|
635
|
+
function rawFileInDir(workingDir, rel) {
|
|
636
|
+
const { abs } = resolvePath(workingDir, rel);
|
|
637
|
+
const st = import_fs3.default.statSync(abs);
|
|
638
|
+
if (st.isDirectory()) throw new Error("\u662F\u76EE\u5F55");
|
|
639
|
+
if (st.size > MAX_RAW) throw new Error("\u6587\u4EF6\u8FC7\u5927");
|
|
640
|
+
const ext = import_path3.default.extname(abs).toLowerCase();
|
|
641
|
+
return { abs, size: st.size, mime: IMAGE_MIME[ext] || OFFICE_MIME[ext] || "application/octet-stream" };
|
|
642
|
+
}
|
|
643
|
+
var SKIP = /* @__PURE__ */ new Set(["node_modules", ".DS_Store"]);
|
|
644
|
+
function listDir(workingDir, rel) {
|
|
645
|
+
const { abs } = resolvePath(workingDir, rel);
|
|
646
|
+
if (!import_fs3.default.statSync(abs).isDirectory()) throw new Error("\u4E0D\u662F\u76EE\u5F55");
|
|
647
|
+
const items = import_fs3.default.readdirSync(abs, { withFileTypes: true }).filter((d) => !SKIP.has(d.name)).map((d) => ({ name: d.name, isDirectory: d.isDirectory() || d.isSymbolicLink() && safeIsDir(import_path3.default.join(abs, d.name)) })).sort((a, b) => a.isDirectory === b.isDirectory ? a.name.localeCompare(b.name) : a.isDirectory ? -1 : 1);
|
|
648
|
+
return { path: rel, items };
|
|
649
|
+
}
|
|
650
|
+
function safeIsDir(p) {
|
|
651
|
+
try {
|
|
652
|
+
return import_fs3.default.statSync(p).isDirectory();
|
|
653
|
+
} catch {
|
|
654
|
+
return false;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// ../server/src/files/attachments.ts
|
|
659
|
+
var import_fs4 = __toESM(require("fs"));
|
|
660
|
+
var import_os2 = __toESM(require("os"));
|
|
661
|
+
var import_path4 = __toESM(require("path"));
|
|
662
|
+
var import_crypto2 = require("crypto");
|
|
663
|
+
var FILE_NAME = "pasted-text.txt";
|
|
664
|
+
var MAX_DIRS = 100;
|
|
665
|
+
var UUID_RE = /^[0-9a-f-]{36}$/i;
|
|
666
|
+
function attachmentsRoot() {
|
|
667
|
+
const semaRoot2 = process.env.SEMA_ROOT ? import_path4.default.resolve(process.env.SEMA_ROOT) : import_path4.default.join(import_os2.default.homedir(), ".sema");
|
|
668
|
+
return import_path4.default.join(semaRoot2, "attachments");
|
|
669
|
+
}
|
|
670
|
+
function savePastedText(text) {
|
|
671
|
+
if (!text) throw new Error("\u7F3A\u5C11 text");
|
|
672
|
+
const root = attachmentsRoot();
|
|
673
|
+
const dir = import_path4.default.join(root, (0, import_crypto2.randomUUID)());
|
|
674
|
+
import_fs4.default.mkdirSync(dir, { recursive: true });
|
|
675
|
+
const file = import_path4.default.join(dir, FILE_NAME);
|
|
676
|
+
import_fs4.default.writeFileSync(file, text, "utf8");
|
|
677
|
+
evict(root);
|
|
678
|
+
return { path: file };
|
|
679
|
+
}
|
|
680
|
+
function removePastedText(p) {
|
|
681
|
+
const root = attachmentsRoot();
|
|
682
|
+
const rel = import_path4.default.relative(root, import_path4.default.resolve(p));
|
|
683
|
+
const parts = rel.split(import_path4.default.sep);
|
|
684
|
+
if (parts.length !== 2 || !UUID_RE.test(parts[0]) || parts[1] !== FILE_NAME) throw new Error("\u8DEF\u5F84\u4E0D\u5408\u6CD5");
|
|
685
|
+
import_fs4.default.rmSync(import_path4.default.join(root, parts[0]), { recursive: true, force: true });
|
|
686
|
+
}
|
|
687
|
+
function evict(root) {
|
|
688
|
+
try {
|
|
689
|
+
const dirs = import_fs4.default.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory() && UUID_RE.test(d.name)).map((d) => {
|
|
690
|
+
try {
|
|
691
|
+
return { name: d.name, mtime: import_fs4.default.statSync(import_path4.default.join(root, d.name)).mtimeMs };
|
|
692
|
+
} catch {
|
|
693
|
+
return null;
|
|
694
|
+
}
|
|
695
|
+
}).filter((x) => !!x).sort((a, b) => b.mtime - a.mtime);
|
|
696
|
+
for (const d of dirs.slice(MAX_DIRS)) import_fs4.default.rmSync(import_path4.default.join(root, d.name), { recursive: true, force: true });
|
|
697
|
+
} catch {
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// ../server/src/files/apps.ts
|
|
702
|
+
var import_fs5 = __toESM(require("fs"));
|
|
703
|
+
var import_path5 = __toESM(require("path"));
|
|
704
|
+
var import_child_process2 = require("child_process");
|
|
705
|
+
var IS_MAC = process.platform === "darwin";
|
|
706
|
+
var ICON_DIR = import_path5.default.join(WEBUI_HOME, "app-icons");
|
|
707
|
+
var listCache = /* @__PURE__ */ new Map();
|
|
708
|
+
function jxa(script, timeout = 15e3) {
|
|
709
|
+
return new Promise((resolve, reject) => (0, import_child_process2.execFile)("osascript", ["-l", "JavaScript", "-e", script], { timeout, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => err ? reject(new Error(stderr || err.message)) : resolve(stdout)));
|
|
710
|
+
}
|
|
711
|
+
function iconFile(id) {
|
|
712
|
+
return import_path5.default.join(ICON_DIR, `${id.replace(/[^\w.\-]/g, "_")}.png`);
|
|
713
|
+
}
|
|
714
|
+
function listOpenWithApps(absPath) {
|
|
715
|
+
if (!IS_MAC) return Promise.resolve({ apps: [] });
|
|
716
|
+
const ext = import_path5.default.extname(absPath).toLowerCase() || import_path5.default.basename(absPath);
|
|
717
|
+
let p = listCache.get(ext);
|
|
718
|
+
if (!p) {
|
|
719
|
+
p = queryApps(absPath).catch((e) => {
|
|
720
|
+
listCache.delete(ext);
|
|
721
|
+
throw e;
|
|
722
|
+
});
|
|
723
|
+
listCache.set(ext, p);
|
|
724
|
+
}
|
|
725
|
+
return p;
|
|
726
|
+
}
|
|
727
|
+
async function queryApps(absPath) {
|
|
728
|
+
import_fs5.default.mkdirSync(ICON_DIR, { recursive: true });
|
|
729
|
+
const script = `
|
|
730
|
+
ObjC.import('AppKit');
|
|
731
|
+
const file = ${JSON.stringify(absPath)};
|
|
732
|
+
const iconDir = ${JSON.stringify(ICON_DIR)};
|
|
733
|
+
const ws = $.NSWorkspace.sharedWorkspace;
|
|
734
|
+
const url = $.NSURL.fileURLWithPath(file);
|
|
735
|
+
const str = x => (x && !x.isNil()) ? ObjC.unwrap(x) : '';
|
|
736
|
+
const defUrl = ws.URLForApplicationToOpenURL(url);
|
|
737
|
+
const def = defUrl.isNil() ? '' : str(defUrl.path);
|
|
738
|
+
const urls = ws.URLsForApplicationsToOpenURL(url);
|
|
739
|
+
const out = [];
|
|
740
|
+
const seen = {};
|
|
741
|
+
function exportIcon(appPath, target) {
|
|
742
|
+
if ($.NSFileManager.defaultManager.fileExistsAtPath(target)) return true;
|
|
743
|
+
const img = ws.iconForFile(appPath);
|
|
744
|
+
img.setSize($.NSMakeSize(64, 64));
|
|
745
|
+
const cg = img.CGImageForProposedRectContextHints($(), $(), $());
|
|
746
|
+
if (!cg) return false;
|
|
747
|
+
const rep = $.NSBitmapImageRep.alloc.initWithCGImage(cg);
|
|
748
|
+
const png = rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $());
|
|
749
|
+
return png.writeToFileAtomically(target, true);
|
|
750
|
+
}
|
|
751
|
+
for (let i = 0; i < urls.count; i++) {
|
|
752
|
+
const u = urls.objectAtIndex(i);
|
|
753
|
+
const appPath = str(u.path);
|
|
754
|
+
const b = $.NSBundle.bundleWithURL(u);
|
|
755
|
+
if (b.isNil()) continue;
|
|
756
|
+
let id = str(b.bundleIdentifier);
|
|
757
|
+
if (!id) id = appPath;
|
|
758
|
+
if (seen[id]) continue; seen[id] = 1;
|
|
759
|
+
const info = k => str(b.objectForInfoDictionaryKey(k));
|
|
760
|
+
const name = info('CFBundleDisplayName') || info('CFBundleName') || appPath.split('/').pop().replace(/\\.app$/, '');
|
|
761
|
+
const target = iconDir + '/' + id.replace(/[^\\w.\\-]/g, '_') + '.png';
|
|
762
|
+
let icon = false;
|
|
763
|
+
try { icon = !!exportIcon(appPath, target); } catch (e) { icon = false; }
|
|
764
|
+
out.push({ id, name, path: appPath, icon, isDefault: appPath === def });
|
|
765
|
+
}
|
|
766
|
+
JSON.stringify(out);
|
|
767
|
+
`;
|
|
768
|
+
const raw = await jxa(script);
|
|
769
|
+
const list = JSON.parse(raw.trim() || "[]");
|
|
770
|
+
list.sort((a, b) => a.isDefault === b.isDefault ? a.name.localeCompare(b.name) : a.isDefault ? -1 : 1);
|
|
771
|
+
return { default: list.find((a) => a.isDefault)?.id, apps: list.map(({ isDefault: _d, ...a }) => a) };
|
|
772
|
+
}
|
|
773
|
+
function appIconPath(id) {
|
|
774
|
+
const f = iconFile(id);
|
|
775
|
+
return import_fs5.default.existsSync(f) ? f : void 0;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// ../server/src/files/gitDiff.ts
|
|
779
|
+
var import_fs7 = __toESM(require("fs"));
|
|
780
|
+
var import_path7 = __toESM(require("path"));
|
|
781
|
+
var import_child_process3 = require("child_process");
|
|
782
|
+
|
|
783
|
+
// ../server/src/turnDiff.ts
|
|
784
|
+
var import_fs6 = __toESM(require("fs"));
|
|
785
|
+
var import_path6 = __toESM(require("path"));
|
|
786
|
+
var import_diff = require("diff");
|
|
787
|
+
var BASELINE_MAX_BYTES = 5 * 1024 * 1024;
|
|
788
|
+
var NEW_FILE_MAX_LINES = 5e3;
|
|
789
|
+
var NEW_FILE_MAX_BYTES = 1024 * 1024;
|
|
790
|
+
var PATCH_MAX_LINES = 2e4;
|
|
791
|
+
function createBaselines() {
|
|
792
|
+
return { turn: /* @__PURE__ */ new Map(), session: /* @__PURE__ */ new Map(), lastKnown: /* @__PURE__ */ new Map() };
|
|
793
|
+
}
|
|
794
|
+
function resetTurn(b) {
|
|
795
|
+
b.turn.clear();
|
|
796
|
+
}
|
|
797
|
+
function resetAll(b) {
|
|
798
|
+
b.turn.clear();
|
|
799
|
+
b.session.clear();
|
|
800
|
+
b.lastKnown.clear();
|
|
801
|
+
}
|
|
802
|
+
function resolveAbs(workingDir, title) {
|
|
803
|
+
return import_path6.default.isAbsolute(title) ? title : import_path6.default.resolve(workingDir, title);
|
|
804
|
+
}
|
|
805
|
+
function normalizeLF(s) {
|
|
806
|
+
return s.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
807
|
+
}
|
|
808
|
+
function readFile(abs) {
|
|
809
|
+
try {
|
|
810
|
+
if (import_fs6.default.statSync(abs).size > BASELINE_MAX_BYTES) return null;
|
|
811
|
+
return { content: normalizeLF(import_fs6.default.readFileSync(abs, "utf8")), existed: true };
|
|
812
|
+
} catch {
|
|
813
|
+
return { content: "", existed: false };
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function captureOnRead(b, workingDir, title) {
|
|
817
|
+
const abs = resolveAbs(workingDir, title);
|
|
818
|
+
b.lastKnown.set(abs, readFile(abs));
|
|
819
|
+
}
|
|
820
|
+
function totalPatch(base, current) {
|
|
821
|
+
if (!base.existed) {
|
|
822
|
+
const lines = current.split("\n");
|
|
823
|
+
if (lines.length > NEW_FILE_MAX_LINES || Buffer.byteLength(current, "utf8") > NEW_FILE_MAX_BYTES) return void 0;
|
|
824
|
+
return [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: lines.length, lines: lines.map((l) => "+" + l) }];
|
|
825
|
+
}
|
|
826
|
+
const hunks = (0, import_diff.structuredPatch)("a", "b", base.content, current, "", "", { context: 3 }).hunks;
|
|
827
|
+
const total = hunks.reduce((s, h) => s + (h.lines?.length || 0), 0);
|
|
828
|
+
if (total > PATCH_MAX_LINES) return void 0;
|
|
829
|
+
return hunks;
|
|
830
|
+
}
|
|
831
|
+
function computeCumulative(b, workingDir, title, content) {
|
|
832
|
+
const abs = resolveAbs(workingDir, title);
|
|
833
|
+
let current;
|
|
834
|
+
try {
|
|
835
|
+
if (import_fs6.default.statSync(abs).size > BASELINE_MAX_BYTES) {
|
|
836
|
+
b.turn.set(abs, null);
|
|
837
|
+
b.session.set(abs, null);
|
|
838
|
+
b.lastKnown.set(abs, null);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
current = normalizeLF(import_fs6.default.readFileSync(abs, "utf8"));
|
|
842
|
+
} catch {
|
|
843
|
+
b.turn.set(abs, null);
|
|
844
|
+
b.session.set(abs, null);
|
|
845
|
+
b.lastKnown.set(abs, null);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
const isNew = content?.type === "new";
|
|
849
|
+
const ensure = (m) => {
|
|
850
|
+
if (m.has(abs)) return m.get(abs);
|
|
851
|
+
const base = isNew ? { content: "", existed: false } : b.lastKnown.get(abs) ?? null;
|
|
852
|
+
m.set(abs, base);
|
|
853
|
+
return base;
|
|
854
|
+
};
|
|
855
|
+
const turnBase = ensure(b.turn);
|
|
856
|
+
const sessBase = ensure(b.session);
|
|
857
|
+
b.lastKnown.set(abs, { content: current, existed: true });
|
|
858
|
+
if (!turnBase) return;
|
|
859
|
+
const patch = totalPatch(turnBase, current);
|
|
860
|
+
if (!patch) {
|
|
861
|
+
b.turn.set(abs, null);
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
const out = { type: turnBase.existed ? "diff" : "new", patch };
|
|
865
|
+
if (!sessBase) out.sessionDropped = true;
|
|
866
|
+
else if (sessBase.content !== turnBase.content || sessBase.existed !== turnBase.existed) {
|
|
867
|
+
const sp = totalPatch(sessBase, current);
|
|
868
|
+
if (sp) {
|
|
869
|
+
out.sessionPatch = sp;
|
|
870
|
+
out.sessionType = sessBase.existed ? "diff" : "new";
|
|
871
|
+
} else {
|
|
872
|
+
out.sessionDropped = true;
|
|
873
|
+
b.session.set(abs, null);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
return out;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// ../server/src/files/gitDiff.ts
|
|
880
|
+
var PREVIEW_LINES = 5;
|
|
881
|
+
function git(cwd, args) {
|
|
882
|
+
return new Promise((resolve, reject) => (0, import_child_process3.execFile)("git", args, { cwd, maxBuffer: 64 * 1024 * 1024, timeout: 15e3 }, (err, stdout) => err ? reject(err) : resolve(stdout)));
|
|
883
|
+
}
|
|
884
|
+
function unquotePath(p) {
|
|
885
|
+
if (!p.startsWith('"') || !p.endsWith('"')) return p;
|
|
886
|
+
const inner = p.slice(1, -1);
|
|
887
|
+
const bytes = [];
|
|
888
|
+
for (let i = 0; i < inner.length; i++) {
|
|
889
|
+
if (inner[i] === "\\") {
|
|
890
|
+
const n = inner[i + 1];
|
|
891
|
+
if (/[0-7]/.test(n)) {
|
|
892
|
+
bytes.push(parseInt(inner.slice(i + 1, i + 4), 8));
|
|
893
|
+
i += 3;
|
|
894
|
+
} else {
|
|
895
|
+
bytes.push({ n: 10, t: 9, r: 13 }[n] ?? n.charCodeAt(0));
|
|
896
|
+
i += 1;
|
|
897
|
+
}
|
|
898
|
+
} else bytes.push(inner.charCodeAt(i));
|
|
899
|
+
}
|
|
900
|
+
return Buffer.from(bytes).toString("utf8");
|
|
901
|
+
}
|
|
902
|
+
function parseUnifiedDiff(out) {
|
|
903
|
+
const files = [];
|
|
904
|
+
let cur = null;
|
|
905
|
+
let hunk = null;
|
|
906
|
+
for (const line of out.split("\n")) {
|
|
907
|
+
if (line.startsWith("diff --git ")) {
|
|
908
|
+
cur = { path: "", toolName: "git", type: "diff", additions: 0, removals: 0, patch: [], cumulative: true };
|
|
909
|
+
files.push(cur);
|
|
910
|
+
hunk = null;
|
|
911
|
+
continue;
|
|
912
|
+
}
|
|
913
|
+
if (!cur) continue;
|
|
914
|
+
if (line.startsWith("new file mode")) {
|
|
915
|
+
cur.type = "new";
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
if (line.startsWith("deleted file mode")) {
|
|
919
|
+
cur.deleted = true;
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
922
|
+
if (line.startsWith("--- ")) {
|
|
923
|
+
const p = unquotePath(line.slice(4).trim());
|
|
924
|
+
if (p !== "/dev/null" && !cur.path) cur.path = p.replace(/^a\//, "");
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
if (line.startsWith("+++ ")) {
|
|
928
|
+
const p = unquotePath(line.slice(4).trim());
|
|
929
|
+
if (p !== "/dev/null") cur.path = p.replace(/^b\//, "");
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
const m = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
|
|
933
|
+
if (m) {
|
|
934
|
+
hunk = { oldStart: +m[1], oldLines: m[2] === void 0 ? 1 : +m[2], newStart: +m[3], newLines: m[4] === void 0 ? 1 : +m[4], lines: [] };
|
|
935
|
+
cur.patch.push(hunk);
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
if (hunk && /^[ +\-\\]/.test(line)) {
|
|
939
|
+
hunk.lines.push(line);
|
|
940
|
+
if (line[0] === "+") cur.additions++;
|
|
941
|
+
else if (line[0] === "-") cur.removals++;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
return files.filter((f) => f.path);
|
|
945
|
+
}
|
|
946
|
+
function untrackedChange(workingDir, rel) {
|
|
947
|
+
const base = { path: rel, toolName: "git", type: "new", additions: 0, removals: 0, patch: [], cumulative: true };
|
|
948
|
+
try {
|
|
949
|
+
const abs = import_path7.default.join(workingDir, rel);
|
|
950
|
+
const st = import_fs7.default.statSync(abs);
|
|
951
|
+
if (!st.isFile()) return null;
|
|
952
|
+
const buf = import_fs7.default.readFileSync(abs);
|
|
953
|
+
if (buf.subarray(0, 8192).includes(0)) return base;
|
|
954
|
+
const lines = buf.toString("utf8").replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
955
|
+
const truncated = lines.length > NEW_FILE_MAX_LINES || st.size > NEW_FILE_MAX_BYTES;
|
|
956
|
+
const shown = truncated ? lines.slice(0, PREVIEW_LINES) : lines;
|
|
957
|
+
return {
|
|
958
|
+
...base,
|
|
959
|
+
additions: lines.length,
|
|
960
|
+
patch: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: lines.length, lines: shown.map((l) => "+" + l) }],
|
|
961
|
+
...truncated ? { diffText: `... (+${lines.length - PREVIEW_LINES} lines)` } : {}
|
|
962
|
+
};
|
|
963
|
+
} catch {
|
|
964
|
+
return base;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
async function untrackedFiles(workingDir) {
|
|
968
|
+
const root = (await git(workingDir, ["rev-parse", "--show-toplevel"])).trim();
|
|
969
|
+
const out = await git(workingDir, ["status", "--porcelain=v1", "-z", "-uall"]);
|
|
970
|
+
const rels = [];
|
|
971
|
+
const entries = out.split("\0");
|
|
972
|
+
for (let i = 0; i < entries.length; i++) {
|
|
973
|
+
const e = entries[i];
|
|
974
|
+
if (e.length < 4) continue;
|
|
975
|
+
if (e[0] === "R" || e[1] === "R") i++;
|
|
976
|
+
if (!e.startsWith("??")) continue;
|
|
977
|
+
const abs = import_path7.default.resolve(root, e.slice(3));
|
|
978
|
+
const rel = import_path7.default.relative(workingDir, abs);
|
|
979
|
+
if (!rel.startsWith("..") && !import_path7.default.isAbsolute(rel)) rels.push(rel.split(import_path7.default.sep).join("/"));
|
|
980
|
+
}
|
|
981
|
+
return rels;
|
|
982
|
+
}
|
|
983
|
+
async function gitRepoCheck(workingDir) {
|
|
984
|
+
try {
|
|
985
|
+
await git(workingDir, ["rev-parse", "--is-inside-work-tree"]);
|
|
986
|
+
return { gitRepo: true };
|
|
987
|
+
} catch {
|
|
988
|
+
return { gitRepo: false };
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
async function gitDiffFiles(workingDir, mode) {
|
|
992
|
+
try {
|
|
993
|
+
await git(workingDir, ["rev-parse", "--is-inside-work-tree"]);
|
|
994
|
+
} catch {
|
|
995
|
+
return { gitRepo: false, files: [], ts: Date.now() };
|
|
996
|
+
}
|
|
997
|
+
let hasHead = true;
|
|
998
|
+
try {
|
|
999
|
+
await git(workingDir, ["rev-parse", "--verify", "HEAD"]);
|
|
1000
|
+
} catch {
|
|
1001
|
+
hasHead = false;
|
|
1002
|
+
}
|
|
1003
|
+
const args = mode === "uncommitted" && hasHead ? ["diff", "HEAD", "--no-color", "--unified=3", "--relative"] : ["diff", "--no-color", "--unified=3", "--relative"];
|
|
1004
|
+
const files = parseUnifiedDiff(await git(workingDir, args));
|
|
1005
|
+
const seen = new Set(files.map((f) => f.path));
|
|
1006
|
+
for (const rel of await untrackedFiles(workingDir)) {
|
|
1007
|
+
if (seen.has(rel)) continue;
|
|
1008
|
+
const c = untrackedChange(workingDir, rel);
|
|
1009
|
+
if (c) files.push(c);
|
|
1010
|
+
}
|
|
1011
|
+
return { gitRepo: true, files, ts: Date.now() };
|
|
1012
|
+
}
|
|
1013
|
+
async function gitDiffList(workingDir) {
|
|
1014
|
+
const full = await gitDiffFiles(workingDir, "uncommitted");
|
|
1015
|
+
return { ...full, files: full.files.map((f) => ({ ...f, patch: [], diffText: void 0 })) };
|
|
1016
|
+
}
|
|
1017
|
+
async function gitDiffFile(workingDir, rel) {
|
|
1018
|
+
if (!rel) return { file: null };
|
|
1019
|
+
try {
|
|
1020
|
+
await git(workingDir, ["rev-parse", "--is-inside-work-tree"]);
|
|
1021
|
+
} catch {
|
|
1022
|
+
return { file: null };
|
|
1023
|
+
}
|
|
1024
|
+
let hasHead = true;
|
|
1025
|
+
try {
|
|
1026
|
+
await git(workingDir, ["rev-parse", "--verify", "HEAD"]);
|
|
1027
|
+
} catch {
|
|
1028
|
+
hasHead = false;
|
|
1029
|
+
}
|
|
1030
|
+
const args = hasHead ? ["diff", "HEAD", "--no-color", "--unified=3", "--relative", "--", rel] : ["diff", "--no-color", "--unified=3", "--relative", "--", rel];
|
|
1031
|
+
const out = await git(workingDir, args).catch(() => "");
|
|
1032
|
+
const parsed = parseUnifiedDiff(out);
|
|
1033
|
+
if (parsed.length) return { file: parsed[0] };
|
|
1034
|
+
return { file: untrackedChange(workingDir, rel) };
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
// ../server/src/http/ecosystem.ts
|
|
1038
|
+
var import_fs9 = __toESM(require("fs"));
|
|
1039
|
+
var import_os4 = __toESM(require("os"));
|
|
1040
|
+
var import_path9 = __toESM(require("path"));
|
|
1041
|
+
var import_child_process4 = require("child_process");
|
|
1042
|
+
var import_util = require("util");
|
|
1043
|
+
|
|
1044
|
+
// ../server/src/errlog.ts
|
|
1045
|
+
var import_fs8 = __toESM(require("fs"));
|
|
1046
|
+
var import_os3 = __toESM(require("os"));
|
|
1047
|
+
var import_path8 = __toESM(require("path"));
|
|
1048
|
+
var ERROR_LOG = import_path8.default.join(import_os3.default.homedir(), ".sema", "webui", "error.log");
|
|
1049
|
+
function initErrorLog(host, version) {
|
|
1050
|
+
try {
|
|
1051
|
+
import_fs8.default.mkdirSync(import_path8.default.dirname(ERROR_LOG), { recursive: true });
|
|
1052
|
+
import_fs8.default.writeFileSync(ERROR_LOG, `[${(/* @__PURE__ */ new Date()).toISOString()}] [${host}] started pid=${process.pid}${version ? ` version=${version}` : ""}
|
|
1053
|
+
`);
|
|
1054
|
+
} catch {
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
function fmt(v) {
|
|
1058
|
+
if (v instanceof Error) return v.stack || v.message;
|
|
1059
|
+
if (typeof v === "string") return v;
|
|
1060
|
+
try {
|
|
1061
|
+
return JSON.stringify(v);
|
|
1062
|
+
} catch {
|
|
1063
|
+
return String(v);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
function logErr(tag, ...args) {
|
|
1067
|
+
try {
|
|
1068
|
+
import_fs8.default.appendFileSync(ERROR_LOG, `[${(/* @__PURE__ */ new Date()).toISOString()}] [${tag}] ${args.map(fmt).join(" ")}
|
|
1069
|
+
`);
|
|
1070
|
+
} catch {
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
function installProcessTraps(tag) {
|
|
1074
|
+
process.on("uncaughtException", (err) => logErr(tag, "uncaughtException:", err));
|
|
1075
|
+
process.on("unhandledRejection", (reason) => logErr(tag, "unhandledRejection:", reason));
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// ../server/src/http/ecosystem.ts
|
|
1079
|
+
var execFileP = (0, import_util.promisify)(import_child_process4.execFile);
|
|
1080
|
+
var RESOURCES_DIR = [import_path9.default.join(__dirname, "resources"), import_path9.default.join(__dirname, "..", "..", "resources")].find((d) => import_fs9.default.existsSync(import_path9.default.join(d, "skills"))) || import_path9.default.join(__dirname, "..", "..", "resources");
|
|
1081
|
+
function semaRoot() {
|
|
1082
|
+
return process.env.SEMA_ROOT ? import_path9.default.resolve(process.env.SEMA_ROOT) : import_path9.default.join(import_os4.default.homedir(), ".sema");
|
|
1083
|
+
}
|
|
1084
|
+
var userSkillDir = (id) => import_path9.default.join(semaRoot(), "skills", id);
|
|
1085
|
+
var userMcpFile = () => import_path9.default.join(semaRoot(), ".mcp.json");
|
|
1086
|
+
var userSettingsFile = () => import_path9.default.join(semaRoot(), "settings.json");
|
|
1087
|
+
function parseRemoteSource(v) {
|
|
1088
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(v?.repo || "")) return null;
|
|
1089
|
+
const ref = v?.ref == null || v.ref === "" ? "HEAD" : v.ref;
|
|
1090
|
+
if (typeof ref !== "string" || !/^[\w./-]+$/.test(ref)) return null;
|
|
1091
|
+
if (typeof v?.path !== "string" || !v.path || v.path.includes("..")) return null;
|
|
1092
|
+
return { repo: v.repo, ref, path: v.path.replace(/^\/+|\/+$/g, "") };
|
|
1093
|
+
}
|
|
1094
|
+
function readJson2(file) {
|
|
1095
|
+
try {
|
|
1096
|
+
return JSON.parse(import_fs9.default.readFileSync(file, "utf8"));
|
|
1097
|
+
} catch {
|
|
1098
|
+
return void 0;
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
function parseFrontmatter(file) {
|
|
1102
|
+
try {
|
|
1103
|
+
const m = import_fs9.default.readFileSync(file, "utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
1104
|
+
if (!m) return {};
|
|
1105
|
+
const lines = m[1].split(/\r?\n/);
|
|
1106
|
+
const pick = (key) => {
|
|
1107
|
+
const idx = lines.findIndex((l) => l.startsWith(`${key}:`));
|
|
1108
|
+
if (idx === -1) return void 0;
|
|
1109
|
+
const inline = lines[idx].slice(key.length + 1).trim();
|
|
1110
|
+
if (/^[|>][+-]?$/.test(inline)) {
|
|
1111
|
+
const block = [];
|
|
1112
|
+
for (let i = idx + 1; i < lines.length; i++) {
|
|
1113
|
+
if (lines[i].trim() === "") {
|
|
1114
|
+
block.push("");
|
|
1115
|
+
continue;
|
|
1116
|
+
}
|
|
1117
|
+
if (!/^\s/.test(lines[i])) break;
|
|
1118
|
+
block.push(lines[i].trim());
|
|
1119
|
+
}
|
|
1120
|
+
while (block.length && !block[block.length - 1]) block.pop();
|
|
1121
|
+
return block.join(inline[0] === ">" ? " " : "\n") || void 0;
|
|
1122
|
+
}
|
|
1123
|
+
return inline.replace(/^["']|["']$/g, "") || void 0;
|
|
1124
|
+
};
|
|
1125
|
+
return { name: pick("name"), description: pick("description") };
|
|
1126
|
+
} catch {
|
|
1127
|
+
return {};
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
function scanResources() {
|
|
1131
|
+
const out = [];
|
|
1132
|
+
const skillsRoot = import_path9.default.join(RESOURCES_DIR, "skills");
|
|
1133
|
+
if (import_fs9.default.existsSync(skillsRoot)) {
|
|
1134
|
+
for (const e of import_fs9.default.readdirSync(skillsRoot, { withFileTypes: true })) {
|
|
1135
|
+
if (e.isDirectory()) {
|
|
1136
|
+
const dir = import_path9.default.join(skillsRoot, e.name);
|
|
1137
|
+
if (!import_fs9.default.existsSync(import_path9.default.join(dir, "SKILL.md"))) continue;
|
|
1138
|
+
const fm = parseFrontmatter(import_path9.default.join(dir, "SKILL.md"));
|
|
1139
|
+
const card = readJson2(import_path9.default.join(dir, "card.json")) || fm;
|
|
1140
|
+
out.push({ kind: "skill", id: e.name, dir, card, skillName: fm.name || e.name });
|
|
1141
|
+
} else if (e.isFile() && e.name.endsWith(".json")) {
|
|
1142
|
+
const conf = readJson2(import_path9.default.join(skillsRoot, e.name));
|
|
1143
|
+
const source = parseRemoteSource(conf?.source);
|
|
1144
|
+
if (!source) continue;
|
|
1145
|
+
const skillName = typeof conf.skillName === "string" && conf.skillName.trim() || source.path.split("/").pop() || "";
|
|
1146
|
+
out.push({ kind: "skill", id: e.name.replace(/\.json$/, ""), card: conf.card || {}, source, skillName });
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
const mcpRoot = import_path9.default.join(RESOURCES_DIR, "mcp");
|
|
1151
|
+
if (import_fs9.default.existsSync(mcpRoot)) {
|
|
1152
|
+
for (const e of import_fs9.default.readdirSync(mcpRoot, { withFileTypes: true })) {
|
|
1153
|
+
if (!e.isFile() || !e.name.endsWith(".json")) continue;
|
|
1154
|
+
const conf = readJson2(import_path9.default.join(mcpRoot, e.name));
|
|
1155
|
+
if (!conf?.server || typeof conf.server !== "object" || !Object.keys(conf.server).length) continue;
|
|
1156
|
+
out.push({ kind: "mcp", id: e.name.replace(/\.json$/, ""), card: conf.card || {}, server: conf.server });
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
return out;
|
|
1160
|
+
}
|
|
1161
|
+
function readUserMcp() {
|
|
1162
|
+
const file = userMcpFile();
|
|
1163
|
+
if (!import_fs9.default.existsSync(file)) return {};
|
|
1164
|
+
try {
|
|
1165
|
+
return JSON.parse(import_fs9.default.readFileSync(file, "utf8"));
|
|
1166
|
+
} catch {
|
|
1167
|
+
throw new Error("\u7528\u6237\u7EA7 .mcp.json \u89E3\u6790\u5931\u8D25\uFF0C\u8BF7\u5148\u624B\u52A8\u4FEE\u590D\u8BE5\u6587\u4EF6");
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
function writeUserMcp(conf) {
|
|
1171
|
+
const file = userMcpFile();
|
|
1172
|
+
import_fs9.default.mkdirSync(import_path9.default.dirname(file), { recursive: true });
|
|
1173
|
+
import_fs9.default.writeFileSync(file, JSON.stringify(conf, null, 2) + "\n");
|
|
1174
|
+
}
|
|
1175
|
+
function readUserSettings() {
|
|
1176
|
+
const file = userSettingsFile();
|
|
1177
|
+
if (!import_fs9.default.existsSync(file)) return {};
|
|
1178
|
+
try {
|
|
1179
|
+
return JSON.parse(import_fs9.default.readFileSync(file, "utf8"));
|
|
1180
|
+
} catch {
|
|
1181
|
+
throw new Error("\u7528\u6237\u7EA7 settings.json \u89E3\u6790\u5931\u8D25\uFF0C\u8BF7\u5148\u624B\u52A8\u4FEE\u590D\u8BE5\u6587\u4EF6");
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
function writeUserSettings(conf) {
|
|
1185
|
+
const file = userSettingsFile();
|
|
1186
|
+
import_fs9.default.mkdirSync(import_path9.default.dirname(file), { recursive: true });
|
|
1187
|
+
import_fs9.default.writeFileSync(file, JSON.stringify(conf, null, 2) + "\n");
|
|
1188
|
+
}
|
|
1189
|
+
function readDisabledSet(key) {
|
|
1190
|
+
try {
|
|
1191
|
+
const v = readUserSettings()[key];
|
|
1192
|
+
return new Set(Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
1193
|
+
} catch {
|
|
1194
|
+
return /* @__PURE__ */ new Set();
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
function setDisabled(key, name, disabled) {
|
|
1198
|
+
const settings = readUserSettings();
|
|
1199
|
+
const list = Array.isArray(settings[key]) ? settings[key] : [];
|
|
1200
|
+
settings[key] = disabled ? list.includes(name) ? list : [...list, name] : list.filter((n) => n !== name);
|
|
1201
|
+
writeUserSettings(settings);
|
|
1202
|
+
}
|
|
1203
|
+
function migrateLegacyDisabled() {
|
|
1204
|
+
let conf;
|
|
1205
|
+
try {
|
|
1206
|
+
conf = readUserMcp();
|
|
1207
|
+
} catch {
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
const legacy = conf.mcpServersDisabled;
|
|
1211
|
+
if (!legacy || typeof legacy !== "object" || !Object.keys(legacy).length) {
|
|
1212
|
+
if ("mcpServersDisabled" in conf) {
|
|
1213
|
+
delete conf.mcpServersDisabled;
|
|
1214
|
+
writeUserMcp(conf);
|
|
1215
|
+
}
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
try {
|
|
1219
|
+
const servers = { ...conf.mcpServers || {} };
|
|
1220
|
+
for (const [name, config] of Object.entries(legacy)) {
|
|
1221
|
+
if (!(name in servers)) servers[name] = config;
|
|
1222
|
+
setDisabled("disabledMcpServers", name, true);
|
|
1223
|
+
}
|
|
1224
|
+
delete conf.mcpServersDisabled;
|
|
1225
|
+
writeUserMcp({ ...conf, mcpServers: servers });
|
|
1226
|
+
} catch {
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
function isInstalled(r) {
|
|
1230
|
+
if (r.kind === "skill") return import_fs9.default.existsSync(userSkillDir(r.id));
|
|
1231
|
+
try {
|
|
1232
|
+
const servers = readUserMcp().mcpServers || {};
|
|
1233
|
+
return Object.keys(r.server).every((k) => k in servers);
|
|
1234
|
+
} catch {
|
|
1235
|
+
return false;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
function listCatalog() {
|
|
1239
|
+
migrateLegacyDisabled();
|
|
1240
|
+
return scanResources().sort((a, b) => (a.card.order ?? Infinity) - (b.card.order ?? Infinity) || a.id.localeCompare(b.id)).map((r) => {
|
|
1241
|
+
const source = r.kind === "skill" ? r.source : void 0;
|
|
1242
|
+
return {
|
|
1243
|
+
id: r.id,
|
|
1244
|
+
kind: r.kind,
|
|
1245
|
+
name: r.card.name || r.id,
|
|
1246
|
+
description: r.card.description || "",
|
|
1247
|
+
category: r.card.category,
|
|
1248
|
+
skillName: r.kind === "skill" ? r.skillName : void 0,
|
|
1249
|
+
repo: source?.repo,
|
|
1250
|
+
repoUrl: source ? `https://github.com/${source.repo}/tree/${source.ref}/${source.path}` : void 0,
|
|
1251
|
+
installed: isInstalled(r)
|
|
1252
|
+
};
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
var TARBALL_MAX = 100 * 1024 * 1024;
|
|
1256
|
+
var inflightTarballs = /* @__PURE__ */ new Map();
|
|
1257
|
+
function downloadTarball(source) {
|
|
1258
|
+
const key = `${source.repo}@${source.ref}`;
|
|
1259
|
+
const inflight3 = inflightTarballs.get(key);
|
|
1260
|
+
if (inflight3) return inflight3;
|
|
1261
|
+
const task = (async () => {
|
|
1262
|
+
const ctl = new AbortController();
|
|
1263
|
+
const timer = setTimeout(() => ctl.abort(), 6e4);
|
|
1264
|
+
try {
|
|
1265
|
+
const res = await fetch(`https://codeload.github.com/${source.repo}/tar.gz/${encodeURIComponent(source.ref)}`, { signal: ctl.signal, redirect: "follow" });
|
|
1266
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
1267
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
1268
|
+
if (buf.length > TARBALL_MAX) throw new Error("\u8D44\u6E90\u5305\u8FC7\u5927");
|
|
1269
|
+
return buf;
|
|
1270
|
+
} catch (e) {
|
|
1271
|
+
throw new Error(e?.name === "AbortError" ? "\u4E0B\u8F7D\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5" : `\u4E0B\u8F7D\u5931\u8D25\uFF08${source.repo}\uFF09: ${e?.message || e}`);
|
|
1272
|
+
} finally {
|
|
1273
|
+
clearTimeout(timer);
|
|
1274
|
+
}
|
|
1275
|
+
})();
|
|
1276
|
+
inflightTarballs.set(key, task);
|
|
1277
|
+
const clean = () => {
|
|
1278
|
+
inflightTarballs.delete(key);
|
|
1279
|
+
};
|
|
1280
|
+
task.then(clean, clean);
|
|
1281
|
+
return task;
|
|
1282
|
+
}
|
|
1283
|
+
async function fetchRemoteSkill(r) {
|
|
1284
|
+
const source = r.source;
|
|
1285
|
+
const tarball = await downloadTarball(source);
|
|
1286
|
+
const tmp = import_fs9.default.mkdtempSync(import_path9.default.join(import_os4.default.tmpdir(), "sema-eco-"));
|
|
1287
|
+
try {
|
|
1288
|
+
const tarFile = import_path9.default.join(tmp, "src.tar.gz");
|
|
1289
|
+
import_fs9.default.writeFileSync(tarFile, tarball);
|
|
1290
|
+
const out = import_path9.default.join(tmp, "out");
|
|
1291
|
+
import_fs9.default.mkdirSync(out);
|
|
1292
|
+
await execFileP("tar", ["-xzf", tarFile, "-C", out]);
|
|
1293
|
+
const top = import_fs9.default.readdirSync(out, { withFileTypes: true }).find((e) => e.isDirectory());
|
|
1294
|
+
const srcDir = top ? import_path9.default.join(out, top.name, source.path) : "";
|
|
1295
|
+
if (!srcDir || !import_fs9.default.existsSync(import_path9.default.join(srcDir, "SKILL.md"))) throw new Error(`\u8D44\u6E90\u5305\u4E2D\u672A\u627E\u5230 ${source.path}/SKILL.md\uFF0C\u6E05\u5355\u7684 path \u53EF\u80FD\u6709\u8BEF`);
|
|
1296
|
+
const dest = userSkillDir(r.id);
|
|
1297
|
+
import_fs9.default.rmSync(dest, { recursive: true, force: true });
|
|
1298
|
+
import_fs9.default.mkdirSync(import_path9.default.dirname(dest), { recursive: true });
|
|
1299
|
+
import_fs9.default.cpSync(srcDir, dest, { recursive: true });
|
|
1300
|
+
} finally {
|
|
1301
|
+
import_fs9.default.rmSync(tmp, { recursive: true, force: true });
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
async function installResource(id, overwrite) {
|
|
1305
|
+
const r = scanResources().find((x) => x.id === id);
|
|
1306
|
+
if (!r) throw new Error(`\u8D44\u6E90\u4E0D\u5B58\u5728: ${id}`);
|
|
1307
|
+
if (r.kind === "skill") {
|
|
1308
|
+
const dest = userSkillDir(r.id);
|
|
1309
|
+
if (import_fs9.default.existsSync(dest) && !overwrite) return { needConfirm: true };
|
|
1310
|
+
if (r.dir) {
|
|
1311
|
+
import_fs9.default.rmSync(dest, { recursive: true, force: true });
|
|
1312
|
+
import_fs9.default.mkdirSync(import_path9.default.dirname(dest), { recursive: true });
|
|
1313
|
+
import_fs9.default.cpSync(r.dir, dest, { recursive: true });
|
|
1314
|
+
} else {
|
|
1315
|
+
await fetchRemoteSkill(r);
|
|
1316
|
+
}
|
|
1317
|
+
return true;
|
|
1318
|
+
}
|
|
1319
|
+
const conf = readUserMcp();
|
|
1320
|
+
const servers = { ...conf.mcpServers || {} };
|
|
1321
|
+
if (Object.keys(r.server).some((k) => k in servers) && !overwrite) return { needConfirm: true };
|
|
1322
|
+
Object.assign(servers, r.server);
|
|
1323
|
+
writeUserMcp({ ...conf, mcpServers: servers });
|
|
1324
|
+
return true;
|
|
1325
|
+
}
|
|
1326
|
+
async function installDefaultSkills(handled) {
|
|
1327
|
+
const pending = scanResources().filter((r) => r.kind === "skill" && !!r.card.defaultInstall && !handled.includes(r.id));
|
|
1328
|
+
const done = await Promise.all(pending.map(async (r) => {
|
|
1329
|
+
try {
|
|
1330
|
+
if (!import_fs9.default.existsSync(userSkillDir(r.id))) await installResource(r.id, false);
|
|
1331
|
+
return r.id;
|
|
1332
|
+
} catch (e) {
|
|
1333
|
+
logErr("eco", `\u9ED8\u8BA4\u6280\u80FD ${r.id} \u5B89\u88C5\u5931\u8D25:`, e?.message || e);
|
|
1334
|
+
return null;
|
|
1335
|
+
}
|
|
1336
|
+
}));
|
|
1337
|
+
return done.filter((x) => !!x);
|
|
1338
|
+
}
|
|
1339
|
+
function uninstallResource(id) {
|
|
1340
|
+
const r = scanResources().find((x) => x.id === id);
|
|
1341
|
+
if (!r) throw new Error(`\u8D44\u6E90\u4E0D\u5B58\u5728: ${id}`);
|
|
1342
|
+
if (r.kind === "skill") {
|
|
1343
|
+
import_fs9.default.rmSync(userSkillDir(r.id), { recursive: true, force: true });
|
|
1344
|
+
try {
|
|
1345
|
+
setDisabled("disabledSkills", r.skillName, false);
|
|
1346
|
+
} catch {
|
|
1347
|
+
}
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
const conf = readUserMcp();
|
|
1351
|
+
const servers = { ...conf.mcpServers || {} };
|
|
1352
|
+
for (const k of Object.keys(r.server)) {
|
|
1353
|
+
delete servers[k];
|
|
1354
|
+
setDisabled("disabledMcpServers", k, false);
|
|
1355
|
+
setUseTools(k, null);
|
|
1356
|
+
}
|
|
1357
|
+
writeUserMcp({ ...conf, mcpServers: servers });
|
|
1358
|
+
return true;
|
|
1359
|
+
}
|
|
1360
|
+
function checkSkillId(id) {
|
|
1361
|
+
if (!id || id === ".disabled" || id.includes("/") || id.includes("\\") || id.includes("..")) throw new Error(`\u975E\u6CD5 skill id: ${id}`);
|
|
1362
|
+
const dir = userSkillDir(id);
|
|
1363
|
+
if (!import_fs9.default.existsSync(import_path9.default.join(dir, "SKILL.md"))) throw new Error(`Skill \u4E0D\u5B58\u5728: ${id}`);
|
|
1364
|
+
return dir;
|
|
1365
|
+
}
|
|
1366
|
+
function mcpSummary(config) {
|
|
1367
|
+
if (config?.url) return String(config.url);
|
|
1368
|
+
if (config?.command) return [config.command, ...Array.isArray(config.args) ? config.args : []].join(" ");
|
|
1369
|
+
return "";
|
|
1370
|
+
}
|
|
1371
|
+
function listInstalled() {
|
|
1372
|
+
migrateLegacyDisabled();
|
|
1373
|
+
const titles = /* @__PURE__ */ new Map();
|
|
1374
|
+
for (const r of scanResources()) {
|
|
1375
|
+
if (!r.card.name) continue;
|
|
1376
|
+
if (r.kind === "skill") {
|
|
1377
|
+
titles.set(`skill:${r.id}`, r.card.name);
|
|
1378
|
+
titles.set(`skill:${r.skillName}`, r.card.name);
|
|
1379
|
+
} else {
|
|
1380
|
+
for (const k of Object.keys(r.server)) titles.set(`mcp:${k}`, r.card.name);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
const disabledSkills = readDisabledSet("disabledSkills");
|
|
1384
|
+
const skills = [];
|
|
1385
|
+
const skillsRoot = import_path9.default.join(semaRoot(), "skills");
|
|
1386
|
+
if (import_fs9.default.existsSync(skillsRoot)) {
|
|
1387
|
+
for (const e of import_fs9.default.readdirSync(skillsRoot, { withFileTypes: true })) {
|
|
1388
|
+
if (!e.isDirectory()) continue;
|
|
1389
|
+
const file = import_path9.default.join(skillsRoot, e.name, "SKILL.md");
|
|
1390
|
+
if (!import_fs9.default.existsSync(file)) continue;
|
|
1391
|
+
const fm = parseFrontmatter(file);
|
|
1392
|
+
const name = fm.name || e.name;
|
|
1393
|
+
const title = titles.get(`skill:${e.name}`) || titles.get(`skill:${name}`);
|
|
1394
|
+
skills.push({ id: e.name, name, description: fm.description || "", enabled: !disabledSkills.has(name), title });
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const disabledMcp = readDisabledSet("disabledMcpServers");
|
|
1398
|
+
const useToolsMap = readUseToolsMap();
|
|
1399
|
+
const mcp = [];
|
|
1400
|
+
for (const [name, config] of Object.entries(readUserMcp().mcpServers || {})) {
|
|
1401
|
+
mcp.push({ id: name, name, description: mcpSummary(config), enabled: !disabledMcp.has(name), config, title: titles.get(`mcp:${name}`), useTools: useToolsMap[name] ?? null });
|
|
1402
|
+
}
|
|
1403
|
+
mcp.sort((a, b) => a.id.localeCompare(b.id));
|
|
1404
|
+
skills.sort((a, b) => a.id.localeCompare(b.id));
|
|
1405
|
+
return { skills, mcp };
|
|
1406
|
+
}
|
|
1407
|
+
function toggleInstalled(kind, id, enabled) {
|
|
1408
|
+
if (kind === "skill") {
|
|
1409
|
+
const dir = checkSkillId(id);
|
|
1410
|
+
const fm = parseFrontmatter(import_path9.default.join(dir, "SKILL.md"));
|
|
1411
|
+
setDisabled("disabledSkills", fm.name || id, !enabled);
|
|
1412
|
+
return true;
|
|
1413
|
+
}
|
|
1414
|
+
if (!(readUserMcp().mcpServers || {})[id]) throw new Error(`MCP server \u4E0D\u5B58\u5728: ${id}`);
|
|
1415
|
+
setDisabled("disabledMcpServers", id, !enabled);
|
|
1416
|
+
return true;
|
|
1417
|
+
}
|
|
1418
|
+
function removeInstalled(kind, id) {
|
|
1419
|
+
if (kind === "skill") {
|
|
1420
|
+
const dir = checkSkillId(id);
|
|
1421
|
+
const fm = parseFrontmatter(import_path9.default.join(dir, "SKILL.md"));
|
|
1422
|
+
import_fs9.default.rmSync(dir, { recursive: true, force: true });
|
|
1423
|
+
try {
|
|
1424
|
+
setDisabled("disabledSkills", fm.name || id, false);
|
|
1425
|
+
} catch {
|
|
1426
|
+
}
|
|
1427
|
+
return true;
|
|
1428
|
+
}
|
|
1429
|
+
const conf = readUserMcp();
|
|
1430
|
+
const servers = { ...conf.mcpServers || {} };
|
|
1431
|
+
if (!(id in servers)) throw new Error(`MCP server \u4E0D\u5B58\u5728: ${id}`);
|
|
1432
|
+
delete servers[id];
|
|
1433
|
+
writeUserMcp({ ...conf, mcpServers: servers });
|
|
1434
|
+
try {
|
|
1435
|
+
setDisabled("disabledMcpServers", id, false);
|
|
1436
|
+
} catch {
|
|
1437
|
+
}
|
|
1438
|
+
try {
|
|
1439
|
+
setUseTools(id, null);
|
|
1440
|
+
} catch {
|
|
1441
|
+
}
|
|
1442
|
+
return true;
|
|
1443
|
+
}
|
|
1444
|
+
function userSkillsRoot() {
|
|
1445
|
+
return import_path9.default.join(semaRoot(), "skills");
|
|
1446
|
+
}
|
|
1447
|
+
function readUseToolsMap() {
|
|
1448
|
+
try {
|
|
1449
|
+
const v = readUserSettings().enabledMcpServerUseTools;
|
|
1450
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
1451
|
+
} catch {
|
|
1452
|
+
return {};
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
function setUseTools(id, toolNames) {
|
|
1456
|
+
const settings = readUserSettings();
|
|
1457
|
+
const map = { ...settings.enabledMcpServerUseTools || {} };
|
|
1458
|
+
if (toolNames === null) delete map[id];
|
|
1459
|
+
else map[id] = toolNames;
|
|
1460
|
+
if (Object.keys(map).length) settings.enabledMcpServerUseTools = map;
|
|
1461
|
+
else delete settings.enabledMcpServerUseTools;
|
|
1462
|
+
writeUserSettings(settings);
|
|
1463
|
+
}
|
|
1464
|
+
function updateMcpUseTools(id, toolNames) {
|
|
1465
|
+
if (!(readUserMcp().mcpServers || {})[id]) throw new Error(`MCP server \u4E0D\u5B58\u5728: ${id}`);
|
|
1466
|
+
if (toolNames !== null && (!Array.isArray(toolNames) || toolNames.some((t) => typeof t !== "string"))) throw new Error("toolNames \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u6216 null");
|
|
1467
|
+
setUseTools(id, toolNames);
|
|
1468
|
+
return true;
|
|
1469
|
+
}
|
|
1470
|
+
function updateMcpConfig(id, config) {
|
|
1471
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error("\u914D\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61");
|
|
1472
|
+
const conf = readUserMcp();
|
|
1473
|
+
const servers = { ...conf.mcpServers || {} };
|
|
1474
|
+
if (!(id in servers)) throw new Error(`MCP server \u4E0D\u5B58\u5728: ${id}`);
|
|
1475
|
+
servers[id] = config;
|
|
1476
|
+
writeUserMcp({ ...conf, mcpServers: servers });
|
|
1477
|
+
return true;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
// ../server/src/http/mcpTools.ts
|
|
1481
|
+
var import_client = require("@modelcontextprotocol/sdk/client/index.js");
|
|
1482
|
+
var import_stdio = require("@modelcontextprotocol/sdk/client/stdio.js");
|
|
1483
|
+
var import_sse = require("@modelcontextprotocol/sdk/client/sse.js");
|
|
1484
|
+
var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
1485
|
+
var CONNECT_TIMEOUT = 2e4;
|
|
1486
|
+
var cache2 = /* @__PURE__ */ new Map();
|
|
1487
|
+
var inflight2 = /* @__PURE__ */ new Map();
|
|
1488
|
+
function withTimeout(promise, ms, message) {
|
|
1489
|
+
let timer;
|
|
1490
|
+
const timeout = new Promise((_, reject) => {
|
|
1491
|
+
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
1492
|
+
});
|
|
1493
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
1494
|
+
}
|
|
1495
|
+
function createTransport(config) {
|
|
1496
|
+
const transport = config.transport || config.type || "stdio";
|
|
1497
|
+
switch (transport) {
|
|
1498
|
+
case "stdio":
|
|
1499
|
+
if (!config.command) throw new Error("stdio \u4F20\u8F93\u9700\u8981\u914D\u7F6E command");
|
|
1500
|
+
return new import_stdio.StdioClientTransport({
|
|
1501
|
+
command: config.command,
|
|
1502
|
+
args: Array.isArray(config.args) ? config.args : void 0,
|
|
1503
|
+
env: config.env && typeof config.env === "object" ? { ...process.env, ...config.env } : void 0
|
|
1504
|
+
});
|
|
1505
|
+
case "sse":
|
|
1506
|
+
if (!config.url) throw new Error("sse \u4F20\u8F93\u9700\u8981\u914D\u7F6E url");
|
|
1507
|
+
return new import_sse.SSEClientTransport(new URL(config.url));
|
|
1508
|
+
case "http":
|
|
1509
|
+
if (!config.url) throw new Error("http \u4F20\u8F93\u9700\u8981\u914D\u7F6E url");
|
|
1510
|
+
return new import_streamableHttp.StreamableHTTPClientTransport(new URL(config.url), {
|
|
1511
|
+
requestInit: config.headers ? { headers: config.headers } : void 0
|
|
1512
|
+
});
|
|
1513
|
+
default:
|
|
1514
|
+
throw new Error(`\u4E0D\u652F\u6301\u7684\u4F20\u8F93\u7C7B\u578B: ${transport}`);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
async function probe(config) {
|
|
1518
|
+
const client = new import_client.Client({ name: "semawork", version: "1.0.0" }, { capabilities: {} });
|
|
1519
|
+
try {
|
|
1520
|
+
await withTimeout(client.connect(createTransport(config)), CONNECT_TIMEOUT, `\u8FDE\u63A5\u8D85\u65F6 (${CONNECT_TIMEOUT / 1e3}s)`);
|
|
1521
|
+
const result = await withTimeout(client.listTools(), CONNECT_TIMEOUT, `\u83B7\u53D6\u5DE5\u5177\u5217\u8868\u8D85\u65F6 (${CONNECT_TIMEOUT / 1e3}s)`);
|
|
1522
|
+
return (result.tools || []).map((t) => ({ name: t.name, description: t.description }));
|
|
1523
|
+
} finally {
|
|
1524
|
+
await withTimeout(client.close(), 5e3, "close timeout").catch(() => void 0);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
function listMcpTools(id, refresh) {
|
|
1528
|
+
const config = (readUserMcp().mcpServers || {})[id];
|
|
1529
|
+
if (!config) throw new Error(`MCP server \u4E0D\u5B58\u5728: ${id}`);
|
|
1530
|
+
const key = JSON.stringify(config);
|
|
1531
|
+
const cached = cache2.get(id);
|
|
1532
|
+
if (!refresh && cached && cached.key === key) return Promise.resolve(cached.tools);
|
|
1533
|
+
const running = inflight2.get(id);
|
|
1534
|
+
if (running) return running;
|
|
1535
|
+
const task = probe(config).then((tools) => {
|
|
1536
|
+
cache2.set(id, { key, tools });
|
|
1537
|
+
return tools;
|
|
1538
|
+
}).finally(() => inflight2.delete(id));
|
|
1539
|
+
inflight2.set(id, task);
|
|
1540
|
+
return task;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
// ../server/src/http/browserControl.ts
|
|
1544
|
+
var import_fs10 = __toESM(require("fs"));
|
|
1545
|
+
var import_os5 = __toESM(require("os"));
|
|
1546
|
+
var import_path10 = __toESM(require("path"));
|
|
1547
|
+
var SKILL_NAME = "chrome-use";
|
|
1548
|
+
var MCP_NAME = "chrome";
|
|
1549
|
+
var SOURCE_CANDIDATES = [
|
|
1550
|
+
import_path10.default.join(__dirname, "resources", "chrome"),
|
|
1551
|
+
import_path10.default.join(__dirname, "..", "..", "..", "chrome", ".sema")
|
|
1552
|
+
];
|
|
1553
|
+
function sourceDir() {
|
|
1554
|
+
const dir = SOURCE_CANDIDATES.find((d) => import_fs10.default.existsSync(import_path10.default.join(d, ".mcp.json")));
|
|
1555
|
+
if (!dir) throw new Error(`\u672A\u627E\u5230\u6D4F\u89C8\u5668\u63A7\u5236\u8D44\u6E90\u76EE\u5F55\uFF08${SOURCE_CANDIDATES.join(" / ")}\uFF09`);
|
|
1556
|
+
return dir;
|
|
1557
|
+
}
|
|
1558
|
+
function userSkillDir2() {
|
|
1559
|
+
const root = process.env.SEMA_ROOT ? import_path10.default.resolve(process.env.SEMA_ROOT) : import_path10.default.join(import_os5.default.homedir(), ".sema");
|
|
1560
|
+
return import_path10.default.join(root, "skills", SKILL_NAME);
|
|
1561
|
+
}
|
|
1562
|
+
function browserControlState(enabled) {
|
|
1563
|
+
return { experimental: process.platform === "linux", enabled };
|
|
1564
|
+
}
|
|
1565
|
+
var BrowserControl = class {
|
|
1566
|
+
constructor(sm) {
|
|
1567
|
+
this.sm = sm;
|
|
1568
|
+
}
|
|
1569
|
+
chain = Promise.resolve();
|
|
1570
|
+
/** 执行开/关动作,串行化;返回动作完成后的开关值(失败则抛错,配置键保持原值) */
|
|
1571
|
+
setEnabled(enabled) {
|
|
1572
|
+
const run3 = () => enabled ? this.enable() : this.disable();
|
|
1573
|
+
const task = this.chain.then(run3, run3);
|
|
1574
|
+
this.chain = task.catch(() => void 0);
|
|
1575
|
+
return task;
|
|
1576
|
+
}
|
|
1577
|
+
core(action, payload = {}) {
|
|
1578
|
+
return this.sm.dispatch(action, void 0, payload);
|
|
1579
|
+
}
|
|
1580
|
+
async enable() {
|
|
1581
|
+
const src = sourceDir();
|
|
1582
|
+
const dest = userSkillDir2();
|
|
1583
|
+
if (!import_fs10.default.existsSync(import_path10.default.join(dest, "SKILL.md"))) {
|
|
1584
|
+
import_fs10.default.mkdirSync(import_path10.default.dirname(dest), { recursive: true });
|
|
1585
|
+
import_fs10.default.cpSync(import_path10.default.join(src, "skills", SKILL_NAME), dest, { recursive: true });
|
|
1586
|
+
}
|
|
1587
|
+
await this.core("core.getSkillsInfo", { refresh: true });
|
|
1588
|
+
const servers = await this.core("core.getMCPServerInfo");
|
|
1589
|
+
if (!findUserMcp(servers)) {
|
|
1590
|
+
const template = JSON.parse(import_fs10.default.readFileSync(import_path10.default.join(src, ".mcp.json"), "utf8"));
|
|
1591
|
+
const entry = template?.mcpServers?.[MCP_NAME];
|
|
1592
|
+
if (!entry) throw new Error(`.mcp.json \u7F3A\u5C11 mcpServers.${MCP_NAME}`);
|
|
1593
|
+
await this.core("core.addMCPServer", { config: { ...entry, name: MCP_NAME, scope: "user" } });
|
|
1594
|
+
}
|
|
1595
|
+
this.sm.registry.setBrowserControl(true);
|
|
1596
|
+
return true;
|
|
1597
|
+
}
|
|
1598
|
+
async disable() {
|
|
1599
|
+
const servers = await this.core("core.getMCPServerInfo");
|
|
1600
|
+
if (findUserMcp(servers)) await this.core("core.removeMCPServer", { name: MCP_NAME });
|
|
1601
|
+
const skills = await this.core("core.getSkillsInfo");
|
|
1602
|
+
if ((skills || []).some((s) => s?.name === SKILL_NAME && s?.locate === "user")) await this.core("core.removeSkillConf", { name: SKILL_NAME });
|
|
1603
|
+
this.sm.registry.setBrowserControl(false);
|
|
1604
|
+
return false;
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
function findUserMcp(servers) {
|
|
1608
|
+
return (servers || []).some((s) => s?.config?.name === MCP_NAME && (s.scope ?? s.config?.scope) === "user");
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
// ../server/src/http/router.ts
|
|
1612
|
+
var HANDLED = Symbol("handled");
|
|
1613
|
+
var faviconCache = /* @__PURE__ */ new Map();
|
|
1614
|
+
async function fetchHtmlHead(url) {
|
|
1615
|
+
const ctl = new AbortController();
|
|
1616
|
+
const timer = setTimeout(() => ctl.abort(), 5e3);
|
|
1617
|
+
try {
|
|
1618
|
+
const r = await fetch(url, { redirect: "follow", signal: ctl.signal, headers: { Accept: "text/html" } });
|
|
1619
|
+
if (!r.ok || !/text\/html/i.test(r.headers.get("content-type") || "") || !r.body) return "";
|
|
1620
|
+
const reader = r.body.getReader();
|
|
1621
|
+
const chunks = [];
|
|
1622
|
+
let size = 0;
|
|
1623
|
+
while (size < 64 * 1024) {
|
|
1624
|
+
const { done, value } = await reader.read();
|
|
1625
|
+
if (done || !value) break;
|
|
1626
|
+
chunks.push(value);
|
|
1627
|
+
size += value.length;
|
|
1628
|
+
if (/<\/head>/i.test(Buffer.concat(chunks).toString("utf8"))) break;
|
|
1629
|
+
}
|
|
1630
|
+
reader.cancel().catch(() => {
|
|
1631
|
+
});
|
|
1632
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
1633
|
+
} catch {
|
|
1634
|
+
return "";
|
|
1635
|
+
} finally {
|
|
1636
|
+
clearTimeout(timer);
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
function decodeEntities(s) {
|
|
1640
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'");
|
|
1641
|
+
}
|
|
1642
|
+
var metaCache = /* @__PURE__ */ new Map();
|
|
1643
|
+
var LOCAL_RE = /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|10\.|192\.168\.|172\.)/i;
|
|
1644
|
+
function parsePageMeta(html, baseUrl) {
|
|
1645
|
+
const tm = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
|
|
1646
|
+
const title = tm ? decodeEntities(tm[1]).replace(/\s+/g, " ").trim().slice(0, 200) : "";
|
|
1647
|
+
let best = "";
|
|
1648
|
+
for (const m of html.matchAll(/<link\b[^>]*>/gi)) {
|
|
1649
|
+
const tag = m[0];
|
|
1650
|
+
const rel = (tag.match(/\brel=["']([^"']*)["']/i)?.[1] || "").toLowerCase();
|
|
1651
|
+
if (!/(^|\s)(icon|shortcut icon|apple-touch-icon)(\s|$)/.test(rel)) continue;
|
|
1652
|
+
const href = tag.match(/\bhref=["']([^"']+)["']/i)?.[1];
|
|
1653
|
+
if (!href) continue;
|
|
1654
|
+
best = decodeEntities(href);
|
|
1655
|
+
if (/(^|\s)icon(\s|$)/.test(rel)) break;
|
|
1656
|
+
}
|
|
1657
|
+
let icon = "";
|
|
1658
|
+
try {
|
|
1659
|
+
if (best) icon = new URL(best, baseUrl).href;
|
|
1660
|
+
} catch {
|
|
1661
|
+
}
|
|
1662
|
+
if (!/^https?:\/\//i.test(icon)) icon = "";
|
|
1663
|
+
return { title, icon };
|
|
1664
|
+
}
|
|
1665
|
+
async function fetchPageMeta(url) {
|
|
1666
|
+
if (/^file:\/\//i.test(url)) {
|
|
1667
|
+
try {
|
|
1668
|
+
const fp = (0, import_url.fileURLToPath)(url);
|
|
1669
|
+
const fd = import_fs11.default.openSync(fp, "r");
|
|
1670
|
+
try {
|
|
1671
|
+
const buf = Buffer.alloc(64 * 1024);
|
|
1672
|
+
const n = import_fs11.default.readSync(fd, buf, 0, buf.length, 0);
|
|
1673
|
+
return { title: parsePageMeta(buf.subarray(0, n).toString("utf8"), url).title, icon: "" };
|
|
1674
|
+
} finally {
|
|
1675
|
+
import_fs11.default.closeSync(fd);
|
|
1676
|
+
}
|
|
1677
|
+
} catch {
|
|
1678
|
+
return { title: "", icon: "" };
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
if (!/^https?:\/\//i.test(url)) return { title: "", icon: "" };
|
|
1682
|
+
const key = url.replace(/#.*$/, "");
|
|
1683
|
+
const hit = metaCache.get(key);
|
|
1684
|
+
if (hit) return hit;
|
|
1685
|
+
const meta = parsePageMeta(await fetchHtmlHead(key), key);
|
|
1686
|
+
if (!meta.icon) {
|
|
1687
|
+
try {
|
|
1688
|
+
meta.icon = new URL("/favicon.ico", key).href;
|
|
1689
|
+
} catch {
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
if (!LOCAL_RE.test(key)) metaCache.set(key, meta);
|
|
1693
|
+
return meta;
|
|
1694
|
+
}
|
|
1695
|
+
async function fetchIcon(url, signal) {
|
|
1696
|
+
const r = await fetch(url, { redirect: "follow", signal });
|
|
1697
|
+
const type = r.headers.get("content-type") || "";
|
|
1698
|
+
if (!r.ok || !/image\//i.test(type)) return null;
|
|
1699
|
+
const buf = Buffer.from(await r.arrayBuffer());
|
|
1700
|
+
if (buf.length > 512 * 1024) return null;
|
|
1701
|
+
return { type, buf };
|
|
1702
|
+
}
|
|
1703
|
+
async function probeEmbeddable(url) {
|
|
1704
|
+
if (!/^https?:\/\//i.test(url)) return { embeddable: false, reason: "scheme" };
|
|
1705
|
+
const ctl = new AbortController();
|
|
1706
|
+
const timer = setTimeout(() => ctl.abort(), 5e3);
|
|
1707
|
+
try {
|
|
1708
|
+
let res = await fetch(url, { method: "HEAD", redirect: "follow", signal: ctl.signal }).catch(() => null);
|
|
1709
|
+
if (!res || res.status === 405 || res.status === 404) res = await fetch(url, { method: "GET", redirect: "follow", signal: ctl.signal });
|
|
1710
|
+
const xfo = (res.headers.get("x-frame-options") || "").toLowerCase();
|
|
1711
|
+
if (xfo.includes("deny") || xfo.includes("sameorigin")) return { embeddable: false, reason: "x-frame-options" };
|
|
1712
|
+
const csp = (res.headers.get("content-security-policy") || "").toLowerCase();
|
|
1713
|
+
const fa = csp.split(";").map((s) => s.trim()).find((s) => s.startsWith("frame-ancestors"));
|
|
1714
|
+
if (fa && !/\*/.test(fa)) return { embeddable: false, reason: "csp" };
|
|
1715
|
+
return { embeddable: true };
|
|
1716
|
+
} catch (e) {
|
|
1717
|
+
return { embeddable: false, reason: e?.name === "AbortError" ? "timeout" : "unreachable" };
|
|
1718
|
+
} finally {
|
|
1719
|
+
clearTimeout(timer);
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
var IS_MAC2 = process.platform === "darwin";
|
|
1723
|
+
var IS_WIN = process.platform === "win32";
|
|
1724
|
+
function run(cmd2, args) {
|
|
1725
|
+
return new Promise((resolve, reject) => (0, import_child_process5.execFile)(cmd2, args, (err, stdout) => err ? reject(err) : resolve(stdout)));
|
|
1726
|
+
}
|
|
1727
|
+
function revealInFileManager(target) {
|
|
1728
|
+
if (IS_MAC2) return run("open", ["-R", target]).catch(() => run("open", [target]));
|
|
1729
|
+
if (IS_WIN) return run("explorer", [target]).catch(() => void 0);
|
|
1730
|
+
return run("xdg-open", [target]);
|
|
1731
|
+
}
|
|
1732
|
+
function openExternal(url) {
|
|
1733
|
+
if (!/^https?:\/\//i.test(url)) throw new Error("\u4EC5\u5141\u8BB8 http/https URL");
|
|
1734
|
+
if (IS_MAC2) return run("open", [url]);
|
|
1735
|
+
if (IS_WIN) return run("cmd", ["/c", "start", "", url]);
|
|
1736
|
+
return run("xdg-open", [url]);
|
|
1737
|
+
}
|
|
1738
|
+
async function trashDir(dir) {
|
|
1739
|
+
if (!import_fs11.default.existsSync(dir)) return;
|
|
1740
|
+
if (IS_MAC2) {
|
|
1741
|
+
try {
|
|
1742
|
+
await run("osascript", ["-e", `tell application "Finder" to delete POSIX file "${dir.replace(/"/g, '\\"')}"`]);
|
|
1743
|
+
return;
|
|
1744
|
+
} catch {
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
import_fs11.default.rmSync(dir, { recursive: true, force: true });
|
|
1748
|
+
}
|
|
1749
|
+
async function pickDirectory() {
|
|
1750
|
+
if (IS_MAC2) {
|
|
1751
|
+
try {
|
|
1752
|
+
const out = await run("osascript", ["-e", 'POSIX path of (choose folder with prompt "\u9009\u62E9\u8981\u5BFC\u5165\u7684\u9879\u76EE\u76EE\u5F55")']);
|
|
1753
|
+
return out.trim().replace(/\/$/, "") || null;
|
|
1754
|
+
} catch {
|
|
1755
|
+
return null;
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
if (IS_WIN) {
|
|
1759
|
+
try {
|
|
1760
|
+
const ps = 'Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; if ($d.ShowDialog() -eq "OK") { $d.SelectedPath }';
|
|
1761
|
+
const out = await run("powershell", ["-NoProfile", "-Command", ps]);
|
|
1762
|
+
return out.trim() || null;
|
|
1763
|
+
} catch {
|
|
1764
|
+
return null;
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
try {
|
|
1768
|
+
return (await run("zenity", ["--file-selection", "--directory"])).trim() || null;
|
|
1769
|
+
} catch {
|
|
1770
|
+
return null;
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
var Router = class {
|
|
1774
|
+
constructor(sm, tm) {
|
|
1775
|
+
this.sm = sm;
|
|
1776
|
+
this.tm = tm;
|
|
1777
|
+
const reg = sm.registry;
|
|
1778
|
+
this.add("GET", "/api/bootstrap", () => ({ registry: reg.snapshot(), settings: reg.getSettings(), status: sm.statusMap(), liveSessions: sm.liveSessionIds(), platform: process.platform, homeDir: import_os6.default.homedir() }));
|
|
1779
|
+
this.add("GET", "/api/registry", () => reg.snapshot());
|
|
1780
|
+
this.add("GET", "/api/settings", () => reg.getSettings());
|
|
1781
|
+
this.add("PUT", "/api/settings", async (_r, _s, _p, body) => {
|
|
1782
|
+
const s = reg.updateSettings(body || {});
|
|
1783
|
+
if (body?.coreConfig) await sm.dispatch("core.updateCoreConfig", void 0, { config: s.coreConfig });
|
|
1784
|
+
return s;
|
|
1785
|
+
});
|
|
1786
|
+
this.add("POST", "/api/projects", (_r, _s, _p, body) => {
|
|
1787
|
+
const p = body?.importPath ? reg.importProject(String(body.importPath), body.name) : reg.createProject(String(body?.name || "").trim());
|
|
1788
|
+
sm.broadcastRegistry();
|
|
1789
|
+
void sm.evictOverflow();
|
|
1790
|
+
return p;
|
|
1791
|
+
});
|
|
1792
|
+
this.add("POST", "/api/projects/pick-directory", async () => ({ path: await pickDirectory() }));
|
|
1793
|
+
this.add("PATCH", "/api/projects/:id", (_r, _s, p, body) => {
|
|
1794
|
+
const r = reg.renameProject(p.id, String(body?.name || ""));
|
|
1795
|
+
sm.broadcastRegistry();
|
|
1796
|
+
return r;
|
|
1797
|
+
});
|
|
1798
|
+
this.add("DELETE", "/api/projects/:id", async (r, _s, p) => {
|
|
1799
|
+
const proj = reg.getProject(p.id);
|
|
1800
|
+
const sessions = reg.listSessions().filter((s) => s.projectId === p.id);
|
|
1801
|
+
for (const s of sessions) {
|
|
1802
|
+
this.tm?.killBySession(s.id);
|
|
1803
|
+
await sm.closeSession(s.id);
|
|
1804
|
+
}
|
|
1805
|
+
const removed = reg.removeProject(p.id);
|
|
1806
|
+
const deleteFiles = new URL(r.url || "/", "http://x").searchParams.get("deleteFiles") === "1";
|
|
1807
|
+
const managedRoot = import_path11.default.resolve(SEMA_DOCS_ROOT) + import_path11.default.sep;
|
|
1808
|
+
if (deleteFiles && proj?.managedWorkingDir && !reg.hasWorkingDirReference(proj.workingDir) && import_path11.default.resolve(proj.workingDir).startsWith(managedRoot)) {
|
|
1809
|
+
await sm.dispatch("core.deleteProjectHistory", void 0, { projectPath: proj.workingDir });
|
|
1810
|
+
await trashDir(proj.workingDir);
|
|
1811
|
+
}
|
|
1812
|
+
sm.broadcastRegistry();
|
|
1813
|
+
return { removed: removed.length };
|
|
1814
|
+
});
|
|
1815
|
+
this.add("POST", "/api/projects/:id/reveal", async (_r, _s, p) => {
|
|
1816
|
+
const proj = reg.getProject(p.id);
|
|
1817
|
+
if (!proj) throw new Error("\u9879\u76EE\u4E0D\u5B58\u5728");
|
|
1818
|
+
await revealInFileManager(proj.workingDir);
|
|
1819
|
+
return true;
|
|
1820
|
+
});
|
|
1821
|
+
this.add("GET", "/api/projects/:id/input-history", (_r, _s, p) => {
|
|
1822
|
+
const proj = reg.getProject(p.id);
|
|
1823
|
+
if (!proj) throw new Error("\u9879\u76EE\u4E0D\u5B58\u5728");
|
|
1824
|
+
try {
|
|
1825
|
+
const semaRoot2 = process.env.SEMA_ROOT ? import_path11.default.resolve(process.env.SEMA_ROOT) : import_path11.default.dirname(WEBUI_HOME);
|
|
1826
|
+
const conf = JSON.parse(import_fs11.default.readFileSync(import_path11.default.join(semaRoot2, "projects.conf"), "utf8"));
|
|
1827
|
+
const h = conf?.[proj.workingDir]?.history;
|
|
1828
|
+
return Array.isArray(h) ? h.filter((x) => typeof x === "string" && !!x) : [];
|
|
1829
|
+
} catch {
|
|
1830
|
+
return [];
|
|
1831
|
+
}
|
|
1832
|
+
});
|
|
1833
|
+
const resolveScope = (id) => {
|
|
1834
|
+
if (id === "~skills") return { workingDir: userSkillsRoot() };
|
|
1835
|
+
const rec = reg.getSession(id) || reg.getProject(id);
|
|
1836
|
+
if (!rec) throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");
|
|
1837
|
+
return rec;
|
|
1838
|
+
};
|
|
1839
|
+
this.add("POST", "/api/sessions", async (_r, _s, _p, body) => sm.createSession({ projectId: body?.projectId || void 0 }));
|
|
1840
|
+
this.add("POST", "/api/sessions/:id/branch", async (_r, _s, p, body) => sm.branchSession(p.id, typeof body?.beforeMessageUuid === "string" ? body.beforeMessageUuid : void 0));
|
|
1841
|
+
this.add("GET", "/api/sessions/:id/snapshot", (_r, _s, p) => sm.getSnapshot(p.id));
|
|
1842
|
+
this.add("PATCH", "/api/sessions/:id", (_r, _s, p, body) => {
|
|
1843
|
+
const r = reg.updateSession(p.id, { title: String(body?.title || "") });
|
|
1844
|
+
sm.broadcastRegistry();
|
|
1845
|
+
return r;
|
|
1846
|
+
});
|
|
1847
|
+
this.add("DELETE", "/api/sessions/:id", async (_r, _s, p) => {
|
|
1848
|
+
const rec = reg.getSession(p.id);
|
|
1849
|
+
if (!rec) return true;
|
|
1850
|
+
this.tm?.killBySession(p.id);
|
|
1851
|
+
await sm.closeSession(p.id);
|
|
1852
|
+
reg.removeSession(p.id);
|
|
1853
|
+
const hasOtherRef = reg.hasWorkingDirReference(rec.workingDir);
|
|
1854
|
+
const managedRoot = import_path11.default.resolve(SEMA_DOCS_ROOT) + import_path11.default.sep;
|
|
1855
|
+
if ((rec.managedWorkingDir ?? !rec.projectId) && !hasOtherRef && import_path11.default.resolve(rec.workingDir).startsWith(managedRoot)) {
|
|
1856
|
+
await sm.dispatch("core.deleteProjectHistory", void 0, { projectPath: rec.workingDir });
|
|
1857
|
+
await trashDir(rec.workingDir);
|
|
1858
|
+
removeEmptyDateParent(rec.workingDir);
|
|
1859
|
+
} else {
|
|
1860
|
+
await sm.dispatch("core.deleteSessionHistory", void 0, { sessionId: rec.id, projectPath: rec.workingDir });
|
|
1861
|
+
}
|
|
1862
|
+
sm.broadcastRegistry();
|
|
1863
|
+
return true;
|
|
1864
|
+
});
|
|
1865
|
+
this.add("POST", "/api/sessions/:id/reveal", async (_r, _s, p) => {
|
|
1866
|
+
const rec = resolveScope(p.id);
|
|
1867
|
+
await revealInFileManager(rec.workingDir);
|
|
1868
|
+
return true;
|
|
1869
|
+
});
|
|
1870
|
+
this.add("POST", "/api/sessions/:id/reveal-file", async (_r, _s, p, body) => {
|
|
1871
|
+
const rec = resolveScope(p.id);
|
|
1872
|
+
const rel = String(body?.path || "");
|
|
1873
|
+
if (!rel) throw new Error("\u7F3A\u5C11 path");
|
|
1874
|
+
await revealInFileManager(resolvePath(rec.workingDir, rel).abs);
|
|
1875
|
+
return true;
|
|
1876
|
+
});
|
|
1877
|
+
this.add("POST", "/api/attachments/paste", async (_r, _s, _p, body) => savePastedText(String(body?.text ?? "")));
|
|
1878
|
+
this.add("POST", "/api/attachments/remove", async (_r, _s, _p, body) => {
|
|
1879
|
+
removePastedText(String(body?.path || ""));
|
|
1880
|
+
return true;
|
|
1881
|
+
});
|
|
1882
|
+
this.add("POST", "/api/sessions/:id/file", async (_r, _s, p, body) => {
|
|
1883
|
+
const rec = resolveScope(p.id);
|
|
1884
|
+
return readFileInDir(rec.workingDir, String(body?.path || ""));
|
|
1885
|
+
});
|
|
1886
|
+
this.add("POST", "/api/sessions/:id/files/stat", async (_r, _s, p, body) => {
|
|
1887
|
+
const rec = resolveScope(p.id);
|
|
1888
|
+
const paths = Array.isArray(body?.paths) ? body.paths.map(String) : [];
|
|
1889
|
+
return statPaths(rec.workingDir, paths);
|
|
1890
|
+
});
|
|
1891
|
+
this.add("GET", "/api/sessions/:id/raw", async (req, res, p) => {
|
|
1892
|
+
const rec = resolveScope(p.id);
|
|
1893
|
+
const q = new URL(req.url || "/", "http://x").searchParams;
|
|
1894
|
+
const { abs, size, mime } = rawFileInDir(rec.workingDir, q.get("path") || "");
|
|
1895
|
+
sendFile(res, abs, { "Content-Type": mime, "Content-Length": size, "Cache-Control": "no-cache", "X-Content-Type-Options": "nosniff" });
|
|
1896
|
+
return HANDLED;
|
|
1897
|
+
});
|
|
1898
|
+
this.add("POST", "/api/sessions/:id/ls", async (_r, _s, p, body) => {
|
|
1899
|
+
const rec = resolveScope(p.id);
|
|
1900
|
+
return listDir(rec.workingDir, String(body?.path || ""));
|
|
1901
|
+
});
|
|
1902
|
+
this.add("POST", "/api/sessions/:id/git-diff", async (_r, _s, p, body) => {
|
|
1903
|
+
const rec = resolveScope(p.id);
|
|
1904
|
+
if (body?.mode === "check") return gitRepoCheck(rec.workingDir);
|
|
1905
|
+
if (body?.mode === "file") return gitDiffFile(rec.workingDir, String(body?.path || ""));
|
|
1906
|
+
return gitDiffList(rec.workingDir);
|
|
1907
|
+
});
|
|
1908
|
+
this.add("POST", "/api/sessions/:id/terminals", async (_r, _s, p, body) => {
|
|
1909
|
+
if (!this.tm) throw new Error("\u7EC8\u7AEF\u4E0D\u53EF\u7528");
|
|
1910
|
+
const rec = resolveScope(p.id);
|
|
1911
|
+
return this.tm.create(p.id, rec.workingDir, Number(body?.cols) || 80, Number(body?.rows) || 24);
|
|
1912
|
+
});
|
|
1913
|
+
this.add("DELETE", "/api/terminals/:id", async (_r, _s, p) => {
|
|
1914
|
+
this.tm?.kill(p.id);
|
|
1915
|
+
return true;
|
|
1916
|
+
});
|
|
1917
|
+
this.add("POST", "/api/sessions/:id/open-file", async (_r, _s, p, body) => {
|
|
1918
|
+
const rec = resolveScope(p.id);
|
|
1919
|
+
const { abs } = resolvePath(rec.workingDir, String(body?.path || ""));
|
|
1920
|
+
const app = body?.app ? String(body.app) : "";
|
|
1921
|
+
if (IS_MAC2) await run("open", app ? ["-a", app, abs] : [abs]);
|
|
1922
|
+
else if (IS_WIN) await run("cmd", ["/c", "start", "", abs]);
|
|
1923
|
+
else await run("xdg-open", [abs]);
|
|
1924
|
+
return true;
|
|
1925
|
+
});
|
|
1926
|
+
this.add("POST", "/api/sessions/:id/open-with", async (_r, _s, p, body) => {
|
|
1927
|
+
const rec = resolveScope(p.id);
|
|
1928
|
+
return listOpenWithApps(resolvePath(rec.workingDir, String(body?.path || "")).abs);
|
|
1929
|
+
});
|
|
1930
|
+
this.add("GET", "/api/app-icon", async (req, res) => {
|
|
1931
|
+
const id = new URL(req.url || "/", "http://x").searchParams.get("id") || "";
|
|
1932
|
+
const file = appIconPath(id);
|
|
1933
|
+
if (!file) throw new Error("\u65E0\u56FE\u6807");
|
|
1934
|
+
sendFile(res, file, { "Content-Type": "image/png", "Cache-Control": "public, max-age=86400" });
|
|
1935
|
+
return HANDLED;
|
|
1936
|
+
});
|
|
1937
|
+
this.add("POST", "/api/files/search", async (_r, _s, _p, body) => {
|
|
1938
|
+
let dir;
|
|
1939
|
+
if (body?.sessionId) dir = resolveScope(String(body.sessionId)).workingDir;
|
|
1940
|
+
else if (body?.projectId) dir = reg.getProject(String(body.projectId))?.workingDir;
|
|
1941
|
+
if (!dir) throw new Error("\u4F1A\u8BDD\u6216\u9879\u76EE\u4E0D\u5B58\u5728");
|
|
1942
|
+
return searchFiles(dir, String(body?.query ?? ""), Number(body?.limit) || 50);
|
|
1943
|
+
});
|
|
1944
|
+
this.add("POST", "/api/open-external", async (_r, _s, _p, body) => {
|
|
1945
|
+
await openExternal(String(body?.url || ""));
|
|
1946
|
+
return true;
|
|
1947
|
+
});
|
|
1948
|
+
this.add("GET", "/api/favicon", async (req, res) => {
|
|
1949
|
+
const q = new URL(req.url || "/", "http://x").searchParams;
|
|
1950
|
+
const origin = q.get("origin") || "";
|
|
1951
|
+
const direct = q.get("url") || "";
|
|
1952
|
+
const cacheKey = direct || origin;
|
|
1953
|
+
if (direct ? !/^https?:\/\/[^/]+\//i.test(direct) : !/^https?:\/\/[^/]+$/i.test(origin)) throw new Error("bad url");
|
|
1954
|
+
let hit = faviconCache.get(cacheKey);
|
|
1955
|
+
if (!hit) {
|
|
1956
|
+
const ctl = new AbortController();
|
|
1957
|
+
const timer = setTimeout(() => ctl.abort(), 8e3);
|
|
1958
|
+
try {
|
|
1959
|
+
if (direct) hit = await fetchIcon(direct, ctl.signal).catch(() => null) || void 0;
|
|
1960
|
+
else {
|
|
1961
|
+
hit = await fetchIcon(`${origin}/favicon.ico`, ctl.signal).catch(() => null) || void 0;
|
|
1962
|
+
if (!hit) {
|
|
1963
|
+
const declared = (await fetchPageMeta(origin + "/")).icon;
|
|
1964
|
+
if (declared) hit = await fetchIcon(declared, ctl.signal).catch(() => null) || void 0;
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
if (!hit) throw new Error("no icon");
|
|
1968
|
+
} catch {
|
|
1969
|
+
hit = { type: "", buf: Buffer.alloc(0) };
|
|
1970
|
+
} finally {
|
|
1971
|
+
clearTimeout(timer);
|
|
1972
|
+
}
|
|
1973
|
+
faviconCache.set(cacheKey, hit);
|
|
1974
|
+
}
|
|
1975
|
+
if (!hit.buf.length) {
|
|
1976
|
+
json(res, 404, { ok: false, error: "no icon" });
|
|
1977
|
+
return HANDLED;
|
|
1978
|
+
}
|
|
1979
|
+
res.writeHead(200, { "Content-Type": hit.type, "Content-Length": hit.buf.length, "Cache-Control": "public, max-age=86400" });
|
|
1980
|
+
res.end(hit.buf);
|
|
1981
|
+
return HANDLED;
|
|
1982
|
+
});
|
|
1983
|
+
this.add("GET", "/api/cron", () => sm.listAllCron());
|
|
1984
|
+
this.add("POST", "/api/cron/:action", (_r, _s, p, body) => {
|
|
1985
|
+
if (p.action !== "delete" && p.action !== "enable" && p.action !== "disable") throw new Error(`\u672A\u77E5\u64CD\u4F5C: ${p.action}`);
|
|
1986
|
+
if (!body?.workingDir || !body?.id) throw new Error("\u7F3A\u5C11 workingDir / id");
|
|
1987
|
+
return sm.cronAction(String(body.workingDir), p.action, String(body.id));
|
|
1988
|
+
});
|
|
1989
|
+
this.add("GET", "/api/usage", () => sm.dispatch("core.getUsageStats", void 0, {}));
|
|
1990
|
+
this.add("POST", "/api/usage/clear", () => sm.dispatch("core.clearUsageStats", void 0, {}));
|
|
1991
|
+
this.add("GET", "/api/eco/catalog", () => listCatalog());
|
|
1992
|
+
const refreshSkills = () => {
|
|
1993
|
+
void sm.dispatch("core.refreshSkills", void 0, {}).catch(() => null);
|
|
1994
|
+
};
|
|
1995
|
+
const refreshMcp = () => {
|
|
1996
|
+
void sm.dispatch("core.refreshMCPServerInfo", void 0, {}).catch(() => null);
|
|
1997
|
+
};
|
|
1998
|
+
void installDefaultSkills(reg.getSettings().defaultSkillsInstalled || []).then((ids) => {
|
|
1999
|
+
if (!ids.length) return;
|
|
2000
|
+
reg.addDefaultSkillsInstalled(ids);
|
|
2001
|
+
refreshSkills();
|
|
2002
|
+
}).catch(() => null);
|
|
2003
|
+
this.add("POST", "/api/eco/install", async (_r, _s, _p, body) => {
|
|
2004
|
+
const id = String(body?.id || "");
|
|
2005
|
+
const r = await installResource(id, !!body?.overwrite);
|
|
2006
|
+
if (r === true) listCatalog().find((i) => i.id === id)?.kind === "skill" ? refreshSkills() : refreshMcp();
|
|
2007
|
+
return r;
|
|
2008
|
+
});
|
|
2009
|
+
this.add("POST", "/api/eco/uninstall", async (_r, _s, _p, body) => {
|
|
2010
|
+
const id = String(body?.id || "");
|
|
2011
|
+
const kind = listCatalog().find((i) => i.id === id)?.kind;
|
|
2012
|
+
const r = await uninstallResource(id);
|
|
2013
|
+
kind === "skill" ? refreshSkills() : refreshMcp();
|
|
2014
|
+
return r;
|
|
2015
|
+
});
|
|
2016
|
+
this.add("GET", "/api/eco/installed", () => listInstalled());
|
|
2017
|
+
const mapMcpStatus = (infos) => {
|
|
2018
|
+
const userKeys = new Set(Object.keys(readUserMcp().mcpServers || {}));
|
|
2019
|
+
return (infos || []).filter((i) => userKeys.has(i?.config?.name)).map((i) => ({
|
|
2020
|
+
id: i.config.name,
|
|
2021
|
+
connectStatus: i.connectStatus || "disconnected",
|
|
2022
|
+
error: i.error,
|
|
2023
|
+
// core 已拼好 "路径:起始行-结束行" 定位串(找不到范围时为纯路径),前端拿去打开文件窗口定位
|
|
2024
|
+
filePath: i.filePath,
|
|
2025
|
+
tools: i.capabilities?.tools ? i.capabilities.tools.map((t) => ({ name: t.name, description: t.description })) : void 0
|
|
2026
|
+
}));
|
|
2027
|
+
};
|
|
2028
|
+
this.add("POST", "/api/eco/installed/toggle", async (_r, _s, _p, body) => {
|
|
2029
|
+
if (body?.kind !== "skill" && body?.kind !== "mcp") throw new Error("kind \u5FC5\u987B\u662F skill / mcp");
|
|
2030
|
+
if (body.kind === "skill") return toggleInstalled("skill", String(body?.id || ""), !!body?.enabled);
|
|
2031
|
+
const infos = await sm.dispatch(body?.enabled ? "core.enableMCPServer" : "core.disableMCPServer", void 0, { name: String(body?.id || "") });
|
|
2032
|
+
refreshMcp();
|
|
2033
|
+
return mapMcpStatus(infos);
|
|
2034
|
+
});
|
|
2035
|
+
this.add("POST", "/api/eco/installed/remove", (_r, _s, _p, body) => {
|
|
2036
|
+
if (body?.kind !== "skill" && body?.kind !== "mcp") throw new Error("kind \u5FC5\u987B\u662F skill / mcp");
|
|
2037
|
+
const r = removeInstalled(body.kind, String(body?.id || ""));
|
|
2038
|
+
body.kind === "skill" ? refreshSkills() : refreshMcp();
|
|
2039
|
+
return r;
|
|
2040
|
+
});
|
|
2041
|
+
this.add("PUT", "/api/eco/installed/mcp", (_r, _s, _p, body) => {
|
|
2042
|
+
const r = updateMcpConfig(String(body?.id || ""), body?.config);
|
|
2043
|
+
refreshMcp();
|
|
2044
|
+
return r;
|
|
2045
|
+
});
|
|
2046
|
+
this.add("POST", "/api/eco/installed/mcp/tools", (_r, _s, _p, body) => listMcpTools(String(body?.id || ""), !!body?.refresh));
|
|
2047
|
+
this.add("PUT", "/api/eco/installed/mcp/use-tools", (_r, _s, _p, body) => {
|
|
2048
|
+
const r = updateMcpUseTools(String(body?.id || ""), body?.toolNames === null || body?.toolNames === void 0 ? null : body.toolNames);
|
|
2049
|
+
refreshMcp();
|
|
2050
|
+
return r;
|
|
2051
|
+
});
|
|
2052
|
+
this.add("GET", "/api/eco/installed/mcp/status", async () => mapMcpStatus(await sm.dispatch("core.getMCPServerInfo", void 0, {})));
|
|
2053
|
+
const browserControl = new BrowserControl(sm);
|
|
2054
|
+
this.add("GET", "/api/browser-control", () => browserControlState(!!reg.getSettings().enableBrowserControl));
|
|
2055
|
+
this.add("POST", "/api/browser-control", async (_r, _s, _p, body) => {
|
|
2056
|
+
const enabled = await browserControl.setEnabled(!!body?.enabled);
|
|
2057
|
+
refreshSkills();
|
|
2058
|
+
refreshMcp();
|
|
2059
|
+
return browserControlState(enabled);
|
|
2060
|
+
});
|
|
2061
|
+
this.add("POST", "/api/probe-url", async (_r, _s, _p, body) => probeEmbeddable(String(body?.url || "")));
|
|
2062
|
+
this.add("POST", "/api/page-meta", async (_r, _s, _p, body) => fetchPageMeta(String(body?.url || "")));
|
|
2063
|
+
}
|
|
2064
|
+
routes = [];
|
|
2065
|
+
add(method, pattern, handler) {
|
|
2066
|
+
const keys = [];
|
|
2067
|
+
const re = new RegExp("^" + pattern.replace(/:(\w+)/g, (_m, k) => {
|
|
2068
|
+
keys.push(k);
|
|
2069
|
+
return "([^/]+)";
|
|
2070
|
+
}) + "/?$");
|
|
2071
|
+
this.routes.push({ method, pattern: re, keys, handler });
|
|
2072
|
+
}
|
|
2073
|
+
/** 命中路由返回 true(已写响应);未命中返回 false */
|
|
2074
|
+
async handle(req, res, pathname) {
|
|
2075
|
+
for (const r of this.routes) {
|
|
2076
|
+
if (r.method !== req.method) continue;
|
|
2077
|
+
const m = r.pattern.exec(pathname);
|
|
2078
|
+
if (!m) continue;
|
|
2079
|
+
const params = {};
|
|
2080
|
+
r.keys.forEach((k, i) => {
|
|
2081
|
+
params[k] = decodeURIComponent(m[i + 1]);
|
|
2082
|
+
});
|
|
2083
|
+
try {
|
|
2084
|
+
let body = void 0;
|
|
2085
|
+
if (req.method !== "GET") body = await readJson3(req);
|
|
2086
|
+
const data = await r.handler(req, res, params, body);
|
|
2087
|
+
if (data !== HANDLED) json(res, 200, { ok: true, data });
|
|
2088
|
+
} catch (e) {
|
|
2089
|
+
json(res, 400, { ok: false, error: e?.message || String(e) });
|
|
2090
|
+
}
|
|
2091
|
+
return true;
|
|
2092
|
+
}
|
|
2093
|
+
return false;
|
|
2094
|
+
}
|
|
2095
|
+
};
|
|
2096
|
+
function sendFile(res, file, headers) {
|
|
2097
|
+
const stream = import_fs11.default.createReadStream(file);
|
|
2098
|
+
stream.on("open", () => {
|
|
2099
|
+
res.writeHead(200, headers);
|
|
2100
|
+
stream.pipe(res);
|
|
2101
|
+
});
|
|
2102
|
+
stream.on("error", (err) => {
|
|
2103
|
+
if (!res.headersSent) json(res, err.code === "ENOENT" ? 404 : 500, { ok: false, error: `\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25: ${err.message}` });
|
|
2104
|
+
else res.destroy();
|
|
2105
|
+
});
|
|
2106
|
+
res.on("close", () => stream.destroy());
|
|
2107
|
+
}
|
|
2108
|
+
function json(res, status2, data) {
|
|
2109
|
+
const buf = Buffer.from(JSON.stringify(data));
|
|
2110
|
+
res.writeHead(status2, { "Content-Type": "application/json; charset=utf-8", "Content-Length": buf.length, "Cache-Control": "no-store" });
|
|
2111
|
+
res.end(buf);
|
|
2112
|
+
}
|
|
2113
|
+
function readJson3(req) {
|
|
2114
|
+
return new Promise((resolve, reject) => {
|
|
2115
|
+
const chunks = [];
|
|
2116
|
+
let size = 0;
|
|
2117
|
+
req.on("data", (c) => {
|
|
2118
|
+
size += c.length;
|
|
2119
|
+
if (size > 20 * 1024 * 1024) {
|
|
2120
|
+
reject(new Error("body too large"));
|
|
2121
|
+
req.destroy();
|
|
2122
|
+
}
|
|
2123
|
+
chunks.push(c);
|
|
2124
|
+
});
|
|
2125
|
+
req.on("end", () => {
|
|
2126
|
+
const s = Buffer.concat(chunks).toString("utf8");
|
|
2127
|
+
if (!s) return resolve(void 0);
|
|
2128
|
+
try {
|
|
2129
|
+
resolve(JSON.parse(s));
|
|
2130
|
+
} catch {
|
|
2131
|
+
reject(new Error("invalid json"));
|
|
2132
|
+
}
|
|
2133
|
+
});
|
|
2134
|
+
req.on("error", reject);
|
|
2135
|
+
});
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
// ../server/src/server.ts
|
|
2139
|
+
var import_http = __toESM(require("http"));
|
|
2140
|
+
var import_fs16 = __toESM(require("fs"));
|
|
2141
|
+
var import_path15 = __toESM(require("path"));
|
|
2142
|
+
var import_ws3 = require("ws");
|
|
2143
|
+
|
|
2144
|
+
// ../server/src/sessions.ts
|
|
2145
|
+
var import_fs14 = __toESM(require("fs"));
|
|
2146
|
+
var import_path13 = __toESM(require("path"));
|
|
2147
|
+
var import_crypto3 = require("crypto");
|
|
2148
|
+
var import_events2 = require("events");
|
|
2149
|
+
|
|
2150
|
+
// ../server/src/workers/pool.ts
|
|
2151
|
+
var import_child_process6 = require("child_process");
|
|
2152
|
+
var import_worker_threads = require("worker_threads");
|
|
2153
|
+
var import_fs12 = __toESM(require("fs"));
|
|
2154
|
+
var import_events = require("events");
|
|
2155
|
+
var WORKER_MODE = process.env.SEMA_WEBUI_WORKER_MODE === "process" ? "process" : "thread";
|
|
2156
|
+
function spawnThread(entryPath, workingDir, coreConfig) {
|
|
2157
|
+
const worker = new import_worker_threads.Worker(entryPath, {
|
|
2158
|
+
workerData: { workingDir, coreConfig },
|
|
2159
|
+
// 共享进程的真实环境变量而不是拷贝:Node 给线程拷出来的 env 是大小写敏感的 map,Windows 上 process.env.PATH / SYSTEMROOT
|
|
2160
|
+
// 会读不到系统存成 Path / SystemRoot 的键(core 的 ComSpec / ProgramFiles 读取、MCP SDK 继承给子进程的 PATH 都受影响);
|
|
2161
|
+
// 共享后与进程模式的视图一致。core 不写 process.env,共享无副作用
|
|
2162
|
+
env: import_worker_threads.SHARE_ENV,
|
|
2163
|
+
// true = 不自动透传到父进程 stdout/stderr;下面 resume 把流排空丢掉(不消费会在内存里积压)
|
|
2164
|
+
stdout: true,
|
|
2165
|
+
stderr: true
|
|
2166
|
+
// 不设 resourceLimits:线程默认堆上限与主线程相同(Node 22 / Electron 44 实测一致),和进程模式等价;超限只结束该线程
|
|
2167
|
+
});
|
|
2168
|
+
worker.stdout.resume();
|
|
2169
|
+
worker.stderr.resume();
|
|
2170
|
+
const post = (msg) => worker.postMessage(JSON.stringify(msg));
|
|
2171
|
+
return {
|
|
2172
|
+
id: `t${worker.threadId}`,
|
|
2173
|
+
send: post,
|
|
2174
|
+
on: (event, fn) => {
|
|
2175
|
+
if (event === "message") worker.on("message", (raw) => fn(typeof raw === "string" ? JSON.parse(raw) : raw));
|
|
2176
|
+
else worker.on(event, fn);
|
|
2177
|
+
},
|
|
2178
|
+
requestExit: () => post({ type: "dispose" }),
|
|
2179
|
+
forceKill: () => {
|
|
2180
|
+
void worker.terminate();
|
|
2181
|
+
}
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
function spawnProcess(entryPath, workingDir, coreConfig) {
|
|
2185
|
+
const child = (0, import_child_process6.fork)(entryPath, [], {
|
|
2186
|
+
cwd: workingDir,
|
|
2187
|
+
env: {
|
|
2188
|
+
...process.env,
|
|
2189
|
+
SEMA_WEBUI_WORKING_DIR: workingDir,
|
|
2190
|
+
SEMA_WEBUI_CORE_CONFIG: JSON.stringify(coreConfig),
|
|
2191
|
+
// 宿主是 Electron 时 fork 用的是 Electron 二进制,显式让子进程按纯 Node 运行
|
|
2192
|
+
...process.versions.electron ? { ELECTRON_RUN_AS_NODE: "1" } : {}
|
|
2193
|
+
},
|
|
2194
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
2195
|
+
// 脱离前台进程组:Ctrl+C 的 SIGINT 只打到主进程,worker 及其 MCP 子进程
|
|
2196
|
+
// 统一走 disconnect → core.dispose() 优雅关闭(主进程被 SIGKILL 时 IPC 断开同样触发)
|
|
2197
|
+
detached: true
|
|
2198
|
+
});
|
|
2199
|
+
return {
|
|
2200
|
+
id: String(child.pid),
|
|
2201
|
+
send: (msg) => {
|
|
2202
|
+
child.send(msg);
|
|
2203
|
+
},
|
|
2204
|
+
on: (event, fn) => {
|
|
2205
|
+
child.on(event, fn);
|
|
2206
|
+
},
|
|
2207
|
+
// disconnect 后 IPC 通道立即不可用;通道已坏时直接 SIGKILL
|
|
2208
|
+
requestExit: () => {
|
|
2209
|
+
try {
|
|
2210
|
+
child.disconnect();
|
|
2211
|
+
} catch {
|
|
2212
|
+
try {
|
|
2213
|
+
child.kill("SIGKILL");
|
|
2214
|
+
} catch {
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
},
|
|
2218
|
+
forceKill: () => {
|
|
2219
|
+
try {
|
|
2220
|
+
child.kill("SIGKILL");
|
|
2221
|
+
} catch {
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
var CRON_IDLE_GUARD_MS = 10 * 6e4;
|
|
2227
|
+
var CRON_STALE_GUARD_MS = 2 * 6e4;
|
|
2228
|
+
var WorkerPool = class extends import_events.EventEmitter {
|
|
2229
|
+
constructor(opts) {
|
|
2230
|
+
super();
|
|
2231
|
+
this.opts = opts;
|
|
2232
|
+
this.timer = setInterval(() => this.reap(), 6e4);
|
|
2233
|
+
this.timer.unref?.();
|
|
2234
|
+
}
|
|
2235
|
+
workers = /* @__PURE__ */ new Map();
|
|
2236
|
+
pending = /* @__PURE__ */ new Map();
|
|
2237
|
+
seq = 0;
|
|
2238
|
+
timer;
|
|
2239
|
+
get size() {
|
|
2240
|
+
return this.workers.size;
|
|
2241
|
+
}
|
|
2242
|
+
list() {
|
|
2243
|
+
return [...this.workers.values()];
|
|
2244
|
+
}
|
|
2245
|
+
get(workingDir) {
|
|
2246
|
+
return this.workers.get(workingDir);
|
|
2247
|
+
}
|
|
2248
|
+
/** 硬上限(clamp 到 [2,16],缺省 8) */
|
|
2249
|
+
maxWorkers() {
|
|
2250
|
+
const v = Math.floor(this.opts.maxWorkers?.() ?? 8);
|
|
2251
|
+
return Math.min(16, Math.max(2, v || 8));
|
|
2252
|
+
}
|
|
2253
|
+
/** 计入上限的 worker 数(豁免目录不算) */
|
|
2254
|
+
countedSize() {
|
|
2255
|
+
let n = 0;
|
|
2256
|
+
for (const w of this.workers.values()) if (!this.opts.exemptDirs?.has(w.workingDir)) n++;
|
|
2257
|
+
return n;
|
|
2258
|
+
}
|
|
2259
|
+
/** 未触顶(预热类调用用:不为预热去淘汰别人) */
|
|
2260
|
+
hasCapacity() {
|
|
2261
|
+
return this.countedSize() < this.maxWorkers();
|
|
2262
|
+
}
|
|
2263
|
+
/** 获取或拉起 worker */
|
|
2264
|
+
async acquire(workingDir) {
|
|
2265
|
+
if (!import_fs12.default.existsSync(workingDir)) throw new Error(`\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728: ${workingDir}`);
|
|
2266
|
+
let w = this.workers.get(workingDir);
|
|
2267
|
+
if (w && w.alive && !import_fs12.default.existsSync(w.workingDir)) {
|
|
2268
|
+
void this.kill(w);
|
|
2269
|
+
w = void 0;
|
|
2270
|
+
}
|
|
2271
|
+
if (w && w.alive) {
|
|
2272
|
+
w.lastUsed = Date.now();
|
|
2273
|
+
await w.ready;
|
|
2274
|
+
return w;
|
|
2275
|
+
}
|
|
2276
|
+
if (!this.opts.exemptDirs?.has(workingDir)) {
|
|
2277
|
+
while (this.countedSize() >= this.maxWorkers()) {
|
|
2278
|
+
if (!await this.evictOne()) {
|
|
2279
|
+
throw new Error(`\u5DF2\u8FBE worker \u4E0A\u9650(${this.maxWorkers()})\u4E14\u5747\u5728\u5904\u7406\u6216\u6709\u8FD0\u884C\u4E2D\u4EFB\u52A1\uFF0C\u8BF7\u7B49\u5F85\u5176\u4ED6\u4F1A\u8BDD\u5B8C\u6210\u6216\u5173\u95ED\u90E8\u5206\u4F1A\u8BDD`);
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
w = this.workers.get(workingDir);
|
|
2283
|
+
if (w && w.alive) {
|
|
2284
|
+
w.lastUsed = Date.now();
|
|
2285
|
+
await w.ready;
|
|
2286
|
+
return w;
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
w = this.spawn(workingDir);
|
|
2290
|
+
this.workers.set(workingDir, w);
|
|
2291
|
+
await w.ready;
|
|
2292
|
+
return w;
|
|
2293
|
+
}
|
|
2294
|
+
spawn(workingDir) {
|
|
2295
|
+
const coreConfig = this.opts.getCoreConfig();
|
|
2296
|
+
const backend = WORKER_MODE === "thread" ? spawnThread(this.opts.entryPath, workingDir, coreConfig) : spawnProcess(this.opts.entryPath, workingDir, coreConfig);
|
|
2297
|
+
let resolveReady;
|
|
2298
|
+
let rejectReady;
|
|
2299
|
+
const handle = {
|
|
2300
|
+
workingDir,
|
|
2301
|
+
id: backend.id,
|
|
2302
|
+
backend,
|
|
2303
|
+
sessions: /* @__PURE__ */ new Set(),
|
|
2304
|
+
lastUsed: Date.now(),
|
|
2305
|
+
stale: false,
|
|
2306
|
+
alive: true,
|
|
2307
|
+
ready: new Promise((resolve, reject) => {
|
|
2308
|
+
resolveReady = resolve;
|
|
2309
|
+
rejectReady = reject;
|
|
2310
|
+
})
|
|
2311
|
+
};
|
|
2312
|
+
handle.ready.catch(() => {
|
|
2313
|
+
});
|
|
2314
|
+
backend.on("message", (m) => {
|
|
2315
|
+
if (!m) return;
|
|
2316
|
+
if (m.type === "ready") {
|
|
2317
|
+
resolveReady();
|
|
2318
|
+
} else if (m.type === "res") {
|
|
2319
|
+
const p = this.pending.get(m.id);
|
|
2320
|
+
if (p) {
|
|
2321
|
+
this.pending.delete(m.id);
|
|
2322
|
+
clearTimeout(p.timer);
|
|
2323
|
+
m.ok ? p.resolve(m.data) : p.reject(new Error(m.error || "worker error"));
|
|
2324
|
+
}
|
|
2325
|
+
} else if (m.type === "event") {
|
|
2326
|
+
this.emit("event", workingDir, m.sessionId, m.event, m.data);
|
|
2327
|
+
} else if (m.type === "proc-event") {
|
|
2328
|
+
this.emit("proc-event", workingDir, m.event, m.data);
|
|
2329
|
+
} else if (m.type === "error") {
|
|
2330
|
+
logErr("pool", `worker id=${backend.id} \u542F\u52A8\u5931\u8D25 dir=${workingDir}: ${m.message}`);
|
|
2331
|
+
}
|
|
2332
|
+
});
|
|
2333
|
+
backend.on("error", (err) => {
|
|
2334
|
+
logErr("pool", `worker id=${backend.id} \u9519\u8BEF dir=${workingDir}:`, err?.message || err);
|
|
2335
|
+
this.rejectPending(backend.id, err instanceof Error ? err : new Error(String(err)));
|
|
2336
|
+
});
|
|
2337
|
+
backend.on("exit", (code) => {
|
|
2338
|
+
handle.alive = false;
|
|
2339
|
+
rejectReady(new Error(`worker exited before ready (code ${code})`));
|
|
2340
|
+
if (code && code !== 0) logErr("pool", `worker id=${backend.id} \u5F02\u5E38\u9000\u51FA code=${code} dir=${workingDir}\uFF08\u82E5\u76EE\u5F55\u5DF2\u88AB\u5220\u9664/\u79FB\u5165\u5E9F\u7EB8\u7BD3\uFF0C\u8BF7\u5220\u9664\u5BF9\u5E94\u4F1A\u8BDD\u6216\u91CD\u65B0\u521B\u5EFA\uFF09`);
|
|
2341
|
+
if (this.workers.get(workingDir) === handle) this.workers.delete(workingDir);
|
|
2342
|
+
this.rejectPending(backend.id, new Error("worker exited"));
|
|
2343
|
+
this.emit("exit", workingDir, [...handle.sessions], code);
|
|
2344
|
+
});
|
|
2345
|
+
return handle;
|
|
2346
|
+
}
|
|
2347
|
+
/** 让某个 worker 的全部未决请求失败 */
|
|
2348
|
+
rejectPending(workerId, err) {
|
|
2349
|
+
for (const [id, p] of this.pending) {
|
|
2350
|
+
if (id.startsWith(`${workerId}:`)) {
|
|
2351
|
+
this.pending.delete(id);
|
|
2352
|
+
clearTimeout(p.timer);
|
|
2353
|
+
p.reject(err);
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
/** 向 worker 发请求;opts.bump=false 时不刷新 lastUsed(池内部的巡检查询,不影响 LRU/空闲判定) */
|
|
2358
|
+
request(w, action, sessionId, payload, timeoutMs = 12e4, opts) {
|
|
2359
|
+
if (!w.alive) return Promise.reject(new Error("worker not alive"));
|
|
2360
|
+
if (opts?.bump !== false) w.lastUsed = Date.now();
|
|
2361
|
+
const id = `${w.id}:${++this.seq}`;
|
|
2362
|
+
return new Promise((resolve, reject) => {
|
|
2363
|
+
const timer = setTimeout(() => {
|
|
2364
|
+
this.pending.delete(id);
|
|
2365
|
+
reject(new Error(`worker request timeout: ${action}`));
|
|
2366
|
+
}, timeoutMs);
|
|
2367
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
2368
|
+
w.backend.send({ type: "req", id, action, sessionId, payload });
|
|
2369
|
+
});
|
|
2370
|
+
}
|
|
2371
|
+
/** 关闭 worker(优雅:请求 worker 自行 dispose 后退出,5 秒未退出则强制结束);resolve 于 worker 真正退出 */
|
|
2372
|
+
kill(w) {
|
|
2373
|
+
if (!w.alive) return Promise.resolve();
|
|
2374
|
+
w.alive = false;
|
|
2375
|
+
if (this.workers.get(w.workingDir) === w) this.workers.delete(w.workingDir);
|
|
2376
|
+
const exited = new Promise((resolve) => w.backend.on("exit", () => resolve()));
|
|
2377
|
+
w.backend.requestExit();
|
|
2378
|
+
const t = setTimeout(() => w.backend.forceKill(), 5e3);
|
|
2379
|
+
t.unref?.();
|
|
2380
|
+
return exited.then(() => clearTimeout(t));
|
|
2381
|
+
}
|
|
2382
|
+
/** 空闲 = 无 processing、无未决交互请求的会话(订阅不算忙:worker 回收后按需恢复) */
|
|
2383
|
+
isIdle(w) {
|
|
2384
|
+
for (const sid of w.sessions) {
|
|
2385
|
+
if (this.opts.isSessionBusy(sid)) return false;
|
|
2386
|
+
}
|
|
2387
|
+
return true;
|
|
2388
|
+
}
|
|
2389
|
+
/** 查询 worker 守护信息(查询失败视为无守护:无响应的 worker 本就该回收) */
|
|
2390
|
+
async guardOf(w) {
|
|
2391
|
+
try {
|
|
2392
|
+
const stats = await this.request(w, "worker.stats", void 0, {}, 5e3, { bump: false });
|
|
2393
|
+
const running = Object.values(stats?.runningTasks || {}).some((n) => Number(n) > 0);
|
|
2394
|
+
const cron = stats?.cron || {};
|
|
2395
|
+
const nonPersisted = Object.values(cron.nonPersisted || {}).some((n) => Number(n) > 0);
|
|
2396
|
+
return { busy: running || nonPersisted, cronWeak: !nonPersisted && Number(cron.active) > 0, nextFireAt: cron.nextFireAt ?? null };
|
|
2397
|
+
} catch {
|
|
2398
|
+
return { busy: false, cronWeak: false, nextFireAt: null };
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* 尝试回收一个空闲 worker;成功回收返回 true。
|
|
2403
|
+
* - busy(后台任务 / 非持久化定时任务):不回收
|
|
2404
|
+
* - cronWeak(仅持久化定时任务):距触发不足 guardMs 不回收;回收后通知 onCronWorkerReclaimed(keeper 临近触发再拉起)
|
|
2405
|
+
*/
|
|
2406
|
+
async tryReclaim(w, reason, guardMs) {
|
|
2407
|
+
if (!w.alive || !this.isIdle(w)) return false;
|
|
2408
|
+
const g = await this.guardOf(w);
|
|
2409
|
+
if (g.busy) return false;
|
|
2410
|
+
if (g.cronWeak && g.nextFireAt != null && g.nextFireAt - Date.now() < guardMs) return false;
|
|
2411
|
+
if (!w.alive || !this.isIdle(w)) return false;
|
|
2412
|
+
const sids = [...w.sessions];
|
|
2413
|
+
await this.kill(w);
|
|
2414
|
+
if (g.cronWeak) this.opts.onCronWorkerReclaimed?.(w.workingDir, sids, reason);
|
|
2415
|
+
return true;
|
|
2416
|
+
}
|
|
2417
|
+
/**
|
|
2418
|
+
* 标记除 except 外所有 worker 为 stale,空闲者立即重启(实际是杀掉,下次按需拉起)。
|
|
2419
|
+
* 持久化定时任务 worker:距触发不足 2 分钟先不动,触发完由 reap 按 stale 重启;非持久化任务 worker 保持 stale,等降级后再处理
|
|
2420
|
+
*/
|
|
2421
|
+
markStale(except) {
|
|
2422
|
+
for (const w of this.workers.values()) {
|
|
2423
|
+
if (w === except) continue;
|
|
2424
|
+
w.stale = true;
|
|
2425
|
+
if (this.isIdle(w)) void this.tryReclaim(w, "stale", CRON_STALE_GUARD_MS);
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* 淘汰一个最久未用且可回收的 worker(豁免目录除外);无可回收返回 false。
|
|
2430
|
+
* 两轮:先只淘汰无定时任务的;都不行再淘汰只有持久化定时任务的(触顶场景下不看临近触发,由 keeper 补拉)
|
|
2431
|
+
*/
|
|
2432
|
+
async evictOne() {
|
|
2433
|
+
const candidates = [...this.workers.values()].filter((w) => w.alive && !this.opts.exemptDirs?.has(w.workingDir) && this.isIdle(w)).sort((a, b) => a.lastUsed - b.lastUsed);
|
|
2434
|
+
for (const w of candidates) {
|
|
2435
|
+
if (await this.tryReclaim(w, "evict", Infinity)) return true;
|
|
2436
|
+
}
|
|
2437
|
+
for (const w of candidates) {
|
|
2438
|
+
if (await this.tryReclaim(w, "evict", -Infinity)) return true;
|
|
2439
|
+
}
|
|
2440
|
+
return false;
|
|
2441
|
+
}
|
|
2442
|
+
reap() {
|
|
2443
|
+
const now = Date.now();
|
|
2444
|
+
const idleMs = this.opts.idleMs ?? 30 * 6e4;
|
|
2445
|
+
for (const w of this.workers.values()) {
|
|
2446
|
+
if (!this.isIdle(w)) continue;
|
|
2447
|
+
if (w.stale) void this.tryReclaim(w, "stale", CRON_STALE_GUARD_MS);
|
|
2448
|
+
else if (now - w.lastUsed > idleMs) void this.tryReclaim(w, "idle", CRON_IDLE_GUARD_MS);
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
async disposeAll() {
|
|
2452
|
+
clearInterval(this.timer);
|
|
2453
|
+
await Promise.all([...this.workers.values()].map((w) => this.kill(w)));
|
|
2454
|
+
this.workers.clear();
|
|
2455
|
+
}
|
|
2456
|
+
};
|
|
2457
|
+
|
|
2458
|
+
// ../shared/protocol.ts
|
|
2459
|
+
var SERVER_EVENTS = {
|
|
2460
|
+
registryUpdate: "registry:update",
|
|
2461
|
+
modelUpdate: "model:update",
|
|
2462
|
+
settingsUpdate: "settings:update",
|
|
2463
|
+
/** 会话事件缓冲不足,前端需重新拉快照 */
|
|
2464
|
+
sessionResync: "session:resync",
|
|
2465
|
+
/** 存活会话列表变化(worker 拉起/退出/会话回收) */
|
|
2466
|
+
livenessUpdate: "liveness:update"
|
|
2467
|
+
};
|
|
2468
|
+
var CORE_ACTIONS = [
|
|
2469
|
+
"core.getModelData",
|
|
2470
|
+
"core.switchModel",
|
|
2471
|
+
"core.addModel",
|
|
2472
|
+
"core.delModel",
|
|
2473
|
+
"core.getModelProfile",
|
|
2474
|
+
"core.applyTaskModel",
|
|
2475
|
+
"core.addImageModel",
|
|
2476
|
+
"core.delImageModel",
|
|
2477
|
+
"core.switchImageModel",
|
|
2478
|
+
"core.getImageModelProfile",
|
|
2479
|
+
"core.testApiConnection",
|
|
2480
|
+
"core.fetchAvailableModels",
|
|
2481
|
+
"core.getToolInfos",
|
|
2482
|
+
"core.getModelAdapter",
|
|
2483
|
+
"core.getCommandsInfo"
|
|
2484
|
+
];
|
|
2485
|
+
var PROJECT_ACTIONS = [
|
|
2486
|
+
"project.warm",
|
|
2487
|
+
"project.getCommandsInfo",
|
|
2488
|
+
"draft.warm"
|
|
2489
|
+
];
|
|
2490
|
+
var SESSION_ACTIONS = [
|
|
2491
|
+
"session.subscribe",
|
|
2492
|
+
"session.unsubscribe",
|
|
2493
|
+
"session.warm",
|
|
2494
|
+
"session.processUserInput",
|
|
2495
|
+
"session.interrupt",
|
|
2496
|
+
"session.respondToToolPermission",
|
|
2497
|
+
"session.respondToPickOption",
|
|
2498
|
+
"session.respondToPlanExit",
|
|
2499
|
+
"session.updateAgentMode",
|
|
2500
|
+
"session.updatePermissionLevel",
|
|
2501
|
+
"session.getForkPreview",
|
|
2502
|
+
"session.fork",
|
|
2503
|
+
"session.getCommandsInfo",
|
|
2504
|
+
"session.getCronTasks",
|
|
2505
|
+
"session.getMemoryInfo",
|
|
2506
|
+
"session.deleteCronTask",
|
|
2507
|
+
"session.enableCronTask",
|
|
2508
|
+
"session.disableCronTask"
|
|
2509
|
+
];
|
|
2510
|
+
var MAIN_AGENT_ID = "main";
|
|
2511
|
+
var FILE_EDIT_TOOLS = /* @__PURE__ */ new Set(["write_file", "patch_file", "edit_notebook"]);
|
|
2512
|
+
var CRON_TOOLS = /* @__PURE__ */ new Set(["create_cron", "del_cron"]);
|
|
2513
|
+
|
|
2514
|
+
// ../shared/paste.ts
|
|
2515
|
+
var PASTE_HEADER = "# Files pasted by the user:";
|
|
2516
|
+
var PASTE_REQUEST = "## My request:";
|
|
2517
|
+
var PASTE_LINE_RE = /^## "(.*)": @(?:"([^"]*[\\/]attachments[\\/][^\\/"]+[\\/]pasted-text\.txt)"|(\S+[\\/]attachments[\\/][^\\/\s]+[\\/]pasted-text\.txt))$/;
|
|
2518
|
+
function parsePasteInput(input) {
|
|
2519
|
+
if (!input.startsWith(PASTE_HEADER)) return void 0;
|
|
2520
|
+
const lines = input.split("\n");
|
|
2521
|
+
const end = lines.indexOf(PASTE_REQUEST);
|
|
2522
|
+
if (end < 0) return void 0;
|
|
2523
|
+
const out = [];
|
|
2524
|
+
for (const line of lines.slice(1, end)) {
|
|
2525
|
+
const m = line.match(PASTE_LINE_RE);
|
|
2526
|
+
if (m) out.push({ preview: m[1], path: m[2] ?? m[3] });
|
|
2527
|
+
}
|
|
2528
|
+
return out.length ? out : void 0;
|
|
2529
|
+
}
|
|
2530
|
+
|
|
2531
|
+
// ../shared/transcript.ts
|
|
2532
|
+
function createSnapshot(init) {
|
|
2533
|
+
return {
|
|
2534
|
+
...init,
|
|
2535
|
+
seq: 0,
|
|
2536
|
+
state: "idle",
|
|
2537
|
+
todos: [],
|
|
2538
|
+
blocks: [],
|
|
2539
|
+
turn: null
|
|
2540
|
+
};
|
|
2541
|
+
}
|
|
2542
|
+
function updateIn(blocks, pred, fn) {
|
|
2543
|
+
for (let i = blocks.length - 1; i >= 0; i--) {
|
|
2544
|
+
const b = blocks[i];
|
|
2545
|
+
if (pred(b)) {
|
|
2546
|
+
const next = blocks.slice();
|
|
2547
|
+
next[i] = fn(b);
|
|
2548
|
+
return { blocks: next, hit: true };
|
|
2549
|
+
}
|
|
2550
|
+
if (b.kind === "agent") {
|
|
2551
|
+
const r = updateIn(b.blocks, pred, fn);
|
|
2552
|
+
if (r.hit) {
|
|
2553
|
+
const next = blocks.slice();
|
|
2554
|
+
next[i] = { ...b, blocks: r.blocks };
|
|
2555
|
+
return { blocks: next, hit: true };
|
|
2556
|
+
}
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
return { blocks, hit: false };
|
|
2560
|
+
}
|
|
2561
|
+
function updateBlock(snap, pred, fn) {
|
|
2562
|
+
const r = updateIn(snap.blocks, pred, fn);
|
|
2563
|
+
if (r.hit) snap.blocks = r.blocks;
|
|
2564
|
+
return r.hit;
|
|
2565
|
+
}
|
|
2566
|
+
function pushBlock(snap, block, agentId) {
|
|
2567
|
+
if (agentId && agentId !== MAIN_AGENT_ID) {
|
|
2568
|
+
const hit = updateBlock(
|
|
2569
|
+
snap,
|
|
2570
|
+
(b) => b.kind === "agent" && b.id === agentId,
|
|
2571
|
+
(b) => ({ ...b, blocks: [...b.blocks, block] })
|
|
2572
|
+
);
|
|
2573
|
+
if (hit) return;
|
|
2574
|
+
}
|
|
2575
|
+
snap.blocks = [...snap.blocks, block];
|
|
2576
|
+
}
|
|
2577
|
+
function dropPendingUser(snap) {
|
|
2578
|
+
if (snap.blocks.some((b) => b.kind === "user" && b.pending)) {
|
|
2579
|
+
snap.blocks = snap.blocks.filter((b) => !(b.kind === "user" && b.pending));
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
function notice(snap, seq, noticeType, level, text, detail, agentId) {
|
|
2583
|
+
pushBlock(snap, { kind: "notice", id: `notice:${seq}`, ts: Date.now(), noticeType, level, text, detail }, agentId);
|
|
2584
|
+
}
|
|
2585
|
+
function countPatch(patch) {
|
|
2586
|
+
let additions = 0, removals = 0;
|
|
2587
|
+
for (const h of patch || []) {
|
|
2588
|
+
let a = 0;
|
|
2589
|
+
for (const l of h.lines || []) {
|
|
2590
|
+
if (l.startsWith("+")) a++;
|
|
2591
|
+
else if (l.startsWith("-")) removals++;
|
|
2592
|
+
}
|
|
2593
|
+
additions += h.oldLines === 0 && typeof h.newLines === "number" && h.newLines > a ? h.newLines : a;
|
|
2594
|
+
}
|
|
2595
|
+
return { additions, removals };
|
|
2596
|
+
}
|
|
2597
|
+
function mergeFileChange(snap, toolName, title, content, cumulative) {
|
|
2598
|
+
if (snap.workingDir && /^\.\.[\\/]/.test(title)) {
|
|
2599
|
+
const stack = [];
|
|
2600
|
+
for (const seg of `${snap.workingDir}/${title}`.split(/[\\/]+/)) {
|
|
2601
|
+
if (seg === "..") stack.pop();
|
|
2602
|
+
else if (seg && seg !== ".") stack.push(seg);
|
|
2603
|
+
}
|
|
2604
|
+
title = (/^[a-zA-Z]:$/.test(stack[0]) ? "" : "/") + stack.join("/");
|
|
2605
|
+
}
|
|
2606
|
+
if (!snap.turn) snap.turn = { files: {} };
|
|
2607
|
+
const prev = snap.turn.files[title];
|
|
2608
|
+
const cum = cumulative && typeof cumulative === "object" && Array.isArray(cumulative.patch) ? cumulative : null;
|
|
2609
|
+
if (cum) {
|
|
2610
|
+
const { additions: additions2, removals: removals2 } = countPatch(cum.patch);
|
|
2611
|
+
const change2 = {
|
|
2612
|
+
path: title,
|
|
2613
|
+
toolName,
|
|
2614
|
+
type: cum.type === "new" ? "new" : "diff",
|
|
2615
|
+
additions: additions2,
|
|
2616
|
+
removals: removals2,
|
|
2617
|
+
patch: cum.patch,
|
|
2618
|
+
cumulative: true,
|
|
2619
|
+
...cum.sessionPatch ? { sessionPatch: cum.sessionPatch, sessionType: cum.sessionType === "new" ? "new" : "diff" } : {},
|
|
2620
|
+
...cum.sessionDropped || prev?.sessionDropped ? { sessionDropped: true } : {}
|
|
2621
|
+
};
|
|
2622
|
+
snap.turn = { ...snap.turn, files: { ...snap.turn.files, [title]: change2 } };
|
|
2623
|
+
return;
|
|
2624
|
+
}
|
|
2625
|
+
const diff = content && typeof content === "object" && Array.isArray(content.patch) ? content : null;
|
|
2626
|
+
const { additions, removals } = countPatch(diff?.patch);
|
|
2627
|
+
const diffText = typeof diff?.diffText === "string" && diff.diffText || void 0;
|
|
2628
|
+
const change = prev ? {
|
|
2629
|
+
...prev,
|
|
2630
|
+
toolName,
|
|
2631
|
+
additions: prev.additions + additions,
|
|
2632
|
+
removals: prev.removals + removals,
|
|
2633
|
+
patch: [...prev.patch, ...diff?.patch || []],
|
|
2634
|
+
diffText: prev.diffText || diffText,
|
|
2635
|
+
cumulative: void 0,
|
|
2636
|
+
sessionPatch: void 0,
|
|
2637
|
+
sessionType: void 0,
|
|
2638
|
+
sessionDropped: true
|
|
2639
|
+
} : { path: title, toolName, type: diff?.type === "new" ? "new" : "diff", additions, removals, patch: diff?.patch || [], diffText, sessionDropped: true };
|
|
2640
|
+
snap.turn = { ...snap.turn, files: { ...snap.turn.files, [title]: change } };
|
|
2641
|
+
}
|
|
2642
|
+
function finishTurn(snap, seq) {
|
|
2643
|
+
if (snap.turn) {
|
|
2644
|
+
const files = Object.values(snap.turn.files);
|
|
2645
|
+
if (files.length) {
|
|
2646
|
+
pushBlock(snap, { kind: "file-changes", id: `files:${seq}`, ts: Date.now(), inputId: snap.turn.inputId, files });
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
snap.turn = null;
|
|
2650
|
+
}
|
|
2651
|
+
function closeStreaming(snap) {
|
|
2652
|
+
if (!snap.streamingId) return;
|
|
2653
|
+
const id = snap.streamingId;
|
|
2654
|
+
updateBlock(snap, (b) => b.kind === "assistant" && b.id === id, (b) => ({ ...b, done: true }));
|
|
2655
|
+
snap.streamingId = void 0;
|
|
2656
|
+
}
|
|
2657
|
+
function voidPending(snap) {
|
|
2658
|
+
const now = Date.now();
|
|
2659
|
+
const mark = (blocks) => blocks.map((b) => {
|
|
2660
|
+
if (b.kind === "permission" && !b.resolved) return { ...b, resolved: "__interrupted", resolvedTs: now };
|
|
2661
|
+
if (b.kind === "pick" && !b.answered) return { ...b, answered: true, resolved: null, resolvedTs: now };
|
|
2662
|
+
if (b.kind === "plan-exit" && !b.resolved) return { ...b, resolved: "__interrupted", resolvedTs: now };
|
|
2663
|
+
if (b.kind === "agent") return { ...b, blocks: mark(b.blocks) };
|
|
2664
|
+
return b;
|
|
2665
|
+
});
|
|
2666
|
+
snap.blocks = mark(snap.blocks);
|
|
2667
|
+
}
|
|
2668
|
+
function toAttachmentMetas(raw) {
|
|
2669
|
+
if (!Array.isArray(raw) || raw.length === 0) return void 0;
|
|
2670
|
+
return raw.map((a) => ({ media_type: a.media_type, dataUrl: a.data ? `data:${a.media_type};base64,${a.data}` : void 0 }));
|
|
2671
|
+
}
|
|
2672
|
+
function pushCronBlock(snap, toolId, now, data) {
|
|
2673
|
+
const title = String(data?.title || "");
|
|
2674
|
+
const summary = String(data?.summary || "");
|
|
2675
|
+
if (data?.toolName === "create_cron") {
|
|
2676
|
+
const m = /^Scheduled\s+(\S+)\s*(?:\((.*)\))?/.exec(summary);
|
|
2677
|
+
if (!m) return;
|
|
2678
|
+
const colon = title.indexOf(": ");
|
|
2679
|
+
pushBlock(snap, { kind: "cron", id: `cron:${toolId}`, ts: now, action: "create", taskId: m[1], title: colon >= 0 ? title.slice(colon + 2) : void 0, schedule: m[2] || void 0 });
|
|
2680
|
+
} else {
|
|
2681
|
+
const taskId = title.trim();
|
|
2682
|
+
if (!taskId) return;
|
|
2683
|
+
pushBlock(snap, { kind: "cron", id: `cron:${toolId}`, ts: now, action: "delete", taskId });
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
function applyEvent(snap, event, data, seq) {
|
|
2687
|
+
snap.seq = seq;
|
|
2688
|
+
const now = Date.now();
|
|
2689
|
+
switch (event) {
|
|
2690
|
+
case "session:ready":
|
|
2691
|
+
snap.historyLoaded = !!data?.historyLoaded;
|
|
2692
|
+
if (Array.isArray(data?.todos) && data.todos.length) snap.todos = data.todos;
|
|
2693
|
+
if (Array.isArray(data?.projectInputHistory)) {
|
|
2694
|
+
snap.inputHistory = data.projectInputHistory.filter((x) => typeof x === "string" && !!x);
|
|
2695
|
+
}
|
|
2696
|
+
if (!snap.historyLoaded && snap.blocks.some((b) => b.kind === "user")) {
|
|
2697
|
+
const last = snap.blocks[snap.blocks.length - 1];
|
|
2698
|
+
if (!(last?.kind === "notice" && last.noticeType === "history-expired")) {
|
|
2699
|
+
notice(snap, seq, "history-expired", "warn", "\u5386\u53F2\u5DF2\u8FC7\u671F\uFF0C\u6A21\u578B\u4FA7\u65E0\u4E0A\u4E0B\u6587\uFF0C\u5C06\u4F5C\u4E3A\u65B0\u5BF9\u8BDD\u7EE7\u7EED");
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
break;
|
|
2703
|
+
case "state:update": {
|
|
2704
|
+
snap.state = data?.state === "processing" ? "processing" : "idle";
|
|
2705
|
+
if (snap.state === "idle") {
|
|
2706
|
+
closeStreaming(snap);
|
|
2707
|
+
finishTurn(snap, seq);
|
|
2708
|
+
voidPending(snap);
|
|
2709
|
+
if (snap.blocks.some((b) => b.kind === "user" && b.queued)) {
|
|
2710
|
+
snap.blocks = snap.blocks.filter((b) => !(b.kind === "user" && b.queued));
|
|
2711
|
+
}
|
|
2712
|
+
while (updateBlock(snap, (b) => b.kind === "user" && !b.doneTs, (b) => ({ ...b, doneTs: now }))) ;
|
|
2713
|
+
updateBlock(snap, (b) => b.kind === "notice" && b.noticeType === "plan-implement" && !b.doneTs, (b) => ({ ...b, doneTs: now }));
|
|
2714
|
+
} else if (!snap.blocks.some((b) => b.kind === "user" && !b.queued && !b.doneTs || b.kind === "notice" && b.noticeType === "plan-implement" && !b.doneTs)) {
|
|
2715
|
+
updateBlock(
|
|
2716
|
+
snap,
|
|
2717
|
+
(b) => b.kind === "user" && !b.queued || b.kind === "notice" && b.noticeType === "plan-implement",
|
|
2718
|
+
(b) => ({ ...b, doneTs: void 0 })
|
|
2719
|
+
);
|
|
2720
|
+
}
|
|
2721
|
+
break;
|
|
2722
|
+
}
|
|
2723
|
+
// 输入预测:空串表示"预计不回复",统一落成 undefined;用户发送/会话重置后作废
|
|
2724
|
+
case "input:predict":
|
|
2725
|
+
snap.predictedInput = data?.prediction || void 0;
|
|
2726
|
+
break;
|
|
2727
|
+
case "input:received": {
|
|
2728
|
+
snap.predictedInput = void 0;
|
|
2729
|
+
dropPendingUser(snap);
|
|
2730
|
+
const text = data?.originalInput ?? data?.input ?? "";
|
|
2731
|
+
const attachments = toAttachmentMetas(data?.attachments);
|
|
2732
|
+
const pastes = parsePasteInput(String(data?.input ?? ""));
|
|
2733
|
+
pushBlock(snap, {
|
|
2734
|
+
kind: "user",
|
|
2735
|
+
id: `user:${data?.inputId || seq}`,
|
|
2736
|
+
ts: now,
|
|
2737
|
+
inputId: data?.inputId,
|
|
2738
|
+
text,
|
|
2739
|
+
queued: !!data?.queued,
|
|
2740
|
+
...attachments ? { attachments } : {},
|
|
2741
|
+
...pastes ? { pastes } : {},
|
|
2742
|
+
...data?.source && data.source !== "user" ? { source: data.source } : {}
|
|
2743
|
+
});
|
|
2744
|
+
if (text && snap.inputHistory?.[0] !== text) {
|
|
2745
|
+
snap.inputHistory = [text, ...snap.inputHistory || []].slice(0, 100);
|
|
2746
|
+
}
|
|
2747
|
+
break;
|
|
2748
|
+
}
|
|
2749
|
+
case "input:processing": {
|
|
2750
|
+
snap.predictedInput = void 0;
|
|
2751
|
+
dropPendingUser(snap);
|
|
2752
|
+
const inputId = data?.inputId;
|
|
2753
|
+
const attachments = toAttachmentMetas(data?.attachments);
|
|
2754
|
+
const src = data?.source && data.source !== "user" ? { source: data.source } : {};
|
|
2755
|
+
const idx = snap.blocks.findIndex((b) => b.kind === "user" && b.inputId === inputId);
|
|
2756
|
+
const cur = idx >= 0 ? snap.blocks[idx] : void 0;
|
|
2757
|
+
if (cur?.queued) {
|
|
2758
|
+
snap.blocks = snap.blocks.filter((_, i) => i !== idx);
|
|
2759
|
+
if (snap.turn && Object.keys(snap.turn.files).length) finishTurn(snap, seq);
|
|
2760
|
+
updateBlock(
|
|
2761
|
+
snap,
|
|
2762
|
+
(b) => b.kind === "user" && !b.queued && !b.doneTs || b.kind === "notice" && b.noticeType === "plan-implement" && !b.doneTs,
|
|
2763
|
+
(b) => ({ ...b, doneTs: now })
|
|
2764
|
+
);
|
|
2765
|
+
const { attachments: _raw, ...rest } = cur;
|
|
2766
|
+
pushBlock(snap, { ...rest, ts: now, queued: false, ...src, ...attachments?.length ? { attachments } : {} });
|
|
2767
|
+
} else {
|
|
2768
|
+
const hit = updateBlock(snap, (b) => b.kind === "user" && b.inputId === inputId, (b) => ({ ...b, queued: false, ...src, ...attachments?.length ? { attachments } : {} }));
|
|
2769
|
+
if (!hit) {
|
|
2770
|
+
const pastes = parsePasteInput(String(data?.input ?? ""));
|
|
2771
|
+
pushBlock(snap, { kind: "user", id: `user:${inputId || seq}`, ts: now, inputId, text: data?.originalInput ?? data?.input ?? "", attachments, ...pastes ? { pastes } : {}, ...src });
|
|
2772
|
+
}
|
|
2773
|
+
if (snap.turn && Object.keys(snap.turn.files).length) finishTurn(snap, seq);
|
|
2774
|
+
}
|
|
2775
|
+
snap.turn = { inputId, files: {} };
|
|
2776
|
+
break;
|
|
2777
|
+
}
|
|
2778
|
+
case "message:thinking:chunk":
|
|
2779
|
+
case "message:text:chunk": {
|
|
2780
|
+
const id = String(data?.id ?? "");
|
|
2781
|
+
const delta = String(data?.delta ?? "");
|
|
2782
|
+
const field = event === "message:text:chunk" ? "text" : "thinking";
|
|
2783
|
+
const hit = updateBlock(snap, (b) => b.kind === "assistant" && b.id === id && !b.done, (b) => ({ ...b, [field]: b[field] + delta }));
|
|
2784
|
+
if (!hit) {
|
|
2785
|
+
closeStreaming(snap);
|
|
2786
|
+
pushBlock(snap, { kind: "assistant", id, ts: now, agentId: MAIN_AGENT_ID, thinking: field === "thinking" ? delta : "", text: field === "text" ? delta : "", done: false });
|
|
2787
|
+
}
|
|
2788
|
+
snap.streamingId = id;
|
|
2789
|
+
break;
|
|
2790
|
+
}
|
|
2791
|
+
case "message:complete": {
|
|
2792
|
+
const id = String(data?.id ?? "");
|
|
2793
|
+
const agentId = data?.agentId || MAIN_AGENT_ID;
|
|
2794
|
+
const content = String(data?.content ?? "");
|
|
2795
|
+
const reasoning = String(data?.reasoning ?? "");
|
|
2796
|
+
const hit = agentId === MAIN_AGENT_ID && updateBlock(
|
|
2797
|
+
snap,
|
|
2798
|
+
(b) => b.kind === "assistant" && b.id === id,
|
|
2799
|
+
(b) => ({ ...b, text: content || b.text, thinking: reasoning || b.thinking, done: true })
|
|
2800
|
+
);
|
|
2801
|
+
if (!hit && (content || reasoning)) {
|
|
2802
|
+
pushBlock(snap, { kind: "assistant", id: agentId === MAIN_AGENT_ID ? id : `${agentId}:${id}`, ts: now, agentId, thinking: reasoning, text: content, done: true }, agentId);
|
|
2803
|
+
}
|
|
2804
|
+
if (agentId === MAIN_AGENT_ID && snap.streamingId === id) snap.streamingId = void 0;
|
|
2805
|
+
break;
|
|
2806
|
+
}
|
|
2807
|
+
case "tool:permission:request": {
|
|
2808
|
+
const block = {
|
|
2809
|
+
kind: "permission",
|
|
2810
|
+
id: String(data?.toolId ?? `perm:${seq}`),
|
|
2811
|
+
ts: now,
|
|
2812
|
+
agentId: data?.agentId || MAIN_AGENT_ID,
|
|
2813
|
+
toolName: data?.toolName,
|
|
2814
|
+
title: data?.title,
|
|
2815
|
+
content: data?.content,
|
|
2816
|
+
options: data?.options || {}
|
|
2817
|
+
};
|
|
2818
|
+
pushBlock(snap, block, block.agentId);
|
|
2819
|
+
break;
|
|
2820
|
+
}
|
|
2821
|
+
case "tool:permission:auto":
|
|
2822
|
+
notice(snap, seq, "auto-permission", "info", data?.content || "\u5DF2\u7531\u6A21\u578B\u5B89\u5168\u5224\u65AD\u81EA\u52A8\u653E\u884C", data?.toolName, data?.agentId);
|
|
2823
|
+
break;
|
|
2824
|
+
case "tool:execution:chunk": {
|
|
2825
|
+
const toolId = String(data?.toolId ?? "");
|
|
2826
|
+
const delta = typeof data?.content === "string" ? data.content : JSON.stringify(data?.content ?? "");
|
|
2827
|
+
const hit = updateBlock(snap, (b) => b.kind === "tool" && b.id === toolId, (b) => ({ ...b, output: (b.output || "") + delta }));
|
|
2828
|
+
if (!hit) {
|
|
2829
|
+
pushBlock(snap, {
|
|
2830
|
+
kind: "tool",
|
|
2831
|
+
id: toolId,
|
|
2832
|
+
ts: now,
|
|
2833
|
+
agentId: data?.agentId || MAIN_AGENT_ID,
|
|
2834
|
+
toolName: data?.toolName,
|
|
2835
|
+
title: data?.title || data?.toolName,
|
|
2836
|
+
summary: data?.summary,
|
|
2837
|
+
output: delta,
|
|
2838
|
+
status: "running"
|
|
2839
|
+
}, data?.agentId);
|
|
2840
|
+
}
|
|
2841
|
+
break;
|
|
2842
|
+
}
|
|
2843
|
+
case "tool:execution:complete": {
|
|
2844
|
+
const toolId = String(data?.toolId ?? `tool:${seq}`);
|
|
2845
|
+
const patch = { title: data?.title || data?.toolName, summary: data?.summary, content: data?.content, status: "done", ...data?.interrupted === true ? { interrupted: true } : {} };
|
|
2846
|
+
const hit = updateBlock(snap, (b) => b.kind === "tool" && b.id === toolId, (b) => ({ ...b, ...patch }));
|
|
2847
|
+
if (!hit) {
|
|
2848
|
+
pushBlock(snap, { kind: "tool", id: toolId, ts: now, agentId: data?.agentId || MAIN_AGENT_ID, toolName: data?.toolName, ...patch }, data?.agentId);
|
|
2849
|
+
}
|
|
2850
|
+
if (FILE_EDIT_TOOLS.has(data?.toolName)) mergeFileChange(snap, data.toolName, data?.title || "", data?.content, data?.cumulative);
|
|
2851
|
+
if (CRON_TOOLS.has(data?.toolName)) pushCronBlock(snap, toolId, now, data);
|
|
2852
|
+
break;
|
|
2853
|
+
}
|
|
2854
|
+
case "tool:execution:error": {
|
|
2855
|
+
const toolId = String(data?.toolId ?? `toolerr:${seq}`);
|
|
2856
|
+
const patch = { title: data?.title || data?.toolName, content: data?.content, status: "error", input: data?.input };
|
|
2857
|
+
const hit = updateBlock(snap, (b) => b.kind === "tool" && b.id === toolId, (b) => ({ ...b, ...patch }));
|
|
2858
|
+
if (!hit) {
|
|
2859
|
+
pushBlock(snap, { kind: "tool", id: toolId, ts: now, agentId: data?.agentId || MAIN_AGENT_ID, toolName: data?.toolName, ...patch }, data?.agentId);
|
|
2860
|
+
}
|
|
2861
|
+
break;
|
|
2862
|
+
}
|
|
2863
|
+
case "task:agent:start": {
|
|
2864
|
+
pushBlock(snap, {
|
|
2865
|
+
kind: "agent",
|
|
2866
|
+
id: String(data?.taskId),
|
|
2867
|
+
ts: now,
|
|
2868
|
+
agentType: data?.agent_type || "",
|
|
2869
|
+
title: data?.title || "",
|
|
2870
|
+
instructions: data?.instructions || "",
|
|
2871
|
+
status: "running",
|
|
2872
|
+
blocks: []
|
|
2873
|
+
});
|
|
2874
|
+
break;
|
|
2875
|
+
}
|
|
2876
|
+
case "task:agent:end": {
|
|
2877
|
+
const taskId = String(data?.taskId);
|
|
2878
|
+
updateBlock(snap, (b) => b.kind === "agent" && b.id === taskId, (b) => ({ ...b, status: data?.status || "completed", result: data?.content }));
|
|
2879
|
+
break;
|
|
2880
|
+
}
|
|
2881
|
+
case "task:start":
|
|
2882
|
+
case "task:transfer":
|
|
2883
|
+
break;
|
|
2884
|
+
case "task:end":
|
|
2885
|
+
notice(snap, seq, "info", data?.status === "failed" ? "warn" : "info", `\u540E\u53F0\u4EFB\u52A1\u7ED3\u675F\uFF08${data?.status}\uFF09\uFF1A${data?.summary || ""}`);
|
|
2886
|
+
break;
|
|
2887
|
+
case "todos:update": {
|
|
2888
|
+
const todos = Array.isArray(data) ? data : [];
|
|
2889
|
+
snap.todos = todos;
|
|
2890
|
+
let idx = -1;
|
|
2891
|
+
for (let i = snap.blocks.length - 1; i >= 0; i--) {
|
|
2892
|
+
const b = snap.blocks[i];
|
|
2893
|
+
if (b.kind === "user") break;
|
|
2894
|
+
if (b.kind === "todos") {
|
|
2895
|
+
idx = i;
|
|
2896
|
+
break;
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
if (idx >= 0) {
|
|
2900
|
+
const next = snap.blocks.slice();
|
|
2901
|
+
next[idx] = { ...next[idx], todos };
|
|
2902
|
+
snap.blocks = next;
|
|
2903
|
+
} else {
|
|
2904
|
+
pushBlock(snap, { kind: "todos", id: `todos:${seq}`, ts: now, todos });
|
|
2905
|
+
}
|
|
2906
|
+
break;
|
|
2907
|
+
}
|
|
2908
|
+
case "pick:option:request":
|
|
2909
|
+
pushBlock(snap, {
|
|
2910
|
+
kind: "pick",
|
|
2911
|
+
id: `pick:${seq}`,
|
|
2912
|
+
ts: now,
|
|
2913
|
+
agentId: data?.agentId || MAIN_AGENT_ID,
|
|
2914
|
+
questions: data?.questions || [],
|
|
2915
|
+
intro: data?.intro,
|
|
2916
|
+
estimatedTime: data?.estimatedTime
|
|
2917
|
+
}, data?.agentId);
|
|
2918
|
+
break;
|
|
2919
|
+
case "plan:exit:request":
|
|
2920
|
+
pushBlock(snap, {
|
|
2921
|
+
kind: "plan-exit",
|
|
2922
|
+
id: `plan:${seq}`,
|
|
2923
|
+
ts: now,
|
|
2924
|
+
agentId: data?.agentId || MAIN_AGENT_ID,
|
|
2925
|
+
planFilePath: data?.planFilePath || "",
|
|
2926
|
+
planContent: data?.planContent || "",
|
|
2927
|
+
options: data?.options || {}
|
|
2928
|
+
}, data?.agentId);
|
|
2929
|
+
break;
|
|
2930
|
+
case "plan:implement":
|
|
2931
|
+
snap.blocks = [];
|
|
2932
|
+
snap.todos = [];
|
|
2933
|
+
snap.turn = null;
|
|
2934
|
+
snap.streamingId = void 0;
|
|
2935
|
+
notice(snap, seq, "plan-implement", "info", `\u5DF2\u6E05\u7406\u4E0A\u4E0B\u6587\uFF0C\u5F00\u59CB\u5B9E\u65BD\u8BA1\u5212\uFF1A${data?.planFilePath || ""}`, data?.planContent);
|
|
2936
|
+
break;
|
|
2937
|
+
case "compact:exec":
|
|
2938
|
+
notice(
|
|
2939
|
+
snap,
|
|
2940
|
+
seq,
|
|
2941
|
+
"compact",
|
|
2942
|
+
"info",
|
|
2943
|
+
data?.mode === "failed" ? `\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\uFF1A${data?.errMsg || ""}` : `\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29\uFF1A${data?.tokenBefore ?? "?"} \u2192 ${data?.tokenCompact ?? "?"} tokens`
|
|
2944
|
+
);
|
|
2945
|
+
break;
|
|
2946
|
+
case "compact:micro":
|
|
2947
|
+
notice(snap, seq, "compact-micro", "info", `\u5DF2\u6E05\u7406 ${data?.clearedCount ?? 0} \u6761\u65E7\u5DE5\u5177\u7ED3\u679C\uFF08\u7EA6\u7701 ${data?.estimatedSavedTokens ?? 0} tokens\uFF09`);
|
|
2948
|
+
break;
|
|
2949
|
+
case "conversation:usage":
|
|
2950
|
+
if (data?.usage) snap.usage = data.usage;
|
|
2951
|
+
break;
|
|
2952
|
+
case "permissionLevel:update":
|
|
2953
|
+
if (data?.level) snap.permissionLevel = data.level;
|
|
2954
|
+
break;
|
|
2955
|
+
case "session:error":
|
|
2956
|
+
notice(snap, seq, "error", "error", data?.error?.message || data?.type || "\u4F1A\u8BDD\u51FA\u9519", data?.error?.code);
|
|
2957
|
+
break;
|
|
2958
|
+
case "session:interrupted": {
|
|
2959
|
+
const agentId = data?.agentId || MAIN_AGENT_ID;
|
|
2960
|
+
if (agentId !== MAIN_AGENT_ID) {
|
|
2961
|
+
updateBlock(snap, (b) => b.kind === "agent" && b.id === agentId, (b) => ({ ...b, status: "interrupted", result: data?.content }));
|
|
2962
|
+
} else {
|
|
2963
|
+
closeStreaming(snap);
|
|
2964
|
+
voidPending(snap);
|
|
2965
|
+
snap.predictedInput = void 0;
|
|
2966
|
+
notice(snap, seq, "interrupted", "warn", data?.content || "\u5DF2\u4E2D\u65AD");
|
|
2967
|
+
}
|
|
2968
|
+
break;
|
|
2969
|
+
}
|
|
2970
|
+
case "session:cleared":
|
|
2971
|
+
snap.blocks = [];
|
|
2972
|
+
snap.todos = [];
|
|
2973
|
+
snap.turn = null;
|
|
2974
|
+
snap.streamingId = void 0;
|
|
2975
|
+
snap.predictedInput = void 0;
|
|
2976
|
+
notice(snap, seq, "cleared", "info", "\u4F1A\u8BDD\u5DF2\u6E05\u7A7A");
|
|
2977
|
+
break;
|
|
2978
|
+
case "hook:notice": {
|
|
2979
|
+
const kind = data?.kind;
|
|
2980
|
+
notice(
|
|
2981
|
+
snap,
|
|
2982
|
+
seq,
|
|
2983
|
+
"hook",
|
|
2984
|
+
kind === "systemMessage" ? "info" : "warn",
|
|
2985
|
+
`${kind === "blocked" ? "\u8F93\u5165\u88AB hook \u62E6\u622A\uFF1A" : ""}${data?.message || ""}`,
|
|
2986
|
+
data?.hookEvent
|
|
2987
|
+
);
|
|
2988
|
+
break;
|
|
2989
|
+
}
|
|
2990
|
+
case "quickchat:response": {
|
|
2991
|
+
const question = String(data?.question || "");
|
|
2992
|
+
if (!question) {
|
|
2993
|
+
notice(snap, seq, "info", "info", "\u7528\u6CD5\uFF1A/quickchat \u95EE\u9898");
|
|
2994
|
+
break;
|
|
2995
|
+
}
|
|
2996
|
+
snap.quickchats = [...snap.quickchats || [], { question, content: String(data?.content || ""), seq, ts: now }];
|
|
2997
|
+
break;
|
|
2998
|
+
}
|
|
2999
|
+
default:
|
|
3000
|
+
break;
|
|
3001
|
+
}
|
|
3002
|
+
return snap;
|
|
3003
|
+
}
|
|
3004
|
+
function applyLocal(snap, action) {
|
|
3005
|
+
switch (action.type) {
|
|
3006
|
+
case "user-pending": {
|
|
3007
|
+
const attachments = toAttachmentMetas(action.attachments);
|
|
3008
|
+
const pastes = parsePasteInput(action.input);
|
|
3009
|
+
pushBlock(snap, {
|
|
3010
|
+
kind: "user",
|
|
3011
|
+
id: action.id,
|
|
3012
|
+
ts: Date.now(),
|
|
3013
|
+
pending: true,
|
|
3014
|
+
text: action.originalInput ?? action.input,
|
|
3015
|
+
...attachments ? { attachments } : {},
|
|
3016
|
+
...pastes ? { pastes } : {}
|
|
3017
|
+
});
|
|
3018
|
+
break;
|
|
3019
|
+
}
|
|
3020
|
+
case "user-pending-clear":
|
|
3021
|
+
snap.blocks = snap.blocks.filter((b) => !(b.kind === "user" && b.pending && b.id === action.id));
|
|
3022
|
+
break;
|
|
3023
|
+
case "user-pending-failed":
|
|
3024
|
+
updateBlock(snap, (b) => b.kind === "user" && !!b.pending && b.id === action.id, (b) => ({ ...b, failed: true }));
|
|
3025
|
+
break;
|
|
3026
|
+
case "permission":
|
|
3027
|
+
updateBlock(snap, (b) => b.kind === "permission" && b.id === action.toolId, (b) => ({ ...b, resolved: action.selected, resolvedTs: Date.now() }));
|
|
3028
|
+
break;
|
|
3029
|
+
case "pick":
|
|
3030
|
+
updateBlock(snap, (b) => b.kind === "pick" && b.id === action.id, (b) => ({ ...b, answered: true, resolved: action.answers, resolvedTs: Date.now() }));
|
|
3031
|
+
break;
|
|
3032
|
+
case "plan-exit":
|
|
3033
|
+
updateBlock(snap, (b) => b.kind === "plan-exit" && b.id === action.id, (b) => ({ ...b, resolved: action.selected, resolvedTs: Date.now() }));
|
|
3034
|
+
break;
|
|
3035
|
+
case "agentMode":
|
|
3036
|
+
snap.agentMode = action.mode;
|
|
3037
|
+
break;
|
|
3038
|
+
case "permissionLevel":
|
|
3039
|
+
snap.permissionLevel = action.level;
|
|
3040
|
+
break;
|
|
3041
|
+
}
|
|
3042
|
+
return snap;
|
|
3043
|
+
}
|
|
3044
|
+
function pendingIn(blocks) {
|
|
3045
|
+
const out = [];
|
|
3046
|
+
const walk = (bs) => {
|
|
3047
|
+
for (const b of bs) {
|
|
3048
|
+
if (b.kind === "permission" && !b.resolved) out.push(b);
|
|
3049
|
+
else if (b.kind === "pick" && !b.answered) out.push(b);
|
|
3050
|
+
else if (b.kind === "plan-exit" && !b.resolved) out.push(b);
|
|
3051
|
+
else if (b.kind === "agent") walk(b.blocks);
|
|
3052
|
+
}
|
|
3053
|
+
};
|
|
3054
|
+
walk(blocks);
|
|
3055
|
+
return out;
|
|
3056
|
+
}
|
|
3057
|
+
function pendingBlocks(snap) {
|
|
3058
|
+
return pendingIn(snap.blocks);
|
|
3059
|
+
}
|
|
3060
|
+
|
|
3061
|
+
// ../server/src/workers/cronFile.ts
|
|
3062
|
+
var import_fs13 = __toESM(require("fs"));
|
|
3063
|
+
var import_path12 = __toESM(require("path"));
|
|
3064
|
+
var TASKS_FILE = import_path12.default.join(".sema", "scheduled_tasks.json");
|
|
3065
|
+
var SETTINGS_FILE2 = import_path12.default.join(".sema", "settings.json");
|
|
3066
|
+
var parser;
|
|
3067
|
+
function cronParser() {
|
|
3068
|
+
if (parser !== void 0) return parser;
|
|
3069
|
+
try {
|
|
3070
|
+
const coreMain = require.resolve("sema-core");
|
|
3071
|
+
parser = require(require.resolve("cron-parser", { paths: [import_path12.default.dirname(coreMain)] }));
|
|
3072
|
+
} catch {
|
|
3073
|
+
try {
|
|
3074
|
+
parser = require("cron-parser");
|
|
3075
|
+
} catch {
|
|
3076
|
+
parser = null;
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
return parser;
|
|
3080
|
+
}
|
|
3081
|
+
function nextFireAt0(expr, fromMs) {
|
|
3082
|
+
const p = cronParser();
|
|
3083
|
+
if (!p) return null;
|
|
3084
|
+
try {
|
|
3085
|
+
const Parser = p.CronExpressionParser || p;
|
|
3086
|
+
const it = Parser.parse(expr, { currentDate: new Date(fromMs) });
|
|
3087
|
+
return it.next().getTime();
|
|
3088
|
+
} catch {
|
|
3089
|
+
return null;
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
function describeCron(expr) {
|
|
3093
|
+
const parts = expr.trim().split(/\s+/);
|
|
3094
|
+
if (parts.length !== 5) return expr;
|
|
3095
|
+
const [minute, hour, dom, month, dow] = parts;
|
|
3096
|
+
if (minute === "*" && hour === "*" && dom === "*" && month === "*" && dow === "*") return "every minute";
|
|
3097
|
+
if (hour === "*" && dom === "*" && month === "*" && dow === "*") {
|
|
3098
|
+
if (minute.startsWith("*/")) return `every ${minute.slice(2)} minutes`;
|
|
3099
|
+
return `at minute ${minute} of every hour`;
|
|
3100
|
+
}
|
|
3101
|
+
if (dom === "*" && month === "*" && dow === "*") {
|
|
3102
|
+
if (hour.startsWith("*/")) return `every ${hour.slice(2)} hours at minute ${minute}`;
|
|
3103
|
+
return `daily at ${hour.padStart(2, "0")}:${minute.padStart(2, "0")}`;
|
|
3104
|
+
}
|
|
3105
|
+
if (dom === "*" && month === "*" && dow !== "*") {
|
|
3106
|
+
const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
3107
|
+
const dayStr = dow.split(",").map((d) => dayNames[parseInt(d)] || d).join(", ");
|
|
3108
|
+
return `${dayStr} at ${hour.padStart(2, "0")}:${minute.padStart(2, "0")}`;
|
|
3109
|
+
}
|
|
3110
|
+
return expr;
|
|
3111
|
+
}
|
|
3112
|
+
function nextFireAts(expr, fromMs, count) {
|
|
3113
|
+
const p = cronParser();
|
|
3114
|
+
if (!p) return [];
|
|
3115
|
+
try {
|
|
3116
|
+
const Parser = p.CronExpressionParser || p;
|
|
3117
|
+
const it = Parser.parse(expr, { currentDate: new Date(fromMs) });
|
|
3118
|
+
const out = [];
|
|
3119
|
+
for (let i = 0; i < count; i++) out.push(it.next().getTime());
|
|
3120
|
+
return out;
|
|
3121
|
+
} catch {
|
|
3122
|
+
return [];
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
function readPersistedTasks(workingDir, now = Date.now()) {
|
|
3126
|
+
const data = readJson4(import_path12.default.join(workingDir, TASKS_FILE));
|
|
3127
|
+
const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
|
|
3128
|
+
if (!tasks.length) return [];
|
|
3129
|
+
const disabled = new Set(readJson4(import_path12.default.join(workingDir, SETTINGS_FILE2))?.disabledCronTasks ?? []);
|
|
3130
|
+
const filePath = import_path12.default.join(workingDir, TASKS_FILE);
|
|
3131
|
+
const out = [];
|
|
3132
|
+
for (const t of tasks) {
|
|
3133
|
+
if (!t?.id || !t.schedule) continue;
|
|
3134
|
+
let nextFireAt;
|
|
3135
|
+
if (t.repeat) {
|
|
3136
|
+
nextFireAt = nextFireAts(t.schedule, now, 4);
|
|
3137
|
+
} else {
|
|
3138
|
+
if (t.lastFiredAt != null) continue;
|
|
3139
|
+
const first = nextFireAt0(t.schedule, Number(t.createdAt) || now);
|
|
3140
|
+
if (first == null || first <= now) continue;
|
|
3141
|
+
nextFireAt = [first];
|
|
3142
|
+
}
|
|
3143
|
+
if (!nextFireAt.length) continue;
|
|
3144
|
+
out.push({
|
|
3145
|
+
id: String(t.id),
|
|
3146
|
+
schedule: String(t.schedule),
|
|
3147
|
+
task: String(t.task ?? ""),
|
|
3148
|
+
title: t.title ? String(t.title) : void 0,
|
|
3149
|
+
repeat: !!t.repeat,
|
|
3150
|
+
persist: true,
|
|
3151
|
+
status: !disabled.has(t.id),
|
|
3152
|
+
filePath,
|
|
3153
|
+
createdAt: Number(t.createdAt) || now,
|
|
3154
|
+
describeCronExpression: describeCron(String(t.schedule)),
|
|
3155
|
+
activatedAt: now,
|
|
3156
|
+
lastFiredAt: t.lastFiredAt ?? void 0,
|
|
3157
|
+
nextFireAt
|
|
3158
|
+
});
|
|
3159
|
+
}
|
|
3160
|
+
return out;
|
|
3161
|
+
}
|
|
3162
|
+
function readJson4(file) {
|
|
3163
|
+
try {
|
|
3164
|
+
return JSON.parse(import_fs13.default.readFileSync(file, "utf8"));
|
|
3165
|
+
} catch {
|
|
3166
|
+
return null;
|
|
3167
|
+
}
|
|
3168
|
+
}
|
|
3169
|
+
function readPersistedCron(workingDir, now = Date.now()) {
|
|
3170
|
+
const out = { active: 0, nextFireAt: null };
|
|
3171
|
+
const data = readJson4(import_path12.default.join(workingDir, TASKS_FILE));
|
|
3172
|
+
const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
|
|
3173
|
+
if (!tasks.length) return out;
|
|
3174
|
+
const disabled = new Set(readJson4(import_path12.default.join(workingDir, SETTINGS_FILE2))?.disabledCronTasks ?? []);
|
|
3175
|
+
for (const t of tasks) {
|
|
3176
|
+
if (!t?.id || !t.schedule || disabled.has(t.id)) continue;
|
|
3177
|
+
let next;
|
|
3178
|
+
if (t.repeat) {
|
|
3179
|
+
next = nextFireAt0(t.schedule, now);
|
|
3180
|
+
} else {
|
|
3181
|
+
if (t.lastFiredAt != null) continue;
|
|
3182
|
+
next = nextFireAt0(t.schedule, Number(t.createdAt) || now);
|
|
3183
|
+
if (next != null && next <= now) continue;
|
|
3184
|
+
}
|
|
3185
|
+
if (next == null) continue;
|
|
3186
|
+
out.active++;
|
|
3187
|
+
if (out.nextFireAt == null || next < out.nextFireAt) out.nextFireAt = next;
|
|
3188
|
+
}
|
|
3189
|
+
return out;
|
|
3190
|
+
}
|
|
3191
|
+
|
|
3192
|
+
// ../server/src/sessions.ts
|
|
3193
|
+
var BUFFER_MAX = 3e3;
|
|
3194
|
+
var SAVE_DEBOUNCE_MS = 500;
|
|
3195
|
+
var SESSION_IDLE_MS = 20 * 6e4;
|
|
3196
|
+
var WARM_GRACE_MS = 5 * 6e4;
|
|
3197
|
+
var MAX_LIVE_SESSIONS = 8;
|
|
3198
|
+
var CRON_KEEPER_LEAD_MS = 3 * 6e4;
|
|
3199
|
+
var CRON_KEEPER_LATE_MS = 6e4;
|
|
3200
|
+
var CRON_KEEP_AFTER_FIRE_MS = 5 * 6e4;
|
|
3201
|
+
var KEEP_AWAKE_CRON_LEAD_MS = 5 * 6e4;
|
|
3202
|
+
var CORE_WRITE_ACTIONS = /* @__PURE__ */ new Set(["core.switchModel", "core.addModel", "core.delModel", "core.applyTaskModel", "core.addImageModel", "core.delImageModel", "core.switchImageModel"]);
|
|
3203
|
+
var PROJECT_LIMIT = 20;
|
|
3204
|
+
var SESSIONS_PER_PROJECT_LIMIT = 30;
|
|
3205
|
+
var STANDALONE_SESSION_LIMIT = 30;
|
|
3206
|
+
var SessionManager = class extends import_events2.EventEmitter {
|
|
3207
|
+
constructor(registry, entryPath) {
|
|
3208
|
+
super();
|
|
3209
|
+
this.registry = registry;
|
|
3210
|
+
this.pool = new WorkerPool({
|
|
3211
|
+
entryPath,
|
|
3212
|
+
maxWorkers: () => registry.getSettings().maxWorkers ?? 8,
|
|
3213
|
+
exemptDirs: /* @__PURE__ */ new Set([CONFIG_WORKSPACE]),
|
|
3214
|
+
getCoreConfig: () => registry.getSettings().coreConfig,
|
|
3215
|
+
isSessionBusy: (sid) => {
|
|
3216
|
+
const rt = this.runtimes.get(sid);
|
|
3217
|
+
return !!rt && (rt.snapshot.state === "processing" || pendingBlocks(rt.snapshot).length > 0);
|
|
3218
|
+
},
|
|
3219
|
+
onCronWorkerReclaimed: (dir, sids, reason) => this.onCronWorkerReclaimed(dir, sids, reason)
|
|
3220
|
+
});
|
|
3221
|
+
this.sessionReapTimer = setInterval(() => {
|
|
3222
|
+
void this.reapSessions().catch(() => void 0);
|
|
3223
|
+
}, 6e4);
|
|
3224
|
+
this.sessionReapTimer.unref?.();
|
|
3225
|
+
this.cronKeeperTimer = setInterval(() => {
|
|
3226
|
+
void this.cronKeeperTick().catch(() => void 0);
|
|
3227
|
+
}, 6e4);
|
|
3228
|
+
this.cronKeeperTimer.unref?.();
|
|
3229
|
+
setTimeout(() => {
|
|
3230
|
+
void this.cronKeeperTick().catch(() => void 0);
|
|
3231
|
+
}, 2e3).unref?.();
|
|
3232
|
+
this.pool.on("event", (dir, sid, event, data) => this.onEvent(sid, event, data));
|
|
3233
|
+
this.pool.on("proc-event", (workingDir, event, data) => this.broadcastAll({ event, data, workingDir }));
|
|
3234
|
+
this.pool.on("exit", (dir, sids, code) => this.onWorkerExit(sids, code));
|
|
3235
|
+
}
|
|
3236
|
+
runtimes = /* @__PURE__ */ new Map();
|
|
3237
|
+
pool;
|
|
3238
|
+
sessionReapTimer;
|
|
3239
|
+
cronKeeperTimer;
|
|
3240
|
+
/** 退场时清理会话关联终端的钩子(由入口注入 TerminalManager.killBySession) */
|
|
3241
|
+
killTerminals;
|
|
3242
|
+
evicting = false;
|
|
3243
|
+
branching = /* @__PURE__ */ new Set();
|
|
3244
|
+
/** 独立会话备用 worker:草稿页未选项目时预先占好目录并拉起 worker,首条消息直接复用,免冷启动 */
|
|
3245
|
+
spare;
|
|
3246
|
+
sparing;
|
|
3247
|
+
// ==================== 快照 / 落盘 ====================
|
|
3248
|
+
transcriptPath(id) {
|
|
3249
|
+
return import_path13.default.join(TRANSCRIPT_DIR, `${id}.json`);
|
|
3250
|
+
}
|
|
3251
|
+
loadRuntime(id) {
|
|
3252
|
+
let rt = this.runtimes.get(id);
|
|
3253
|
+
if (rt) return rt;
|
|
3254
|
+
const rec = this.registry.getSession(id);
|
|
3255
|
+
if (!rec) throw new Error(`\u4F1A\u8BDD\u4E0D\u5B58\u5728: ${id}`);
|
|
3256
|
+
let snapshot;
|
|
3257
|
+
try {
|
|
3258
|
+
const file = this.transcriptPath(id);
|
|
3259
|
+
if (import_fs14.default.existsSync(file)) snapshot = JSON.parse(import_fs14.default.readFileSync(file, "utf8"));
|
|
3260
|
+
} catch {
|
|
3261
|
+
}
|
|
3262
|
+
if (!snapshot) snapshot = createSnapshot({ sessionId: id, workingDir: rec.workingDir, agentMode: rec.agentMode, permissionLevel: rec.permissionLevel });
|
|
3263
|
+
if (snapshot.blocks.some((b) => b.kind === "user" && b.queued)) {
|
|
3264
|
+
snapshot.blocks = snapshot.blocks.filter((b) => !(b.kind === "user" && b.queued));
|
|
3265
|
+
}
|
|
3266
|
+
if (snapshot.state === "processing") {
|
|
3267
|
+
applyEvent(snapshot, "session:interrupted", { agentId: "main", content: "\u670D\u52A1\u5DF2\u91CD\u542F\uFF0C\u672C\u8F6E\u5DF2\u4E2D\u65AD" }, snapshot.seq + 1);
|
|
3268
|
+
applyEvent(snapshot, "state:update", { state: "idle" }, snapshot.seq + 1);
|
|
3269
|
+
}
|
|
3270
|
+
snapshot.workingDir = rec.workingDir;
|
|
3271
|
+
rt = { snapshot, buffer: [], subscribers: /* @__PURE__ */ new Set() };
|
|
3272
|
+
this.runtimes.set(id, rt);
|
|
3273
|
+
return rt;
|
|
3274
|
+
}
|
|
3275
|
+
scheduleSave(rt) {
|
|
3276
|
+
if (rt.saveTimer) return;
|
|
3277
|
+
rt.saveTimer = setTimeout(() => {
|
|
3278
|
+
rt.saveTimer = void 0;
|
|
3279
|
+
try {
|
|
3280
|
+
writeJsonAtomic(this.transcriptPath(rt.snapshot.sessionId), rt.snapshot);
|
|
3281
|
+
rt.saveFailed = false;
|
|
3282
|
+
} catch (e) {
|
|
3283
|
+
if (!rt.saveFailed) logErr("transcript", `\u4F1A\u8BDD ${rt.snapshot.sessionId} \u843D\u76D8\u5931\u8D25\uFF08\u540E\u7EED\u540C\u7C7B\u5931\u8D25\u4E0D\u518D\u8BB0\u5F55\uFF09:`, e?.message || e);
|
|
3284
|
+
rt.saveFailed = true;
|
|
3285
|
+
}
|
|
3286
|
+
}, SAVE_DEBOUNCE_MS);
|
|
3287
|
+
}
|
|
3288
|
+
getSnapshot(id) {
|
|
3289
|
+
return this.loadRuntime(id).snapshot;
|
|
3290
|
+
}
|
|
3291
|
+
// ==================== 事件 ====================
|
|
3292
|
+
/**
|
|
3293
|
+
* 新建文件事件核心只带前几行预览:在事件到达的此刻读盘补成全量内容(此时磁盘内容就是刚写入的内容,
|
|
3294
|
+
* 与本轮真实新增一致),补全后的 patch 随快照落盘,之后文件再被改动审阅里仍是当时的内容。
|
|
3295
|
+
* 超限/读取失败/内容对不上(极小概率已被后续工具改过)则保留预览,由前端按 diffText 显示省略提示。
|
|
3296
|
+
*/
|
|
3297
|
+
backfillNewFilePatch(sid, event, data) {
|
|
3298
|
+
if (event !== "tool:execution:complete" || !FILE_EDIT_TOOLS.has(data?.toolName)) return;
|
|
3299
|
+
const c = data?.content;
|
|
3300
|
+
if (!c || c.type !== "new" || !Array.isArray(c.patch) || c.patch.length !== 1) return;
|
|
3301
|
+
const h = c.patch[0];
|
|
3302
|
+
const preview = Array.isArray(h?.lines) ? h.lines : [];
|
|
3303
|
+
if (!h || h.oldLines !== 0 || typeof h.newLines !== "number" || h.newLines <= preview.length) return;
|
|
3304
|
+
if (h.newLines > NEW_FILE_MAX_LINES) return;
|
|
3305
|
+
const rec = this.registry.getSession(sid);
|
|
3306
|
+
const title = String(data?.title || "");
|
|
3307
|
+
if (!rec || !title) return;
|
|
3308
|
+
try {
|
|
3309
|
+
const abs = import_path13.default.isAbsolute(title) ? title : import_path13.default.resolve(rec.workingDir, title);
|
|
3310
|
+
if (import_fs14.default.statSync(abs).size > NEW_FILE_MAX_BYTES) return;
|
|
3311
|
+
const lines = import_fs14.default.readFileSync(abs, "utf8").replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n").map((l) => "+" + l);
|
|
3312
|
+
if (lines.length !== h.newLines || !preview.every((l, i) => lines[i] === l)) return;
|
|
3313
|
+
data.content = { ...c, patch: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: lines.length, lines }], diffText: "" };
|
|
3314
|
+
} catch {
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
/**
|
|
3318
|
+
* 审阅总 diff 维护:轮次边界重置轮级基线(与 shared/transcript 的轮次逻辑对齐),
|
|
3319
|
+
* 编辑完成事件读盘重算「轮前→当前」「会话首次触及前→当前」的总 diff,附加到 data.cumulative
|
|
3320
|
+
* (不动 data.content,聊天流工具卡片仍显示单步 diff)。
|
|
3321
|
+
*/
|
|
3322
|
+
updateReviewDiff(sid, rt, event, data) {
|
|
3323
|
+
if (event === "input:processing") {
|
|
3324
|
+
if (rt.diffBase) resetTurn(rt.diffBase);
|
|
3325
|
+
return;
|
|
3326
|
+
}
|
|
3327
|
+
if (event === "state:update") {
|
|
3328
|
+
if (rt.diffBase && data?.state !== "processing") resetTurn(rt.diffBase);
|
|
3329
|
+
return;
|
|
3330
|
+
}
|
|
3331
|
+
if (event === "session:cleared" || event === "plan:implement") {
|
|
3332
|
+
if (rt.diffBase) resetAll(rt.diffBase);
|
|
3333
|
+
return;
|
|
3334
|
+
}
|
|
3335
|
+
if (event === "session:ready") {
|
|
3336
|
+
const rec2 = this.registry.getSession(sid);
|
|
3337
|
+
const stamps = data?.readFileTimestamps;
|
|
3338
|
+
if (rec2 && stamps && typeof stamps === "object") {
|
|
3339
|
+
const b2 = rt.diffBase ??= createBaselines();
|
|
3340
|
+
for (const p of Object.keys(stamps)) captureOnRead(b2, rec2.workingDir, p);
|
|
3341
|
+
}
|
|
3342
|
+
return;
|
|
3343
|
+
}
|
|
3344
|
+
if (event === "file:reference") {
|
|
3345
|
+
const rec2 = this.registry.getSession(sid);
|
|
3346
|
+
if (rec2 && Array.isArray(data?.references)) {
|
|
3347
|
+
const b2 = rt.diffBase ??= createBaselines();
|
|
3348
|
+
for (const ref of data.references) {
|
|
3349
|
+
if (ref?.type === "file" && ref.name) captureOnRead(b2, rec2.workingDir, String(ref.name));
|
|
3350
|
+
}
|
|
3351
|
+
}
|
|
3352
|
+
return;
|
|
3353
|
+
}
|
|
3354
|
+
if (event !== "tool:execution:complete") return;
|
|
3355
|
+
const rec = this.registry.getSession(sid);
|
|
3356
|
+
const title = String(data?.title || "");
|
|
3357
|
+
if (!rec || !title) return;
|
|
3358
|
+
const b = rt.diffBase ??= createBaselines();
|
|
3359
|
+
if (data?.toolName === "view_file") {
|
|
3360
|
+
captureOnRead(b, rec.workingDir, title);
|
|
3361
|
+
return;
|
|
3362
|
+
}
|
|
3363
|
+
if (!FILE_EDIT_TOOLS.has(data?.toolName)) return;
|
|
3364
|
+
const cum = computeCumulative(b, rec.workingDir, title, data?.content);
|
|
3365
|
+
if (cum) data.cumulative = cum;
|
|
3366
|
+
}
|
|
3367
|
+
onEvent(sid, event, data) {
|
|
3368
|
+
let rt;
|
|
3369
|
+
try {
|
|
3370
|
+
rt = this.loadRuntime(sid);
|
|
3371
|
+
} catch {
|
|
3372
|
+
return;
|
|
3373
|
+
}
|
|
3374
|
+
this.backfillNewFilePatch(sid, event, data);
|
|
3375
|
+
this.updateReviewDiff(sid, rt, event, data);
|
|
3376
|
+
const seq = rt.snapshot.seq + 1;
|
|
3377
|
+
applyEvent(rt.snapshot, event, data, seq);
|
|
3378
|
+
const frame = { event, sessionId: sid, seq, data };
|
|
3379
|
+
rt.buffer.push(frame);
|
|
3380
|
+
if (rt.buffer.length > BUFFER_MAX) rt.buffer.splice(0, rt.buffer.length - BUFFER_MAX);
|
|
3381
|
+
for (const s of rt.subscribers) s.send(frame);
|
|
3382
|
+
this.scheduleSave(rt);
|
|
3383
|
+
if (event === "topic:update" && data?.title) {
|
|
3384
|
+
this.registry.updateSession(sid, { title: String(data.title) });
|
|
3385
|
+
this.broadcastRegistry();
|
|
3386
|
+
} else if (event === "input:received" && data?.source === "cron") {
|
|
3387
|
+
const rec = this.registry.getSession(sid);
|
|
3388
|
+
const w = rec ? this.pool.get(rec.workingDir) : void 0;
|
|
3389
|
+
if (w?.alive) w.lastUsed = Date.now();
|
|
3390
|
+
} else if (event === "input:processing") {
|
|
3391
|
+
const rec = this.registry.getSession(sid);
|
|
3392
|
+
if (rec && !rec.title && (!data?.source || data.source === "user")) {
|
|
3393
|
+
const t = String(data?.originalInput ?? data?.input ?? "").replace(/\s+/g, " ").trim().slice(0, 40);
|
|
3394
|
+
if (t) this.registry.updateSession(sid, { title: t });
|
|
3395
|
+
}
|
|
3396
|
+
this.registry.touchSession(sid);
|
|
3397
|
+
this.broadcastRegistry();
|
|
3398
|
+
} else if (event === "permissionLevel:update" && data?.level) {
|
|
3399
|
+
this.registry.updateSession(sid, { permissionLevel: data.level });
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
onWorkerExit(sids, code) {
|
|
3403
|
+
for (const sid of sids) {
|
|
3404
|
+
const rt = this.runtimes.get(sid);
|
|
3405
|
+
if (!rt) continue;
|
|
3406
|
+
if (rt.snapshot.state === "processing" || pendingBlocks(rt.snapshot).length) {
|
|
3407
|
+
this.onEvent(sid, "session:interrupted", { agentId: "main", content: `core \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF08code ${code}\uFF09` });
|
|
3408
|
+
this.onEvent(sid, "state:update", { state: "idle" });
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
this.broadcastLiveness();
|
|
3412
|
+
}
|
|
3413
|
+
broadcastAll(frame) {
|
|
3414
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3415
|
+
for (const rt of this.runtimes.values()) for (const s of rt.subscribers) seen.add(s);
|
|
3416
|
+
for (const s of this.globalSubscribers) seen.add(s);
|
|
3417
|
+
for (const s of seen) s.send(frame);
|
|
3418
|
+
}
|
|
3419
|
+
/** 全局订阅者(所有 WS 连接),用于 registry/model 更新广播 */
|
|
3420
|
+
globalSubscribers = /* @__PURE__ */ new Set();
|
|
3421
|
+
broadcastRegistry() {
|
|
3422
|
+
this.broadcastAll({ event: SERVER_EVENTS.registryUpdate, data: this.registry.snapshot() });
|
|
3423
|
+
}
|
|
3424
|
+
/** 存活会话:worker 进程活着且其中已创建该 SemaSession */
|
|
3425
|
+
liveSessionIds() {
|
|
3426
|
+
return this.pool.list().filter((w) => w.alive).flatMap((w) => [...w.sessions]);
|
|
3427
|
+
}
|
|
3428
|
+
broadcastLiveness() {
|
|
3429
|
+
this.broadcastAll({ event: SERVER_EVENTS.livenessUpdate, data: { sessions: this.liveSessionIds() } });
|
|
3430
|
+
}
|
|
3431
|
+
// ==================== 订阅 ====================
|
|
3432
|
+
subscribe(sub, sid, afterSeq) {
|
|
3433
|
+
const rt = this.loadRuntime(sid);
|
|
3434
|
+
rt.subscribers.add(sub);
|
|
3435
|
+
if (afterSeq === void 0 || afterSeq >= rt.snapshot.seq) return { seq: rt.snapshot.seq, resync: false };
|
|
3436
|
+
const oldest = rt.buffer[0]?.seq;
|
|
3437
|
+
if (oldest === void 0 || oldest > afterSeq + 1) return { seq: rt.snapshot.seq, resync: true };
|
|
3438
|
+
for (const f of rt.buffer) if (f.seq > afterSeq) sub.send(f);
|
|
3439
|
+
return { seq: rt.snapshot.seq, resync: false };
|
|
3440
|
+
}
|
|
3441
|
+
unsubscribe(sub, sid) {
|
|
3442
|
+
if (sid) {
|
|
3443
|
+
this.runtimes.get(sid)?.subscribers.delete(sub);
|
|
3444
|
+
return;
|
|
3445
|
+
}
|
|
3446
|
+
for (const rt of this.runtimes.values()) rt.subscribers.delete(sub);
|
|
3447
|
+
}
|
|
3448
|
+
// ==================== worker / 会话存活 ====================
|
|
3449
|
+
async ensureLive(sid) {
|
|
3450
|
+
const rt = this.loadRuntime(sid);
|
|
3451
|
+
rt.lastWarmAt = Date.now();
|
|
3452
|
+
if (rt.ensuring) return rt.ensuring;
|
|
3453
|
+
const rec = this.registry.getSession(sid);
|
|
3454
|
+
rt.ensuring = (async () => {
|
|
3455
|
+
if (!import_fs14.default.existsSync(rec.workingDir)) {
|
|
3456
|
+
if (rec.projectId) throw new Error(`\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728: ${rec.workingDir}`);
|
|
3457
|
+
import_fs14.default.mkdirSync(rec.workingDir, { recursive: true });
|
|
3458
|
+
}
|
|
3459
|
+
const w = await this.pool.acquire(rec.workingDir);
|
|
3460
|
+
if (!w.sessions.has(sid)) {
|
|
3461
|
+
await this.pool.request(w, "session.create", void 0, {
|
|
3462
|
+
sessionId: sid,
|
|
3463
|
+
agentMode: rt.snapshot.agentMode,
|
|
3464
|
+
permissionLevel: rt.snapshot.permissionLevel
|
|
3465
|
+
});
|
|
3466
|
+
w.sessions.add(sid);
|
|
3467
|
+
this.broadcastLiveness();
|
|
3468
|
+
}
|
|
3469
|
+
return w;
|
|
3470
|
+
})();
|
|
3471
|
+
try {
|
|
3472
|
+
return await rt.ensuring;
|
|
3473
|
+
} finally {
|
|
3474
|
+
rt.ensuring = void 0;
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
/**
|
|
3478
|
+
* 进程级操作(模型/系统配置等全局 ~/.sema 配置)固定走专用 worker:
|
|
3479
|
+
* cwd 为 ~/.sema/webui/workspace(不在 macOS「文稿」授权范围内,也不会污染用户项目目录),与会话 worker 的回收互不影响。
|
|
3480
|
+
* 项目作用域的查询(P1:项目级 Skills/Agents/MCP 等)应按 projectId 路由到该项目的 worker,不走这里。
|
|
3481
|
+
*/
|
|
3482
|
+
async configWorker() {
|
|
3483
|
+
import_fs14.default.mkdirSync(CONFIG_WORKSPACE, { recursive: true });
|
|
3484
|
+
return this.pool.acquire(CONFIG_WORKSPACE);
|
|
3485
|
+
}
|
|
3486
|
+
/** 服务启动即拉起配置 worker(不等就绪):首屏取模型列表不再等冷启动,也避开与会话 worker 同时冷启动 */
|
|
3487
|
+
prewarmConfigWorker() {
|
|
3488
|
+
void this.configWorker().catch(() => void 0);
|
|
3489
|
+
}
|
|
3490
|
+
// ==================== 独立会话备用 worker ====================
|
|
3491
|
+
/**
|
|
3492
|
+
* 预热备用 worker:占一个独立会话目录并拉起 worker,不建会话记录。
|
|
3493
|
+
* 已有备用则只确保其 worker 存活(被空闲回收后重新拉起);触顶时不预热,避免为预热淘汰在用 worker。失败静默。
|
|
3494
|
+
*/
|
|
3495
|
+
async warmSpare() {
|
|
3496
|
+
if (this.sparing) return this.sparing;
|
|
3497
|
+
this.sparing = (async () => {
|
|
3498
|
+
if (this.spare && !import_fs14.default.existsSync(this.spare.workingDir)) this.spare = void 0;
|
|
3499
|
+
if (!this.spare) {
|
|
3500
|
+
const id = (0, import_crypto3.randomUUID)();
|
|
3501
|
+
this.spare = { id, workingDir: this.registry.allocStandaloneDir(id) };
|
|
3502
|
+
}
|
|
3503
|
+
const w = this.pool.get(this.spare.workingDir);
|
|
3504
|
+
if (w?.alive) {
|
|
3505
|
+
w.lastUsed = Date.now();
|
|
3506
|
+
return;
|
|
3507
|
+
}
|
|
3508
|
+
if (!this.pool.hasCapacity()) return;
|
|
3509
|
+
await this.pool.acquire(this.spare.workingDir);
|
|
3510
|
+
})().catch(() => void 0).finally(() => {
|
|
3511
|
+
this.sparing = void 0;
|
|
3512
|
+
});
|
|
3513
|
+
return this.sparing;
|
|
3514
|
+
}
|
|
3515
|
+
/** 取走备用目录给新独立会话(worker 若已被回收也复用目录,不留空目录);没有则返回 undefined */
|
|
3516
|
+
takeSpare() {
|
|
3517
|
+
const s = this.spare;
|
|
3518
|
+
this.spare = void 0;
|
|
3519
|
+
return s && import_fs14.default.existsSync(s.workingDir) ? s : void 0;
|
|
3520
|
+
}
|
|
3521
|
+
/** 退出时清掉没用上的备用目录(worker 已随 pool.disposeAll 退出) */
|
|
3522
|
+
discardSpare() {
|
|
3523
|
+
const s = this.spare;
|
|
3524
|
+
this.spare = void 0;
|
|
3525
|
+
if (!s) return;
|
|
3526
|
+
try {
|
|
3527
|
+
if (import_fs14.default.existsSync(s.workingDir) && import_fs14.default.readdirSync(s.workingDir).filter((n) => n !== ".DS_Store").length === 0) {
|
|
3528
|
+
import_fs14.default.rmSync(s.workingDir, { recursive: true, force: true });
|
|
3529
|
+
removeEmptyDateParent(s.workingDir);
|
|
3530
|
+
}
|
|
3531
|
+
} catch {
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
// ==================== 动作分发 ====================
|
|
3535
|
+
async dispatch(action, sid, payload) {
|
|
3536
|
+
if (action.startsWith("core.")) {
|
|
3537
|
+
if (action === "core.updateCoreConfig" || action === "core.refreshSkills" || action === "core.refreshMCPServerInfo") {
|
|
3538
|
+
await Promise.all(this.pool.list().filter((w3) => w3.alive).map((w3) => this.pool.request(w3, action, void 0, payload).catch(() => null)));
|
|
3539
|
+
return true;
|
|
3540
|
+
}
|
|
3541
|
+
const w2 = await this.configWorker();
|
|
3542
|
+
const result2 = await this.pool.request(w2, action, void 0, payload);
|
|
3543
|
+
if (CORE_WRITE_ACTIONS.has(action)) {
|
|
3544
|
+
this.pool.markStale(w2);
|
|
3545
|
+
this.broadcastAll({ event: SERVER_EVENTS.modelUpdate, data: result2 });
|
|
3546
|
+
}
|
|
3547
|
+
return result2;
|
|
3548
|
+
}
|
|
3549
|
+
if (action === "draft.warm") {
|
|
3550
|
+
await this.warmSpare();
|
|
3551
|
+
return true;
|
|
3552
|
+
}
|
|
3553
|
+
if (action === "project.warm" || action === "project.getCommandsInfo") {
|
|
3554
|
+
const proj = this.registry.getProject(String(payload?.projectId || ""));
|
|
3555
|
+
if (!proj) throw new Error(`\u9879\u76EE\u4E0D\u5B58\u5728: ${payload?.projectId}`);
|
|
3556
|
+
const w2 = await this.pool.acquire(proj.workingDir);
|
|
3557
|
+
if (action === "project.warm") {
|
|
3558
|
+
void this.pool.request(w2, "core.getCommandsInfo", void 0, {}).catch(() => null);
|
|
3559
|
+
return true;
|
|
3560
|
+
}
|
|
3561
|
+
return this.pool.request(w2, "core.getCommandsInfo", void 0, {});
|
|
3562
|
+
}
|
|
3563
|
+
if (!sid) throw new Error("\u7F3A\u5C11 sessionId");
|
|
3564
|
+
const rt = this.loadRuntime(sid);
|
|
3565
|
+
if (action === "session.warm") {
|
|
3566
|
+
await this.ensureLive(sid);
|
|
3567
|
+
return true;
|
|
3568
|
+
}
|
|
3569
|
+
switch (action) {
|
|
3570
|
+
case "session.updateAgentMode":
|
|
3571
|
+
applyLocal(rt.snapshot, { type: "agentMode", mode: payload.mode });
|
|
3572
|
+
this.registry.updateSession(sid, { agentMode: payload.mode });
|
|
3573
|
+
this.scheduleSave(rt);
|
|
3574
|
+
break;
|
|
3575
|
+
case "session.updatePermissionLevel":
|
|
3576
|
+
applyLocal(rt.snapshot, { type: "permissionLevel", level: payload.level });
|
|
3577
|
+
this.registry.updateSession(sid, { permissionLevel: payload.level });
|
|
3578
|
+
this.scheduleSave(rt);
|
|
3579
|
+
break;
|
|
3580
|
+
case "session.respondToToolPermission":
|
|
3581
|
+
applyLocal(rt.snapshot, { type: "permission", toolId: payload.response?.toolId, selected: payload.response?.selected });
|
|
3582
|
+
this.scheduleSave(rt);
|
|
3583
|
+
break;
|
|
3584
|
+
case "session.respondToPickOption":
|
|
3585
|
+
applyLocal(rt.snapshot, { type: "pick", id: payload.blockId, answers: payload.response?.answers ?? null });
|
|
3586
|
+
this.scheduleSave(rt);
|
|
3587
|
+
break;
|
|
3588
|
+
case "session.respondToPlanExit":
|
|
3589
|
+
applyLocal(rt.snapshot, { type: "plan-exit", id: payload.blockId, selected: payload.response?.selected });
|
|
3590
|
+
this.scheduleSave(rt);
|
|
3591
|
+
break;
|
|
3592
|
+
case "session.processUserInput":
|
|
3593
|
+
this.registry.touchSession(sid);
|
|
3594
|
+
break;
|
|
3595
|
+
}
|
|
3596
|
+
const w = await this.ensureLive(sid);
|
|
3597
|
+
const result = await this.pool.request(w, action, sid, payload);
|
|
3598
|
+
if (action === "session.interrupt") {
|
|
3599
|
+
await this.pool.request(w, "session.stopAllTasks", sid, {}).catch(() => null);
|
|
3600
|
+
}
|
|
3601
|
+
if (action === "session.fork" && result?.ok !== false) {
|
|
3602
|
+
const uuid = payload.messageUuid;
|
|
3603
|
+
const idx = rt.snapshot.blocks.findIndex((b) => b.kind === "user" && b.inputId === uuid);
|
|
3604
|
+
if (idx >= 0) {
|
|
3605
|
+
rt.snapshot.blocks = rt.snapshot.blocks.slice(0, idx);
|
|
3606
|
+
rt.snapshot.turn = null;
|
|
3607
|
+
rt.snapshot.streamingId = void 0;
|
|
3608
|
+
if (rt.diffBase) {
|
|
3609
|
+
resetTurn(rt.diffBase);
|
|
3610
|
+
const rec = this.registry.getSession(sid);
|
|
3611
|
+
if (rec && Array.isArray(result?.restoredFiles)) {
|
|
3612
|
+
for (const p of result.restoredFiles) captureOnRead(rt.diffBase, rec.workingDir, String(p));
|
|
3613
|
+
}
|
|
3614
|
+
}
|
|
3615
|
+
this.scheduleSave(rt);
|
|
3616
|
+
for (const s of rt.subscribers) s.send({ event: SERVER_EVENTS.sessionResync, data: { sessionId: sid } });
|
|
3617
|
+
}
|
|
3618
|
+
}
|
|
3619
|
+
return result;
|
|
3620
|
+
}
|
|
3621
|
+
// ==================== 生命周期 ====================
|
|
3622
|
+
/** 新会话:建注册表记录 + 立刻拉起 worker;启动失败回滚注册表/transcript/独立目录,不留垃圾。
|
|
3623
|
+
* 独立会话优先复用草稿页预热好的备用目录与 worker(ensureLive 命中已存活 worker,只做 session.create) */
|
|
3624
|
+
async createSession(opts) {
|
|
3625
|
+
const rec = this.registry.createSession({ ...opts, preallocated: opts.projectId ? void 0 : this.takeSpare() });
|
|
3626
|
+
const rt = this.loadRuntime(rec.id);
|
|
3627
|
+
this.broadcastRegistry();
|
|
3628
|
+
try {
|
|
3629
|
+
await this.ensureLive(rec.id);
|
|
3630
|
+
} catch (e) {
|
|
3631
|
+
if (rt.saveTimer) clearTimeout(rt.saveTimer);
|
|
3632
|
+
this.runtimes.delete(rec.id);
|
|
3633
|
+
this.registry.removeSession(rec.id);
|
|
3634
|
+
try {
|
|
3635
|
+
import_fs14.default.unlinkSync(this.transcriptPath(rec.id));
|
|
3636
|
+
} catch {
|
|
3637
|
+
}
|
|
3638
|
+
if (!rec.projectId) {
|
|
3639
|
+
try {
|
|
3640
|
+
import_fs14.default.rmSync(rec.workingDir, { recursive: true, force: true });
|
|
3641
|
+
} catch {
|
|
3642
|
+
}
|
|
3643
|
+
}
|
|
3644
|
+
this.broadcastRegistry();
|
|
3645
|
+
throw e;
|
|
3646
|
+
}
|
|
3647
|
+
void this.evictOverflow();
|
|
3648
|
+
return { record: rec, snapshot: rt.snapshot };
|
|
3649
|
+
}
|
|
3650
|
+
/** 分支到新聊天:core 复制模型历史,WebUI 复制展示快照,并在同目录 worker 中创建新的 SemaSession。
|
|
3651
|
+
* beforeMessageUuid:截断锚点(某条用户输入的 inputId),历史截到该输入之前;不传则全量复制。 */
|
|
3652
|
+
async branchSession(sourceId, beforeMessageUuid) {
|
|
3653
|
+
if (this.branching.has(sourceId)) throw new Error("\u6B63\u5728\u521B\u5EFA\u5206\u652F\uFF0C\u8BF7\u52FF\u91CD\u590D\u64CD\u4F5C");
|
|
3654
|
+
const source = this.registry.getSession(sourceId);
|
|
3655
|
+
if (!source) throw new Error("\u6E90\u4F1A\u8BDD\u4E0D\u5B58\u5728");
|
|
3656
|
+
const sourceRt = this.loadRuntime(sourceId);
|
|
3657
|
+
if (sourceRt.snapshot.state !== "idle" || pendingBlocks(sourceRt.snapshot).length > 0 || sourceRt.snapshot.blocks.some((b) => b.kind === "user" && b.queued)) {
|
|
3658
|
+
throw new Error("\u4F1A\u8BDD\u5904\u7406\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u7A7A\u95F2\u540E\u518D\u5206\u652F");
|
|
3659
|
+
}
|
|
3660
|
+
const cutIdx = beforeMessageUuid !== void 0 ? sourceRt.snapshot.blocks.findIndex((b) => b.kind === "user" && b.inputId === beforeMessageUuid) : -1;
|
|
3661
|
+
if (beforeMessageUuid !== void 0 && cutIdx < 0) throw new Error("\u5206\u652F\u951A\u70B9\u4E0D\u5B58\u5728");
|
|
3662
|
+
this.branching.add(sourceId);
|
|
3663
|
+
let targetId;
|
|
3664
|
+
let targetOwned = false;
|
|
3665
|
+
try {
|
|
3666
|
+
const worker = await this.ensureLive(sourceId);
|
|
3667
|
+
const result = await this.pool.request(worker, "session.branch", sourceId, { beforeMessageUuid });
|
|
3668
|
+
if (!result?.ok) throw new Error(result?.error || "\u5206\u652F\u5931\u8D25");
|
|
3669
|
+
targetId = String(result.sessionId || "");
|
|
3670
|
+
if (!targetId || this.registry.getSession(targetId)) throw new Error("\u5206\u652F\u4F1A\u8BDD ID \u65E0\u6548\u6216\u5DF2\u5B58\u5728");
|
|
3671
|
+
targetOwned = true;
|
|
3672
|
+
const record = this.registry.createBranchedSession(sourceId, targetId);
|
|
3673
|
+
const cloned = structuredClone(sourceRt.snapshot);
|
|
3674
|
+
if (cutIdx >= 0) cloned.blocks = cloned.blocks.slice(0, cutIdx);
|
|
3675
|
+
const snapshot = {
|
|
3676
|
+
...cloned,
|
|
3677
|
+
sessionId: record.id,
|
|
3678
|
+
workingDir: record.workingDir,
|
|
3679
|
+
seq: 0,
|
|
3680
|
+
state: "idle",
|
|
3681
|
+
agentMode: record.agentMode,
|
|
3682
|
+
permissionLevel: record.permissionLevel,
|
|
3683
|
+
blocks: [...cloned.blocks, {
|
|
3684
|
+
kind: "branch-origin",
|
|
3685
|
+
id: `branch-origin:${record.id}`,
|
|
3686
|
+
ts: Date.now(),
|
|
3687
|
+
sourceSessionId: source.id,
|
|
3688
|
+
sourceTitle: source.title || "\u539F\u804A\u5929"
|
|
3689
|
+
}],
|
|
3690
|
+
turn: null,
|
|
3691
|
+
streamingId: void 0,
|
|
3692
|
+
historyLoaded: true,
|
|
3693
|
+
quickchats: void 0
|
|
3694
|
+
};
|
|
3695
|
+
const targetRt = { snapshot, buffer: [], subscribers: /* @__PURE__ */ new Set() };
|
|
3696
|
+
this.runtimes.set(record.id, targetRt);
|
|
3697
|
+
writeJsonAtomic(this.transcriptPath(record.id), snapshot);
|
|
3698
|
+
await this.ensureLive(record.id);
|
|
3699
|
+
this.broadcastRegistry();
|
|
3700
|
+
void this.evictOverflow();
|
|
3701
|
+
return { record, snapshot: targetRt.snapshot };
|
|
3702
|
+
} catch (error) {
|
|
3703
|
+
if (targetId && targetOwned) {
|
|
3704
|
+
const targetRt = this.runtimes.get(targetId);
|
|
3705
|
+
if (targetRt?.saveTimer) clearTimeout(targetRt.saveTimer);
|
|
3706
|
+
this.runtimes.delete(targetId);
|
|
3707
|
+
this.registry.removeSession(targetId);
|
|
3708
|
+
try {
|
|
3709
|
+
import_fs14.default.unlinkSync(this.transcriptPath(targetId));
|
|
3710
|
+
} catch {
|
|
3711
|
+
}
|
|
3712
|
+
const worker = this.pool.get(source.workingDir);
|
|
3713
|
+
if (worker?.alive && worker.sessions.has(targetId)) {
|
|
3714
|
+
await this.pool.request(worker, "session.close", targetId, {}).catch(() => null);
|
|
3715
|
+
worker.sessions.delete(targetId);
|
|
3716
|
+
this.broadcastLiveness();
|
|
3717
|
+
}
|
|
3718
|
+
await this.dispatch("core.deleteSessionHistory", void 0, { sessionId: targetId, projectPath: source.workingDir }).catch(() => null);
|
|
3719
|
+
this.broadcastRegistry();
|
|
3720
|
+
}
|
|
3721
|
+
throw error;
|
|
3722
|
+
} finally {
|
|
3723
|
+
this.branching.delete(sourceId);
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
async closeSession(sid) {
|
|
3727
|
+
const rec = this.registry.getSession(sid);
|
|
3728
|
+
if (rec) {
|
|
3729
|
+
const w = this.pool.get(rec.workingDir);
|
|
3730
|
+
if (w?.alive && w.sessions.has(sid)) {
|
|
3731
|
+
await this.pool.request(w, "session.close", sid, {}).catch(() => null);
|
|
3732
|
+
w.sessions.delete(sid);
|
|
3733
|
+
this.broadcastLiveness();
|
|
3734
|
+
}
|
|
3735
|
+
if (w?.alive && (rec.managedWorkingDir ?? !rec.projectId) && !this.registry.hasWorkingDirReference(rec.workingDir, sid)) await this.pool.kill(w);
|
|
3736
|
+
}
|
|
3737
|
+
const rt = this.runtimes.get(sid);
|
|
3738
|
+
if (rt?.saveTimer) clearTimeout(rt.saveTimer);
|
|
3739
|
+
this.runtimes.delete(sid);
|
|
3740
|
+
try {
|
|
3741
|
+
import_fs14.default.unlinkSync(this.transcriptPath(sid));
|
|
3742
|
+
} catch {
|
|
3743
|
+
}
|
|
3744
|
+
}
|
|
3745
|
+
isBusy(sid) {
|
|
3746
|
+
const rt = this.runtimes.get(sid);
|
|
3747
|
+
return !!rt && (rt.snapshot.state === "processing" || pendingBlocks(rt.snapshot).length > 0);
|
|
3748
|
+
}
|
|
3749
|
+
// ==================== 超限退场 ====================
|
|
3750
|
+
/** 忙碌中、有前端订阅、或名下有非持久化定时任务的会话不参与退场 */
|
|
3751
|
+
isEvictable(sid, cronGuard) {
|
|
3752
|
+
return !this.isBusy(sid) && (this.runtimes.get(sid)?.subscribers.size ?? 0) === 0 && !cronGuard?.has(sid) && !this.isKept(sid);
|
|
3753
|
+
}
|
|
3754
|
+
/** keeper 保活期内的会话(等待定时任务注入/执行) */
|
|
3755
|
+
isKept(sid) {
|
|
3756
|
+
const until = this.runtimes.get(sid)?.keepUntil;
|
|
3757
|
+
return until != null && until > Date.now();
|
|
3758
|
+
}
|
|
3759
|
+
/** 各存活 worker 的 worker.stats(失败的 worker 跳过) */
|
|
3760
|
+
async workerStats() {
|
|
3761
|
+
const out = /* @__PURE__ */ new Map();
|
|
3762
|
+
await Promise.all(this.pool.list().filter((w) => w.alive).map(async (w) => {
|
|
3763
|
+
try {
|
|
3764
|
+
out.set(w, await this.pool.request(w, "worker.stats", void 0, {}, 5e3, { bump: false }));
|
|
3765
|
+
} catch {
|
|
3766
|
+
}
|
|
3767
|
+
}));
|
|
3768
|
+
return out;
|
|
3769
|
+
}
|
|
3770
|
+
/** 名下有非持久化定时任务的会话集合(丢了就是真丢,退场/回收一律跳过) */
|
|
3771
|
+
cronGuardedSessions(stats) {
|
|
3772
|
+
const out = /* @__PURE__ */ new Set();
|
|
3773
|
+
for (const st of stats.values()) {
|
|
3774
|
+
for (const [sid, n] of Object.entries(st?.cron?.nonPersisted || {})) if (Number(n) > 0) out.add(sid);
|
|
3775
|
+
}
|
|
3776
|
+
return out;
|
|
3777
|
+
}
|
|
3778
|
+
/** 目录下是否仍有启用的持久化定时任务(退场项目时跳过,留给更旧的无任务项目先退) */
|
|
3779
|
+
hasPersistedCron(workingDir) {
|
|
3780
|
+
try {
|
|
3781
|
+
return readPersistedCron(workingDir).active > 0;
|
|
3782
|
+
} catch {
|
|
3783
|
+
return false;
|
|
3784
|
+
}
|
|
3785
|
+
}
|
|
3786
|
+
/** 退场一个会话:杀终端 → 关闭对应 SemaSession → 删 transcript → 移除注册表记录 */
|
|
3787
|
+
async evictSession(sid) {
|
|
3788
|
+
this.killTerminals?.(sid);
|
|
3789
|
+
await this.closeSession(sid);
|
|
3790
|
+
return this.registry.removeSession(sid);
|
|
3791
|
+
}
|
|
3792
|
+
/**
|
|
3793
|
+
* 超限退场(LRU,均按 lastActiveAt):
|
|
3794
|
+
* 1. 独立会话超 {@link STANDALONE_SESSION_LIMIT}:移除注册表/transcript + 硬删独占目录 + 删 core 对应 history 项目
|
|
3795
|
+
* 2. 项目内会话超 {@link SESSIONS_PER_PROJECT_LIMIT}:移除注册表/transcript + 删 core 该会话历史文件(项目目录不动)
|
|
3796
|
+
* 3. 项目超 {@link PROJECT_LIMIT}:仅移除索引及其会话记录/transcript,磁盘与 core history 均保留,重新导入可恢复
|
|
3797
|
+
*/
|
|
3798
|
+
async evictOverflow() {
|
|
3799
|
+
if (this.evicting) return;
|
|
3800
|
+
this.evicting = true;
|
|
3801
|
+
try {
|
|
3802
|
+
let changed = false;
|
|
3803
|
+
const cronGuard = this.cronGuardedSessions(await this.workerStats());
|
|
3804
|
+
const byActiveDesc = (a, b) => b.lastActiveAt - a.lastActiveAt;
|
|
3805
|
+
const standalone = this.registry.listSessions().filter((s) => !s.projectId).sort(byActiveDesc);
|
|
3806
|
+
for (const rec of standalone.slice(STANDALONE_SESSION_LIMIT)) {
|
|
3807
|
+
if (!this.isEvictable(rec.id, cronGuard)) continue;
|
|
3808
|
+
await this.evictSession(rec.id);
|
|
3809
|
+
const hasOtherRef = this.registry.hasWorkingDirReference(rec.workingDir);
|
|
3810
|
+
const managedRoot = import_path13.default.resolve(SEMA_DOCS_ROOT) + import_path13.default.sep;
|
|
3811
|
+
if ((rec.managedWorkingDir ?? !rec.projectId) && !hasOtherRef && import_path13.default.resolve(rec.workingDir).startsWith(managedRoot)) {
|
|
3812
|
+
try {
|
|
3813
|
+
import_fs14.default.rmSync(rec.workingDir, { recursive: true, force: true });
|
|
3814
|
+
} catch {
|
|
3815
|
+
}
|
|
3816
|
+
removeEmptyDateParent(rec.workingDir);
|
|
3817
|
+
await this.dispatch("core.deleteProjectHistory", void 0, { projectPath: rec.workingDir }).catch((e) => logErr("evict", "\u5220\u9664 history \u9879\u76EE\u5931\u8D25:", e?.message || e));
|
|
3818
|
+
} else {
|
|
3819
|
+
await this.dispatch("core.deleteSessionHistory", void 0, { sessionId: rec.id, projectPath: rec.workingDir }).catch((e) => logErr("evict", "\u5220\u9664\u4F1A\u8BDD\u5386\u53F2\u5931\u8D25:", e?.message || e));
|
|
3820
|
+
}
|
|
3821
|
+
changed = true;
|
|
3822
|
+
}
|
|
3823
|
+
const byProject = /* @__PURE__ */ new Map();
|
|
3824
|
+
for (const s of this.registry.listSessions()) {
|
|
3825
|
+
if (!s.projectId) continue;
|
|
3826
|
+
const list = byProject.get(s.projectId) || [];
|
|
3827
|
+
list.push(s);
|
|
3828
|
+
byProject.set(s.projectId, list);
|
|
3829
|
+
}
|
|
3830
|
+
for (const [pid, list] of byProject) {
|
|
3831
|
+
const proj = this.registry.getProject(pid);
|
|
3832
|
+
list.sort(byActiveDesc);
|
|
3833
|
+
for (const rec of list.slice(SESSIONS_PER_PROJECT_LIMIT)) {
|
|
3834
|
+
if (!this.isEvictable(rec.id, cronGuard)) continue;
|
|
3835
|
+
await this.evictSession(rec.id);
|
|
3836
|
+
await this.dispatch("core.deleteSessionHistory", void 0, { sessionId: rec.id, projectPath: proj?.workingDir || rec.workingDir }).catch((e) => logErr("evict", "\u5220\u9664\u4F1A\u8BDD\u5386\u53F2\u5931\u8D25:", e?.message || e));
|
|
3837
|
+
changed = true;
|
|
3838
|
+
}
|
|
3839
|
+
}
|
|
3840
|
+
const projects = [...this.registry.snapshot().projects].sort(byActiveDesc);
|
|
3841
|
+
for (const proj of projects.slice(PROJECT_LIMIT)) {
|
|
3842
|
+
const sess = this.registry.listSessions().filter((s) => s.projectId === proj.id);
|
|
3843
|
+
if (sess.some((s) => !this.isEvictable(s.id, cronGuard))) continue;
|
|
3844
|
+
if (this.hasPersistedCron(proj.workingDir)) continue;
|
|
3845
|
+
for (const s of sess) {
|
|
3846
|
+
this.killTerminals?.(s.id);
|
|
3847
|
+
await this.closeSession(s.id);
|
|
3848
|
+
}
|
|
3849
|
+
this.registry.removeProject(proj.id);
|
|
3850
|
+
changed = true;
|
|
3851
|
+
}
|
|
3852
|
+
if (changed) this.broadcastRegistry();
|
|
3853
|
+
} catch (e) {
|
|
3854
|
+
logErr("evict", "\u9000\u573A\u5931\u8D25:", e?.message || e);
|
|
3855
|
+
} finally {
|
|
3856
|
+
this.evicting = false;
|
|
3857
|
+
}
|
|
3858
|
+
}
|
|
3859
|
+
/**
|
|
3860
|
+
* 会话级回收:worker 内常驻的 SemaSession 空闲超时、或超出每 worker 上限时关闭。
|
|
3861
|
+
* 历史已由 core 落盘,用户再操作时 ensureLive 会自动 session.create 恢复,只回收内存态。
|
|
3862
|
+
* 忙会话(processing/未决交互)和有运行中后台任务的会话不回收。
|
|
3863
|
+
*/
|
|
3864
|
+
async reapSessions() {
|
|
3865
|
+
const now = Date.now();
|
|
3866
|
+
for (const w of this.pool.list()) {
|
|
3867
|
+
if (!w.alive) continue;
|
|
3868
|
+
let guarded = /* @__PURE__ */ new Set();
|
|
3869
|
+
try {
|
|
3870
|
+
const st = await this.pool.request(w, "worker.stats", void 0, {}, 5e3, { bump: false });
|
|
3871
|
+
guarded = this.cronGuardedSessions(/* @__PURE__ */ new Map([[w, st]]));
|
|
3872
|
+
} catch {
|
|
3873
|
+
continue;
|
|
3874
|
+
}
|
|
3875
|
+
const total = w.sessions.size;
|
|
3876
|
+
const idle = [...w.sessions].filter((sid) => !this.isBusy(sid) && !guarded.has(sid) && !this.isKept(sid)).map((sid) => {
|
|
3877
|
+
const active = this.registry.getSession(sid)?.lastActiveAt ?? 0;
|
|
3878
|
+
const warm = this.runtimes.get(sid)?.lastWarmAt ?? 0;
|
|
3879
|
+
return { sid, t: Math.max(active, warm), active, warm };
|
|
3880
|
+
}).sort((a, b) => a.t - b.t);
|
|
3881
|
+
const excess = Math.max(0, total - MAX_LIVE_SESSIONS);
|
|
3882
|
+
for (let i = 0; i < idle.length; i++) {
|
|
3883
|
+
const { sid, active, warm } = idle[i];
|
|
3884
|
+
if (i >= excess && (now - active <= SESSION_IDLE_MS || now - warm <= WARM_GRACE_MS)) continue;
|
|
3885
|
+
if (this.isBusy(sid)) continue;
|
|
3886
|
+
try {
|
|
3887
|
+
const tasks = await this.pool.request(w, "session.getTaskList", sid, {}, 5e3, { bump: false });
|
|
3888
|
+
if (Array.isArray(tasks) && tasks.some((task) => task?.status === "running")) continue;
|
|
3889
|
+
await this.pool.request(w, "session.close", sid, {}, 1e4, { bump: false });
|
|
3890
|
+
w.sessions.delete(sid);
|
|
3891
|
+
this.broadcastLiveness();
|
|
3892
|
+
} catch {
|
|
3893
|
+
}
|
|
3894
|
+
}
|
|
3895
|
+
}
|
|
3896
|
+
}
|
|
3897
|
+
// ==================== 定时任务守护 ====================
|
|
3898
|
+
/**
|
|
3899
|
+
* 持久化定时任务 worker 被回收后的处理:
|
|
3900
|
+
* - evict(触顶淘汰):向该 worker 上的会话注入提示,用户能看到任务为何暂停
|
|
3901
|
+
* - idle / stale:正常路径,由 keeper 临近触发再拉起,不打扰用户
|
|
3902
|
+
*/
|
|
3903
|
+
onCronWorkerReclaimed(workingDir, sids, reason) {
|
|
3904
|
+
if (reason !== "evict") return;
|
|
3905
|
+
for (const sid of sids) {
|
|
3906
|
+
if (!this.registry.getSession(sid)) continue;
|
|
3907
|
+
this.onEvent(sid, "hook:notice", { kind: "systemMessage", message: "\u8FDB\u7A0B\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u672C\u9879\u76EE\u7684\u5B9A\u65F6\u4EFB\u52A1\u8FDB\u7A0B\u5DF2\u88AB\u56DE\u6536\uFF1B\u4E34\u8FD1\u89E6\u53D1\u65F6\u4F1A\u81EA\u52A8\u62C9\u8D77\uFF0C\u4E5F\u53EF\u6253\u5F00\u672C\u9879\u76EE\u4EFB\u4E00\u4F1A\u8BDD\u7ACB\u5373\u6062\u590D" });
|
|
3908
|
+
}
|
|
3909
|
+
}
|
|
3910
|
+
/** 持久化定时任务的扫描范围 = 项目目录 ∪ 会话目录:项目下会话全被删/退场时任务文件仍在,也要能触发 */
|
|
3911
|
+
cronDirs() {
|
|
3912
|
+
const dirs = /* @__PURE__ */ new Map();
|
|
3913
|
+
for (const p of this.registry.snapshot().projects) dirs.set(p.workingDir, { projectId: p.id, sessions: [] });
|
|
3914
|
+
for (const rec of this.registry.listSessions()) {
|
|
3915
|
+
const e = dirs.get(rec.workingDir) || { projectId: rec.projectId, sessions: [] };
|
|
3916
|
+
e.sessions.push(rec);
|
|
3917
|
+
dirs.set(rec.workingDir, e);
|
|
3918
|
+
}
|
|
3919
|
+
return dirs;
|
|
3920
|
+
}
|
|
3921
|
+
/**
|
|
3922
|
+
* 是否有不该被系统睡眠打断的工作(桌面版据此阻止睡眠):
|
|
3923
|
+
* 会话正在处理且没有等待用户的交互、worker 有运行中的后台任务、
|
|
3924
|
+
* 或定时任务将在 {@link KEEP_AWAKE_CRON_LEAD_MS} 内触发(持久化的看任务文件,非持久化的看 worker.stats)。
|
|
3925
|
+
* 等待权限确认的会话不算:卡在用户身上,机器醒着也没用。
|
|
3926
|
+
*/
|
|
3927
|
+
async hasActiveWork() {
|
|
3928
|
+
for (const rt of this.runtimes.values()) {
|
|
3929
|
+
if (rt.snapshot.state === "processing" && pendingBlocks(rt.snapshot).length === 0) return true;
|
|
3930
|
+
}
|
|
3931
|
+
const now = Date.now();
|
|
3932
|
+
const soon = (at) => at != null && at - now <= KEEP_AWAKE_CRON_LEAD_MS;
|
|
3933
|
+
for (const st of (await this.workerStats()).values()) {
|
|
3934
|
+
if (Object.values(st?.runningTasks || {}).some((n) => Number(n) > 0)) return true;
|
|
3935
|
+
if (soon(st?.cron?.nextFireAt)) return true;
|
|
3936
|
+
}
|
|
3937
|
+
for (const dir of this.cronDirs().keys()) {
|
|
3938
|
+
if (!import_fs14.default.existsSync(import_path13.default.join(dir, ".sema", "scheduled_tasks.json"))) continue;
|
|
3939
|
+
const sum = readPersistedCron(dir, now);
|
|
3940
|
+
if (sum.active && soon(sum.nextFireAt)) return true;
|
|
3941
|
+
}
|
|
3942
|
+
return false;
|
|
3943
|
+
}
|
|
3944
|
+
/**
|
|
3945
|
+
* cron keeper(每分钟):扫描注册表里所有目录的持久化定时任务文件,
|
|
3946
|
+
* 距最近触发不足 {@link CRON_KEEPER_LEAD_MS} 且该目录没有"活着且带会话"的 worker 时,
|
|
3947
|
+
* 拉起该目录最近活跃的会话(worker + session.create),让 core 重载任务并按时触发。
|
|
3948
|
+
* 受 maxWorkers 约束:拉起失败只记日志,下一轮重试。
|
|
3949
|
+
*/
|
|
3950
|
+
async cronKeeperTick() {
|
|
3951
|
+
const now = Date.now();
|
|
3952
|
+
for (const [dir, { projectId, sessions }] of this.cronDirs()) {
|
|
3953
|
+
if (!import_fs14.default.existsSync(import_path13.default.join(dir, ".sema", "scheduled_tasks.json"))) continue;
|
|
3954
|
+
const sum = readPersistedCron(dir, now);
|
|
3955
|
+
if (!sum.active || sum.nextFireAt == null) continue;
|
|
3956
|
+
const delta = sum.nextFireAt - now;
|
|
3957
|
+
if (delta > CRON_KEEPER_LEAD_MS || delta < -CRON_KEEPER_LATE_MS) continue;
|
|
3958
|
+
const w = this.pool.get(dir);
|
|
3959
|
+
if (w?.alive && w.sessions.size > 0) {
|
|
3960
|
+
const live = [...w.sessions].map((id) => this.registry.getSession(id)).filter((r) => !!r).sort((a, b) => b.lastActiveAt - a.lastActiveAt)[0];
|
|
3961
|
+
if (live) this.loadRuntime(live.id).keepUntil = sum.nextFireAt + CRON_KEEP_AFTER_FIRE_MS;
|
|
3962
|
+
continue;
|
|
3963
|
+
}
|
|
3964
|
+
let target = [...sessions].sort((a, b) => b.lastActiveAt - a.lastActiveAt)[0];
|
|
3965
|
+
try {
|
|
3966
|
+
if (!target) {
|
|
3967
|
+
if (!projectId) continue;
|
|
3968
|
+
target = this.registry.createSession({ projectId });
|
|
3969
|
+
this.loadRuntime(target.id);
|
|
3970
|
+
this.broadcastRegistry();
|
|
3971
|
+
}
|
|
3972
|
+
const rt = this.loadRuntime(target.id);
|
|
3973
|
+
rt.keepUntil = sum.nextFireAt + CRON_KEEP_AFTER_FIRE_MS;
|
|
3974
|
+
await this.ensureLive(target.id);
|
|
3975
|
+
} catch (e) {
|
|
3976
|
+
logErr("cron", `keeper \u62C9\u8D77\u5931\u8D25 ${dir}:`, e?.message || e);
|
|
3977
|
+
}
|
|
3978
|
+
}
|
|
3979
|
+
}
|
|
3980
|
+
/**
|
|
3981
|
+
* 日程页:全部目录的定时任务。worker 存活 → 问 worker(含非持久化任务);未拉起 → 读持久化文件。
|
|
3982
|
+
* 无任务的目录不返回;按最近触发时间升序。
|
|
3983
|
+
*/
|
|
3984
|
+
async listAllCron() {
|
|
3985
|
+
const now = Date.now();
|
|
3986
|
+
const dirs = /* @__PURE__ */ new Map();
|
|
3987
|
+
for (const rec of this.registry.listSessions()) {
|
|
3988
|
+
const list = dirs.get(rec.workingDir) || [];
|
|
3989
|
+
list.push(rec);
|
|
3990
|
+
dirs.set(rec.workingDir, list);
|
|
3991
|
+
}
|
|
3992
|
+
for (const p of this.registry.snapshot().projects) if (!dirs.has(p.workingDir)) dirs.set(p.workingDir, []);
|
|
3993
|
+
const out = [];
|
|
3994
|
+
await Promise.all([...dirs].map(async ([dir, sessions]) => {
|
|
3995
|
+
const w = this.pool.get(dir);
|
|
3996
|
+
let tasks = [];
|
|
3997
|
+
let live = false;
|
|
3998
|
+
if (w?.alive) {
|
|
3999
|
+
try {
|
|
4000
|
+
tasks = await this.pool.request(w, "session.getCronTasks", void 0, {}, 5e3, { bump: false });
|
|
4001
|
+
live = true;
|
|
4002
|
+
} catch {
|
|
4003
|
+
tasks = readPersistedTasks(dir, now);
|
|
4004
|
+
}
|
|
4005
|
+
} else {
|
|
4006
|
+
tasks = readPersistedTasks(dir, now);
|
|
4007
|
+
}
|
|
4008
|
+
if (!tasks.length) return;
|
|
4009
|
+
const latest = [...sessions].sort((a, b) => b.lastActiveAt - a.lastActiveAt)[0];
|
|
4010
|
+
const proj = latest?.projectId ? this.registry.getProject(latest.projectId) : this.registry.snapshot().projects.find((p) => p.workingDir === dir);
|
|
4011
|
+
out.push({ workingDir: dir, projectId: proj?.id, projectName: proj?.name || (latest?.title || import_path13.default.basename(dir)), live, latestSessionId: latest?.id, tasks });
|
|
4012
|
+
}));
|
|
4013
|
+
const soonest = (g) => Math.min(...g.tasks.filter((t) => t.status).map((t) => t.nextFireAt[0] ?? Infinity), Infinity);
|
|
4014
|
+
return out.sort((a, b) => soonest(a) - soonest(b));
|
|
4015
|
+
}
|
|
4016
|
+
/** 日程页操作:worker 存活直接发;未拉起则临时拉起(之后按空闲规则回收),保证文件/disabled 记录由 core 统一改写 */
|
|
4017
|
+
async cronAction(workingDir, action, id) {
|
|
4018
|
+
const w = await this.pool.acquire(workingDir);
|
|
4019
|
+
const act = action === "delete" ? "session.deleteCronTask" : action === "enable" ? "session.enableCronTask" : "session.disableCronTask";
|
|
4020
|
+
return this.pool.request(w, act, void 0, { id });
|
|
4021
|
+
}
|
|
4022
|
+
/** 会话状态摘要(左侧角标用) */
|
|
4023
|
+
statusMap() {
|
|
4024
|
+
const out = {};
|
|
4025
|
+
for (const [sid, rt] of this.runtimes) out[sid] = { state: rt.snapshot.state, pending: pendingBlocks(rt.snapshot).length };
|
|
4026
|
+
return out;
|
|
4027
|
+
}
|
|
4028
|
+
async dispose() {
|
|
4029
|
+
clearInterval(this.sessionReapTimer);
|
|
4030
|
+
clearInterval(this.cronKeeperTimer);
|
|
4031
|
+
for (const rt of this.runtimes.values()) {
|
|
4032
|
+
if (rt.saveTimer) {
|
|
4033
|
+
clearTimeout(rt.saveTimer);
|
|
4034
|
+
try {
|
|
4035
|
+
writeJsonAtomic(this.transcriptPath(rt.snapshot.sessionId), rt.snapshot);
|
|
4036
|
+
} catch {
|
|
4037
|
+
}
|
|
4038
|
+
}
|
|
4039
|
+
}
|
|
4040
|
+
await this.pool.disposeAll();
|
|
4041
|
+
this.discardSpare();
|
|
4042
|
+
}
|
|
4043
|
+
};
|
|
4044
|
+
|
|
4045
|
+
// ../server/src/ws/handler.ts
|
|
4046
|
+
var import_ws = require("ws");
|
|
4047
|
+
var ALLOWED = /* @__PURE__ */ new Set([...CORE_ACTIONS, ...PROJECT_ACTIONS, ...SESSION_ACTIONS]);
|
|
4048
|
+
function attachWs(wss, sm) {
|
|
4049
|
+
wss.on("connection", (ws, _req) => {
|
|
4050
|
+
const sub = {
|
|
4051
|
+
send: (frame) => {
|
|
4052
|
+
if (ws.readyState === import_ws.WebSocket.OPEN) ws.send(JSON.stringify(frame));
|
|
4053
|
+
}
|
|
4054
|
+
};
|
|
4055
|
+
sm.globalSubscribers.add(sub);
|
|
4056
|
+
ws.on("message", async (raw) => {
|
|
4057
|
+
let frame;
|
|
4058
|
+
try {
|
|
4059
|
+
frame = JSON.parse(String(raw));
|
|
4060
|
+
} catch {
|
|
4061
|
+
return;
|
|
4062
|
+
}
|
|
4063
|
+
if (!frame || typeof frame.id !== "string" || typeof frame.action !== "string") return;
|
|
4064
|
+
const reply = (ok, data, error) => sub.send({ id: frame.id, ok, data, error });
|
|
4065
|
+
try {
|
|
4066
|
+
if (!ALLOWED.has(frame.action)) throw new Error(`action \u4E0D\u5141\u8BB8: ${frame.action}`);
|
|
4067
|
+
if (frame.action === "session.subscribe") {
|
|
4068
|
+
if (!frame.sessionId) throw new Error("\u7F3A\u5C11 sessionId");
|
|
4069
|
+
reply(true, sm.subscribe(sub, frame.sessionId, frame.payload?.afterSeq));
|
|
4070
|
+
return;
|
|
4071
|
+
}
|
|
4072
|
+
if (frame.action === "session.unsubscribe") {
|
|
4073
|
+
sm.unsubscribe(sub, frame.sessionId);
|
|
4074
|
+
reply(true, true);
|
|
4075
|
+
return;
|
|
4076
|
+
}
|
|
4077
|
+
const data = await sm.dispatch(frame.action, frame.sessionId, frame.payload);
|
|
4078
|
+
reply(true, data);
|
|
4079
|
+
} catch (e) {
|
|
4080
|
+
reply(false, void 0, e?.message || String(e));
|
|
4081
|
+
}
|
|
4082
|
+
});
|
|
4083
|
+
ws.on("close", () => {
|
|
4084
|
+
sm.globalSubscribers.delete(sub);
|
|
4085
|
+
sm.unsubscribe(sub);
|
|
4086
|
+
});
|
|
4087
|
+
ws.on("error", () => {
|
|
4088
|
+
});
|
|
4089
|
+
});
|
|
4090
|
+
}
|
|
4091
|
+
|
|
4092
|
+
// ../server/src/terminal/manager.ts
|
|
4093
|
+
var import_fs15 = __toESM(require("fs"));
|
|
4094
|
+
var import_path14 = __toESM(require("path"));
|
|
4095
|
+
var import_crypto4 = require("crypto");
|
|
4096
|
+
var pty = __toESM(require("node-pty"));
|
|
4097
|
+
var SCROLLBACK_MAX = 200 * 1024;
|
|
4098
|
+
function defaultShell() {
|
|
4099
|
+
if (process.platform === "win32") return { file: "powershell.exe", args: [] };
|
|
4100
|
+
return { file: process.env.SHELL || (process.platform === "darwin" ? "/bin/zsh" : "/bin/bash"), args: ["-l"] };
|
|
4101
|
+
}
|
|
4102
|
+
function fixSpawnHelper() {
|
|
4103
|
+
try {
|
|
4104
|
+
const dir = import_path14.default.join(import_path14.default.dirname(require.resolve("node-pty/package.json")), "prebuilds");
|
|
4105
|
+
for (const d of import_fs15.default.readdirSync(dir)) {
|
|
4106
|
+
const helper = import_path14.default.join(dir, d, "spawn-helper");
|
|
4107
|
+
if (import_fs15.default.existsSync(helper)) import_fs15.default.chmodSync(helper, 493);
|
|
4108
|
+
}
|
|
4109
|
+
} catch {
|
|
4110
|
+
}
|
|
4111
|
+
}
|
|
4112
|
+
fixSpawnHelper();
|
|
4113
|
+
var TerminalManager = class {
|
|
4114
|
+
terms = /* @__PURE__ */ new Map();
|
|
4115
|
+
create(sessionId, cwd, cols = 80, rows = 24) {
|
|
4116
|
+
const id = (0, import_crypto4.randomBytes)(8).toString("hex");
|
|
4117
|
+
const { file, args } = defaultShell();
|
|
4118
|
+
const p = pty.spawn(file, args, {
|
|
4119
|
+
name: "xterm-256color",
|
|
4120
|
+
cwd: import_fs15.default.existsSync(cwd) ? cwd : process.cwd(),
|
|
4121
|
+
cols,
|
|
4122
|
+
rows,
|
|
4123
|
+
env: { ...process.env, TERM_PROGRAM: "semawork" }
|
|
4124
|
+
});
|
|
4125
|
+
const term = { id, sessionId, p, buf: [], bufBytes: 0, exited: false, listeners: /* @__PURE__ */ new Set(), exitListeners: /* @__PURE__ */ new Set() };
|
|
4126
|
+
p.onData((data) => {
|
|
4127
|
+
term.buf.push(data);
|
|
4128
|
+
term.bufBytes += Buffer.byteLength(data);
|
|
4129
|
+
while (term.bufBytes > SCROLLBACK_MAX && term.buf.length > 1) term.bufBytes -= Buffer.byteLength(term.buf.shift());
|
|
4130
|
+
term.listeners.forEach((f) => f(data));
|
|
4131
|
+
});
|
|
4132
|
+
p.onExit(({ exitCode }) => {
|
|
4133
|
+
term.exited = true;
|
|
4134
|
+
term.exitListeners.forEach((f) => f(exitCode));
|
|
4135
|
+
});
|
|
4136
|
+
this.terms.set(id, term);
|
|
4137
|
+
return { id, sessionId, title: import_path14.default.basename(cwd) || "shell" };
|
|
4138
|
+
}
|
|
4139
|
+
get(id) {
|
|
4140
|
+
const t = this.terms.get(id);
|
|
4141
|
+
return t ? { exited: t.exited } : null;
|
|
4142
|
+
}
|
|
4143
|
+
/** attach:先回放缓冲,再订阅实时输出;返回取消订阅函数 */
|
|
4144
|
+
attach(id, onData, onExit) {
|
|
4145
|
+
const t = this.terms.get(id);
|
|
4146
|
+
if (!t) return null;
|
|
4147
|
+
if (t.buf.length) onData(t.buf.join(""));
|
|
4148
|
+
if (t.exited) {
|
|
4149
|
+
onExit(0);
|
|
4150
|
+
return () => void 0;
|
|
4151
|
+
}
|
|
4152
|
+
t.listeners.add(onData);
|
|
4153
|
+
t.exitListeners.add(onExit);
|
|
4154
|
+
return () => {
|
|
4155
|
+
t.listeners.delete(onData);
|
|
4156
|
+
t.exitListeners.delete(onExit);
|
|
4157
|
+
};
|
|
4158
|
+
}
|
|
4159
|
+
write(id, data) {
|
|
4160
|
+
const t = this.terms.get(id);
|
|
4161
|
+
if (t && !t.exited) t.p.write(data);
|
|
4162
|
+
}
|
|
4163
|
+
resize(id, cols, rows) {
|
|
4164
|
+
const t = this.terms.get(id);
|
|
4165
|
+
if (t && !t.exited && cols > 0 && rows > 0) {
|
|
4166
|
+
try {
|
|
4167
|
+
t.p.resize(Math.floor(cols), Math.floor(rows));
|
|
4168
|
+
} catch {
|
|
4169
|
+
}
|
|
4170
|
+
}
|
|
4171
|
+
}
|
|
4172
|
+
kill(id) {
|
|
4173
|
+
const t = this.terms.get(id);
|
|
4174
|
+
if (!t) return;
|
|
4175
|
+
this.terms.delete(id);
|
|
4176
|
+
if (!t.exited) {
|
|
4177
|
+
try {
|
|
4178
|
+
t.p.kill();
|
|
4179
|
+
} catch {
|
|
4180
|
+
}
|
|
4181
|
+
}
|
|
4182
|
+
}
|
|
4183
|
+
killBySession(sessionId) {
|
|
4184
|
+
for (const [id, t] of this.terms) if (t.sessionId === sessionId) this.kill(id);
|
|
4185
|
+
}
|
|
4186
|
+
killAll() {
|
|
4187
|
+
for (const id of [...this.terms.keys()]) this.kill(id);
|
|
4188
|
+
}
|
|
4189
|
+
};
|
|
4190
|
+
|
|
4191
|
+
// ../server/src/ws/terminal.ts
|
|
4192
|
+
var import_ws2 = require("ws");
|
|
4193
|
+
function attachTermWs(wss, tm) {
|
|
4194
|
+
wss.on("connection", (ws, req) => {
|
|
4195
|
+
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
|
4196
|
+
const id = url.searchParams.get("id") || "";
|
|
4197
|
+
const detach = tm.attach(
|
|
4198
|
+
id,
|
|
4199
|
+
(data) => {
|
|
4200
|
+
if (ws.readyState === import_ws2.WebSocket.OPEN) ws.send(Buffer.from(data, "utf8"));
|
|
4201
|
+
},
|
|
4202
|
+
(code) => {
|
|
4203
|
+
if (ws.readyState === import_ws2.WebSocket.OPEN) ws.send(JSON.stringify({ type: "exit", code }));
|
|
4204
|
+
}
|
|
4205
|
+
);
|
|
4206
|
+
if (!detach) {
|
|
4207
|
+
ws.close(4404, "terminal not found");
|
|
4208
|
+
return;
|
|
4209
|
+
}
|
|
4210
|
+
ws.on("message", (raw) => {
|
|
4211
|
+
let msg;
|
|
4212
|
+
try {
|
|
4213
|
+
msg = JSON.parse(String(raw));
|
|
4214
|
+
} catch {
|
|
4215
|
+
return;
|
|
4216
|
+
}
|
|
4217
|
+
if (msg?.type === "input" && typeof msg.data === "string") tm.write(id, msg.data);
|
|
4218
|
+
else if (msg?.type === "resize") tm.resize(id, Number(msg.cols), Number(msg.rows));
|
|
4219
|
+
});
|
|
4220
|
+
ws.on("close", () => detach());
|
|
4221
|
+
ws.on("error", () => void 0);
|
|
4222
|
+
});
|
|
4223
|
+
}
|
|
4224
|
+
|
|
4225
|
+
// ../shared/viz.ts
|
|
4226
|
+
var VIZ_PATH_RE = /[\\/]attachments[\\/][0-9a-f-]{36}[\\/][^\\/]+\.html?$/i;
|
|
4227
|
+
function isVizPath(p) {
|
|
4228
|
+
return VIZ_PATH_RE.test(p);
|
|
4229
|
+
}
|
|
4230
|
+
|
|
4231
|
+
// ../server/src/server.ts
|
|
4232
|
+
var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
4233
|
+
var MIME = {
|
|
4234
|
+
".html": "text/html; charset=utf-8",
|
|
4235
|
+
".js": "application/javascript; charset=utf-8",
|
|
4236
|
+
".css": "text/css; charset=utf-8",
|
|
4237
|
+
".svg": "image/svg+xml",
|
|
4238
|
+
".png": "image/png",
|
|
4239
|
+
".ico": "image/x-icon",
|
|
4240
|
+
".json": "application/json",
|
|
4241
|
+
".woff2": "font/woff2",
|
|
4242
|
+
".map": "application/json",
|
|
4243
|
+
// pdf.js 的 worker 产物是 .mjs(module worker 严格校验 JS mime),解码器是 .wasm
|
|
4244
|
+
".mjs": "application/javascript; charset=utf-8",
|
|
4245
|
+
".wasm": "application/wasm"
|
|
4246
|
+
};
|
|
4247
|
+
var VIZ_INJECT_MAX_BYTES = 4 * 1024 * 1024;
|
|
4248
|
+
var LOCAL_MIME = {
|
|
4249
|
+
...MIME,
|
|
4250
|
+
".htm": "text/html; charset=utf-8",
|
|
4251
|
+
".txt": "text/plain; charset=utf-8",
|
|
4252
|
+
".md": "text/plain; charset=utf-8",
|
|
4253
|
+
".pdf": "application/pdf",
|
|
4254
|
+
".jpg": "image/jpeg",
|
|
4255
|
+
".jpeg": "image/jpeg",
|
|
4256
|
+
".gif": "image/gif",
|
|
4257
|
+
".webp": "image/webp",
|
|
4258
|
+
".avif": "image/avif",
|
|
4259
|
+
".bmp": "image/bmp",
|
|
4260
|
+
".woff": "font/woff",
|
|
4261
|
+
".ttf": "font/ttf",
|
|
4262
|
+
".mp4": "video/mp4",
|
|
4263
|
+
".webm": "video/webm",
|
|
4264
|
+
".mp3": "audio/mpeg",
|
|
4265
|
+
".wav": "audio/wav"
|
|
4266
|
+
};
|
|
4267
|
+
function startServer(opts) {
|
|
4268
|
+
const host = opts.host || "127.0.0.1";
|
|
4269
|
+
const { token } = opts;
|
|
4270
|
+
if (!LOOPBACK.has(host)) return Promise.reject(new Error(`\u5F53\u524D\u9636\u6BB5\u4EC5\u652F\u6301 loopback \u76D1\u542C\uFF08--host ${host}\uFF09`));
|
|
4271
|
+
if (!/^[0-9a-f]{32}$/.test(token)) return Promise.reject(new Error("token \u987B\u4E3A 32 \u4F4D\u5341\u516D\u8FDB\u5236"));
|
|
4272
|
+
const entryPath = import_path15.default.join(__dirname, "worker-entry.js");
|
|
4273
|
+
if (!import_fs16.default.existsSync(entryPath)) return Promise.reject(new Error(`\u627E\u4E0D\u5230 worker \u5165\u53E3 ${entryPath}\uFF0C\u8BF7\u5148\u5728 webui/ \u6267\u884C npm run build`));
|
|
4274
|
+
const registry = new RegistryStore();
|
|
4275
|
+
const sm = new SessionManager(registry, entryPath);
|
|
4276
|
+
sm.prewarmConfigWorker();
|
|
4277
|
+
const tm = new TerminalManager();
|
|
4278
|
+
sm.killTerminals = (sid) => tm.killBySession(sid);
|
|
4279
|
+
const router = new Router(sm, tm);
|
|
4280
|
+
const CLIENT_DIST = [import_path15.default.join(__dirname, "..", "..", "client", "dist"), import_path15.default.join(__dirname, "public")].find((p) => import_fs16.default.existsSync(import_path15.default.join(p, "index.html")));
|
|
4281
|
+
function authorized(req, url) {
|
|
4282
|
+
const h = req.headers.authorization;
|
|
4283
|
+
if (h && h === `Bearer ${token}`) return true;
|
|
4284
|
+
return url.searchParams.get("token") === token;
|
|
4285
|
+
}
|
|
4286
|
+
function serveLocalFile(res, pathname) {
|
|
4287
|
+
const rest = pathname.slice("/api/local/".length);
|
|
4288
|
+
const slash = rest.indexOf("/");
|
|
4289
|
+
const tok = decodeURIComponent(slash >= 0 ? rest.slice(0, slash) : rest);
|
|
4290
|
+
if (tok !== token) {
|
|
4291
|
+
json(res, 401, { ok: false, error: "unauthorized" });
|
|
4292
|
+
return;
|
|
4293
|
+
}
|
|
4294
|
+
const abs = import_path15.default.resolve("/", decodeURIComponent(slash >= 0 ? rest.slice(slash + 1) : ""));
|
|
4295
|
+
if (!import_fs16.default.existsSync(abs) || import_fs16.default.statSync(abs).isDirectory()) {
|
|
4296
|
+
json(res, 404, { ok: false, error: "\u6587\u4EF6\u4E0D\u5B58\u5728" });
|
|
4297
|
+
return;
|
|
4298
|
+
}
|
|
4299
|
+
const st = import_fs16.default.statSync(abs);
|
|
4300
|
+
if (isVizPath(abs) && st.size <= VIZ_INJECT_MAX_BYTES) {
|
|
4301
|
+
let html = import_fs16.default.readFileSync(abs, "utf8");
|
|
4302
|
+
const tag = '<script src="/viz-runtime.js"></script>';
|
|
4303
|
+
html = /<\/head>/i.test(html) ? html.replace(/<\/head>/i, `${tag}</head>`) : tag + html;
|
|
4304
|
+
const buf = Buffer.from(html, "utf8");
|
|
4305
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": buf.length, "Cache-Control": "no-cache", "X-Content-Type-Options": "nosniff" });
|
|
4306
|
+
res.end(buf);
|
|
4307
|
+
return;
|
|
4308
|
+
}
|
|
4309
|
+
sendFile(res, abs, {
|
|
4310
|
+
"Content-Type": LOCAL_MIME[import_path15.default.extname(abs).toLowerCase()] || "application/octet-stream",
|
|
4311
|
+
"Content-Length": st.size,
|
|
4312
|
+
"Cache-Control": "no-cache",
|
|
4313
|
+
"X-Content-Type-Options": "nosniff"
|
|
4314
|
+
});
|
|
4315
|
+
}
|
|
4316
|
+
function serveStatic(res, pathname) {
|
|
4317
|
+
if (!CLIENT_DIST) {
|
|
4318
|
+
json(res, 503, { ok: false, error: "client \u672A\u6784\u5EFA\uFF1A\u8BF7\u5728 webui/ \u6267\u884C npm run build\uFF0C\u6216\u7528 npm run dev \u8D70 vite" });
|
|
4319
|
+
return;
|
|
4320
|
+
}
|
|
4321
|
+
let file = import_path15.default.join(CLIENT_DIST, pathname === "/" ? "index.html" : pathname);
|
|
4322
|
+
if (!file.startsWith(CLIENT_DIST) || !import_fs16.default.existsSync(file) || import_fs16.default.statSync(file).isDirectory()) file = import_path15.default.join(CLIENT_DIST, "index.html");
|
|
4323
|
+
const ext = import_path15.default.extname(file);
|
|
4324
|
+
const noStore = ext === ".html" || pathname === "/viz-runtime.js";
|
|
4325
|
+
sendFile(res, file, { "Content-Type": MIME[ext] || "application/octet-stream", "Cache-Control": noStore ? "no-store" : "public, max-age=31536000, immutable" });
|
|
4326
|
+
}
|
|
4327
|
+
const server = import_http.default.createServer(async (req, res) => {
|
|
4328
|
+
try {
|
|
4329
|
+
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
|
4330
|
+
const pathname = url.pathname;
|
|
4331
|
+
if (pathname.startsWith("/api/")) {
|
|
4332
|
+
if (pathname === "/api/health") {
|
|
4333
|
+
json(res, 200, { ok: true, name: "semawork", version: opts.version || null, pid: process.pid });
|
|
4334
|
+
return;
|
|
4335
|
+
}
|
|
4336
|
+
if (pathname.startsWith("/api/local/")) {
|
|
4337
|
+
serveLocalFile(res, pathname);
|
|
4338
|
+
return;
|
|
4339
|
+
}
|
|
4340
|
+
if (!authorized(req, url)) {
|
|
4341
|
+
json(res, 401, { ok: false, error: "unauthorized" });
|
|
4342
|
+
return;
|
|
4343
|
+
}
|
|
4344
|
+
if (!await router.handle(req, res, pathname)) json(res, 404, { ok: false, error: "not found" });
|
|
4345
|
+
return;
|
|
4346
|
+
}
|
|
4347
|
+
serveStatic(res, pathname);
|
|
4348
|
+
} catch (e) {
|
|
4349
|
+
logErr("http", "\u672A\u6355\u83B7\u5F02\u5E38:", e?.stack || e?.message || e);
|
|
4350
|
+
try {
|
|
4351
|
+
if (!res.headersSent) json(res, 500, { ok: false, error: "internal error" });
|
|
4352
|
+
else res.end();
|
|
4353
|
+
} catch {
|
|
4354
|
+
}
|
|
4355
|
+
}
|
|
4356
|
+
});
|
|
4357
|
+
const wss = new import_ws3.WebSocketServer({ noServer: true });
|
|
4358
|
+
attachWs(wss, sm);
|
|
4359
|
+
const termWss = new import_ws3.WebSocketServer({ noServer: true });
|
|
4360
|
+
attachTermWs(termWss, tm);
|
|
4361
|
+
server.on("upgrade", (req, socket, head) => {
|
|
4362
|
+
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
|
4363
|
+
if (!authorized(req, url)) {
|
|
4364
|
+
socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
|
4365
|
+
return;
|
|
4366
|
+
}
|
|
4367
|
+
if (url.pathname === "/ws") {
|
|
4368
|
+
wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req));
|
|
4369
|
+
return;
|
|
4370
|
+
}
|
|
4371
|
+
if (url.pathname === "/ws/term") {
|
|
4372
|
+
termWss.handleUpgrade(req, socket, head, (ws) => termWss.emit("connection", ws, req));
|
|
4373
|
+
return;
|
|
4374
|
+
}
|
|
4375
|
+
socket.destroy();
|
|
4376
|
+
});
|
|
4377
|
+
let closed = false;
|
|
4378
|
+
async function close() {
|
|
4379
|
+
if (closed) return;
|
|
4380
|
+
closed = true;
|
|
4381
|
+
tm.killAll();
|
|
4382
|
+
await sm.dispose();
|
|
4383
|
+
for (const ws of wss.clients) ws.terminate();
|
|
4384
|
+
for (const ws of termWss.clients) ws.terminate();
|
|
4385
|
+
wss.close();
|
|
4386
|
+
termWss.close();
|
|
4387
|
+
server.closeAllConnections();
|
|
4388
|
+
await new Promise((resolve) => {
|
|
4389
|
+
const t = setTimeout(resolve, 3e3);
|
|
4390
|
+
server.close(() => {
|
|
4391
|
+
clearTimeout(t);
|
|
4392
|
+
resolve();
|
|
4393
|
+
});
|
|
4394
|
+
});
|
|
4395
|
+
}
|
|
4396
|
+
return new Promise((resolve, reject) => {
|
|
4397
|
+
server.once("error", (e) => {
|
|
4398
|
+
reject(new Error(e?.code === "EADDRINUSE" ? `\u7AEF\u53E3 ${opts.port} \u5DF2\u88AB\u5360\u7528\uFF0C\u8BF7\u6362 --port \u6216\u5173\u95ED\u5360\u7528\u8FDB\u7A0B` : String(e?.message || e)));
|
|
4399
|
+
});
|
|
4400
|
+
server.listen(opts.port, host, () => {
|
|
4401
|
+
const addr = server.address();
|
|
4402
|
+
const port = typeof addr === "object" && addr ? addr.port : opts.port;
|
|
4403
|
+
resolve({
|
|
4404
|
+
host,
|
|
4405
|
+
port,
|
|
4406
|
+
token,
|
|
4407
|
+
url: `http://${host}:${port}/?token=${token}`,
|
|
4408
|
+
close,
|
|
4409
|
+
preventSleepMode: () => registry.getSettings().preventSleep || "off",
|
|
4410
|
+
hasActiveWork: () => sm.hasActiveWork()
|
|
4411
|
+
});
|
|
4412
|
+
});
|
|
4413
|
+
});
|
|
4414
|
+
}
|
|
4415
|
+
|
|
4416
|
+
// ../server/src/cliUtil.ts
|
|
4417
|
+
var import_fs17 = __toESM(require("fs"));
|
|
4418
|
+
var import_path16 = __toESM(require("path"));
|
|
4419
|
+
var import_crypto5 = require("crypto");
|
|
4420
|
+
function arg(name, def, argv = process.argv) {
|
|
4421
|
+
const i = argv.indexOf(`--${name}`);
|
|
4422
|
+
if (i >= 0) return argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : "true";
|
|
4423
|
+
return def;
|
|
4424
|
+
}
|
|
4425
|
+
function loadOrCreateToken() {
|
|
4426
|
+
const file = import_path16.default.join(WEBUI_HOME, "token");
|
|
4427
|
+
try {
|
|
4428
|
+
const t2 = import_fs17.default.readFileSync(file, "utf8").trim();
|
|
4429
|
+
if (/^[0-9a-f]{32}$/.test(t2)) return t2;
|
|
4430
|
+
} catch {
|
|
4431
|
+
}
|
|
4432
|
+
const t = (0, import_crypto5.randomBytes)(16).toString("hex");
|
|
4433
|
+
try {
|
|
4434
|
+
import_fs17.default.mkdirSync(WEBUI_HOME, { recursive: true });
|
|
4435
|
+
import_fs17.default.writeFileSync(file, t, { mode: 384 });
|
|
4436
|
+
} catch (e) {
|
|
4437
|
+
console.warn("[token] \u6301\u4E45\u5316\u5931\u8D25\uFF0C\u672C\u6B21\u4F7F\u7528\u4E34\u65F6 token:", e?.message);
|
|
4438
|
+
}
|
|
4439
|
+
return t;
|
|
4440
|
+
}
|
|
4441
|
+
|
|
4442
|
+
// src/cli.ts
|
|
4443
|
+
if (!process.env.UV_THREADPOOL_SIZE) process.env.UV_THREADPOOL_SIZE = "16";
|
|
4444
|
+
var { version: VERSION } = require_package();
|
|
4445
|
+
var HOST = "127.0.0.1";
|
|
4446
|
+
var RUN_FILE = import_path17.default.join(WEBUI_HOME, "run.json");
|
|
4447
|
+
var PROBE_TIMEOUT_MS = 1e3;
|
|
4448
|
+
var STOP_WAIT_MS = 1e4;
|
|
4449
|
+
var HELP = `sema-ui ${VERSION}
|
|
4450
|
+
|
|
4451
|
+
\u7528\u6CD5\uFF1A
|
|
4452
|
+
sema-ui [--port 3210] [--token xxx] [--no-open] \u542F\u52A8\u670D\u52A1\u5E76\u6253\u5F00\u6D4F\u89C8\u5668\uFF08\u5DF2\u5728\u8FD0\u884C\u5219\u53EA\u6253\u5F00\u9875\u9762\uFF09\uFF0C\u7B49\u540C sema-ui start
|
|
4453
|
+
sema-ui status \u67E5\u770B\u8FD0\u884C\u72B6\u6001
|
|
4454
|
+
sema-ui open \u6253\u5F00\u9875\u9762\uFF0C\u4E0D\u91CD\u590D\u8D77\u670D\u52A1
|
|
4455
|
+
sema-ui stop \u7ED3\u675F\u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B
|
|
4456
|
+
sema-ui --version
|
|
4457
|
+
sema-ui --help
|
|
4458
|
+
|
|
4459
|
+
Ctrl+C \u6216\u5173\u95ED\u7EC8\u7AEF\u5373\u505C\u6B62\u670D\u52A1\uFF0C\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u4F1A\u88AB\u4E2D\u65AD\u3002\u6570\u636E\u76EE\u5F55 ~/.sema/webui/\uFF0C\u9519\u8BEF\u65E5\u5FD7 ~/.sema/webui/error.log\u3002`;
|
|
4460
|
+
function readRecord() {
|
|
4461
|
+
try {
|
|
4462
|
+
const r = JSON.parse(import_fs18.default.readFileSync(RUN_FILE, "utf8"));
|
|
4463
|
+
return r && typeof r.port === "number" && typeof r.url === "string" ? r : null;
|
|
4464
|
+
} catch {
|
|
4465
|
+
return null;
|
|
4466
|
+
}
|
|
4467
|
+
}
|
|
4468
|
+
function writeRecord(r) {
|
|
4469
|
+
try {
|
|
4470
|
+
import_fs18.default.mkdirSync(WEBUI_HOME, { recursive: true });
|
|
4471
|
+
import_fs18.default.writeFileSync(RUN_FILE, JSON.stringify(r, null, 2), { mode: 384 });
|
|
4472
|
+
} catch (e) {
|
|
4473
|
+
console.warn("[run] \u8FD0\u884C\u8BB0\u5F55\u5199\u5165\u5931\u8D25\uFF1A", e?.message);
|
|
4474
|
+
}
|
|
4475
|
+
}
|
|
4476
|
+
function removeRecord() {
|
|
4477
|
+
try {
|
|
4478
|
+
import_fs18.default.unlinkSync(RUN_FILE);
|
|
4479
|
+
} catch {
|
|
4480
|
+
}
|
|
4481
|
+
}
|
|
4482
|
+
function probe2(port) {
|
|
4483
|
+
return new Promise((resolve) => {
|
|
4484
|
+
const req = import_http2.default.get({ host: HOST, port, path: "/api/health", timeout: PROBE_TIMEOUT_MS }, (res) => {
|
|
4485
|
+
let body = "";
|
|
4486
|
+
res.setEncoding("utf8");
|
|
4487
|
+
res.on("data", (c) => {
|
|
4488
|
+
body += c;
|
|
4489
|
+
});
|
|
4490
|
+
res.on("end", () => {
|
|
4491
|
+
try {
|
|
4492
|
+
const j = JSON.parse(body);
|
|
4493
|
+
resolve(j && j.name === "semawork" ? j : null);
|
|
4494
|
+
} catch {
|
|
4495
|
+
resolve(null);
|
|
4496
|
+
}
|
|
4497
|
+
});
|
|
4498
|
+
});
|
|
4499
|
+
req.on("timeout", () => {
|
|
4500
|
+
req.destroy();
|
|
4501
|
+
resolve(null);
|
|
4502
|
+
});
|
|
4503
|
+
req.on("error", () => resolve(null));
|
|
4504
|
+
});
|
|
4505
|
+
}
|
|
4506
|
+
async function findRunning(port) {
|
|
4507
|
+
const rec = readRecord();
|
|
4508
|
+
if (rec) {
|
|
4509
|
+
const h = await probe2(rec.port);
|
|
4510
|
+
if (h) return { port: rec.port, url: rec.url, version: h.version, pid: h.pid, startedAt: rec.startedAt };
|
|
4511
|
+
removeRecord();
|
|
4512
|
+
}
|
|
4513
|
+
if (port) {
|
|
4514
|
+
const h = await probe2(port);
|
|
4515
|
+
if (h) return { port, url: `http://${HOST}:${port}/?token=${loadOrCreateToken()}`, version: h.version, pid: h.pid };
|
|
4516
|
+
}
|
|
4517
|
+
return null;
|
|
4518
|
+
}
|
|
4519
|
+
function describe(r) {
|
|
4520
|
+
const lines = [`\u5730\u5740 ${r.url}`, `\u7AEF\u53E3 ${r.port}`, `\u7248\u672C ${r.version || "\u672A\u77E5"}`, `pid ${r.pid}`];
|
|
4521
|
+
if (r.startedAt) lines.push(`\u542F\u52A8\u4E8E ${new Date(r.startedAt).toLocaleString()}`);
|
|
4522
|
+
return lines.join("\n");
|
|
4523
|
+
}
|
|
4524
|
+
function open(url) {
|
|
4525
|
+
return openExternal(url).catch((e) => console.warn("\u6253\u5F00\u6D4F\u89C8\u5668\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE\uFF1A", e?.message || e));
|
|
4526
|
+
}
|
|
4527
|
+
async function start() {
|
|
4528
|
+
const port = Number(arg("port", process.env.PORT || "3210"));
|
|
4529
|
+
const noOpen = arg("no-open") === "true";
|
|
4530
|
+
const running = await findRunning(port);
|
|
4531
|
+
if (running) {
|
|
4532
|
+
console.log(`SemaWork \u5DF2\u5728\u8FD0\u884C\uFF0C\u4E0D\u91CD\u590D\u542F\u52A8\u3002
|
|
4533
|
+
${describe(running)}`);
|
|
4534
|
+
if (running.version && running.version !== VERSION) console.log(`
|
|
4535
|
+
\u6CE8\u610F\uFF1A\u8FD0\u884C\u4E2D\u7684\u7248\u672C ${running.version} \u4E0E\u5F53\u524D\u547D\u4EE4 ${VERSION} \u4E0D\u4E00\u81F4\uFF0C\u53EF\u5148 sema-ui stop \u518D\u91CD\u65B0\u8FD0\u884C sema-ui\u3002`);
|
|
4536
|
+
if (!noOpen) await open(running.url);
|
|
4537
|
+
return;
|
|
4538
|
+
}
|
|
4539
|
+
const token = arg("token") || process.env.SEMA_WEBUI_TOKEN || loadOrCreateToken();
|
|
4540
|
+
let handle = null;
|
|
4541
|
+
let closing = false;
|
|
4542
|
+
let closingAt = 0;
|
|
4543
|
+
async function shutdown() {
|
|
4544
|
+
if (closing) {
|
|
4545
|
+
if (Date.now() - closingAt < 1e3) return;
|
|
4546
|
+
console.log("\n\u518D\u6B21\u6536\u5230\u4FE1\u53F7\uFF0C\u5F3A\u5236\u9000\u51FA");
|
|
4547
|
+
removeRecord();
|
|
4548
|
+
process.exit(1);
|
|
4549
|
+
}
|
|
4550
|
+
closing = true;
|
|
4551
|
+
closingAt = Date.now();
|
|
4552
|
+
console.log("\n\u6B63\u5728\u5173\u95ED\u2026");
|
|
4553
|
+
await handle?.close();
|
|
4554
|
+
removeRecord();
|
|
4555
|
+
process.exit(0);
|
|
4556
|
+
}
|
|
4557
|
+
initErrorLog("cli", VERSION);
|
|
4558
|
+
installProcessTraps("server");
|
|
4559
|
+
process.on("SIGINT", shutdown);
|
|
4560
|
+
process.on("SIGTERM", shutdown);
|
|
4561
|
+
process.on("SIGHUP", shutdown);
|
|
4562
|
+
process.on("exit", removeRecord);
|
|
4563
|
+
try {
|
|
4564
|
+
handle = await startServer({ port, host: HOST, token, version: VERSION });
|
|
4565
|
+
} catch (e) {
|
|
4566
|
+
console.error(e?.message || e);
|
|
4567
|
+
process.exit(1);
|
|
4568
|
+
}
|
|
4569
|
+
writeRecord({ pid: process.pid, port: handle.port, url: handle.url, version: VERSION, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
4570
|
+
console.log(`
|
|
4571
|
+
SemaWork ${VERSION} \u5DF2\u542F\u52A8\uFF1A${handle.url}
|
|
4572
|
+
\u6309 Ctrl+C \u505C\u6B62\u3002
|
|
4573
|
+
`);
|
|
4574
|
+
if (!noOpen) await open(handle.url);
|
|
4575
|
+
}
|
|
4576
|
+
async function status() {
|
|
4577
|
+
const running = await findRunning(Number(arg("port", process.env.PORT || "3210")));
|
|
4578
|
+
if (!running) {
|
|
4579
|
+
console.log("SemaWork \u672A\u8FD0\u884C\u3002\u542F\u52A8\uFF1Asema-ui");
|
|
4580
|
+
return;
|
|
4581
|
+
}
|
|
4582
|
+
console.log(`SemaWork \u8FD0\u884C\u4E2D
|
|
4583
|
+
${describe(running)}`);
|
|
4584
|
+
}
|
|
4585
|
+
async function openPage() {
|
|
4586
|
+
const running = await findRunning(Number(arg("port", process.env.PORT || "3210")));
|
|
4587
|
+
if (!running) {
|
|
4588
|
+
console.error("SemaWork \u672A\u8FD0\u884C\uFF0C\u8BF7\u5148\u8FD0\u884C sema-ui");
|
|
4589
|
+
process.exit(1);
|
|
4590
|
+
}
|
|
4591
|
+
await open(running.url);
|
|
4592
|
+
console.log(`\u5DF2\u6253\u5F00 ${running.url}`);
|
|
4593
|
+
}
|
|
4594
|
+
async function stop() {
|
|
4595
|
+
const running = await findRunning(Number(arg("port", process.env.PORT || "3210")));
|
|
4596
|
+
if (!running) {
|
|
4597
|
+
console.log("SemaWork \u672A\u8FD0\u884C\u3002");
|
|
4598
|
+
return;
|
|
4599
|
+
}
|
|
4600
|
+
try {
|
|
4601
|
+
process.kill(running.pid, "SIGTERM");
|
|
4602
|
+
} catch (e) {
|
|
4603
|
+
console.error(`\u7ED3\u675F\u8FDB\u7A0B ${running.pid} \u5931\u8D25\uFF1A`, e?.message || e);
|
|
4604
|
+
process.exit(1);
|
|
4605
|
+
}
|
|
4606
|
+
const deadline = Date.now() + STOP_WAIT_MS;
|
|
4607
|
+
while (Date.now() < deadline) {
|
|
4608
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
4609
|
+
if (!await probe2(running.port)) {
|
|
4610
|
+
removeRecord();
|
|
4611
|
+
console.log(`SemaWork \u5DF2\u505C\u6B62\uFF08pid ${running.pid}\uFF09`);
|
|
4612
|
+
return;
|
|
4613
|
+
}
|
|
4614
|
+
}
|
|
4615
|
+
console.error(`\u5DF2\u53D1\u9001\u505C\u6B62\u4FE1\u53F7\uFF0C\u4F46 ${STOP_WAIT_MS / 1e3} \u79D2\u5185\u670D\u52A1\u4ECD\u5728\u54CD\u5E94\uFF0C\u8BF7\u68C0\u67E5\u8FDB\u7A0B ${running.pid}`);
|
|
4616
|
+
process.exit(1);
|
|
4617
|
+
}
|
|
4618
|
+
var cmd = process.argv[2];
|
|
4619
|
+
var run2 = { start, status, open: openPage, stop };
|
|
4620
|
+
if (cmd === "--version" || cmd === "-v") {
|
|
4621
|
+
console.log(VERSION);
|
|
4622
|
+
} else if (cmd === "help" || cmd === "--help" || cmd === "-h") {
|
|
4623
|
+
console.log(HELP);
|
|
4624
|
+
} else if (!cmd || cmd.startsWith("--")) {
|
|
4625
|
+
start().catch((e) => {
|
|
4626
|
+
console.error(e?.message || e);
|
|
4627
|
+
process.exit(1);
|
|
4628
|
+
});
|
|
4629
|
+
} else if (run2[cmd]) {
|
|
4630
|
+
run2[cmd]().catch((e) => {
|
|
4631
|
+
console.error(e?.message || e);
|
|
4632
|
+
process.exit(1);
|
|
4633
|
+
});
|
|
4634
|
+
} else {
|
|
4635
|
+
console.error(`\u672A\u77E5\u547D\u4EE4\uFF1A${cmd}
|
|
4636
|
+
|
|
4637
|
+
${HELP}`);
|
|
4638
|
+
process.exit(1);
|
|
4639
|
+
}
|