@memo-code/memo 0.8.0 → 0.8.5
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 +66 -14
- package/README.zh.md +57 -14
- package/dist/index.js +122 -107
- package/dist/web/server/app.controller.d.ts +6 -0
- package/dist/web/server/app.controller.js +33 -0
- package/dist/web/server/app.module.d.ts +4 -0
- package/dist/web/server/app.module.js +61 -0
- package/dist/web/server/auth/access-token.guard.d.ts +9 -0
- package/dist/web/server/auth/access-token.guard.js +53 -0
- package/dist/web/server/auth/auth.controller.d.ts +18 -0
- package/dist/web/server/auth/auth.controller.js +75 -0
- package/dist/web/server/auth/auth.module.d.ts +2 -0
- package/dist/web/server/auth/auth.module.js +24 -0
- package/dist/web/server/auth/auth.service.d.ts +15 -0
- package/dist/web/server/auth/auth.service.js +146 -0
- package/dist/web/server/auth/auth.types.d.ts +26 -0
- package/dist/web/server/auth/auth.types.js +2 -0
- package/dist/web/server/auth/public.decorator.d.ts +2 -0
- package/dist/web/server/auth/public.decorator.js +7 -0
- package/dist/web/server/chat/chat.controller.d.ts +30 -0
- package/dist/web/server/chat/chat.controller.js +150 -0
- package/dist/web/server/chat/chat.module.d.ts +2 -0
- package/dist/web/server/chat/chat.module.js +26 -0
- package/dist/web/server/chat/chat.service.d.ts +61 -0
- package/dist/web/server/chat/chat.service.js +847 -0
- package/dist/web/server/chat/chat.types.d.ts +38 -0
- package/dist/web/server/chat/chat.types.js +2 -0
- package/dist/web/server/common/constants.d.ts +1 -0
- package/dist/web/server/common/constants.js +4 -0
- package/dist/web/server/common/filters/api-error.filter.d.ts +7 -0
- package/dist/web/server/common/filters/api-error.filter.js +95 -0
- package/dist/web/server/common/interceptors/api-response.interceptor.d.ts +15 -0
- package/dist/web/server/common/interceptors/api-response.interceptor.js +51 -0
- package/dist/web/server/common/middleware/request-logging.middleware.d.ts +7 -0
- package/dist/web/server/common/middleware/request-logging.middleware.js +42 -0
- package/dist/web/server/config/memo-config.service.d.ts +7 -0
- package/dist/web/server/config/memo-config.service.js +106 -0
- package/dist/web/server/config/memo-config.types.d.ts +6 -0
- package/dist/web/server/config/memo-config.types.js +2 -0
- package/dist/web/server/config/server-config.module.d.ts +2 -0
- package/dist/web/server/config/server-config.module.js +22 -0
- package/dist/web/server/config/server-config.service.d.ts +14 -0
- package/dist/web/server/config/server-config.service.js +326 -0
- package/dist/web/server/config/server-config.service.test.d.ts +1 -0
- package/dist/web/server/config/server-config.service.test.js +193 -0
- package/dist/web/server/config/server-config.types.d.ts +27 -0
- package/dist/web/server/config/server-config.types.js +2 -0
- package/dist/web/server/main.d.ts +1 -0
- package/dist/web/server/main.js +19 -0
- package/dist/web/server/mcp/mcp.controller.d.ts +38 -0
- package/dist/web/server/mcp/mcp.controller.js +126 -0
- package/dist/web/server/mcp/mcp.module.d.ts +2 -0
- package/dist/web/server/mcp/mcp.module.js +22 -0
- package/dist/web/server/mcp/mcp.service.d.ts +25 -0
- package/dist/web/server/mcp/mcp.service.js +56 -0
- package/dist/web/server/package.json +3 -0
- package/dist/web/server/server.d.ts +18 -0
- package/dist/web/server/server.js +142 -0
- package/dist/web/server/sessions/sessions.controller.d.ts +8 -0
- package/dist/web/server/sessions/sessions.controller.js +59 -0
- package/dist/web/server/sessions/sessions.module.d.ts +2 -0
- package/dist/web/server/sessions/sessions.module.js +24 -0
- package/dist/web/server/sessions/sessions.service.d.ts +22 -0
- package/dist/web/server/sessions/sessions.service.js +217 -0
- package/dist/web/server/sessions/sessions.types.d.ts +18 -0
- package/dist/web/server/sessions/sessions.types.js +2 -0
- package/dist/web/server/skills/skills.controller.d.ts +31 -0
- package/dist/web/server/skills/skills.controller.js +86 -0
- package/dist/web/server/skills/skills.module.d.ts +2 -0
- package/dist/web/server/skills/skills.module.js +24 -0
- package/dist/web/server/skills/skills.service.d.ts +38 -0
- package/dist/web/server/skills/skills.service.js +97 -0
- package/dist/web/server/stream/stream.module.d.ts +2 -0
- package/dist/web/server/stream/stream.module.js +20 -0
- package/dist/web/server/stream/stream.service.d.ts +26 -0
- package/dist/web/server/stream/stream.service.js +166 -0
- package/dist/web/server/tsconfig.build.tsbuildinfo +1 -0
- package/dist/web/server/workspaces/workspaces.module.d.ts +2 -0
- package/dist/web/server/workspaces/workspaces.module.js +20 -0
- package/dist/web/server/workspaces/workspaces.service.d.ts +38 -0
- package/dist/web/server/workspaces/workspaces.service.js +378 -0
- package/dist/web/server/workspaces/workspaces.types.d.ts +1 -0
- package/dist/web/server/workspaces/workspaces.types.js +2 -0
- package/dist/web/server/workspaces/workspaces.utils.d.ts +1 -0
- package/dist/web/server/workspaces/workspaces.utils.js +9 -0
- package/dist/web/server/ws/rpc-router.service.d.ts +20 -0
- package/dist/web/server/ws/rpc-router.service.js +275 -0
- package/dist/web/server/ws/session-runtime-registry.service.d.ts +37 -0
- package/dist/web/server/ws/session-runtime-registry.service.js +118 -0
- package/dist/web/server/ws/ws-event-bus.service.d.ts +5 -0
- package/dist/web/server/ws/ws-event-bus.service.js +27 -0
- package/dist/web/server/ws/ws-gateway.module.d.ts +2 -0
- package/dist/web/server/ws/ws-gateway.module.js +42 -0
- package/dist/web/server/ws/ws-gateway.service.d.ts +42 -0
- package/dist/web/server/ws/ws-gateway.service.js +473 -0
- package/dist/web/server/ws/ws.errors.d.ts +8 -0
- package/dist/web/server/ws/ws.errors.js +16 -0
- package/dist/web/server/ws/ws.types.d.ts +34 -0
- package/dist/web/server/ws/ws.types.js +2 -0
- package/dist/web/ui/assets/_baseUniq-kMerwpPq.js +1 -0
- package/dist/web/ui/assets/abap-BdImnpbu.js +1 -0
- package/dist/web/ui/assets/actionscript-3-CoDkCxhg.js +1 -0
- package/dist/web/ui/assets/ada-bCR0ucgS.js +1 -0
- package/dist/web/ui/assets/andromeeda-C4gqWexZ.js +1 -0
- package/dist/web/ui/assets/angular-html-CU67Zn6k.js +1 -0
- package/dist/web/ui/assets/angular-ts-BwZT4LLn.js +1 -0
- package/dist/web/ui/assets/apache-Pmp26Uib.js +1 -0
- package/dist/web/ui/assets/apex-D8_7TLub.js +1 -0
- package/dist/web/ui/assets/apl-dKokRX4l.js +1 -0
- package/dist/web/ui/assets/applescript-Co6uUVPk.js +1 -0
- package/dist/web/ui/assets/ara-BRHolxvo.js +1 -0
- package/dist/web/ui/assets/arc-BulUmzON.js +1 -0
- package/dist/web/ui/assets/architectureDiagram-VXUJARFQ-CkXEUKP9.js +36 -0
- package/dist/web/ui/assets/asciidoc-Dv7Oe6Be.js +1 -0
- package/dist/web/ui/assets/asm-D_Q5rh1f.js +1 -0
- package/dist/web/ui/assets/astro-CbQHKStN.js +1 -0
- package/dist/web/ui/assets/aurora-x-D-2ljcwZ.js +1 -0
- package/dist/web/ui/assets/awk-DMzUqQB5.js +1 -0
- package/dist/web/ui/assets/ayu-dark-CMjwMIkn.js +1 -0
- package/dist/web/ui/assets/ayu-light-C47S-Tmv.js +1 -0
- package/dist/web/ui/assets/ayu-mirage-CjoLj4QM.js +1 -0
- package/dist/web/ui/assets/ballerina-BFfxhgS-.js +1 -0
- package/dist/web/ui/assets/bat-BkioyH1T.js +1 -0
- package/dist/web/ui/assets/beancount-k_qm7-4y.js +1 -0
- package/dist/web/ui/assets/berry-uYugtg8r.js +1 -0
- package/dist/web/ui/assets/bibtex-CHM0blh-.js +1 -0
- package/dist/web/ui/assets/bicep-Bmn6On1c.js +1 -0
- package/dist/web/ui/assets/blade-D4QpJJKB.js +1 -0
- package/dist/web/ui/assets/blockDiagram-VD42YOAC-DXcW7NDi.js +122 -0
- package/dist/web/ui/assets/bsl-BO_Y6i37.js +1 -0
- package/dist/web/ui/assets/c-BIGW1oBm.js +1 -0
- package/dist/web/ui/assets/c3-VCDPK7BO.js +1 -0
- package/dist/web/ui/assets/c4Diagram-YG6GDRKO-QrajWDN7.js +10 -0
- package/dist/web/ui/assets/cadence-Bv_4Rxtq.js +1 -0
- package/dist/web/ui/assets/cairo-KRGpt6FW.js +1 -0
- package/dist/web/ui/assets/catppuccin-frappe-DFWUc33u.js +1 -0
- package/dist/web/ui/assets/catppuccin-latte-C9dUb6Cb.js +1 -0
- package/dist/web/ui/assets/catppuccin-macchiato-DQyhUUbL.js +1 -0
- package/dist/web/ui/assets/catppuccin-mocha-D87Tk5Gz.js +1 -0
- package/dist/web/ui/assets/channel-DcFyxfzD.js +1 -0
- package/dist/web/ui/assets/chunk-4BX2VUAB-CzB06K-m.js +1 -0
- package/dist/web/ui/assets/chunk-55IACEB6-e5LXEkOB.js +1 -0
- package/dist/web/ui/assets/chunk-B4BG7PRW-YVg5pH4D.js +165 -0
- package/dist/web/ui/assets/chunk-DI55MBZ5-Carl7-xm.js +220 -0
- package/dist/web/ui/assets/chunk-FMBD7UC4-06dN5sRQ.js +15 -0
- package/dist/web/ui/assets/chunk-QN33PNHL-Cl3zdZ7K.js +1 -0
- package/dist/web/ui/assets/chunk-QZHKN3VN-CDOQBeOx.js +1 -0
- package/dist/web/ui/assets/chunk-TZMSLE5B-DWeaVk_X.js +1 -0
- package/dist/web/ui/assets/clarity-D53aC0YG.js +1 -0
- package/dist/web/ui/assets/classDiagram-2ON5EDUG-DmyEwwBr.js +1 -0
- package/dist/web/ui/assets/classDiagram-v2-WZHVMYZB-DmyEwwBr.js +1 -0
- package/dist/web/ui/assets/clojure-P80f7IUj.js +1 -0
- package/dist/web/ui/assets/clone-DZ5SCP6k.js +1 -0
- package/dist/web/ui/assets/cmake-D1j8_8rp.js +1 -0
- package/dist/web/ui/assets/cobol-nwyudZeR.js +1 -0
- package/dist/web/ui/assets/code-block-OCS4YCEC-DmdcLUqO.js +2 -0
- package/dist/web/ui/assets/codeowners-Bp6g37R7.js +1 -0
- package/dist/web/ui/assets/codeql-DsOJ9woJ.js +1 -0
- package/dist/web/ui/assets/coffee-Ch7k5sss.js +1 -0
- package/dist/web/ui/assets/common-lisp-Cg-RD9OK.js +1 -0
- package/dist/web/ui/assets/coq-DkFqJrB1.js +1 -0
- package/dist/web/ui/assets/cose-bilkent-S5V4N54A-CDHjR7aY.js +1 -0
- package/dist/web/ui/assets/cpp-CofmeUqb.js +1 -0
- package/dist/web/ui/assets/crystal-tKQVLTB8.js +1 -0
- package/dist/web/ui/assets/csharp-COcwbKMJ.js +1 -0
- package/dist/web/ui/assets/css-DPfMkruS.js +1 -0
- package/dist/web/ui/assets/csv-fuZLfV_i.js +1 -0
- package/dist/web/ui/assets/cue-D82EKSYY.js +1 -0
- package/dist/web/ui/assets/cypher-COkxafJQ.js +1 -0
- package/dist/web/ui/assets/cytoscape.esm-5J0xJHOV.js +321 -0
- package/dist/web/ui/assets/d-85-TOEBH.js +1 -0
- package/dist/web/ui/assets/dagre-6UL2VRFP-BvAH8ysH.js +4 -0
- package/dist/web/ui/assets/dark-plus-C3mMm8J8.js +1 -0
- package/dist/web/ui/assets/dart-CF10PKvl.js +1 -0
- package/dist/web/ui/assets/dax-CEL-wOlO.js +1 -0
- package/dist/web/ui/assets/defaultLocale-DX6XiGOO.js +1 -0
- package/dist/web/ui/assets/desktop-BmXAJ9_W.js +1 -0
- package/dist/web/ui/assets/diagram-PSM6KHXK-CKk6ZAaV.js +24 -0
- package/dist/web/ui/assets/diagram-QEK2KX5R-Ewj4cQfm.js +43 -0
- package/dist/web/ui/assets/diagram-S2PKOQOG-B-i75ELR.js +24 -0
- package/dist/web/ui/assets/diff-D97Zzqfu.js +1 -0
- package/dist/web/ui/assets/docker-BcOcwvcX.js +1 -0
- package/dist/web/ui/assets/dotenv-Da5cRb03.js +1 -0
- package/dist/web/ui/assets/dracula-BzJJZx-M.js +1 -0
- package/dist/web/ui/assets/dracula-soft-BXkSAIEj.js +1 -0
- package/dist/web/ui/assets/dream-maker-BtqSS_iP.js +1 -0
- package/dist/web/ui/assets/edge-BkV0erSs.js +1 -0
- package/dist/web/ui/assets/elixir-CDX3lj18.js +1 -0
- package/dist/web/ui/assets/elm-DbKCFpqz.js +1 -0
- package/dist/web/ui/assets/emacs-lisp-C9XAeP06.js +1 -0
- package/dist/web/ui/assets/erDiagram-Q2GNP2WA-BMe1fyY7.js +60 -0
- package/dist/web/ui/assets/erb-CgJxNhIT.js +1 -0
- package/dist/web/ui/assets/erlang-DsQrWhSR.js +1 -0
- package/dist/web/ui/assets/everforest-dark-BgDCqdQA.js +1 -0
- package/dist/web/ui/assets/everforest-light-C8M2exoo.js +1 -0
- package/dist/web/ui/assets/fennel-BYunw83y.js +1 -0
- package/dist/web/ui/assets/fish-BvzEVeQv.js +1 -0
- package/dist/web/ui/assets/flowDiagram-NV44I4VS-DTOpgGDg.js +162 -0
- package/dist/web/ui/assets/fluent-C4IJs8-o.js +1 -0
- package/dist/web/ui/assets/fortran-fixed-form-CkoXwp7k.js +1 -0
- package/dist/web/ui/assets/fortran-free-form-BxgE0vQu.js +1 -0
- package/dist/web/ui/assets/fsharp-CXgrBDvD.js +1 -0
- package/dist/web/ui/assets/ganttDiagram-JELNMOA3-DdrlqPr-.js +267 -0
- package/dist/web/ui/assets/gdresource-BOOCDP_w.js +1 -0
- package/dist/web/ui/assets/gdscript-C5YyOfLZ.js +1 -0
- package/dist/web/ui/assets/gdshader-DkwncUOv.js +1 -0
- package/dist/web/ui/assets/genie-D0YGMca9.js +1 -0
- package/dist/web/ui/assets/gherkin-DyxjwDmM.js +1 -0
- package/dist/web/ui/assets/git-commit-F4YmCXRG.js +1 -0
- package/dist/web/ui/assets/git-rebase-r7XF79zn.js +1 -0
- package/dist/web/ui/assets/gitGraphDiagram-NY62KEGX-DOpYoqH8.js +65 -0
- package/dist/web/ui/assets/github-dark-DHJKELXO.js +1 -0
- package/dist/web/ui/assets/github-dark-default-Cuk6v7N8.js +1 -0
- package/dist/web/ui/assets/github-dark-dimmed-DH5Ifo-i.js +1 -0
- package/dist/web/ui/assets/github-dark-high-contrast-E3gJ1_iC.js +1 -0
- package/dist/web/ui/assets/github-light-DAi9KRSo.js +1 -0
- package/dist/web/ui/assets/github-light-default-D7oLnXFd.js +1 -0
- package/dist/web/ui/assets/github-light-high-contrast-BfjtVDDH.js +1 -0
- package/dist/web/ui/assets/gleam-BspZqrRM.js +1 -0
- package/dist/web/ui/assets/glimmer-js-Rg0-pVw9.js +1 -0
- package/dist/web/ui/assets/glimmer-ts-U6CK756n.js +1 -0
- package/dist/web/ui/assets/glsl-DplSGwfg.js +1 -0
- package/dist/web/ui/assets/gn-n2N0HUVH.js +1 -0
- package/dist/web/ui/assets/gnuplot-DdkO51Og.js +1 -0
- package/dist/web/ui/assets/go-CxLEBnE3.js +1 -0
- package/dist/web/ui/assets/graph-DNq5-vTB.js +1 -0
- package/dist/web/ui/assets/graphql-ChdNCCLP.js +1 -0
- package/dist/web/ui/assets/groovy-gcz8RCvz.js +1 -0
- package/dist/web/ui/assets/gruvbox-dark-hard-CFHQjOhq.js +1 -0
- package/dist/web/ui/assets/gruvbox-dark-medium-GsRaNv29.js +1 -0
- package/dist/web/ui/assets/gruvbox-dark-soft-CVdnzihN.js +1 -0
- package/dist/web/ui/assets/gruvbox-light-hard-CH1njM8p.js +1 -0
- package/dist/web/ui/assets/gruvbox-light-medium-DRw_LuNl.js +1 -0
- package/dist/web/ui/assets/gruvbox-light-soft-hJgmCMqR.js +1 -0
- package/dist/web/ui/assets/hack-CaT9iCJl.js +1 -0
- package/dist/web/ui/assets/haml-B8DHNrY2.js +1 -0
- package/dist/web/ui/assets/handlebars-BL8al0AC.js +1 -0
- package/dist/web/ui/assets/haskell-Df6bDoY_.js +1 -0
- package/dist/web/ui/assets/haxe-CzTSHFRz.js +1 -0
- package/dist/web/ui/assets/hcl-BWvSN4gD.js +1 -0
- package/dist/web/ui/assets/hjson-D5-asLiD.js +1 -0
- package/dist/web/ui/assets/hlsl-D3lLCCz7.js +1 -0
- package/dist/web/ui/assets/horizon-BUw7H-hv.js +1 -0
- package/dist/web/ui/assets/houston-DnULxvSX.js +1 -0
- package/dist/web/ui/assets/html-GMplVEZG.js +1 -0
- package/dist/web/ui/assets/html-derivative-BFtXZ54Q.js +1 -0
- package/dist/web/ui/assets/http-jrhK8wxY.js +1 -0
- package/dist/web/ui/assets/hurl-irOxFIW8.js +1 -0
- package/dist/web/ui/assets/hxml-Bvhsp5Yf.js +1 -0
- package/dist/web/ui/assets/hy-DFXneXwc.js +1 -0
- package/dist/web/ui/assets/imba-DGztddWO.js +1 -0
- package/dist/web/ui/assets/index-B3TLzmaO.js +441 -0
- package/dist/web/ui/assets/index-BSSBc2rS.css +1 -0
- package/dist/web/ui/assets/infoDiagram-WHAUD3N6-D3Wwcqmd.js +2 -0
- package/dist/web/ui/assets/ini-BEwlwnbL.js +1 -0
- package/dist/web/ui/assets/init-Gi6I4Gst.js +1 -0
- package/dist/web/ui/assets/java-CylS5w8V.js +1 -0
- package/dist/web/ui/assets/javascript-wDzz0qaB.js +1 -0
- package/dist/web/ui/assets/jinja-4LBKfQ-Z.js +1 -0
- package/dist/web/ui/assets/jison-wvAkD_A8.js +1 -0
- package/dist/web/ui/assets/journeyDiagram-XKPGCS4Q-BKDrlvIB.js +139 -0
- package/dist/web/ui/assets/json-Cp-IABpG.js +1 -0
- package/dist/web/ui/assets/json5-C9tS-k6U.js +1 -0
- package/dist/web/ui/assets/jsonc-Des-eS-w.js +1 -0
- package/dist/web/ui/assets/jsonl-DcaNXYhu.js +1 -0
- package/dist/web/ui/assets/jsonnet-DFQXde-d.js +1 -0
- package/dist/web/ui/assets/jssm-C2t-YnRu.js +1 -0
- package/dist/web/ui/assets/jsx-g9-lgVsj.js +1 -0
- package/dist/web/ui/assets/julia-CxzCAyBv.js +1 -0
- package/dist/web/ui/assets/kanagawa-dragon-CkXjmgJE.js +1 -0
- package/dist/web/ui/assets/kanagawa-lotus-CfQXZHmo.js +1 -0
- package/dist/web/ui/assets/kanagawa-wave-DWedfzmr.js +1 -0
- package/dist/web/ui/assets/kanban-definition-3W4ZIXB7-Dj6sXTJI.js +89 -0
- package/dist/web/ui/assets/katex-DhXJpUyf.js +261 -0
- package/dist/web/ui/assets/kdl-DV7GczEv.js +1 -0
- package/dist/web/ui/assets/kotlin-BdnUsdx6.js +1 -0
- package/dist/web/ui/assets/kusto-DZf3V79B.js +1 -0
- package/dist/web/ui/assets/laserwave-DUszq2jm.js +1 -0
- package/dist/web/ui/assets/latex-DGMBWnxU.js +1 -0
- package/dist/web/ui/assets/layout-4XvXY0m8.js +1 -0
- package/dist/web/ui/assets/lean-BZvkOJ9d.js +1 -0
- package/dist/web/ui/assets/less-B1dDrJ26.js +1 -0
- package/dist/web/ui/assets/light-plus-B7mTdjB0.js +1 -0
- package/dist/web/ui/assets/linear-CUPS720l.js +1 -0
- package/dist/web/ui/assets/liquid-DYVedYrR.js +1 -0
- package/dist/web/ui/assets/llvm-BtvRca6l.js +1 -0
- package/dist/web/ui/assets/log-2UxHyX5q.js +1 -0
- package/dist/web/ui/assets/logo-BtOb2qkB.js +1 -0
- package/dist/web/ui/assets/lua-BaeVxFsk.js +1 -0
- package/dist/web/ui/assets/luau-C-HG3fhB.js +1 -0
- package/dist/web/ui/assets/make-CHLpvVh8.js +1 -0
- package/dist/web/ui/assets/markdown-Cvjx9yec.js +1 -0
- package/dist/web/ui/assets/marko-DZsq8hO1.js +1 -0
- package/dist/web/ui/assets/material-theme-D5KoaKCx.js +1 -0
- package/dist/web/ui/assets/material-theme-darker-BfHTSMKl.js +1 -0
- package/dist/web/ui/assets/material-theme-lighter-B0m2ddpp.js +1 -0
- package/dist/web/ui/assets/material-theme-ocean-CyktbL80.js +1 -0
- package/dist/web/ui/assets/material-theme-palenight-Csfq5Kiy.js +1 -0
- package/dist/web/ui/assets/matlab-D7o27uSR.js +1 -0
- package/dist/web/ui/assets/mdc-DUICxH0z.js +1 -0
- package/dist/web/ui/assets/mdx-Cmh6b_Ma.js +1 -0
- package/dist/web/ui/assets/mermaid-mWjccvbQ.js +1 -0
- package/dist/web/ui/assets/min-KWXImKVx.js +1 -0
- package/dist/web/ui/assets/min-dark-CafNBF8u.js +1 -0
- package/dist/web/ui/assets/min-light-CTRr51gU.js +1 -0
- package/dist/web/ui/assets/mindmap-definition-VGOIOE7T-D9ty43l7.js +68 -0
- package/dist/web/ui/assets/mipsasm-CKIfxQSi.js +1 -0
- package/dist/web/ui/assets/mojo-B93PlW-d.js +1 -0
- package/dist/web/ui/assets/monokai-D4h5O-jR.js +1 -0
- package/dist/web/ui/assets/moonbit-Ba13S78F.js +1 -0
- package/dist/web/ui/assets/move-IF9eRakj.js +1 -0
- package/dist/web/ui/assets/narrat-DRg8JJMk.js +1 -0
- package/dist/web/ui/assets/nextflow-BrzmwbiE.js +1 -0
- package/dist/web/ui/assets/nginx-BpAMiNFr.js +1 -0
- package/dist/web/ui/assets/night-owl-C39BiMTA.js +1 -0
- package/dist/web/ui/assets/night-owl-light-CMTm3GFP.js +1 -0
- package/dist/web/ui/assets/nim-CVrawwO9.js +1 -0
- package/dist/web/ui/assets/nix-CwoSXNpI.js +1 -0
- package/dist/web/ui/assets/nord-Ddv68eIx.js +1 -0
- package/dist/web/ui/assets/nushell-C-sUppwS.js +1 -0
- package/dist/web/ui/assets/objective-c-DXmwc3jG.js +1 -0
- package/dist/web/ui/assets/objective-cpp-CLxacb5B.js +1 -0
- package/dist/web/ui/assets/ocaml-C0hk2d4L.js +1 -0
- package/dist/web/ui/assets/odin-BBf5iR-q.js +1 -0
- package/dist/web/ui/assets/one-dark-pro-DVMEJ2y_.js +1 -0
- package/dist/web/ui/assets/one-light-C3Wv6jpd.js +1 -0
- package/dist/web/ui/assets/openscad-C4EeE6gA.js +1 -0
- package/dist/web/ui/assets/ordinal-Cboi1Yqb.js +1 -0
- package/dist/web/ui/assets/pascal-D93ZcfNL.js +1 -0
- package/dist/web/ui/assets/perl-C0TMdlhV.js +1 -0
- package/dist/web/ui/assets/php-Dhbhpdrm.js +1 -0
- package/dist/web/ui/assets/pieDiagram-ADFJNKIX-BlMxxSdO.js +30 -0
- package/dist/web/ui/assets/pkl-u5AG7uiY.js +1 -0
- package/dist/web/ui/assets/plastic-3e1v2bzS.js +1 -0
- package/dist/web/ui/assets/plsql-ChMvpjG-.js +1 -0
- package/dist/web/ui/assets/po-BTJTHyun.js +1 -0
- package/dist/web/ui/assets/poimandres-CS3Unz2-.js +1 -0
- package/dist/web/ui/assets/polar-C0HS_06l.js +1 -0
- package/dist/web/ui/assets/postcss-CXtECtnM.js +1 -0
- package/dist/web/ui/assets/powerquery-CEu0bR-o.js +1 -0
- package/dist/web/ui/assets/powershell-Dpen1YoG.js +1 -0
- package/dist/web/ui/assets/prisma-Dd19v3D-.js +1 -0
- package/dist/web/ui/assets/prolog-CbFg5uaA.js +1 -0
- package/dist/web/ui/assets/proto-C7zT0LnQ.js +1 -0
- package/dist/web/ui/assets/pug-CGlum2m_.js +1 -0
- package/dist/web/ui/assets/puppet-BMWR74SV.js +1 -0
- package/dist/web/ui/assets/purescript-CklMAg4u.js +1 -0
- package/dist/web/ui/assets/python-B6aJPvgy.js +1 -0
- package/dist/web/ui/assets/qml-3beO22l8.js +1 -0
- package/dist/web/ui/assets/qmldir-C8lEn-DE.js +1 -0
- package/dist/web/ui/assets/qss-IeuSbFQv.js +1 -0
- package/dist/web/ui/assets/quadrantDiagram-AYHSOK5B-Cam0yXvU.js +7 -0
- package/dist/web/ui/assets/r-Dspwwk_N.js +1 -0
- package/dist/web/ui/assets/racket-BqYA7rlc.js +1 -0
- package/dist/web/ui/assets/raku-DXvB9xmW.js +1 -0
- package/dist/web/ui/assets/razor-Uh8Bk_45.js +1 -0
- package/dist/web/ui/assets/red-bN70gL4F.js +1 -0
- package/dist/web/ui/assets/reg-C-SQnVFl.js +1 -0
- package/dist/web/ui/assets/regexp-CDVJQ6XC.js +1 -0
- package/dist/web/ui/assets/rel-C3B-1QV4.js +1 -0
- package/dist/web/ui/assets/requirementDiagram-UZGBJVZJ-D_yH3UAt.js +64 -0
- package/dist/web/ui/assets/riscv-BM1_JUlF.js +1 -0
- package/dist/web/ui/assets/ron-BhRPY-oY.js +1 -0
- package/dist/web/ui/assets/rose-pine-dawn-DHQR4-dF.js +1 -0
- package/dist/web/ui/assets/rose-pine-moon-D4_iv3hh.js +1 -0
- package/dist/web/ui/assets/rose-pine-qdsjHGoJ.js +1 -0
- package/dist/web/ui/assets/rosmsg-BJDFO7_C.js +1 -0
- package/dist/web/ui/assets/rst-D5oM4XIm.js +1 -0
- package/dist/web/ui/assets/ruby-Cw6WdidG.js +1 -0
- package/dist/web/ui/assets/rust-B1yitclQ.js +1 -0
- package/dist/web/ui/assets/sankeyDiagram-TZEHDZUN-Dm93-uJ1.js +10 -0
- package/dist/web/ui/assets/sas-cz2c8ADy.js +1 -0
- package/dist/web/ui/assets/sass-Cj5Yp3dK.js +1 -0
- package/dist/web/ui/assets/scala-C151Ov-r.js +1 -0
- package/dist/web/ui/assets/scheme-C98Dy4si.js +1 -0
- package/dist/web/ui/assets/scss-OYdSNvt2.js +1 -0
- package/dist/web/ui/assets/sdbl-DVxCFoDh.js +1 -0
- package/dist/web/ui/assets/sequenceDiagram-WL72ISMW-D6C4PHTO.js +145 -0
- package/dist/web/ui/assets/shaderlab-Dg9Lc6iA.js +1 -0
- package/dist/web/ui/assets/shellscript-Yzrsuije.js +1 -0
- package/dist/web/ui/assets/shellsession-BADoaaVG.js +1 -0
- package/dist/web/ui/assets/slack-dark-BthQWCQV.js +1 -0
- package/dist/web/ui/assets/slack-ochin-DqwNpetd.js +1 -0
- package/dist/web/ui/assets/smalltalk-BERRCDM3.js +1 -0
- package/dist/web/ui/assets/snazzy-light-Bw305WKR.js +1 -0
- package/dist/web/ui/assets/solarized-dark-DXbdFlpD.js +1 -0
- package/dist/web/ui/assets/solarized-light-L9t79GZl.js +1 -0
- package/dist/web/ui/assets/solidity-rGO070M0.js +1 -0
- package/dist/web/ui/assets/soy-Brmx7dQM.js +1 -0
- package/dist/web/ui/assets/sparql-rVzFXLq3.js +1 -0
- package/dist/web/ui/assets/splunk-BtCnVYZw.js +1 -0
- package/dist/web/ui/assets/sql-BLtJtn59.js +1 -0
- package/dist/web/ui/assets/ssh-config-_ykCGR6B.js +1 -0
- package/dist/web/ui/assets/stata-BH5u7GGu.js +1 -0
- package/dist/web/ui/assets/stateDiagram-FKZM4ZOC-msXCFM-o.js +1 -0
- package/dist/web/ui/assets/stateDiagram-v2-4FDKWEC3-BxRi32Am.js +1 -0
- package/dist/web/ui/assets/stylus-BEDo0Tqx.js +1 -0
- package/dist/web/ui/assets/surrealql-Bq5Q-fJD.js +1 -0
- package/dist/web/ui/assets/svelte-zxCyuUbr.js +1 -0
- package/dist/web/ui/assets/swift-Dg5xB15N.js +1 -0
- package/dist/web/ui/assets/synthwave-84-CbfX1IO0.js +1 -0
- package/dist/web/ui/assets/system-verilog-CnnmHF94.js +1 -0
- package/dist/web/ui/assets/systemd-4A_iFExJ.js +1 -0
- package/dist/web/ui/assets/talonscript-CkByrt1z.js +1 -0
- package/dist/web/ui/assets/tasl-QIJgUcNo.js +1 -0
- package/dist/web/ui/assets/tcl-dwOrl1Do.js +1 -0
- package/dist/web/ui/assets/templ-P3uqSqPl.js +1 -0
- package/dist/web/ui/assets/terraform-BETggiCN.js +1 -0
- package/dist/web/ui/assets/tex-CvyZ59Mk.js +1 -0
- package/dist/web/ui/assets/timeline-definition-IT6M3QCI-OhdHqGpr.js +61 -0
- package/dist/web/ui/assets/tokyo-night-hegEt444.js +1 -0
- package/dist/web/ui/assets/toml-vGWfd6FD.js +1 -0
- package/dist/web/ui/assets/treemap-KMMF4GRG-BBa7Tuyx.js +128 -0
- package/dist/web/ui/assets/ts-tags-zn1MmPIZ.js +1 -0
- package/dist/web/ui/assets/tsv-B_m7g4N7.js +1 -0
- package/dist/web/ui/assets/tsx-COt5Ahok.js +1 -0
- package/dist/web/ui/assets/turtle-BsS91CYL.js +1 -0
- package/dist/web/ui/assets/twig-ChbOoGGc.js +1 -0
- package/dist/web/ui/assets/typescript-BPQ3VLAy.js +1 -0
- package/dist/web/ui/assets/typespec-BGHnOYBU.js +1 -0
- package/dist/web/ui/assets/typst-DHCkPAjA.js +1 -0
- package/dist/web/ui/assets/v-BcVCzyr7.js +1 -0
- package/dist/web/ui/assets/vala-CsfeWuGM.js +1 -0
- package/dist/web/ui/assets/vb-D17OF-Vu.js +1 -0
- package/dist/web/ui/assets/verilog-BQ8w6xss.js +1 -0
- package/dist/web/ui/assets/vesper-DU1UobuO.js +1 -0
- package/dist/web/ui/assets/vhdl-CeAyd5Ju.js +1 -0
- package/dist/web/ui/assets/viml-CJc9bBzg.js +1 -0
- package/dist/web/ui/assets/vitesse-black-Bkuqu6BP.js +1 -0
- package/dist/web/ui/assets/vitesse-dark-D0r3Knsf.js +1 -0
- package/dist/web/ui/assets/vitesse-light-CVO1_9PV.js +1 -0
- package/dist/web/ui/assets/vue-DN_0RTcg.js +1 -0
- package/dist/web/ui/assets/vue-html-AaS7Mt5G.js +1 -0
- package/dist/web/ui/assets/vue-vine-CQOfvN7w.js +1 -0
- package/dist/web/ui/assets/vyper-CDx5xZoG.js +1 -0
- package/dist/web/ui/assets/wasm-CG6Dc4jp.js +1 -0
- package/dist/web/ui/assets/wasm-MzD3tlZU.js +1 -0
- package/dist/web/ui/assets/wenyan-BV7otONQ.js +1 -0
- package/dist/web/ui/assets/wgsl-Dx-B1_4e.js +1 -0
- package/dist/web/ui/assets/wikitext-BhOHFoWU.js +1 -0
- package/dist/web/ui/assets/wit-5i3qLPDT.js +1 -0
- package/dist/web/ui/assets/wolfram-lXgVvXCa.js +1 -0
- package/dist/web/ui/assets/xml-sdJ4AIDG.js +1 -0
- package/dist/web/ui/assets/xsl-CtQFsRM5.js +1 -0
- package/dist/web/ui/assets/xychartDiagram-PRI3JC2R-CwWrUftO.js +7 -0
- package/dist/web/ui/assets/yaml-Buea-lGh.js +1 -0
- package/dist/web/ui/assets/zenscript-DVFEvuxE.js +1 -0
- package/dist/web/ui/assets/zig-VOosw3JB.js +1 -0
- package/dist/web/ui/index.html +19 -0
- package/dist/web/ui/logo-dark.svg +10 -0
- package/dist/web/ui/logo.svg +10 -0
- package/package.json +17 -2
package/dist/index.js
CHANGED
|
@@ -1,109 +1,123 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Ra=Object.create;var Qr=Object.defineProperty;var Ia=Object.getOwnPropertyDescriptor;var Oa=Object.getOwnPropertyNames;var La=Object.getPrototypeOf,Na=Object.prototype.hasOwnProperty;var eo=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $a=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Oa(e))!Na.call(t,o)&&o!==n&&Qr(t,o,{get:()=>e[o],enumerable:!(r=Ia(e,o))||r.enumerable});return t};var to=(t,e,n)=>(n=t!=null?Ra(La(t)):{},$a(e||!t||!t.__esModule?Qr(n,"default",{value:t,enumerable:!0}):n,t));var Oo=eo((Oh,Io)=>{"use strict";function wo(t){return Array.isArray(t)?t:[t]}var Gn="",Mo=" ",Wn="\\",rc=/^\s+$/,oc=/(?:[^\\]|^)\\$/,sc=/^\\!/,ic=/^\\#/,ac=/\r?\n/g,lc=/^\.*\/|^\.+$/,jn="/",Po="node-ignore";typeof Symbol<"u"&&(Po=Symbol.for("node-ignore"));var Eo=Po,cc=(t,e,n)=>Object.defineProperty(t,e,{value:n}),uc=/([0-z])-([0-z])/g,ko=()=>!1,pc=t=>t.replace(uc,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Gn),dc=t=>{let{length:e}=t;return t.slice(0,e-e%2)},mc=[[/^\uFEFF/,()=>Gn],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?Mo:Gn)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+Mo}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return e+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Wn],[/\\\\/g,()=>Wn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===Wn?`\\[${n}${dc(r)}${o}`:o==="]"&&r.length%2===0?`[${pc(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Ao=Object.create(null),fc=(t,e)=>{let n=Ao[t];return n||(n=mc.reduce((r,[o,s])=>r.replace(o,s.bind(t)),t),Ao[t]=n),e?new RegExp(n,"i"):new RegExp(n)},Kn=t=>typeof t=="string",gc=t=>t&&Kn(t)&&!rc.test(t)&&!oc.test(t)&&t.indexOf("#")!==0,hc=t=>t.split(ac),zn=class{constructor(e,n,r,o){this.origin=e,this.pattern=n,this.negative=r,this.regex=o}},yc=(t,e)=>{let n=t,r=!1;t.indexOf("!")===0&&(r=!0,t=t.substr(1)),t=t.replace(sc,"!").replace(ic,"#");let o=fc(t,e);return new zn(n,t,r,o)},_c=(t,e)=>{throw new e(t)},Oe=(t,e,n)=>Kn(t)?t?Oe.isNotRelative(t)?n(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${e}\``,TypeError),Ro=t=>lc.test(t);Oe.isNotRelative=Ro;Oe.convert=t=>t;var qn=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){cc(this,Eo,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[Eo]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(gc(e)){let n=yc(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,wo(Kn(e)?hc(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,n){let r=!1,o=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(o===i&&r!==o||i&&!r&&!o&&!n)return;s.regex.test(e)&&(r=!i,o=i)}),{ignored:r,unignored:o}}_test(e,n,r,o){let s=e&&Oe.convert(e);return Oe(s,e,this._allowRelativePaths?ko:_c),this._t(s,n,r,o)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(jn)),o.pop(),!o.length)return n[e]=this._testOne(e,r);let s=this._t(o.join(jn)+jn,n,r,o);return n[e]=s.ignored?s:this._testOne(e,r)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return wo(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Xt=t=>new qn(t),Sc=t=>Oe(t&&Oe.convert(t),t,ko);Xt.isPathValid=Sc;Xt.default=Xt;Io.exports=Xt;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Oe.convert=t;let e=/^[a-z]:\//i;Oe.isNotRelative=n=>e.test(n)||Ro(n)}});var Ai=eo((oT,yn)=>{"use strict";function bi(t){return Array.isArray(t)?t:[t]}var Wd=void 0,Pr="",Ti=" ",Ar="\\",jd=/^\s+$/,Gd=/(?:[^\\]|^)\\$/,zd=/^\\!/,qd=/^\\#/,Kd=/\r?\n/g,Vd=/^\.{0,2}\/|^\.{1,2}$/,Xd=/\/$/,gt="/",Ci="node-ignore";typeof Symbol<"u"&&(Ci=Symbol.for("node-ignore"));var xi=Ci,ht=(t,e,n)=>(Object.defineProperty(t,e,{value:n}),n),Jd=/([0-z])-([0-z])/g,wi=()=>!1,Yd=t=>t.replace(Jd,(e,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?e:Pr),Zd=t=>{let{length:e}=t;return t.slice(0,e-e%2)},Qd=[[/^\uFEFF/,()=>Pr],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,n)=>e+(n.indexOf("\\")===0?Ti:Pr)],[/(\\+?)\s/g,(t,e)=>{let{length:n}=e;return e.slice(0,n-n%2)+Ti}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,n)=>e+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return e+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Ar],[/\\\\/g,()=>Ar],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,n,r,o)=>e===Ar?`\\[${n}${Zd(r)}${o}`:o==="]"&&r.length%2===0?`[${Yd(n)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],em=/(^|\\\/)?\\\*$/,$t="regex",gn="checkRegex",vi="_",tm={[$t](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[gn](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},nm=t=>Qd.reduce((e,[n,r])=>e.replace(n,r.bind(t)),t),hn=t=>typeof t=="string",rm=t=>t&&hn(t)&&!jd.test(t)&&!Gd.test(t)&&t.indexOf("#")!==0,om=t=>t.split(Kd).filter(Boolean),kr=class{constructor(e,n,r,o,s,i){this.pattern=e,this.mark=n,this.negative=s,ht(this,"body",r),ht(this,"ignoreCase",o),ht(this,"regexPrefix",i)}get regex(){let e=vi+$t;return this[e]?this[e]:this._make($t,e)}get checkRegex(){let e=vi+gn;return this[e]?this[e]:this._make(gn,e)}_make(e,n){let r=this.regexPrefix.replace(em,tm[e]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return ht(this,n,o)}},sm=({pattern:t,mark:e},n)=>{let r=!1,o=t;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(zd,"!").replace(qd,"#");let s=nm(o);return new kr(t,e,o,n,r,s)},Rr=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[xi]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(hn(e)&&(e={pattern:e}),rm(e.pattern)){let n=sm(e,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(e){return this._added=!1,bi(hn(e)?om(e):e).forEach(this._add,this),this._added}test(e,n,r){let o=!1,s=!1,i;this._rules.forEach(l=>{let{negative:c}=l;s===c&&o!==s||c&&!o&&!s&&!n||!l[r].test(e)||(o=!c,s=c,i=c?Wd:l)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},im=(t,e)=>{throw new e(t)},De=(t,e,n)=>hn(t)?t?De.isNotRelative(t)?n(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${e}\``,TypeError),Mi=t=>Vd.test(t);De.isNotRelative=Mi;De.convert=t=>t;var Ir=class{constructor({ignorecase:e=!0,ignoreCase:n=e,allowRelativePaths:r=!1}={}){ht(this,xi,!0),this._rules=new Rr(n),this._strictPathCheck=!r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,n,r,o){let s=e&&De.convert(e);return De(s,e,this._strictPathCheck?im:wi),this._t(s,n,r,o)}checkIgnore(e){if(!Xd.test(e))return this.test(e);let n=e.split(gt).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(gt)+gt,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(e,!1,gn)}_t(e,n,r,o){if(e in n)return n[e];if(o||(o=e.split(gt).filter(Boolean)),o.pop(),!o.length)return n[e]=this._rules.test(e,r,$t);let s=this._t(o.join(gt)+gt,n,r,o);return n[e]=s.ignored?s:this._rules.test(e,r,$t)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return bi(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Or=t=>new Ir(t),am=t=>De(t&&De.convert(t),t,wi),Ei=()=>{let t=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");De.convert=t;let e=/^[a-z]:\//i;De.isNotRelative=n=>e.test(n)||Mi(n)};typeof process<"u"&&process.platform==="win32"&&Ei();yn.exports=Or;Or.default=Or;yn.exports.isPathValid=am;ht(yn.exports,Symbol.for("setupWindows"),Ei)});import{randomUUID as Ca}from"crypto";import{createInterface as Ig}from"readline/promises";import{stdin as Og,stdout as Lg}from"process";import{render as Ng}from"ink";import al from"os";import{readFile as lo}from"fs/promises";import{join as co,dirname as ll}from"path";import{fileURLToPath as cl}from"url";import{access as Da,readFile as Ua,readdir as Ha,stat as Fa}from"fs/promises";import{constants as Ba}from"fs";import{homedir as ro}from"os";import{dirname as Wa,isAbsolute as ja,join as it,resolve as qt}from"path";import Ga from"fast-glob";var za="SKILL.md",qa=6,Ka=200,Va=64,Xa=1024,Ja="- Discovery: The list above is the skills available in this session (name + description + file path). Skill bodies live on disk at the listed paths.\n- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\n- Missing/blocked: If a named skill isn't in the list or the path can't be read, say so briefly and continue with the best fallback.\n- How to use a skill (progressive disclosure):\n 1) After deciding to use a skill, open its `SKILL.md`. Read only enough to follow the workflow.\n 2) When `SKILL.md` references relative paths (e.g., `scripts/foo.py`), resolve them relative to the skill directory listed above first, and only consider other paths if needed.\n 3) If `SKILL.md` points to extra folders such as `references/`, load only the specific files needed for the request; don't bulk-load everything.\n 4) If `scripts/` exist, prefer running or patching them instead of retyping large code blocks.\n 5) If `assets/` or templates exist, reuse them instead of recreating from scratch.\n- Coordination and sequencing:\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\n - Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why.\n- Context hygiene:\n - Keep context small: summarize long sections instead of pasting them; only load extra files when needed.\n - Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked.\n - When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice.\n- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue.";function oo(t){return t.trim().split(/\s+/).join(" ")}function Ya(t){let e=t.trim();return e.length>=2&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))?e.slice(1,-1):e}function Za(t){let e=t.split(/\r?\n/);if(e[0]?.trim()!=="---")return null;let n=[],r=!1;for(let o of e.slice(1)){if(o.trim()==="---"){r=!0;break}n.push(o)}return!r||n.length===0?null:n.join(`
|
|
3
|
-
`)}function
|
|
4
|
-
`)}var
|
|
2
|
+
var gl=Object.create;var ur=Object.defineProperty;var hl=Object.getOwnPropertyDescriptor;var yl=Object.getOwnPropertyNames;var _l=Object.getPrototypeOf,Sl=Object.prototype.hasOwnProperty;var Xo=(e,t)=>()=>(e&&(t=e(e=0)),t);var Jo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vl=(e,t)=>{for(var n in t)ur(e,n,{get:t[n],enumerable:!0})},Tl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yl(t))!Sl.call(e,o)&&o!==n&&ur(e,o,{get:()=>t[o],enumerable:!(r=hl(t,o))||r.enumerable});return e};var Yo=(e,t,n)=>(n=e!=null?gl(_l(e)):{},Tl(t||!e||!e.__esModule?ur(n,"default",{value:e,enumerable:!0}):n,e));var Cs=Jo((yS,hn)=>{"use strict";function ys(e){return Array.isArray(e)?e:[e]}var xu=void 0,hr="",gs=" ",gr="\\",Mu=/^\s+$/,ku=/(?:[^\\]|^)\\$/,Au=/^\\!/,Pu=/^\\#/,Eu=/\r?\n/g,Ru=/^\.{0,2}\/|^\.{1,2}$/,Iu=/\/$/,gt="/",_s="node-ignore";typeof Symbol<"u"&&(_s=Symbol.for("node-ignore"));var Ss=_s,ht=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),Ou=/([0-z])-([0-z])/g,vs=()=>!1,Lu=e=>e.replace(Ou,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:hr),Nu=e=>{let{length:t}=e;return e.slice(0,t-t%2)},$u=[[/^\uFEFF/,()=>hr],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?gs:hr)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+gs}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>gr],[/\\\\/g,()=>gr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===gr?`\\[${n}${Nu(r)}${o}`:o==="]"&&r.length%2===0?`[${Lu(n)}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],Du=/(^|\\\/)?\\\*$/,Ft="regex",fn="checkRegex",hs="_",Uu={[Ft](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[fn](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Fu=e=>$u.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),gn=e=>typeof e=="string",Hu=e=>e&&gn(e)&&!Mu.test(e)&&!ku.test(e)&&e.indexOf("#")!==0,Bu=e=>e.split(Eu).filter(Boolean),yr=class{constructor(t,n,r,o,s,i){this.pattern=t,this.mark=n,this.negative=s,ht(this,"body",r),ht(this,"ignoreCase",o),ht(this,"regexPrefix",i)}get regex(){let t=hs+Ft;return this[t]?this[t]:this._make(Ft,t)}get checkRegex(){let t=hs+fn;return this[t]?this[t]:this._make(fn,t)}_make(t,n){let r=this.regexPrefix.replace(Du,Uu[t]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return ht(this,n,o)}},Wu=({pattern:e,mark:t},n)=>{let r=!1,o=e;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(Au,"!").replace(Pu,"#");let s=Fu(o);return new yr(e,t,o,n,r,s)},_r=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[Ss]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(gn(t)&&(t={pattern:t}),Hu(t.pattern)){let n=Wu(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,ys(gn(t)?Bu(t):t).forEach(this._add,this),this._added}test(t,n,r){let o=!1,s=!1,i;this._rules.forEach(a=>{let{negative:l}=a;s===l&&o!==s||l&&!o&&!s&&!n||!a[r].test(t)||(o=!l,s=l,i=l?xu:a)});let c={ignored:o,unignored:s};return i&&(c.rule=i),c}},ju=(e,t)=>{throw new t(e)},Ue=(e,t,n)=>gn(e)?e?Ue.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),Ts=e=>Ru.test(e);Ue.isNotRelative=Ts;Ue.convert=e=>e;var Sr=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){ht(this,Ss,!0),this._rules=new _r(n),this._strictPathCheck=!r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,r,o){let s=t&&Ue.convert(t);return Ue(s,t,this._strictPathCheck?ju:vs),this._t(s,n,r,o)}checkIgnore(t){if(!Iu.test(t))return this.test(t);let n=t.split(gt).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(gt)+gt,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(t,!1,fn)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(gt).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,r,Ft);let s=this._t(o.join(gt)+gt,n,r,o);return n[t]=s.ignored?s:this._rules.test(t,r,Ft)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return ys(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},vr=e=>new Sr(e),zu=e=>Ue(e&&Ue.convert(e),e,vs),ws=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Ue.convert=e;let t=/^[a-z]:\//i;Ue.isNotRelative=n=>t.test(n)||Ts(n)};typeof process<"u"&&process.platform==="win32"&&ws();hn.exports=vr;vr.default=vr;hn.exports.isPathValid=zu;ht(hn.exports,Symbol.for("setupWindows"),ws)});var xi=Jo((Wv,bi)=>{"use strict";function yi(e){return Array.isArray(e)?e:[e]}var qr="",_i=" ",Gr="\\",Hd=/^\s+$/,Bd=/(?:[^\\]|^)\\$/,Wd=/^\\!/,jd=/^\\#/,zd=/\r?\n/g,Gd=/^\.*\/|^\.+$/,Kr="/",Ti="node-ignore";typeof Symbol<"u"&&(Ti=Symbol.for("node-ignore"));var Si=Ti,Kd=(e,t,n)=>Object.defineProperty(e,t,{value:n}),qd=/([0-z])-([0-z])/g,wi=()=>!1,Vd=e=>e.replace(qd,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:qr),Xd=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Jd=[[/^\uFEFF/,()=>qr],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?_i:qr)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+_i}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Gr],[/\\\\/g,()=>Gr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===Gr?`\\[${n}${Xd(r)}${o}`:o==="]"&&r.length%2===0?`[${Vd(n)}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`]],vi=Object.create(null),Yd=(e,t)=>{let n=vi[e];return n||(n=Jd.reduce((r,[o,s])=>r.replace(o,s.bind(e)),e),vi[e]=n),t?new RegExp(n,"i"):new RegExp(n)},Jr=e=>typeof e=="string",Qd=e=>e&&Jr(e)&&!Hd.test(e)&&!Bd.test(e)&&e.indexOf("#")!==0,Zd=e=>e.split(zd),Vr=class{constructor(t,n,r,o){this.origin=t,this.pattern=n,this.negative=r,this.regex=o}},em=(e,t)=>{let n=e,r=!1;e.indexOf("!")===0&&(r=!0,e=e.substr(1)),e=e.replace(Wd,"!").replace(jd,"#");let o=Yd(e,t);return new Vr(n,e,r,o)},tm=(e,t)=>{throw new t(e)},We=(e,t,n)=>Jr(e)?e?We.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),Ci=e=>Gd.test(e);We.isNotRelative=Ci;We.convert=e=>e;var Xr=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){Kd(this,Si,!0),this._rules=[],this._ignoreCase=n,this._allowRelativePaths=r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(t){if(t&&t[Si]){this._rules=this._rules.concat(t._rules),this._added=!0;return}if(Qd(t)){let n=em(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,yi(Jr(t)?Zd(t):t).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(t){return this.add(t)}_testOne(t,n){let r=!1,o=!1;return this._rules.forEach(s=>{let{negative:i}=s;if(o===i&&r!==o||i&&!r&&!o&&!n)return;s.regex.test(t)&&(r=!i,o=i)}),{ignored:r,unignored:o}}_test(t,n,r,o){let s=t&&We.convert(t);return We(s,t,this._allowRelativePaths?wi:tm),this._t(s,n,r,o)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(Kr)),o.pop(),!o.length)return n[t]=this._testOne(t,r);let s=this._t(o.join(Kr)+Kr,n,r,o);return n[t]=s.ignored?s:this._testOne(t,r)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return yi(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},bn=e=>new Xr(e),nm=e=>We(e&&We.convert(e),e,wi);bn.isPathValid=nm;bn.default=bn;bi.exports=bn;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");We.convert=e;let t=/^[a-z]:\//i;We.isNotRelative=n=>t.test(n)||Ci(n)}});function S_(e){let t=Number.parseInt(e,10);return!Number.isInteger(t)||t<=0||t>65535?null:t}function Zc(e){let t={open:!0};for(let n=0;n<e.length;n++){let r=e[n];if(r){if(r==="--open"){t.open=!0;continue}if(r==="--no-open"){t.open=!1;continue}if(r==="--host"){let o=e[n+1];o&&!o.startsWith("-")&&(t.host=o,n+=1);continue}if(r==="--port"){let o=e[n+1];if(o&&!o.startsWith("-")){let s=S_(o);s!==null&&(t.port=s,n+=1)}continue}if(r==="--static-dir"){let o=e[n+1];o&&!o.startsWith("-")&&(t.staticDir=o,n+=1);continue}}}return t}var el=Xo(()=>{"use strict"});var sl={};vl(sl,{runWebCommand:()=>R_});import{spawn as tl}from"child_process";import{existsSync as nl,readFileSync as v_}from"fs";import{createServer as T_}from"net";import{dirname as ir,join as _e,resolve as Ot}from"path";import{fileURLToPath as Vo}from"url";function sr(e){let t=Ot(e);for(;;){let n=_e(t,"package.json");if(nl(n))try{if(JSON.parse(v_(n,"utf8")).name==="@memo-code/memo")return t}catch{}let r=ir(t);if(r===t)break;t=r}return null}function rl(e){return nl(e)}function b_(e){let t=[];e&&t.push(Ot(e)),process.env.MEMO_WEB_SERVER_ENTRY&&t.push(Ot(process.env.MEMO_WEB_SERVER_ENTRY));let n=ir(Vo(import.meta.url)),r=sr(n)??sr(process.cwd());r&&(t.push(_e(r,"dist/web/server/main.cjs")),t.push(_e(r,"dist/web/server/main.js")),t.push(_e(r,"packages/web-server/dist/main.cjs")),t.push(_e(r,"packages/web-server/dist/main.js"))),t.push(_e(process.cwd(),"dist/web/server/main.cjs")),t.push(_e(process.cwd(),"dist/web/server/main.js")),t.push(_e(process.cwd(),"packages/web-server/dist/main.cjs")),t.push(_e(process.cwd(),"packages/web-server/dist/main.js"));for(let o of t)if(rl(o))return o;return null}function x_(e){let t=[];e&&t.push(Ot(e)),process.env.MEMO_WEB_STATIC_DIR&&t.push(Ot(process.env.MEMO_WEB_STATIC_DIR));let n=ir(Vo(import.meta.url)),r=sr(n)??sr(process.cwd());r&&(t.push(_e(r,"dist/web/ui")),t.push(_e(r,"packages/web-ui/dist"))),t.push(_e(process.cwd(),"dist/web/ui")),t.push(_e(process.cwd(),"packages/web-ui/dist"));for(let o of t)if(rl(_e(o,"index.html")))return o;return null}async function ol(e,t){return new Promise(n=>{let r=T_();r.unref(),r.once("error",()=>n(!1)),r.listen({host:e,port:t},()=>{r.close(()=>n(!0))})})}async function M_(e,t){for(let n=0;n<30;n++){let r=t+n;if(r>65535)break;if(await ol(e,r))return r}throw new Error(`No available port found from ${t} to ${t+29}`)}function k_(e,t){return t==="darwin"?{command:"open",args:[e]}:t==="win32"?{command:"cmd",args:["/c","start","",e]}:t==="linux"?{command:"xdg-open",args:[e]}:null}function A_(e){let t=k_(e,process.platform);if(!t)return!1;try{return tl(t.command,t.args,{stdio:"ignore",detached:!0}).unref(),!0}catch{return!1}}function P_(e,t){return`http://${e.includes(":")?`[${e}]`:e}:${t}`}async function E_(e,t,n=8e3){let r=Date.now();for(;Date.now()-r<n;){if(!await ol(e,t))return!0;await new Promise(o=>setTimeout(o,120))}return!1}async function R_(e){let t=Zc(e),n=t.host??w_,r=t.port??C_,o=await M_(n,r),s=b_();if(!s){console.error("web-server entry not found (main.js missing)."),console.error("Please run `pnpm run web:server:build` or `pnpm run build` first."),process.exitCode=1;return}let i=x_(t.staticDir);if(!i){console.error("web-ui static assets not found (index.html missing)."),console.error("Please run `pnpm run web:ui:build` or `pnpm run build` first."),process.exitCode=1;return}o!==r&&console.log(`[memo web] Port ${r} is busy, using ${o}`);let c=P_(n,o);console.log(`[memo web] Server: ${c}`),console.log(`[memo web] Entry: ${s}`),console.log(`[memo web] Static: ${i}`);let a=tl(process.execPath,[s],{stdio:"inherit",env:{...process.env,MEMO_WEB_HOST:n,MEMO_WEB_PORT:String(o),MEMO_WEB_STATIC_DIR:i,MEMO_CLI_ENTRY:process.argv[1],MEMO_TASK_PROMPTS_DIR:Ot(ir(Vo(import.meta.url)),"../task-prompts")}});t.open&&(!await E_(n,o)||!A_(c))&&console.warn(`[memo web] Failed to auto-open browser. Open manually: ${c}`);let l=p=>{a.killed||a.kill(p)};process.once("SIGINT",()=>{l("SIGINT")}),process.once("SIGTERM",()=>{l("SIGTERM")}),await new Promise(p=>{a.once("exit",(u,d)=>{if(d){process.exitCode=0,p();return}process.exitCode=u??0,p()})})}var w_,C_,il=Xo(()=>{"use strict";el();w_="127.0.0.1",C_=5494});import{randomUUID as al}from"crypto";import{readFile as I_}from"fs/promises";import{createInterface as O_}from"readline/promises";import{stdin as L_,stdout as N_}from"process";import{render as $_}from"ink";import Kl from"os";import{readFile as ss}from"fs/promises";import{join as is,dirname as ql,resolve as Vl}from"path";import{fileURLToPath as Xl}from"url";import{access as wl,readFile as Cl,readdir as bl,stat as xl}from"fs/promises";import{constants as Ml}from"fs";import{homedir as Zo}from"os";import{dirname as kl,isAbsolute as Al,join as ft,resolve as cn}from"path";import Pl from"fast-glob";var El="SKILL.md",Rl=6,Il=200,Ol=64,Ll=1024,Nl="- Discovery: The list above is the skills available in this session (name + description + file path). Skill bodies live on disk at the listed paths.\n- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\n- Missing/blocked: If a named skill isn't in the list or the path can't be read, say so briefly and continue with the best fallback.\n- How to use a skill (progressive disclosure):\n 1) After deciding to use a skill, open its `SKILL.md`. Read only enough to follow the workflow.\n 2) When `SKILL.md` references relative paths (e.g., `scripts/foo.py`), resolve them relative to the skill directory listed above first, and only consider other paths if needed.\n 3) If `SKILL.md` points to extra folders such as `references/`, load only the specific files needed for the request; don't bulk-load everything.\n 4) If `scripts/` exist, prefer running or patching them instead of retyping large code blocks.\n 5) If `assets/` or templates exist, reuse them instead of recreating from scratch.\n- Coordination and sequencing:\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\n - Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why.\n- Context hygiene:\n - Keep context small: summarize long sections instead of pasting them; only load extra files when needed.\n - Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked.\n - When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice.\n- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue.";function es(e){return e.trim().split(/\s+/).join(" ")}function $l(e){let t=e.trim();return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function Dl(e){let t=e.split(/\r?\n/);if(t[0]?.trim()!=="---")return null;let n=[],r=!1;for(let o of t.slice(1)){if(o.trim()==="---"){r=!0;break}n.push(o)}return!r||n.length===0?null:n.join(`
|
|
3
|
+
`)}function Ul(e,t){let n=e.split(/\r?\n/),r=!1,o=[];for(let s of n){if(!r){s.match(new RegExp(`^${t}\\s*:\\s*[|>]\\s*$`))&&(r=!0);continue}if(!/^\s+/.test(s))break;o.push(s.replace(/^\s+/,""))}return o.length===0?null:es(o.join(" "))}function Qo(e,t){let n=Ul(e,t);if(n)return n;let r=new RegExp(`^${t}\\s*:\\s*(.+?)\\s*$`,"m"),o=e.match(r);return o?.[1]?es($l(o[1])):null}function Fl(e,t){let n=Dl(e);if(!n)return null;let r=Qo(n,"name"),o=Qo(n,"description");return!r||!o||r.length>Ol||o.length>Ll?null:{name:r,description:o,path:t}}function ts(e,t){return e==="~"?t:e.startsWith("~/")?ft(t,e.slice(2)):e}async function Hl(e){try{return(await xl(e)).isDirectory()}catch{return!1}}async function Bl(e){try{return await wl(ft(e,".git"),Ml.F_OK),!0}catch{return!1}}async function Wl(e){let t=cn(e),n=t;for(;;){if(await Bl(n))return n;let r=kl(n);if(r===n)break;n=r}return t}async function jl(e){let t=[ft(e,".agents","skills")];try{let r=(await bl(e,{withFileTypes:!0})).filter(o=>o.isDirectory()&&o.name.startsWith(".")).map(o=>o.name).filter(o=>o!==".git").sort((o,s)=>o.localeCompare(s));for(let o of r)t.push(ft(e,o,"skills"))}catch{return an(t)}return an(t)}function an(e){let t=[],n=new Set;for(let r of e){let o=cn(r);n.has(o)||(n.add(o),t.push(o))}return t}async function zl(e){let t=e.cwd??process.cwd(),n=e.homeDir??Zo(),r=ts(e.memoHome??process.env.MEMO_HOME??ft(n,".memo"),n),o=await Wl(t),s=await jl(o);return s.push(ft(r,"skills")),an(s)}async function Gl(e){if(e.skillRoots&&e.skillRoots.length>0){let t=e.homeDir??Zo(),n=e.skillRoots.map(r=>{let o=ts(r,t);return Al(o)?o:cn(o)});return an(n)}return zl(e)}async function ns(e={}){let t=await Gl(e),n=Math.max(1,e.maxSkills??Il),r=[],o=new Set;for(let s of t){if(!await Hl(s))continue;let i=await Pl(`**/${El}`,{cwd:s,absolute:!0,onlyFiles:!0,deep:Rl,caseSensitiveMatch:!1,followSymbolicLinks:!0,suppressErrors:!0,unique:!0,ignore:["**/.git/**","**/node_modules/**"]});i.sort((c,a)=>c.localeCompare(a));for(let c of i){let a=cn(c);if(o.has(a))continue;let l;try{l=await Cl(a,"utf-8")}catch{continue}let p=Fl(l,a);if(p&&(r.push(p),o.add(a),r.length>=n))return r}}return r}function rs(e){if(e.length===0)return null;let t=[];t.push("## Skills"),t.push("A skill is a set of local instructions to follow that is stored in a `SKILL.md` file. Below is the list of skills that can be used. Each entry includes a name, description, and file path so you can open the source for full instructions when using a specific skill."),t.push("### Available skills");for(let n of e)t.push(`- ${n.name}: ${n.description} (file: ${n.path})`);return t.push("### How to use skills"),t.push(Nl),t.join(`
|
|
4
|
+
`)}var Jl=/{{\s*([\w.-]+)\s*}}/g;function Yl(e,t){return e.replace(Jl,(n,r)=>t[r]??"")}function Ql(){try{return Kl.userInfo().username}catch{return process.env.USER??process.env.USERNAME??"unknown"}}function os(e){return Vl(e)}function Zl(e,t){if(!Array.isArray(t))return e;let n=new Set(t.map(r=>os(r)));return e.filter(r=>n.has(os(r.path)))}async function eu(e){let t=is(e,"AGENTS.md");try{let n=await ss(t,"utf-8");return n.trim()?{path:t,content:n}:null}catch{return null}}function tu(e,t){return`${e}
|
|
5
5
|
|
|
6
6
|
## Project AGENTS.md (Startup Root)
|
|
7
|
-
Loaded from: ${
|
|
7
|
+
Loaded from: ${t.path}
|
|
8
8
|
|
|
9
|
-
${
|
|
9
|
+
${t.content}`}function nu(e,t){return`${e}
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
`,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function
|
|
13
|
-
`)
|
|
14
|
-
`).
|
|
15
|
-
`).split(`
|
|
16
|
-
`)
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
`))}catch(o){return m(`grep_files failed: ${o.message}`,!0)}}});import{z as Ne}from"zod";import{createHash as lu}from"crypto";import{mkdir as cu,readFile as uu,rename as pu,writeFile as du}from"fs/promises";import{homedir as Jn}from"os";import{dirname as mu,join as Qn}from"path";var fu="mcp.json",Zt=2,gu=120,hu=600*1e3,Wo=1440*60*1e3;function Vn(){return process.env.MEMO_FORCE_MCP_DISK_CACHE==="1"?!0:!(process.env.MEMO_FORCE_MCP_DISK_CACHE==="0"||process.env.NODE_ENV==="test"||typeof process.env.VITEST<"u"||typeof process.env.VITEST_WORKER_ID<"u")}function yu(t){return t==="~"?Jn():t.startsWith("~/")?Qn(Jn(),t.slice(2)):t}function _u(){let t=process.env.MEMO_HOME?.trim();return t?yu(t):Qn(Jn(),".memo")}function jo(){return Qn(_u(),"cache",fu)}function Yn(t){if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(r=>Yn(r)).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Yn(e[r])}`).join(",")}}`}function Go(t){return lu("sha256").update(Yn(t)).digest("hex")}function Su(t){return t instanceof Error?t.message:String(t)}function Yt(){return{version:Zt,toolsByServer:{},responses:{}}}var Zn=class{data=Yt();loaded=!1;loadPromise=null;persistTimer=null;persistRunning=!1;persistRequested=!1;responseInflight=new Map;pruneExpiredResponses(e=Date.now()){for(let[n,r]of Object.entries(this.data.responses))r.expiresAt<=e&&delete this.data.responses[n]}pruneExpiredTools(e=Date.now()){for(let[n,r]of Object.entries(this.data.toolsByServer))e-r.fetchedAt>Wo&&delete this.data.toolsByServer[n]}async ensureLoaded(){if(!Vn()){this.loaded=!0;return}if(!this.loaded){if(this.loadPromise){await this.loadPromise;return}this.loadPromise=(async()=>{let e=jo();try{let n=await uu(e,"utf8"),r=JSON.parse(n);if(r.version===Zt){let o=r;this.data={version:Zt,toolsByServer:o.toolsByServer??{},responses:o.responses??{}}}else r.version===1&&r.entries?this.data={version:Zt,toolsByServer:{},responses:r.entries}:this.data=Yt()}catch{this.data=Yt()}finally{this.pruneExpiredResponses(),this.pruneExpiredTools(),this.loaded=!0}})(),await this.loadPromise}}async persistToDisk(){if(!Vn())return;this.pruneExpiredResponses(),this.pruneExpiredTools();let e=jo(),n=`${e}.tmp`,r=mu(e);await cu(r,{recursive:!0}),await du(n,JSON.stringify(this.data,null,2),"utf8"),await pu(n,e)}async flushPersistQueue(){if(!(!this.persistRequested||this.persistRunning)){this.persistRequested=!1,this.persistRunning=!0;try{await this.persistToDisk()}catch{}finally{this.persistRunning=!1,this.persistRequested&&this.flushPersistQueue()}}}schedulePersist(){Vn()&&(this.persistRequested=!0,!this.persistTimer&&(this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersistQueue()},gu),this.persistTimer.unref?.()))}async getServerTools(e,n){await this.ensureLoaded();let r=this.data.toolsByServer[e];if(!r)return null;if(r.configHash!==Go(n))return delete this.data.toolsByServer[e],this.schedulePersist(),null;let o=Date.now()-r.fetchedAt;return o>Wo?(delete this.data.toolsByServer[e],this.schedulePersist(),null):{tools:r.tools,stale:o>hu,ageMs:o}}async setServerTools(e,n,r){await this.ensureLoaded(),this.data.toolsByServer[e]={fetchedAt:Date.now(),configHash:Go(n),tools:r},this.schedulePersist()}async withResponseCache(e,n,r){await this.ensureLoaded();let o=this.data.responses[e];if(o&&o.expiresAt>Date.now())return o.value;o&&o.expiresAt<=Date.now()&&delete this.data.responses[e];let s=this.responseInflight.get(e);if(s)return await s;let i=(async()=>{let a=await r();return this.data.responses[e]={expiresAt:Date.now()+n,value:a},this.schedulePersist(),a})();this.responseInflight.set(e,i);try{return await i}catch(a){throw new Error(Su(a))}finally{this.responseInflight.delete(e)}}async flushForTests(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.persistRequested=!0,await this.flushPersistQueue()}resetForTests(){this.data=Yt(),this.loaded=!1,this.loadPromise=null,this.responseInflight.clear(),this.persistRequested=!1,this.persistRunning=!1,this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null)}},Xn=null;function Qt(){return Xn||(Xn=new Zn),Xn}var zo=null,qo=null;function er(t){zo=t}function Ko(){return zo}function tr(t){qo=t}function Vo(){return qo}var Tu=Ne.object({server:Ne.string().optional(),cursor:Ne.string().optional()}).strict(),vu=Ne.object({server:Ne.string().optional(),cursor:Ne.string().optional()}).strict(),bu=Ne.object({server:Ne.string().min(1),uri:Ne.string().min(1)}).strict(),en=15e3,Cu=6e4;function nr(){let t=Ko();if(!t)throw new Error("MCP pool is not initialized");return t}function rr(){return Vo()??Qt()}function Yo(t){return t instanceof Error?t.message:String(t)}function Xo(t,e){return`list_resources:${t}:${e??""}`}function Jo(t,e){return`list_resource_templates:${t}:${e??""}`}function xu(t,e){return`read_resource:${t}:${e}`}function or(t,e){return typeof t.hasServer=="function"?t.hasServer(e):typeof t.get=="function"?!!t.get(e):!1}async function sr(t,e){if(typeof t.get=="function"){let n=t.get(e);if(n)return n}if(typeof t.connect=="function")return t.connect(e)}async function Zo(t){if(typeof t.getKnownServerNames=="function"&&typeof t.connect=="function"){let n=t.getKnownServerNames().sort((s,i)=>s.localeCompare(i)),r=await Promise.allSettled(n.map(s=>t.connect(s))),o=[];return r.forEach((s,i)=>{if(s.status==="fulfilled"){o.push(s.value);return}let a=n[i];a&&o.push({name:a,client:null,__error:s.reason})}),o.sort((s,i)=>s.name.localeCompare(i.name))}return(typeof t.getAll=="function"?t.getAll():[]).sort((n,r)=>n.name.localeCompare(r.name))}var Qo=N({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:Tu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=nr(),r=rr(),o=t?.trim();if(o){if(!or(n,o))return m(`MCP server not found: ${t}`,!0);let l=await sr(n,o);if(!l)return m(`MCP server not found: ${t}`,!0);let c=await r.withResponseCache(Xo(l.name,e),en,async()=>{let p=await l.client.listResources(e?{cursor:e}:void 0);return{server:l.name,resources:p.resources,nextCursor:p.nextCursor}});return m(JSON.stringify(c,null,2))}if(e)return m("cursor is only supported when server is specified",!0);let s=await Zo(n),i=`all:${s.map(l=>l.name).join(",")}`,a=await r.withResponseCache(Xo(i),en,async()=>{let l=await Promise.allSettled(s.map(async u=>{if(!u.client)throw new Error(`MCP server '${u.name}' is not connected`);return{server:u.name,result:await u.client.listResources()}})),c=[],p=[];return l.forEach((u,g)=>{let v=s[g]?.name??"unknown";if(u.status==="rejected"){p.push({server:v,error:Yo(u.reason)});return}for(let h of u.value.result.resources)c.push({server:u.value.server,...h})}),{resources:c,...p.length>0?{errors:p}:{}}});return m(JSON.stringify(a,null,2))}catch(n){return m(`list_mcp_resources failed: ${n.message}`,!0)}}}),es=N({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:vu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,cursor:e})=>{try{let n=nr(),r=rr(),o=t?.trim();if(o){if(!or(n,o))return m(`MCP server not found: ${t}`,!0);let l=await sr(n,o);if(!l)return m(`MCP server not found: ${t}`,!0);let c=await r.withResponseCache(Jo(l.name,e),en,async()=>{let p=await l.client.listResourceTemplates(e?{cursor:e}:void 0);return{server:l.name,resourceTemplates:p.resourceTemplates,nextCursor:p.nextCursor}});return m(JSON.stringify(c,null,2))}if(e)return m("cursor is only supported when server is specified",!0);let s=await Zo(n),i=`all:${s.map(l=>l.name).join(",")}`,a=await r.withResponseCache(Jo(i),en,async()=>{let l=await Promise.allSettled(s.map(async u=>{if(!u.client)throw new Error(`MCP server '${u.name}' is not connected`);return{server:u.name,result:await u.client.listResourceTemplates()}})),c=[],p=[];return l.forEach((u,g)=>{let v=s[g]?.name??"unknown";if(u.status==="rejected"){p.push({server:v,error:Yo(u.reason)});return}for(let h of u.value.result.resourceTemplates)c.push({server:u.value.server,...h})}),{resourceTemplates:c,...p.length>0?{errors:p}:{}}});return m(JSON.stringify(a,null,2))}catch(n){return m(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),ts=N({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:bu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:t,uri:e})=>{try{let n=nr(),r=rr(),o=t.trim();if(!or(n,o))return m(`MCP server not found: ${t}`,!0);let s=await sr(n,o);if(!s)return m(`MCP server not found: ${t}`,!0);let i=await r.withResponseCache(xu(o,e),Cu,async()=>{let a=await s.client.readResource({uri:e});return{server:o,uri:e,...a}});return m(JSON.stringify(i,null,2))}catch(n){return m(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as lt}from"zod";var wu=lt.object({step:lt.string().min(1),status:lt.enum(["pending","in_progress","completed"])}).strict(),Mu=lt.object({explanation:lt.string().optional(),plan:lt.array(wu).min(1)}).strict(),ns=[],rs=N({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:Mu,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:t,plan:e})=>{if(e.filter(r=>r.status==="in_progress").length>1)return m("At most one step can be in_progress at a time",!0);if(e.length<4){let r=e[0]?.step??"";return m(`<system_hint tool="update_plan" reason="simple_task">Task "${r}" is simple (${e.length} step${e.length>1?"s":""}) - execute directly without update_plan.</system_hint>`)}return ns=e,m(JSON.stringify({message:"Plan updated",explanation:t,plan:ns},null,2))}});import{readFile as Eu}from"fs/promises";import{homedir as Au}from"os";import{join as os}from"path";import{z as ss}from"zod";var Pu=ss.object({memory_id:ss.string().min(1)}).strict();function ku(){let t=process.env.MEMO_HOME?.trim()||os(Au(),".memo");return os(t,"Agents.md")}var is=N({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:Pu,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:t})=>{try{let e=ku(),n=await Eu(e,"utf8");return m(JSON.stringify({memory_id:t,memory_summary:n},null,2))}catch{return m(`memory not found for memory_id=${t}`,!0)}}});import{z as as}from"zod";var Ru=as.object({url:as.string().min(1)}).strict(),ls=1e4,Pt=512e3,ir=4e3,Iu=new Set(["http:","https:"]),Ou=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,Lu=/<\s*(br|hr)\s*\/?>/gi,Nu=/<\s*li[^>]*>/gi,$u=/<[^>]+>/g,Du=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,Uu=t=>t.replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/g,"'").replace(/&#(x?[0-9a-fA-F]+);/g,(r,o)=>{try{let s=o.startsWith("x")||o.startsWith("X")?parseInt(o.slice(1),16):parseInt(o,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),Hu=t=>{let r=t.replace(Du," ").replace(Nu,"- ").replace(Lu,`
|
|
24
|
-
`).
|
|
25
|
-
|
|
26
|
-
`).map(a=>a.trim().replace(/[ \t]{2,}/g," "));return s.filter((a,l)=>a.length>0||l>0&&(s[l-1]?.length??0)>0).join(`
|
|
27
|
-
`).trim()},Fu=t=>t.replace(/\s+/g," ").trim(),cs=N({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:Ru,supportsParallelToolCalls:!0,isMutating:!1,execute:async t=>{let e;try{e=new URL(t.url)}catch{return m(`Invalid URL: ${t.url}`,!0)}if(!Iu.has(e.protocol))return m(`Unsupported protocol: ${e.protocol}`,!0);let n=new AbortController,r=setTimeout(()=>n.abort(),ls);try{let o=await globalThis.fetch(e,{signal:n.signal}),s=o.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>Pt)return m(`Request rejected: response body too large (${i} bytes)`,!0);let a=0,l="";if(o.body&&o.body.getReader){let x=o.body.getReader(),b=[];for(;;){let{done:q,value:fe}=await x.read();if(q)break;if(fe){if(a+=fe.byteLength,a>Pt)return n.abort(),m(`Request aborted: response body exceeds ${Pt} bytes`,!0);b.push(fe)}}let E=new Uint8Array(a),B=0;for(let q of b)E.set(q,B),B+=q.byteLength;l=new TextDecoder().decode(E)}else if(l=await o.text(),a=new TextEncoder().encode(l).byteLength,a>Pt)return m(`Request rejected: response body exceeds ${Pt} bytes`,!0);let c=o.headers.get("content-type")||"",p=/text\/html/i.test(c)||/^\s*<!doctype html/i.test(l)||/^\s*<html[\s>]/i.test(l),u=p?Hu(l):l.trim(),g=Fu(u),v=g.length>ir?`${g.slice(0,ir)}...`:g,h=g.length>ir?" text_truncated=true":"",f=p?" source=html_stripped":"";return m(`status=${o.status} bytes=${a} text_chars=${g.length} text="${v}"${h}${f}`)}catch(o){return o.name==="AbortError"?m(`Request timeout or aborted (${ls}ms)`,!0):m(`Request failed: ${o.message}`,!0)}finally{clearTimeout(r)}}});import{spawn as Bu}from"child_process";import{existsSync as Wu}from"fs";import{resolve as ju}from"path";import{z as le}from"zod";var Gu=3e4,zu=1e4,qu=3e5,us=4,Ku=1500,ps=2e3,We=new Map,Vu=le.object({message:le.string().min(1),agent_type:le.string().optional()}).strict(),Xu=le.object({id:le.string().min(1),message:le.string().min(1),interrupt:le.boolean().optional()}).strict(),Ju=le.object({id:le.string().min(1)}).strict(),Yu=le.object({ids:le.array(le.string().min(1)).min(1),timeout_ms:le.number().int().positive().optional()}).strict(),Zu=le.object({id:le.string().min(1)}).strict();function ct(){return new Date().toISOString()}function ar(t){return m(`agent not found: ${t}`,!0)}function Qu(){let t=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!t)return us;let e=Number(t);return!Number.isFinite(e)||e<=0?us:Math.floor(e)}function ep(){let t=0;for(let e of We.values())e.running&&(t+=1);return t}function tp(){let t=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(t)return t;let e=ju(process.cwd(),"dist/index.js");return Wu(e)?`node ${JSON.stringify(e)} --dangerous`:"memo --dangerous"}function np(t){return t!=="running"}function rp(t){return new Promise(e=>{setTimeout(e,t)})}function op(t){return t===void 0?Gu:t<=0?null:Math.max(zu,Math.min(qu,t))}function sp(t){return t.length<=ps?t:`${t.slice(0,ps)}
|
|
28
|
-
...[truncated]`}function ip(t,e){let n=[],r=t.trim(),o=e.trim();return r&&n.push(r),o&&n.push(`stderr:
|
|
29
|
-
${o}`),sp(n.join(`
|
|
30
|
-
|
|
31
|
-
`))}async function ds(t){let e=t.running;if(!e)return;e.interrupted=!0;let n=e.process;n.exitCode!==null||n.killed||await new Promise(r=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(i),n.off("close",s),r())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},Ku);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function ap(t){let e=We.get(t);return e?e.status:"not_found"}function lp(t){let e=We.get(t);return e?{status:e.status,last_message:e.lastMessage,last_output:e.lastOutput,last_error:e.lastError,last_submission_id:e.lastSubmissionId,updated_at:e.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function cp(t){return{agent_id:t.id,status:t.status,created_at:t.createdAt,updated_at:t.updatedAt,last_message:t.lastMessage,last_submission_id:t.lastSubmissionId,has_last_output:!!t.lastOutput,has_last_error:!!t.lastError}}function up(t){let{record:e,submissionId:n,stdout:r,stderr:o,exitCode:s,interrupted:i}=t;if(!(!e.running||e.running.id!==n)&&(e.running=null,e.updatedAt=ct(),e.lastOutput=ip(r,o)||null,e.lastError=null,e.status!=="closed")){if(i){e.status="errored",e.lastError="interrupted",e.statusBeforeClose="errored";return}if(s===0){e.status="completed",e.statusBeforeClose="completed";return}e.status="errored",e.lastError=`submission failed with exit code ${s}`,e.statusBeforeClose="errored"}}async function ms(t,e){let n=Qu();if(ep()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=tp(),s=Bu(o,{cwd:process.cwd(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],a=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",l=>i.push(l)),s.stderr?.on("data",l=>a.push(l)),s.on("error",l=>{a.push(`[spawn error] ${l.message}`)}),t.running={id:r,message:e,process:s,startedAt:ct(),interrupted:!1},t.status="running",t.lastMessage=e,t.lastSubmissionId=r,t.updatedAt=ct(),s.on("close",l=>{let c=typeof l=="number"?l:-1,p=!!(t.running?.id===r&&t.running.interrupted);up({record:t,submissionId:r,stdout:i.join(""),stderr:a.join(""),exitCode:c,interrupted:p})});try{s.stdin?.write(`${e.trim()}
|
|
32
|
-
`)}catch{}try{s.stdin?.end()}catch{}return r}var fs=N({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:Vu,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:t})=>{let e=t.trim();if(!e)return m("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=ct(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:e,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};We.set(n,o);try{let s=await ms(o,e);return m(JSON.stringify({...cp(o),submission_id:s},null,2))}catch(s){return We.delete(n),m(`spawn_agent failed: ${s.message}`,!0)}}}),gs=N({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Xu,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t,message:e,interrupt:n})=>{let r=We.get(t);if(!r)return ar(t);let o=e.trim();if(!o)return m("send_input failed: message must not be empty",!0);if(r.status==="closed")return m(`send_input failed: agent ${t} is closed; run resume_agent first`,!0);if(r.running){if(!n)return m(`send_input failed: agent ${t} is busy; set interrupt=true to cancel current submission`,!0);await ds(r)}try{let s=await ms(r,o);return m(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return m(`send_input failed: ${s.message}`,!0)}}}),hs=N({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Ju,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=We.get(t);return e?(e.status==="closed"&&(e.status=e.statusBeforeClose,e.updatedAt=ct()),m(JSON.stringify({agent_id:t,status:e.status},null,2))):ar(t)}}),ys=N({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Yu,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:t,timeout_ms:e})=>{let n=op(e);if(n===null)return m("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},a={};for(let l of t){let c=ap(l);np(c)&&(i[l]=c,a[l]=lp(l))}return{status:i,details:a}},o=r();if(Object.keys(o.status).length>0)return m(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await rp(100),o=r(),Object.keys(o.status).length>0)return m(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return m(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),_s=N({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:Zu,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:t})=>{let e=We.get(t);return e?e.status==="closed"?m(JSON.stringify({agent_id:t,status:"closed"},null,2)):(e.statusBeforeClose=e.running?"completed":e.status,e.status="closed",e.updatedAt=ct(),await ds(e),m(JSON.stringify({agent_id:t,status:"closed"},null,2))):ar(t)}});var lr={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_file:"read",list_dir:"read",grep_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},Ss=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),tn={read:0,write:1,execute:2},Ts=["exec","run","shell","command","stdin"],vs=["write","patch","create","delete","modify","update"],bs=["read","get","fetch","search","list","find"],Cs=new Set(["write","execute"]);function ur(t){let e={...lr,...t?.customLevels};return{getRiskLevel(n){if(n in e)return e[n];let r=n.toLowerCase();return cr(r,Ts)?"execute":cr(r,vs)?"write":cr(r,bs)?"read":"write"},compareRisk(n,r){return tn[n]-tn[r]},needsApproval(n,r){return r==="strict"?!0:Cs.has(n)}}}function cr(t,e){return e.some(n=>t.includes(n))}import{createHash as pp}from"crypto";function nn(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>nn(n)).join(",")+"]":`{${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${nn(r)}`).join(",")}}`}function pr(t,e){let n=nn(e),r=`${t}:${n}`;return pp("sha256").update(r).digest("hex").slice(0,16)}function dp(t){return`Tool "${t}" requires approval.`}function dr(t){let{mode:e="auto",dangerous:n=!1,toolRiskLevels:r}=t||{},o=e==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=ur({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(a){return s.getRiskLevel(a)},check(a,l){if(Ss.has(a))return{needApproval:!1,decision:"auto-execute"};let c=s.getRiskLevel(a);if(!s.needsApproval(c,o))return{needApproval:!1,decision:"auto-execute"};let p=pr(a,l);return i.toolByFingerprint.set(p,a),i.sessionTools.has(a)||i.onceTools.has(a)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(a)?{needApproval:!0,fingerprint:p,riskLevel:c,reason:"This request was previously denied.",toolName:a,params:l}:{needApproval:!0,fingerprint:p,riskLevel:c,reason:dp(a),toolName:a,params:l}},recordDecision(a,l){let c=i.toolByFingerprint.get(a);if(c)switch(i.sessionTools.delete(c),i.onceTools.delete(c),i.deniedTools.delete(c),l){case"session":i.sessionTools.add(c);break;case"once":i.onceTools.add(c);break;case"deny":i.deniedTools.add(c);break}},isGranted(a){let l=i.toolByFingerprint.get(a);return l?i.sessionTools.has(l)||i.onceTools.has(l):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var xs=12e3,ws=1e5;function mp(){let t=process.env.MEMO_TOOL_RESULT_MAX_CHARS?.trim();if(!t)return xs;let e=Number(t);return!Number.isFinite(e)||e<=0?xs:Math.floor(e)}function fp(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function gp(t){let e=0;for(let n of t.content??[]){if(n.type==="text"){e+=n.text.length;continue}try{e+=JSON.stringify(n).length}catch{e+=100}}return e}function hp(t,e,n){return`<system_hint type="tool_output_omitted" tool="${fp(t)}" reason="too_long" actual_chars="${e}" max_chars="${n}">Tool output too long, automatically omitted. Please narrow the scope or add limit parameters and try again.</system_hint>`}function yp(t,e){let n=mp(),r=gp(e);return r<=n?e:{content:[{type:"text",text:hp(t,r,n)}],isError:!1}}function _p(t){return(t.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
|
|
33
|
-
`)}function Ms(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Sp(t,e){let n=e;if(typeof e=="string"){if(e.length>ws)return{ok:!1,error:`${t.name} invalid input: input string too large (max ${ws} chars)`};let r=e.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!Ms(n))return{ok:!1,error:`${t.name} invalid input: expected object`};if(typeof t.validateInput=="function"){let r=t.validateInput(n);return r.ok?Ms(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${t.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function Tp(t){let e=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();return e.includes("sandbox")||e.includes("permission denied")||e.includes("operation not permitted")||e.includes("eacces")?"sandbox_denied":"execution_failed"}var mr=class{constructor(e){this.config=e;this.approvalManager=dr(e.approval)}approvalManager;async executeAction(e,n){let r=Date.now(),o=e.id??`${e.name}:${r}`,s=this.approvalManager.check(e.name,e.input);if(s.needApproval){let a={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(a);let l=n?.requestApproval?await n.requestApproval(a):"deny";if(this.approvalManager.recordDecision(s.fingerprint,l),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:l}),l==="deny")return{actionId:o,tool:e.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`User denied tool execution: ${e.name}`,durationMs:Date.now()-r,rejected:!0}}let i=this.config.tools[e.name];if(!i)return{actionId:o,tool:e.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${e.name}`,durationMs:Date.now()-r};try{let a=Sp(i,e.input);if(!a.ok)return{actionId:o,tool:e.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:a.error,durationMs:Date.now()-r};let l=await i.execute(a.data),c=yp(e.name,l);return{actionId:o,tool:e.name,status:"success",success:!0,observation:_p(c)||"(no tool output)",durationMs:Date.now()-r}}catch(a){let l=Tp(a);return{actionId:o,tool:e.name,status:l,errorType:l,success:!1,observation:`Tool execution failed: ${a.message}`,durationMs:Date.now()-r}}}async executeActions(e,n={}){let r=n.executionMode??"sequential",o=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(r==="parallel"){let l=await Promise.all(e.map(c=>this.executeAction(c,n)));if(o==="fail_fast"){let c=l.findIndex(p=>p.rejected);s=c>=0?l.slice(0,c+1):l}else s=l}else for(let l of e){let c=await this.executeAction(l,n);if(s.push(c),c.rejected&&o==="fail_fast")break}let i=s.some(l=>l.rejected),a=s.map(l=>`[${l.tool}]: ${l.observation}`).join(`
|
|
34
|
-
|
|
35
|
-
`);return{results:s,combinedObservation:a,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function Es(t){return new mr(t)}var rn=class{tools=new Map;register(e){this.tools.set(e.name,e)}registerMany(e){for(let n of e)this.register(n)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}toRegistry(){let e={};for(let[n,r]of this.tools)e[n]=r;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}};import{Client as vp}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as bp}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as Cp}from"@modelcontextprotocol/sdk/client/stdio.js";function xp(t){if(!t)return;let e={...process.env,...t},n=Object.entries(e).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function As(){return new vp({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function wp(t){if(!(!t||Object.keys(t).length===0))return{headers:t}}function Mp(t){let e={...t.http_headers??t.headers??{}};if(t.bearer_token_env_var){let n=process.env[t.bearer_token_env_var];n&&!e.Authorization&&(e.Authorization=`Bearer ${n}`)}return e}async function Ep(t){let e=new URL(t.url),n=wp(Mp(t));try{let r=As(),o=new bp(e,{requestInit:n});return await r.connect(o),{client:r,transport:o}}catch(r){let o=`Failed to connect via streamable_http (${r.message})`,s=new Error(o);throw s.cause=r,s}}async function Ap(t){if("url"in t)return Ep(t);let e={command:t.command,args:t.args,env:xp(t.env),stderr:t.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},n=new Cp(e),r=As();return await r.connect(n),{client:r,transport:n}}var on=class{connections=new Map;pendingConnections=new Map;serverConfigs=new Map;setServerConfigs(e){this.serverConfigs=new Map(Object.entries(e))}hasServer(e){return this.connections.has(e)||this.serverConfigs.has(e)}async connect(e,n){n&&this.serverConfigs.set(e,n);let r=this.connections.get(e);if(r)return r;let o=this.pendingConnections.get(e);if(o)return o;let s=n??this.serverConfigs.get(e);if(!s)throw new Error(`MCP server config not found: ${e}`);let i=(async()=>{let{client:a,transport:l}=await Ap(s);try{let c=await a.listTools(),p={name:e,client:a,transport:l,tools:(c.tools||[]).map(u=>({name:`${e}_${u.name}`,description:u.description||`Tool from ${e}: ${u.name}`,source:"mcp",serverName:e,originalName:u.name,inputSchema:u.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(e,p),p}catch(c){try{await a.close()}catch{}throw c}})();this.pendingConnections.set(e,i);try{return await i}finally{this.pendingConnections.delete(e)}}get(e){return this.connections.get(e)}getAll(){return Array.from(this.connections.values())}getKnownServerNames(){let e=new Set([...Array.from(this.serverConfigs.keys()),...Array.from(this.connections.keys())]);return Array.from(e.values())}getAllTools(){let e=[];for(let n of this.connections.values())for(let r of n.tools)e.push({name:r.name,description:r.description,serverName:r.serverName,originalName:r.originalName,inputSchema:r.inputSchema,client:n.client});return e}async closeAll(){let e=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(r){console.error(`[MCP] Error closing client ${n.name}:`,r)}});await Promise.all(e),this.connections.clear(),this.pendingConnections.clear()}get size(){return this.connections.size}};var sn=class{pool;serverToolNames=new Map;refreshPromises=new Map;tools=new Map;cacheStore=Qt();shouldLog;constructor(){this.pool=new on,er(this.pool),tr(this.cacheStore),this.shouldLog=!(process.stdout.isTTY&&process.stdin.isTTY)}buildTool(e,n,r){return{name:`${e}_${r.originalName}`,description:r.description||`Tool from ${e}: ${r.originalName}`,source:"mcp",serverName:e,originalName:r.originalName,inputSchema:r.inputSchema??{},execute:async o=>(await this.pool.connect(e,n)).client.callTool({name:r.originalName,arguments:o})}}replaceServerTools(e,n){let r=this.serverToolNames.get(e);if(r)for(let s of r)this.tools.delete(s);let o=new Set;for(let s of n)this.tools.set(s.name,s),o.add(s.name);this.serverToolNames.set(e,o)}connectionToDescriptors(e,n){return n.tools.map(r=>({originalName:r.originalName,description:r.description||`Tool from ${e}: ${r.originalName}`,inputSchema:r.inputSchema}))}async refreshServer(e,n,r){let o=this.refreshPromises.get(e);if(o){r==="sync"&&await o;return}let s=(async()=>{try{let i=await this.pool.connect(e,n),a=this.connectionToDescriptors(e,i);await this.cacheStore.setServerTools(e,n,a);let l=a.map(c=>this.buildTool(e,n,c));this.replaceServerTools(e,l),this.shouldLog&&r==="background"&&console.log(`[MCP] Refreshed '${e}' tools in background (${l.length})`)}catch(i){this.shouldLog&&console.error(`[MCP] Failed to refresh server '${e}':`,i)}})();this.refreshPromises.set(e,s),s.finally(()=>{this.refreshPromises.delete(e)}),r==="sync"&&await s}removeToolsForMissingServers(e){for(let[n,r]of this.serverToolNames.entries())if(!e.has(n)){for(let o of r)this.tools.delete(o);this.serverToolNames.delete(n)}}async loadServers(e){if(!e||Object.keys(e).length===0)return 0;let n=Object.entries(e);this.pool.setServerConfigs(e),this.removeToolsForMissingServers(new Set(n.map(([o])=>o)));let r=[];for(let[o,s]of n){let i=await this.cacheStore.getServerTools(o,s);if(i){let a=i.tools.map(l=>this.buildTool(o,s,l));this.replaceServerTools(o,a),this.shouldLog&&console.log(`[MCP] Loaded ${a.length} cached tools for '${o}' (${i.stale?"stale":"fresh"})`),i.stale&&this.refreshServer(o,s,"background");continue}r.push(this.refreshServer(o,s,"sync"))}return await Promise.all(r),this.tools.size}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}toRegistry(){let e={};for(let[n,r]of this.tools)e[n]=r;return e}has(e){return this.tools.has(e)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),this.serverToolNames.clear(),this.refreshPromises.clear(),er(null),tr(null)}getPool(){return this.pool}};var an=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new rn,this.mcpRegistry=new sn}registerNativeTool(e){this.nativeRegistry.register(e)}registerNativeTools(e){for(let n of e)this.registerNativeTool(n)}async loadMcpServers(e){return this.mcpRegistry.loadServers(e)}getTool(e){return this.nativeRegistry.get(e)??this.mcpRegistry.get(e)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(e){return this.nativeRegistry.has(e)||this.mcpRegistry.has(e)}getToolCount(){let e=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:e,mcp:n,total:e+n}}async execute(e,n){let r=this.getTool(e);if(!r)throw new Error(`Tool '${e}' not found`);return r.execute(n)}generateToolDefinitions(){return this.getAllTools().map(e=>({name:e.name,description:e.description,input_schema:e.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let e=this.getAllTools();if(e.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let r=e.filter(s=>s.source==="native"),o=e.filter(s=>s.source==="mcp");if(r.length>0){n.push("### Built-in Tools"),n.push("");for(let s of r)n.push(this.formatToolDescription(s));n.push("")}if(o.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(o);for(let[i,a]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let l of a)n.push(this.formatToolDescription(l));n.push("")}}return n.join(`
|
|
36
|
-
`)}formatToolDescription(e){let n=[];return n.push(`#### ${e.name}`),n.push(`- **Description**: ${e.description}`),e.inputSchema&&Object.keys(e.inputSchema).length>0&&n.push(`- **Input Schema**: ${JSON.stringify(e.inputSchema)}`),n.join(`
|
|
37
|
-
`)}groupByServer(e){let n={};for(let r of e)if(r.source==="mcp"){let o=r.serverName;n[o]||(n[o]=[]),n[o].push(r)}return n}getToolDescriptions(){return this.getAllTools().map(e=>({name:e.name,description:e.description,source:e.source,serverName:e.source==="mcp"?e.serverName:void 0,inputSchema:e.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};function Pp(t){let e=process.env[t]?.trim();return e?new Set(e.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function kp(){let t=[],e=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=Pp("MEMO_EXPERIMENTAL_TOOLS"),r=n.size===0,o=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return e==="shell"?t.push(Co):e==="shell_command"?t.push(xo):e==="unified_exec"?t.push(Fn,Bn):e!=="disabled"&&t.push(Fn,Bn),t.push(Qo,es,ts),t.push(rs),t.push($o),(r||n.has("grep_files"))&&t.push(Bo),(r||n.has("read_file"))&&t.push(Ho),(r||n.has("list_dir"))&&t.push(Fo),s&&t.push(is),t.push(cs),o&&t.push(fs,gs,hs,ys,_s),t}function Rp(t){let e={};for(let n of t)e[n.name]=n;return e}var Ip=Rp(kp()),Op=Object.values(Ip),Ps=Op;import td from"openai";import{encoding_for_model as Lp,get_encoding as Np}from"@dqbd/tiktoken";var ks="cl100k_base";function $p(t){let e=t?.trim()||ks;try{let n=()=>Lp(e);return n().free(),{model:e,factory:n}}catch{let n=ks,r=()=>Np(n);return r().free(),{model:n,factory:r}}}function Dp(t){if(t.role==="assistant"){let e=t.reasoning_content?`
|
|
38
|
-
${t.reasoning_content}`:"";return t.tool_calls?.length?`${t.content}${e}
|
|
39
|
-
${JSON.stringify(t.tool_calls)}`:`${t.content}${e}`}return t.role==="tool"?`${t.content}
|
|
40
|
-
${t.tool_call_id}
|
|
41
|
-
${t.name??""}`:t.content}function Rs(t){let{model:e,factory:n}=$p(t),r=n(),o=4,s=2,i=1,a=c=>c?r.encode(c).length:0;return{model:e,countText:a,countMessages:c=>{if(!c.length)return 0;let p=0;for(let u of c)p+=o,p+=a(Dp(u)),u.name&&(p+=i);return p+=s,p},dispose:()=>r.free()}}import{mkdir as Up,writeFile as Hp,readFile as Fp,access as Bp}from"fs/promises";import{homedir as Ls}from"os";import{dirname as Wp,join as Ye,parse as jp,resolve as Gp}from"path";import{randomUUID as q_}from"crypto";import{parse as zp}from"toml";var qp=Ye(Ls(),".memo"),Kp="sessions",gr=12e4,kt={current_provider:"deepseek",max_prompt_tokens:gr,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function fr(t){return t.trim().toLowerCase()}function Is(t){if(typeof t?.context_window=="number"&&Number.isFinite(t.context_window)&&t.context_window>0)return Math.floor(t.context_window)}function ut(t,e){let n=t.model_profiles;if(!n)return gr;let r=new Map;for(let[a,l]of Object.entries(n))r.set(fr(a),l);let o=fr(e.name),s=fr(e.model),i=`${o}:${s}`;return Is(r.get(i))??Is(r.get(s))??gr}function Os(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:JSON.stringify(t)}function Vp(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=[];for(let[n,r]of Object.entries(t)){if(!r)continue;let o=Array.isArray(r)?r:[r];for(let s of o){if(!s||typeof s!="object")continue;let i={...s};(typeof i.name!="string"||i.name.length===0)&&n&&(i.name=n),e.push(i)}}return e}function Xp(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,r]of Object.entries(t)){if(!r||typeof r!="object"||Array.isArray(r))continue;let o=r,s={};typeof o.supports_parallel_tool_calls=="boolean"&&(s.supports_parallel_tool_calls=o.supports_parallel_tool_calls),typeof o.supports_reasoning_content=="boolean"&&(s.supports_reasoning_content=o.supports_reasoning_content),typeof o.context_window=="number"&&Number.isFinite(o.context_window)&&o.context_window>0&&(s.context_window=Math.floor(o.context_window)),Object.keys(s).length>0&&(e[n]=s)}return Object.keys(e).length>0?e:void 0}function Ns(t){return t.startsWith("~")?Ye(Ls(),t.slice(1)):t}function Jp(t){let e=t.providers.map(i=>{let a=typeof i?.name=="string"?i.name:"";if(!a)return"";let c=[`[[providers.${Os(a)}]]`,`name = ${JSON.stringify(a)}`,`env_api_key = ${JSON.stringify(String(i.env_api_key??""))}`,`model = ${JSON.stringify(String(i.model??""))}`];return i.base_url&&c.push(`base_url = ${JSON.stringify(String(i.base_url))}`),c.join(`
|
|
11
|
+
${t}`}function ru(){return typeof __dirname=="string"?__dirname:ql(Xl(import.meta.url))}async function as(e={}){let t=e.cwd??process.cwd(),n=is(ru(),"prompt.md"),r=await ss(n,"utf-8"),o={date:new Date().toISOString(),user:Ql(),pwd:t},s=Yl(r,o),i=await eu(t);if(i&&(s=tu(s,i)),e.includeSkills!==!1){let c=await ns({cwd:t,skillRoots:e.skillRoots,homeDir:e.homeDir,memoHome:e.memoHome}),a=Zl(c,e.activeSkillPaths),l=rs(a);l&&(s=nu(s,l))}return s}import{appendFile as ou,mkdir as su}from"fs/promises";import{dirname as iu}from"path";var ln=class{constructor(t){this.filePath=t}ensureDirPromise=null;writeQueue=Promise.resolve();closed=!1;ensureDirectory(){return this.ensureDirPromise||(this.ensureDirPromise=su(iu(this.filePath),{recursive:!0}).then(()=>{})),this.ensureDirPromise}async append(t){if(this.closed)throw new Error("History sink is closed");return this.writeQueue=this.writeQueue.then(async()=>{await this.ensureDirectory(),await ou(this.filePath,`${JSON.stringify(t)}
|
|
12
|
+
`,"utf8")}),this.writeQueue}async flush(){await this.writeQueue}async close(){this.closed||(this.closed=!0,await this.flush())}};function cs(e){return{ts:new Date().toISOString(),sessionId:e.sessionId,turn:e.turn,step:e.step,type:e.type,content:e.content,role:e.role,meta:e.meta}}import{basename as ds}from"path";import{createHash as au}from"crypto";import{basename as aS,resolve as cu}from"path";function lu(e){return e==="/"?e:e.replace(/\/+$/g,"")}function un(e){let n=cu(e.trim()).replace(/\\/g,"/");return n==="/"?n:lu(n)}function ls(e){let t=un(e);return au("sha256").update(t).digest("hex").slice(0,16)}function us(e,t){let n=un(e),r=un(t);return n===r?!0:n.startsWith(`${r}/`)}function pr(){return{prompt:0,completion:0,total:0}}function uu(){return{total:0,success:0,failed:0,denied:0,cancelled:0}}function pe(e){return typeof e!="string"?"":e.trim()}function dr(e){let t=pe(e);return t?t.replace(/<\s*(think|thinking)\b[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi," ").replace(/<\s*\/?\s*(think|thinking)\b[^>]*>/gi," ").replace(/\s+/g," ").trim():""}function Ut(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Number.parseFloat(e);if(Number.isFinite(t))return t}return null}function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pu(e,t){for(let s of t){let i=s.meta?.sessionId;if(typeof i=="string"&&i.trim())return i.trim()}let n=t.find(s=>{if(!s.meta)return!1;let i=s.meta.sessionId;return typeof i=="string"&&i.trim().length>0});if(n?.meta&&typeof n.meta.sessionId=="string")return n.meta.sessionId;let r=ds(e,".jsonl"),o=r.lastIndexOf("-");return o<=0||o>=r.length-1?r:r.slice(o+1)}function du(e,t){if(e){let r=e.replace(/\\/g,"/").split("/").filter(Boolean),o=r[r.length-1];if(o)return o}return ds(t,".jsonl")}function Dt(e,t){let n=e.turnsById.get(t);if(n)return n;let r={turn:t,steps:[],byStep:new Map};return e.turnsById.set(t,r),r}function mr(e,t){let n=e.byStep.get(t);if(n)return n;let r={step:t};return e.byStep.set(t,r),e.steps=Array.from(e.byStep.values()).sort((o,s)=>o.step-s.step),r}function mu(e,t){if(!e.trim())return null;let n;try{n=JSON.parse(e)}catch{return null}if(!st(n))return null;let r=pe(n.ts),o=pe(n.type);if(!r||!o)return null;let s={index:t,ts:r,type:o},i=Ut(n.turn),c=Ut(n.step);i!==null&&(s.turn=Math.floor(i)),c!==null&&(s.step=Math.floor(c));let a=pe(n.role);return a&&(s.role=a),typeof n.content=="string"&&(s.content=n.content),st(n.meta)&&(s.meta=n.meta),s}function pn(e,t){if(!t)return;let n=Ut(t.prompt),r=Ut(t.completion),o=Ut(t.total);n!==null&&(e.prompt+=Math.floor(n)),r!==null&&(e.completion+=Math.floor(r)),o!==null&&(e.total+=Math.floor(o))}function ps(e){if(!e)return"idle";let t=e.trim().toLowerCase();return t?t==="cancelled"?"cancelled":t==="error"||t==="prompt_limit"?"error":t==="running"?"running":"idle":"idle"}function fu(e){if(!e)return[];let t=[],n=pe(e.tool);n&&t.push(n);let r=e.tools;if(Array.isArray(r))for(let s of r){let i=pe(s);i&&t.push(i)}let o=e.toolBlocks;if(Array.isArray(o))for(let s of o){if(!st(s))continue;let i=pe(s.name);i&&t.push(i)}return Array.from(new Set(t))}function gu(e,t){if(!t)return;let n=t.trim().toLowerCase();if(n){if(n==="success"){e.toolUsage.success+=1;return}if(n==="approval_denied"){e.toolUsage.denied+=1,e.toolUsage.failed+=1,e.hasCancelled=!0;return}if(n==="cancelled"){e.toolUsage.cancelled+=1,e.hasCancelled=!0;return}e.toolUsage.failed+=1,e.hasError=!0}}function hu(e){let t=e.split(`
|
|
13
|
+
`),n=[];for(let r=0;r<t.length;r+=1){let o=mu(t[r]??"",r);o&&n.push(o)}return n}function dn(e,t){let n=hu(e),r=new Date().toISOString(),o={sessionId:"",title:"",project:"",cwd:"",startedAt:n[0]?.ts??r,updatedAt:n[n.length-1]?.ts??n[0]?.ts??r,status:"idle",turnCount:0,tokenUsage:pr(),toolUsage:uu(),turnsById:new Map,summaryParts:[],hasError:!1,hasCancelled:!1};for(let a of n){if(a.ts>o.updatedAt&&(o.updatedAt=a.ts),a.type==="session_start"&&a.meta){let l=pe(a.meta.cwd);l&&(o.cwd=l)}if(a.type==="session_title"){let l=dr(a.content);l&&(o.title=l)}if(a.type==="turn_start"){let l=a.turn??o.turnCount+1,p=Dt(o,l);p.input=a.content,p.startedAt=a.ts,o.turnCount=Math.max(o.turnCount,l),a.content&&a.content.trim()&&(o.title||(o.title=dr(a.content)),o.summaryParts.push(`User: ${a.content.trim()}`))}if(a.type==="assistant"&&typeof a.turn=="number"){let l=Dt(o,a.turn),p=mr(l,a.step??l.steps.length),u=p.assistantText??"";p.assistantText=`${u}${a.content??""}`,a.content?.trim()&&o.summaryParts.push(`Assistant: ${a.content.trim()}`)}if(a.type==="action"&&typeof a.turn=="number"){let l=Dt(o,a.turn),p=mr(l,a.step??l.steps.length),u=fu(a.meta);for(let g of u)o.toolUsage.total+=1;let d=pe(a.meta?.tool);d&&(p.action={tool:d,input:a.meta?.input});let m=pe(a.meta?.thinking);if(m&&(p.thinking=m),Array.isArray(a.meta?.toolBlocks)){let g=a.meta.toolBlocks.filter(st).map(y=>{let b=pe(y.name);return b?{tool:b,input:y.input}:null}).filter(y=>!!y);g.length>1&&(p.parallelActions=g)}}if(a.type==="observation"&&typeof a.turn=="number"){let l=Dt(o,a.turn),p=mr(l,a.step??l.steps.length);p.observation=a.content;let u=pe(a.meta?.status);u&&(p.resultStatus=u),gu(o,u)}if(a.type==="final"&&typeof a.turn=="number"){let l=Dt(o,a.turn);l.finalText=a.content;let p=pe(a.meta?.status);if(p){l.status=p;let d=ps(p);d==="error"&&(o.hasError=!0),d==="cancelled"&&(o.hasCancelled=!0)}let u=pe(a.meta?.errorMessage);if(u&&(l.errorMessage=u),st(a.meta?.tokens)){let d=pr();pn(d,a.meta.tokens),l.tokenUsage=d,pn(o.tokenUsage,a.meta.tokens)}}if(a.type==="turn_end"){let l=pe(a.meta?.status);if(l){let p=ps(l);p==="error"&&(o.hasError=!0),p==="cancelled"&&(o.hasCancelled=!0)}st(a.meta?.tokens)&&pn(o.tokenUsage,a.meta.tokens)}a.type==="session_end"&&st(a.meta?.tokens)&&(o.tokenUsage=pr(),pn(o.tokenUsage,a.meta.tokens))}o.sessionId=pu(t,n),o.project=du(o.cwd,t),o.title=dr(o.title),o.title||(o.title=o.project||o.sessionId),o.hasError?o.status="error":o.hasCancelled?o.status="cancelled":o.status="idle";let s=o.startedAt.slice(0,10),i=Array.from(o.turnsById.values()).sort((a,l)=>a.turn-l.turn).map(a=>({turn:a.turn,input:a.input,startedAt:a.startedAt,finalText:a.finalText,status:a.status,errorMessage:a.errorMessage,tokenUsage:a.tokenUsage,steps:a.steps}));return{...{id:o.sessionId,sessionId:o.sessionId,filePath:t,title:o.title,project:o.project,workspaceId:o.cwd?ls(o.cwd):"",cwd:o.cwd,date:{day:/^\d{4}-\d{2}-\d{2}$/.test(s)?s:r.slice(0,10),startedAt:o.startedAt,updatedAt:o.updatedAt},status:o.status,turnCount:o.turnCount,tokenUsage:o.tokenUsage,toolUsage:o.toolUsage},summary:o.summaryParts.join(`
|
|
14
|
+
`),turns:i,events:n}}import{readdir as yu,readFile as _u,stat as Su}from"fs/promises";import{join as vu,resolve as fr}from"path";function Tu(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;let n=Math.floor(e);return n>0?n:t}function ms(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;let n=Math.floor(e);return n<=0?t:Math.min(n,100)}function fs(e){if(!e)return null;let t=e.trim();return t&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:null}async function wu(e){let t=[],n=async r=>{let o;try{o=await yu(r,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async s=>{if(s.isSymbolicLink())return;let i=vu(r,s.name);if(s.isDirectory()){await n(i);return}if(!(!s.isFile()||!s.name.endsWith(".jsonl")))try{let c=await Su(i);t.push({filePath:fr(i),mtimeMs:c.mtimeMs,size:c.size})}catch{}}))};return await n(fr(e)),t}function Cu(e,t,n,r){let o=r==="asc"?1:-1;if(n==="project"){let s=e.project.localeCompare(t.project);return s===0?e.date.updatedAt.localeCompare(t.date.updatedAt)*o:s*o}if(n==="title"){let s=e.title.localeCompare(t.title);return s===0?e.date.updatedAt.localeCompare(t.date.updatedAt)*o:s*o}return n==="startedAt"?e.date.startedAt.localeCompare(t.date.startedAt)*o:e.date.updatedAt.localeCompare(t.date.updatedAt)*o}function bu(e,t){let n=e.project.trim(),r=e.cwd.trim(),o=/^\d{4}-\d{2}-\d{2}T\d{2}[-:]\d{2}[-:]\d{2}(?:\.\d+)?(?:Z)?-[A-Za-z0-9._-]+$/i.test(n)||/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)||n===e.sessionId;if(!n||!r||o||t.workspaceCwd&&!us(r,t.workspaceCwd))return!1;if(t.project){let a=t.project.trim().toLowerCase();if(a&&n.toLowerCase()!==a)return!1}let s=fs(t.dateFrom),i=fs(t.dateTo);if(s&&e.date.day<s||i&&e.date.day>i)return!1;let c=t.q?.trim().toLowerCase();return!(c&&![e.title,n,r,e.sessionId,e.filePath].join(`
|
|
15
|
+
`).toLowerCase().includes(c))}var mn=class{sessionsDir;cache=new Map;sessionIdToPath=new Map;refreshInFlight=null;constructor(t){this.sessionsDir=fr(t.sessionsDir)}async refresh(){if(this.refreshInFlight){await this.refreshInFlight;return}let t=this.refreshInternal();this.refreshInFlight=t;try{await t}finally{this.refreshInFlight=null}}async list(t={}){await this.refresh();let n=Tu(t.page,1),r=ms(t.pageSize,20),o=t.sortBy??"updatedAt",s=t.order??"desc",i=Array.from(this.cache.values()).map(u=>u.summary).filter(u=>bu(u,t)).sort((u,d)=>Cu(u,d,o,s)),c=i.length,a=c===0?0:Math.ceil(c/r),l=(n-1)*r;return{items:i.slice(l,l+r),page:n,pageSize:r,total:c,totalPages:a}}async getSessionDetail(t){await this.refresh();let n=this.sessionIdToPath.get(t);return n?this.cache.get(n)?.detail??null:null}async getSessionEvents(t,n,r){let o=await this.getSessionDetail(t);if(!o)return null;let s=Number.parseInt(n??"0",10),i=Number.isFinite(s)&&s>=0?s:0,c=ms(r,100),a=o.events.slice(i,i+c),l=i+a.length;return{items:a,nextCursor:l>=o.events.length?null:String(l)}}async getAllSummaries(){return await this.refresh(),Array.from(this.cache.values()).map(t=>t.summary)}async refreshInternal(){let t=await wu(this.sessionsDir),n=new Set(t.map(r=>r.filePath));for(let r of Array.from(this.cache.keys()))if(!n.has(r)){let o=this.cache.get(r);o&&this.sessionIdToPath.delete(o.summary.sessionId),this.cache.delete(r)}for(let r of t){let o=this.cache.get(r.filePath);if(!(o&&o.mtimeMs===r.mtimeMs&&o.size===r.size))try{let s=await _u(r.filePath,"utf8"),i=dn(s,r.filePath),c=i,a={filePath:r.filePath,mtimeMs:r.mtimeMs,size:r.size,summary:c,detail:i};o&&this.sessionIdToPath.delete(o.summary.sessionId),this.cache.set(r.filePath,a),this.sessionIdToPath.set(c.sessionId,r.filePath)}catch{}}}};var ks=Yo(Cs(),1);import{existsSync as bs,statSync as Gu}from"fs";import{readFile as Ku,readdir as qu}from"fs/promises";import{dirname as xs,join as Sn,relative as Ms,resolve as Vu,sep as Xu}from"path";var Ju=6,Yu=2500,As=25,Qu=new Set([".git",".svn",".hg","node_modules","dist","build",".next",".turbo",".cache",".output","coverage","tmp","temp","logs"]),yn=new Map,Tr=new Map,yt=new Map,Zu=256;function _n(e,t){if(yt.size>=Zu&&!yt.has(e)){let n=yt.keys().next().value;typeof n=="string"&&yt.delete(n)}yt.set(e,t)}function Ps(e){return e.split(Xu).join("/")}function ep(e){return{maxDepth:typeof e.maxDepth=="number"?Math.max(1,e.maxDepth):Ju,maxEntries:typeof e.maxEntries=="number"?Math.max(100,e.maxEntries):Yu,limit:typeof e.limit=="number"?Math.max(1,e.limit):As,respectGitIgnore:e.respectGitIgnore??!0,ignoreGlobs:e.ignoreGlobs?.length?e.ignoreGlobs:[]}}function tp(e,t){let n=e.split("/").filter(Boolean),r=n[n.length-1]??"";return n.some(o=>Qu.has(o))||r.endsWith(".log")?!0:t.ignoreGlobs.length?t.ignoreGlobs.some(o=>{let s=o.replace(/\\/g,"/").trim();if(!s)return!1;if(s.endsWith("/**")){let i=s.slice(0,-3);return e.startsWith(i)}if(s.startsWith("*")){let i=s.slice(1);return e.endsWith(i)}return e.includes(s)}):!1}function np(e){return e.replace(/\\/g,"/")}function rp(e){let t=Vu(e),n=yt.get(t);if(n)return n;let r=t;try{Gu(r).isFile()&&(r=xs(r))}catch{r=process.cwd()}let o=r,s=[];for(;;){if(s.push(r),bs(Sn(r,".gitignore"))||bs(Sn(r,".git"))){for(let c of s)_n(c,r);return _n(t,r),r}let i=xs(r);if(i===r){for(let c of s)_n(c,o);return _n(t,o),o}r=i}}async function op(e){let t=Sn(e,".gitignore");try{return(await Ku(t,"utf8")).split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#"))}catch{return[]}}function sp(e){let t=(0,ks.default)();return e.length>0&&t.add(e),t}async function ip(e){let t=sp(await op(e));return{root:e,ignores:n=>{let r=Ms(e,n);return!r||r.startsWith("..")?!1:t.ignores(np(r))}}}async function ap(e){let t=rp(e),n=Tr.get(t);if(n)return n;let r=ip(t).catch(o=>{throw Tr.delete(t),o});return Tr.set(t,r),r}function cp(e){return JSON.stringify({maxDepth:e.maxDepth,maxEntries:e.maxEntries,respectGitIgnore:e.respectGitIgnore,ignoreGlobs:e.ignoreGlobs})}async function lp(e,t){let n=[],r=t.respectGitIgnore?await ap(e):null,o=async(s,i)=>{if(n.length>=t.maxEntries)return;let c;try{c=await qu(s,{withFileTypes:!0})}catch{return}for(let a of c){if(n.length>=t.maxEntries)break;if(a.isSymbolicLink())continue;let l=Sn(s,a.name);if(r?.ignores(l))continue;let p=Ms(e,l);if(!p)continue;let u=Ps(p);if(tp(u,t))continue;let d=u.split("/").filter(Boolean),m=a.isDirectory();n.push({path:u,pathLower:u.toLowerCase(),segments:d,segmentsLower:d.map(g=>g.toLowerCase()),depth:i,isDir:m}),m&&i<t.maxDepth&&await o(l,i+1)}};return await o(e,0),n.sort((s,i)=>s.path.localeCompare(i.path)),n}async function up(e,t){let n=ep(t),r=cp(n),o=yn.get(e);if(o&&o.signature===r)return o.pending?o.pending:o.entries;let s=lp(e,n).then(i=>(yn.set(e,{entries:i,signature:r}),i)).catch(i=>{throw yn.delete(e),i});return yn.set(e,{entries:[],signature:r,pending:s}),s}function pp(e,t){if(!t.length)return e.depth+(e.isDir?-.2:.2);let n=e.depth,r=0;for(let o of t){let s=-1;for(let i=r;i<e.segmentsLower.length;i++){let c=e.segmentsLower[i];if(c.startsWith(o)){s=i,n+=(i-r)*1.2,n+=c.length-o.length;break}let a=c.indexOf(o);if(a!==-1){s=i,n+=(i-r)*2+a+2;break}}if(s===-1)return null;r=s+1}return e.isDir&&(n-=.5),n}function dp(e,t,n){let o=t.trim().replace(/\\/g,"/").split("/").filter(Boolean).map(i=>i.toLowerCase()),s=[];for(let i of e){let c=pp(i,o);c!==null&&s.push({entry:i,score:c})}return s.sort((i,c)=>{let a=i.score-c.score;return a!==0?a:i.entry.path.localeCompare(c.entry.path)}),s.slice(0,n).map(({entry:i})=>({id:i.path,path:i.path,name:i.segments[i.segments.length-1]??i.path,parent:i.segments.length>1?i.segments.slice(0,-1).join("/"):void 0,isDir:i.isDir}))}async function Es(e){let t=await up(e.cwd,e),n=typeof e.limit=="number"?Math.max(1,e.limit):As;return dp(t,e.query,n)}var W={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",REVIEW:"review",MODELS:"models",TOOLS:"tools",COMPACT:"compact",MCP:"mcp",INIT:"init"},de={NONE:"none",ONCE:"once",FULL:"full"};function Ht(e){return`/${e}`}var Bt=[{name:W.HELP,description:"Show command and shortcut help"},{name:W.EXIT,description:"Exit current session"},{name:W.NEW,description:"Start a fresh session"},{name:W.RESUME,description:"List and load session history"},{name:W.REVIEW,description:"Review a GitHub pull request and post comments"},{name:W.MODELS,description:"List or switch configured models"},{name:W.TOOLS,description:"Set tool permission mode (none/once/full)"},{name:W.COMPACT,description:"Compact conversation context now"},{name:W.MCP,description:"Show configured MCP servers"},{name:W.INIT,description:"Generate AGENTS.md with agent instructions"}],mp={none:de.NONE,off:de.NONE,disabled:de.NONE,"no-tools":de.NONE,once:de.ONCE,ask:de.ONCE,single:de.ONCE,strict:de.ONCE,full:de.FULL,all:de.FULL,dangerous:de.FULL,"full-access":de.FULL};function fp(e){if(!e)return null;let t=e.trim().toLowerCase();return t?mp[t]??null:null}function Rs(e){return e===de.NONE?"none (no tools)":e===de.ONCE?"once (approval required)":"full (no approval)"}function Is(){let e=Bt.reduce((n,r)=>Math.max(n,r.name.length),0);return["Available commands:",...Bt.map(n=>` ${Ht(n.name).padEnd(e+3)} ${n.description}`)," exit Exit session (without slash)","","Shortcuts:"," Enter Send message"," Shift+Enter New line"," Up/Down Browse local input history"," Tab Accept active suggestion"," Ctrl+L Clear screen and start new session"," Esc Esc Interrupt running turn / clear input"].join(`
|
|
16
|
+
`)}function gp(e){if(!e)return null;let t=e.trim();if(!t)return null;let n=t.match(/^#?(\d+)$/);if(n){let o=Number(n[1]);return Number.isInteger(o)&&o>0?o:null}let r=t.match(/\/pull\/(\d+)(?:[/?#].*)?$/i);if(r){let o=Number(r[1]);return Number.isInteger(o)&&o>0?o:null}return null}function wr(e,t){let[n,...r]=e.trim().slice(1).split(/\s+/);switch((n??"").toLowerCase()){case W.HELP:return{kind:"message",title:"Help",content:Is()};case W.EXIT:return{kind:"exit"};case W.NEW:return{kind:"new"};case W.RESUME:return{kind:"message",title:"Resume",content:'Type "resume" followed by keywords to load local session history.'};case W.REVIEW:{let s=r.join(" ").trim(),i=gp(s);return i?{kind:"review_pr",prNumber:i}:{kind:"message",title:"Review",content:`Usage: ${Ht(W.REVIEW)} <prNumber>
|
|
17
|
+
Examples: /review 999, /review #999`}}case W.MODELS:{if(!t.providers.length)return{kind:"message",title:"Models",content:`No providers configured. Check ${t.configPath}`};let s=r.join(" ").trim(),i=t.providers.find(l=>l.name===s)??t.providers.find(l=>l.model===s);if(i)return{kind:"switch_model",provider:i};let c=t.providers.map(l=>{let p=l.name===t.providerName&&l.model===t.model?" (current)":"",u=l.base_url?` @ ${l.base_url}`:"";return`- ${l.name}: ${l.model}${u}${p}`});return{kind:"message",title:"Models",content:`${s?`Not found: ${s}
|
|
18
|
+
|
|
19
|
+
`:""}${c.join(`
|
|
20
|
+
`)}`}}case W.TOOLS:{let s=r.join(" ").trim(),i=fp(s),c=["none","once","full"].join(", ");return s?i?i===t.toolPermissionMode?{kind:"message",title:"Tools",content:`Already using ${Rs(i)}.`}:{kind:"set_tool_permission",mode:i}:{kind:"message",title:"Tools",content:`Unsupported mode: ${s}
|
|
21
|
+
Choose one of: ${c}`}:{kind:"message",title:"Tools",content:`Current: ${Rs(t.toolPermissionMode)}
|
|
22
|
+
Usage: ${Ht(W.TOOLS)} <mode>
|
|
23
|
+
Modes: ${c}`}}case W.COMPACT:return{kind:"compact"};case W.MCP:{let s=Object.keys(t.mcpServers);if(!s.length)return{kind:"message",title:"MCP Servers",content:"No MCP servers configured in current config."};let i=[];i.push(`Total: ${s.length}`),i.push("");for(let[c,a]of Object.entries(t.mcpServers))i.push(`- ${c}`),"url"in a?(i.push(` type: ${a.type??"streamable_http"}`),i.push(` url: ${a.url}`),a.bearer_token_env_var&&i.push(` bearer: ${a.bearer_token_env_var}`)):(i.push(` type: ${a.type??"stdio"}`),i.push(` command: ${a.command}`),a.args?.length&&i.push(` args: ${a.args.join(" ")}`)),i.push("");return{kind:"message",title:"MCP Servers",content:i.join(`
|
|
24
|
+
`)}}case W.INIT:return{kind:"init_agents_md"};default:return{kind:"message",title:"Unknown",content:`Unknown command: ${e}
|
|
25
|
+
Type ${Ht(W.HELP)} for available commands.`}}}import{mkdir as hp,writeFile as yp,readFile as _p,access as Sp}from"fs/promises";import{homedir as $s}from"os";import{dirname as vp,join as it,parse as Tp,resolve as wp}from"path";import{randomUUID as IS}from"crypto";import{parse as Cp}from"toml";var bp=it($s(),".memo"),xp="sessions",Os=12e4,Ds=80,Wt={current_provider:"deepseek",mcp_oauth_credentials_store_mode:"auto",auto_compact_threshold_percent:Ds,providers:[{name:"deepseek",env_api_key:"DEEPSEEK_API_KEY",model:"deepseek-chat",base_url:"https://api.deepseek.com"}],mcp_servers:{}};function Us(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isFinite(e)&&e>=1&&e<=100?e:Ds}function Cr(e){return e.trim().toLowerCase()}function Ls(e){if(typeof e?.context_window=="number"&&Number.isFinite(e.context_window)&&e.context_window>0)return Math.floor(e.context_window)}function _t(e,t){let n=e.model_profiles;if(!n)return Os;let r=new Map;for(let[c,a]of Object.entries(n))r.set(Cr(c),a);let o=Cr(t.name),s=Cr(t.model),i=`${o}:${s}`;return Ls(r.get(i))??Ls(r.get(s))??Os}function Ns(e){return/^[A-Za-z0-9_-]+$/.test(e)?e:JSON.stringify(e)}function Mp(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=[];for(let[n,r]of Object.entries(e)){if(!r)continue;let o=Array.isArray(r)?r:[r];for(let s of o){if(!s||typeof s!="object")continue;let i={...s};(typeof i.name!="string"||i.name.length===0)&&n&&(i.name=n),t.push(i)}}return t}function kp(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return Array.from(new Set(t))}function Ap(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e)){if(!r||typeof r!="object"||Array.isArray(r))continue;let o=r,s={};typeof o.supports_parallel_tool_calls=="boolean"&&(s.supports_parallel_tool_calls=o.supports_parallel_tool_calls),typeof o.supports_reasoning_content=="boolean"&&(s.supports_reasoning_content=o.supports_reasoning_content),typeof o.context_window=="number"&&Number.isFinite(o.context_window)&&o.context_window>0&&(s.context_window=Math.floor(o.context_window)),Object.keys(s).length>0&&(t[n]=s)}return Object.keys(t).length>0?t:void 0}function Fs(e){return e.startsWith("~")?it($s(),e.slice(1)):e}function Pp(e){let t=e.providers.map(c=>{let a=typeof c?.name=="string"?c.name:"";if(!a)return"";let p=[`[[providers.${Ns(a)}]]`,`name = ${JSON.stringify(a)}`,`env_api_key = ${JSON.stringify(String(c.env_api_key??""))}`,`model = ${JSON.stringify(String(c.model??""))}`];return c.base_url&&p.push(`base_url = ${JSON.stringify(String(c.base_url))}`),p.join(`
|
|
42
26
|
`)}).filter(Boolean).join(`
|
|
43
27
|
|
|
44
|
-
`),n=
|
|
28
|
+
`),n=e.model_profiles?Object.entries(e.model_profiles).map(([c,a])=>{let l=[],p=Ns(c);return l.push(`[model_profiles.${p}]`),typeof a.supports_parallel_tool_calls=="boolean"&&l.push(`supports_parallel_tool_calls = ${a.supports_parallel_tool_calls}`),typeof a.supports_reasoning_content=="boolean"&&l.push(`supports_reasoning_content = ${a.supports_reasoning_content}`),typeof a.context_window=="number"&&Number.isFinite(a.context_window)&&a.context_window>0&&l.push(`context_window = ${Math.floor(a.context_window)}`),l.length>1?l.join(`
|
|
45
29
|
`):""}).filter(Boolean).join(`
|
|
46
30
|
|
|
47
|
-
`):"",r="";
|
|
48
|
-
`)}let l=a.args?`args = ${JSON.stringify(a.args)}`:"",
|
|
49
|
-
`:"",
|
|
50
|
-
`:"",
|
|
51
|
-
${
|
|
52
|
-
${
|
|
53
|
-
`);return`${
|
|
54
|
-
|
|
55
|
-
[mcp_servers.${
|
|
56
|
-
${
|
|
57
|
-
|
|
58
|
-
`));let o=[`current_provider = "${
|
|
59
|
-
`),
|
|
60
|
-
|
|
61
|
-
`)}async function Me(t,e){await Up(Wp(t),{recursive:!0}),await Hp(t,Jp(e),"utf-8")}async function de(){let t=process.env.MEMO_HOME?Ns(process.env.MEMO_HOME):qp,e=Ye(t,"config.toml");try{await Bp(e);let n=await Fp(e,"utf-8"),r=zp(n),o=Vp(r.providers),s=typeof r.max_prompt_tokens=="number"&&Number.isFinite(r.max_prompt_tokens)&&r.max_prompt_tokens>0?Math.floor(r.max_prompt_tokens):void 0,i=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(p=>typeof p=="string"&&p.trim().length>0):void 0,a=Xp(r.model_profiles),l={current_provider:r.current_provider??kt.current_provider,max_prompt_tokens:s??kt.max_prompt_tokens,providers:o,model_profiles:a,mcp_servers:r.mcp_servers??{},active_mcp_servers:i},c=!l.providers.length;return{config:c?kt:l,home:t,configPath:e,needsSetup:c}}catch{return{config:kt,home:t,configPath:e,needsSetup:!0}}}function Ze(t,e){let n=e||t.current_provider,r=t.providers.find(o=>o.name===n);return r||(t.providers?.[0]??kt.providers[0])}function ln(t,e){let n=e.historyDir??Ye(t.home,Kp),r=Ns(n),o=Gp(process.cwd()),s=jp(o).root,a=o.slice(s.length).split(/[\\/]+/).filter(Boolean);if(process.platform==="win32"){let c=/^([A-Za-z]):/.exec(s)?.[1];c&&a.unshift(c.toUpperCase())}if(a.length===0)return Ye(r,"-root");let l=`-${a.map(c=>c.replace(/[^A-Za-z0-9._-]/g,"_")).join("-")}`;return Ye(r,l)}function $s(t,e){let n=new Date,r=String(n.getFullYear()),o=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),a=String(n.getMinutes()).padStart(2,"0"),l=String(n.getSeconds()).padStart(2,"0"),c=`${r}-${o}-${s}T${i}-${a}-${l}`,p=e.replace(/[^A-Za-z0-9._-]/g,"_"),u=`${c}-${p}.jsonl`;return Ye(t,u)}import"openai";var Yp={supportsParallelToolCalls:!1,supportsReasoningContent:!1};function hr(t){return t.trim().toLowerCase()}function Zp(t,e,n){if(!n)return;let r=new Map;for(let[s,i]of Object.entries(n))r.set(hr(s),i);let o=r.get(`${t}:${e}`);return o||r.get(e)}function Qp(t,e){if(!e)return{capabilities:t,usedOverride:!1};let n={...t},r=!1;return typeof e.supports_parallel_tool_calls=="boolean"&&(n.supportsParallelToolCalls=e.supports_parallel_tool_calls,r=!0),typeof e.supports_reasoning_content=="boolean"&&(n.supportsReasoningContent=e.supports_reasoning_content,r=!0),typeof e.context_window=="number"&&Number.isFinite(e.context_window)&&e.context_window>0&&(n.contextWindow=Math.floor(e.context_window),r=!0),{capabilities:n,usedOverride:r}}function Ds(t,e){let n=hr(t.name),r=hr(t.model),{capabilities:o,usedOverride:s}=Qp(Yp,Zp(n,r,e));return{profile:{wireApi:"chat_completions",...o,isFallback:!s}}}function ed(t){if(t.length!==0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}function Us(t){let e=ed(t.toolDefinitions),n={model:t.model,messages:t.messages,tools:e,tool_choice:e?"auto":void 0};return e&&t.profile.supportsParallelToolCalls&&(n.parallel_tool_calls=!0),n}function nd(t,e){if(!t||!e)return t;let n=new Set(e.map(o=>o.trim()).filter(Boolean));if(n.size===0)return{};let r={};for(let[o,s]of Object.entries(t))n.has(o)&&(r[o]=s);return r}function rd(t){try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,raw:t,error:e.message}}}function od(t){if(t.role==="assistant"){let e={role:"assistant",content:t.content,tool_calls:t.tool_calls?.map(n=>({id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}))};return t.reasoning_content&&(e.reasoning_content=t.reasoning_content),e}return t.role==="tool"?{role:"tool",content:t.content,tool_call_id:t.tool_call_id}:{role:t.role,content:t.content}}function sd(t){let e=t?.reasoning_content;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}async function Hs(t,e,n){let r=await de(),o=r.config,s=new an;if(s.registerNativeTools(Ps),await s.loadMcpServers(nd(o.mcp_servers,e.activeMcpServers)),t.tools)for(let[g,v]of Object.entries(t.tools))s.registerNativeTool({name:g,description:v.description,source:"native",inputSchema:{type:"object"},execute:v.execute});let i=s.toRegistry(),a=async()=>{let g=await(t.loadPrompt??uo)(),v=s.generateToolDescriptions();return v&&(g+=`
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
`)
|
|
65
|
-
|
|
66
|
-
`):
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
-
|
|
71
|
-
|
|
72
|
-
`)}function js(t){if(t.toolPermissionMode==="none")return{mode:"none",toolsDisabled:!0,dangerous:!1,approvalMode:"auto"};if(t.toolPermissionMode==="once")return{mode:"once",toolsDisabled:!1,dangerous:!1,approvalMode:"auto"};if(t.toolPermissionMode==="full")return{mode:"full",toolsDisabled:!1,dangerous:!0,approvalMode:"auto"};let e=t.dangerous??!1;return{mode:e?"full":"auto",toolsDisabled:!1,dangerous:e,approvalMode:"auto"}}function Sr(){return{prompt:0,completion:0,total:0}}function Tr(t,e){if(!e)return;let n=e.prompt??0,r=e.completion??0,o=e.total??n+r;t.prompt+=n,t.completion+=r,t.total+=o}function Gs(t){let e=t.content.filter(r=>r.type==="text"),n=t.content.filter(r=>r.type==="tool_use");return{textContent:e.map(r=>r.text).join(`
|
|
73
|
-
`),toolUseBlocks:n.map(r=>({id:r.id,name:r.name,input:r.input})),reasoningContent:typeof t.reasoning_content=="string"&&t.reasoning_content.trim().length>0?t.reasoning_content:void 0,stopReason:t.stop_reason,usage:t.usage}}async function zs(t,e){for(let n of e)try{await n.append(t)}catch(r){ld({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function vr(t){return t instanceof Error&&t.name==="AbortError"}function un(t){return yr(t,new WeakSet,0)}var cd=100;function yr(t,e,n){if(n>cd)return JSON.stringify("[MaxDepthExceeded]");if(typeof t=="bigint")return JSON.stringify(t.toString());if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(e.has(t))return JSON.stringify("[Circular]");if(e.add(t),Array.isArray(t)){let s=`[${t.map(i=>yr(i,e,n+1)).join(",")}]`;return e.delete(t),s}let o=`{${Object.entries(t).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${JSON.stringify(s)}:${yr(i,e,n+1)}`).join(",")}}`;return e.delete(t),o}function qs(t){return t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:un(e.input)}}))}function Ks(t,e){let n=t.trim();if(!n)return null;let r=[n],o=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);o?.[1]&&r.push(o[1].trim());for(let s of r)if(!(!s.startsWith("{")||!s.endsWith("}")))try{let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,l=typeof a.tool=="string"?a.tool.trim():"";if(!l||!Object.prototype.hasOwnProperty.call(e,l))continue;return{tool:l,input:a.input??{}}}catch{}return null}function Vs(t){return t.length<=60?t:`${t.slice(0,57).trimEnd()}...`}function Xs(t){let e=t.replace(/\r?\n+/g," ").replace(/\s+/g," ").trim();if(!e)return"";let n=e.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g,"").trim();return n?Vs(n):""}function Js(t){let e=t.replace(/\s+/g," ").trim();if(!e)return"New Session";if(!e.includes(" "))return e.length<=20?e:`${e.slice(0,20).trimEnd()}...`;let r=e.split(" ").filter(Boolean).slice(0,8).join(" ");return Vs(r||e)}function br(t){return{role:"tool",content:t.observation,tool_call_id:t.actionId,name:t.tool}}function Ys(t,e,n){let r=new Map(e.map(o=>[o.actionId,o]));return t.map(o=>{let s=r.get(o.id);return s||{actionId:o.id,tool:o.name,status:n?"approval_denied":"execution_failed",errorType:n?"approval_denied":"execution_failed",success:!1,observation:n?`${ad} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as dd}from"crypto";function ud(){return{onTurnStart:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function Zs(t,e){e&&(e.onTurnStart&&t.onTurnStart.push(e.onTurnStart),e.onAction&&t.onAction.push(e.onAction),e.onObservation&&t.onObservation.push(e.onObservation),e.onFinal&&t.onFinal.push(e.onFinal),e.onApprovalRequest&&t.onApprovalRequest.push(e.onApprovalRequest),e.onApprovalResponse&&t.onApprovalResponse.push(e.onApprovalResponse),e.onTitleGenerated&&t.onTitleGenerated.push(e.onTitleGenerated))}function Qs(t){let e=ud();if(Zs(e,t.hooks),Array.isArray(t.middlewares))for(let n of t.middlewares)Zs(e,n);return e}async function Q(t,e,n){let r=t[e];if(r.length)for(let o of r)try{await o(n)}catch(s){console.warn(`Hook ${e} failed: ${s.message}`)}}function dt(t){return t.map(e=>e.role==="assistant"&&e.tool_calls?.length?{...e,tool_calls:e.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...e})}var pn=class{constructor(e,n,r,o,s){this.deps=e;this.options=n;this.id=n.sessionId||dd(),this.mode=n.mode||cn,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=e.historySinks??[],this.hooks=Qs(e),this.historyFilePath=s;let i=js(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=Es({tools:e.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=Sr();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;toolsDisabled=!1;toolPermissionMode="auto";async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(e,n){let r=`${e}:${un(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=un(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${e}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${o}${o.length>=200?"\u2026":""}\uFF09\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u9677\u5165\u5FAA\u73AF\uFF0C\u5FC5\u8981\u65F6\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u56DE\u7B54\u6216\u8C03\u6574\u53C2\u6570\u3002`;this.history.push({role:"system",content:s})}}buildToolApprovalHooks(e,n){return{onApprovalRequest:async r=>{await Q(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:e,step:n,request:r})},requestApproval:async r=>this.deps.requestApproval?this.deps.requestApproval(r):"deny",onApprovalResponse:async({fingerprint:r,decision:o})=>{await Q(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:e,step:n,fingerprint:r,decision:o})}}}async executeToolAction(e,n,r,o,s){return this.toolOrchestrator.executeAction({id:e,name:n,input:r},this.buildToolApprovalHooks(o,s))}async maybeGenerateSessionTitle(e,n,r){if(e!==1||this.title)return;let o=Js(n),s="fallback";try{let i=await this.deps.callLLM([{role:"system",content:Bs},{role:"user",content:n}],void 0,{signal:r,tools:[]}),a=Xs(i.content.filter(l=>l.type==="text").map(l=>l.text).join(" "));a&&(o=a,s="llm")}catch(i){if(vr(i))return}this.title=o,await this.emitEvent("session_title",{turn:e,content:o,meta:{source:s,original_prompt:n}}),await Q(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:e,title:o,originalPrompt:n})}async runTurn(e){let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=Sr(),i=Date.now(),a=this.options.maxPromptTokens??12e4;if(!this.sessionStartEmitted){let l=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:l,role:l?"system":void 0,meta:{mode:this.mode,cwd:process.cwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,maxPromptTokens:a,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:e});try{let l=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:e,meta:{tokens:{prompt:l}}}),await Q(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:e,promptTokens:l,history:dt(this.history)}),this.options.generateSessionTitle&&await this.maybeGenerateSessionTitle(r,e,n.signal);let c="",p="ok",u,g=0,v=null,h=-1;for(let f=0;;f++){let x=this.tokenCounter.countMessages(this.history);if(x>a){let M=`Context tokens (${x}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:M}),p="prompt_limit",c=M,u=M,await this.emitEvent("final",{turn:r,step:f,content:M,role:"assistant",meta:{tokens:{prompt:x}}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:M,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&x>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${x}`);let b="",E=[],B,q,fe,ce=!1;try{let M=await this.deps.callLLM(this.history,te=>{te&&(ce=!0),this.deps.onAssistantStep?.(te,f)},{signal:n.signal}),I=Gs(M);b=I.textContent,E=I.toolUseBlocks,q=I.stopReason,B=I.usage,fe=I.reasoningContent,b.trim().length>0&&(v=b,h=f)}catch(M){if(this.cancelling&&vr(M)){p="cancelled",c="",u="Turn cancelled",await this.emitEvent("final",{turn:r,step:f,content:"",role:"assistant",meta:{cancelled:!0}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}let I=`LLM call failed: ${M.message}`;this.history.push({role:"assistant",content:I}),p="error",c=I,u=I,await this.emitEvent("final",{turn:r,content:I,role:"assistant"}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,turnUsage:{...s},steps:o});break}!ce&&b&&this.deps.onAssistantStep?.(b,f);let J=E.length===0&&b?Ks(b,this.deps.tools):null,P,Y=null;if(E.length>0){let M=E[0];if(M){let I=b?Fs([b]):void 0;P={action:{tool:M.name,input:M.input},thinking:I},Y={role:"assistant",content:b,reasoning_content:fe,tool_calls:qs(E)}}else P={}}else b?(P={final:b},Y={role:"assistant",content:b,reasoning_content:fe}):P={};let H=this.tokenCounter.countText(b),O=B?.prompt??x,K=B?.completion??H,V=B?.total??O+K,R={prompt:O,completion:K,total:V};if(Tr(s,R),Tr(this.sessionUsage,R),o.push({index:f,assistantText:b,parsed:P,tokenUsage:R}),await this.emitEvent("assistant",{turn:r,step:f,content:b,role:"assistant",meta:{tokens:R,protocol_violation:!!J,protocol_violation_count:J?g+1:g||void 0}}),J){g+=1;let M=`Model protocol error: returned plain-text tool JSON for "${J.tool}" ${g} times. Structured tool calls are required.`;p="error",c=M,u=M,this.history.push({role:"assistant",content:M}),await this.emitEvent("final",{turn:r,step:f,content:M,role:"assistant",meta:{error_type:"model_protocol_error",tool:J.tool,protocol_violation:!0,protocol_violation_count:g,tokens:R}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:c,status:p,errorMessage:u,tokenUsage:R,turnUsage:{...s},steps:o});break}if(Y&&this.history.push(Y),E.length>0&&this.toolsDisabled){for(let M of E)this.history.push({role:"tool",content:Ws,tool_call_id:M.id,name:M.name});p="error",c=pt,u=pt,this.history.push({role:"assistant",content:pt}),await this.emitEvent("final",{turn:r,step:f,content:pt,role:"assistant",meta:{error_type:"tool_disabled",tool_count:E.length,tools:E.map(M=>M.name).join(","),tokens:R}}),await Q(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:f,finalText:pt,status:p,errorMessage:u,tokenUsage:R,turnUsage:{...s},steps:o});break}if(E.length>1){for(let A of E)this.maybeWarnRepeatedAction(A.name,A.input);await this.emitEvent("action",{turn:r,step:f,meta:{tools:E.map(A=>A.name),action_ids:E.map(A=>A.id),action_id:E[0]?.id,parallel:!0,phase:"dispatch",thinking:P.thinking,toolBlocks:E.map(A=>({id:A.id,name:A.name,input:A.input}))}});let M=E[0];M&&await Q(this.hooks,"onAction",{sessionId:this.id,turn:r,step:f,action:{tool:M.name,input:M.input},parallelActions:E.map(A=>({tool:A.name,input:A.input})),thinking:P.thinking,history:dt(this.history)});let I=E.every(A=>!!this.deps.tools[A.name]?.supportsParallelToolCalls),te=E.some(A=>!!this.deps.tools[A.name]?.isMutating),ue=I&&!te?"parallel":"sequential",Ae=await this.toolOrchestrator.executeActions(E.map(A=>({id:A.id,name:A.name,input:A.input})),{...this.buildToolApprovalHooks(r,f),executionMode:ue,failurePolicy:"fail_fast"}),_e=Ys(E,Ae.results,Ae.hasRejection);for(let[A,j]of _e.entries())this.history.push(br(j)),await this.emitEvent("observation",{turn:r,step:f,content:j.observation,meta:{tool:j.tool,index:A,action_id:j.actionId,phase:"result",status:j.status,error_type:j.errorType,duration_ms:j.durationMs,execution_mode:ue}});let Se=_e.map(A=>`[${A.tool}]: ${A.observation}`).join(`
|
|
74
|
-
|
|
75
|
-
`)
|
|
76
|
-
`)
|
|
77
|
-
`
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
`)})
|
|
81
|
-
`);if(e.
|
|
82
|
-
`)}function
|
|
83
|
-
|
|
84
|
-
`)}function
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
`:""}${
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
`)}}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
`)
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
`),messages:e,turns:n,maxSequence:a}}function Vr(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function qf(t,e){return{index:t,userInput:"",steps:[],sequence:e}}function Kr(t,e){if(t.length>e)return t;let n=t.slice();for(;n.length<=e;)n.push({index:n.length,assistantText:""});return n}function Bt(t,e,n){let r=t.turns.slice(),o=r.findIndex(i=>i.index===e);if(o===-1){let i=t.sequence+1;return r.push(n(qf(e,i))),{turns:r,sequence:i}}let s=r[o];return s?(r[o]=n(s),{turns:r,sequence:t.sequence}):{turns:r,sequence:t.sequence}}function Kf(t){return{id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,title:t.title,content:t.content,tone:t.tone??"info",sequence:t.sequence}}function da(t,e){switch(e.type){case"append_system_message":{let n=t.sequence+1;return{...t,sequence:n,systemMessages:[...t.systemMessages,Kf({title:e.title,content:e.content,tone:e.tone,sequence:n})]}}case"turn_start":{let n=Bt(t,e.turn,r=>({...r,index:e.turn,userInput:e.input,steps:[],finalText:void 0,status:void 0,errorMessage:void 0,tokenUsage:void 0,startedAt:Date.now(),durationMs:void 0,contextPromptTokens:e.promptTokens??r.contextPromptTokens}));return{...t,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Bt(t,e.turn,r=>{let o=Kr(r.steps,e.step),s=o[e.step];if(!s)return r;let i=`${s.assistantText}${e.chunk}`;return i===s.assistantText?r:(o[e.step]={...s,assistantText:i},{...r,steps:o})});return{...t,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=Bt(t,e.turn,r=>{let o=Kr(r.steps,e.step),s=o[e.step];return s?(o[e.step]={...s,action:e.action,thinking:e.thinking,parallelActions:e.parallelActions&&e.parallelActions.length>1?e.parallelActions:void 0,toolStatus:$e.EXECUTING},{...r,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Bt(t,e.turn,r=>{let o=Kr(r.steps,e.step),s=o[e.step];return s?(o[e.step]={...s,observation:e.observation,toolStatus:e.toolStatus,parallelToolStatuses:e.parallelToolStatuses},{...r,steps:o}):r});return{...t,turns:n.turns,sequence:n.sequence}}case"turn_final":{let n=Bt(t,e.turn,r=>{let o=r.startedAt??Date.now(),s=Math.max(0,Date.now()-o),i=e.tokenUsage?.prompt??r.contextPromptTokens;return{...r,finalText:e.finalText,status:e.status,errorMessage:e.errorMessage,tokenUsage:e.turnUsage,contextPromptTokens:i,startedAt:o,durationMs:s}});return{...t,turns:n.turns,sequence:n.sequence}}case"replace_history":return{...t,historicalTurns:e.turns,sequence:Math.max(t.sequence,e.maxSequence)};case"clear_current_timeline":return{...t,turns:[],systemMessages:[]};case"reset_all":return Vr();default:return t}}import{dirname as kn,join as fa,resolve as Vf}from"path";import{statSync as Xf,existsSync as ga,readFileSync as Jf}from"fs";import{readFile as Yf}from"fs/promises";import{get as Zf}from"https";import{fileURLToPath as Qf}from"url";function ma(t){let e=t.trim().replace(/^v/i,""),[n="",r]=e.split("-",2),o=n.split(".").map(s=>Number(s));return o.length<3||o.some(s=>!Number.isFinite(s))?null:{major:o[0]??0,minor:o[1]??0,patch:o[2]??0,prerelease:r??null}}function eg(t,e){let n=ma(t),r=ma(e);return!n||!r?!1:n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch!==r.patch?n.patch>r.patch:n.prerelease&&!r.prerelease?!1:!n.prerelease&&r.prerelease?!0:n.prerelease&&r.prerelease?n.prerelease>r.prerelease:!1}function ha(){try{let e=Qf(import.meta.url);return kn(e)}catch{}let t=Vf(process.argv[1]??process.cwd());try{return Xf(t).isFile()?kn(t):t}catch{return process.cwd()}}async function tg(t){let e=fa(t,"package.json");if(!ga(e))return null;let n=await Yf(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function ng(t){let e=fa(t,"package.json");if(!ga(e))return null;try{let n=Jf(e,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function rg(){let t=ha();for(;;){let e=await tg(t);if(e&&e.name==="@memo-code/memo")return e;let n=kn(t);if(n===t)break;t=n}return null}function Rn(){let t=ha();for(;;){let e=ng(t);if(e&&e.name==="@memo-code/memo")return e;let n=kn(t);if(n===t)break;t=n}return null}async function og(t,e=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`;return new Promise(o=>{let s=Zf(r,{timeout:e},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{try{let l=JSON.parse(Buffer.concat(a).toString("utf8"));o(l.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function ya(){let t=await rg();if(!t)return null;let e=await og(t.name);return!e||!eg(e,t.version)?null:{current:t.version,latest:e}}import{readFile as sg}from"fs/promises";import{dirname as ig,join as ag}from"path";import{fileURLToPath as lg}from"url";var cg=/{{\s*([\w.-]+)\s*}}/g;function ug(t,e){return t.replace(cg,(n,r)=>e[r]??"")}async function Xr(t,e={}){let n=ig(lg(import.meta.url)),r=ag(n,"task-prompts",`${t}.md`),o=await sg(r,"utf-8");return ug(o,e)}import{spawn as pg}from"child_process";var dg=12e3,mg=new Set(["WRITE","MAINTAIN","ADMIN"]),fg=["pull_request_read","list_pull_requests","search_pull_requests","add_issue_comment","add_comment_to_pending_review","issue_read","get_me"];function gg(t){return t.replace(/\\/g,"/").toLowerCase()}function hg(t,e){if(t.toLowerCase().includes("github"))return!0;if("command"in e){let o=gg(e.command),s=(e.args??[]).join(" ").toLowerCase();return!!(o.includes("github")||o.includes("gh-")||s.includes("github")||s.includes("gh-"))}let r=e.url.toLowerCase();return r.includes("github")||r.includes("api.github.com")}function yg(t,e){let n=new Set(e),r=Object.entries(t).filter(([i,a])=>hg(i,a)).map(([i])=>i),o=r.find(i=>n.has(i))??null,s=r.filter(i=>!n.has(i));return{active:o,inactiveCandidates:s}}function _g(t){let e=new Map;for(let n of t)for(let r of fg){let o=`_${r}`;if(!n.endsWith(o))continue;let s=n.slice(0,-o.length);s&&e.set(s,(e.get(s)??0)+1)}return Array.from(e.entries()).filter(([,n])=>n>=2).sort((n,r)=>r[1]-n[1]).map(([n])=>n)}async function Jr(t,e,n,r=dg){return new Promise(o=>{let s=pg(t,e,{cwd:n,env:process.env,stdio:["ignore","pipe","pipe"]}),i="",a="",l=!1,c=u=>{l||(l=!0,clearTimeout(p),o(u))},p=setTimeout(()=>{s.kill("SIGTERM"),c({ok:!1,stdout:i,stderr:a,code:null,errorMessage:`${t} ${e.join(" ")} timed out after ${r}ms`})},r);s.stdout.on("data",u=>{i+=u.toString()}),s.stderr.on("data",u=>{a+=u.toString()}),s.on("error",u=>{c({ok:!1,stdout:i,stderr:a,code:null,errorMessage:u.message})}),s.on("close",u=>{c({ok:u===0,stdout:i,stderr:a,code:u})})})}async function Sg(t){if(!(await Jr("gh",["--version"],t)).ok)return{ok:!1,reason:"GitHub MCP not available, and GitHub CLI (gh) is not installed or not executable. Install gh: https://cli.github.com/"};let n=await Jr("gh",["auth","status","-h","github.com"],t);if(!n.ok)return{ok:!1,reason:`GitHub CLI is installed but not authenticated for github.com. Run: gh auth login -h github.com (detail: ${n.stderr.trim()||n.stdout.trim()||n.errorMessage||"unknown error"})`};let r=await Jr("gh",["repo","view","--json","nameWithOwner,viewerPermission"],t);if(!r.ok)return{ok:!1,reason:`GitHub CLI authentication works, but this directory is not a readable GitHub repo for gh (detail: ${r.stderr.trim()||r.stdout.trim()||r.errorMessage||"unknown error"})`};let o;try{o=JSON.parse(r.stdout)}catch{return{ok:!1,reason:"Failed to parse `gh repo view` output. Try upgrading gh and retry."}}let s=o.nameWithOwner?.trim(),i=o.viewerPermission?.trim().toUpperCase();return!s||!i?{ok:!1,reason:"GitHub CLI did not return repository or permission info from `gh repo view`."}:mg.has(i)?{ok:!0,repository:s,viewerPermission:i}:{ok:!1,reason:`GitHub CLI connected to ${s}, but permission is ${i}. PR review comments require WRITE/MAINTAIN/ADMIN permission.`}}async function _a(t){let e=_g(t.availableToolNames??[]),n=t.activeMcpServerNames.find(c=>e.includes(c))??null,r=c=>{let p=t.availableToolNames;if(!p||p.length===0)return!0;let u=`${c}_`;return p.some(g=>g.startsWith(u))};if(n&&r(n))return{kind:"github_mcp",strategy:"github_mcp",details:`Using active GitHub MCP server \`${n}\` (detected from loaded MCP tool signatures).`,mcpServerPrefix:n};let{active:o,inactiveCandidates:s}=yg(t.mcpServers,t.activeMcpServerNames);if(o&&r(o))return{kind:"github_mcp",strategy:"github_mcp",details:`Using active GitHub MCP server \`${o}\`.`,mcpServerPrefix:o};let i=await Sg(t.cwd);if(i.ok){let c=s.length?` GitHub MCP server(s) configured but inactive in this session: ${s.join(", ")}.`:"";return{kind:"gh_cli",strategy:"gh_cli",details:`Using gh CLI on repo \`${i.repository}\` with permission \`${i.viewerPermission}\`.${c}`,repository:i.repository,viewerPermission:i.viewerPermission}}let a=s.length?` Also found configured but inactive GitHub MCP server(s): ${s.join(", ")}. Start a new session and activate one of them, or fix gh CLI access.`:"",l=o&&!r(o)?` Active MCP server \`${o}\` is configured, but no tools with prefix \`${o}_\` are currently loaded in this session.`:"";return{kind:"unavailable",reason:`${i.reason}${l}${a}`}}import{jsx as qe,jsxs as Eg}from"react/jsx-runtime";function xg(t,e){if(t.length===0)return[];if(e===void 0)return[...t];if(e.length===0)return[];let n=new Set(t),r=e.filter(o=>n.has(o));return r.length>0?r:[...t]}function wg(t,e){if(t.length===0)return[];if(e.length===0)return[];let n=new Set(t);return e.filter(r=>n.has(r))}function Mg(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function Ta({sessionOptions:t,providerName:e,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:a,modelProfiles:l,dangerous:c=!1,needsSetup:p=!1}){let{exit:u}=Cg(),g=jt(()=>Object.keys(o??{}).sort(),[o]),v=jt(()=>xg(g,t.activeMcpServers),[g,t.activeMcpServers]),h=t.toolPermissionMode??(c?U.FULL:U.ONCE),[f,x]=vg(da,void 0,Vr),[b,E]=ee(e),[B,q]=ee(n),[fe,ce]=ee(a),[J,P]=ee(l),[Y,H]=ee(h),O=X(d=>ut({model_profiles:J},d),[J]),[K,V]=ee({...t,providerName:e,maxPromptTokens:O({name:e,model:n}),dangerous:h===U.FULL,toolPermissionMode:h}),[R,M]=ee(!1),[I,te]=ee([]),[ue,Ae]=ee(null),[_e,Se]=ee(null),[rt,He]=ee(O({name:e,model:n})),[Ke,A]=ee(0),[j,vt]=ee(p),[G,Gt]=ee(!p&&g.length>0),[ge,z]=ee(v),[L,bt]=ee(null),[D,Ve]=ee(null),ie=In(null),Fe=In(null),ot=In(null),[ne,Be]=ee(null),Xe=In(null),T=jt(()=>Rn(),[]),_=X(d=>{x(d)},[]);Wt(()=>{j||(z(v),Gt(g.length>0))},[j,v,g.length]);let y=X((d,S,w="info")=>{_({type:"append_system_message",title:d,content:S,tone:w})},[_]),Z=jt(()=>({onAssistantStep:(d,S)=>{let w=Fe.current;w&&_({type:"assistant_chunk",turn:w,step:S,chunk:d})},requestApproval:Y===U.FULL||Y===U.NONE?void 0:d=>new Promise(S=>{la(d),Be(d),Xe.current=S}),hooks:{onTurnStart:({turn:d,input:S,promptTokens:w})=>{Fe.current=d;let oe=ot.current;oe&&(ot.current=null);let ke=oe??S;w&&w>0&&A(w),_({type:"turn_start",turn:d,input:ke,promptTokens:w})},onAction:({turn:d,step:S,action:w,thinking:oe,parallelActions:ke})=>{_({type:"tool_action",turn:d,step:S,action:w,thinking:oe,parallelActions:ke})},onObservation:({turn:d,step:S,observation:w,resultStatus:oe,parallelResultStatuses:ke})=>{_({type:"tool_observation",turn:d,step:S,observation:w,toolStatus:Cr(oe),parallelToolStatuses:ei(ke)})},onFinal:({turn:d,finalText:S,status:w,errorMessage:oe,turnUsage:ke,tokenUsage:ka})=>{_({type:"turn_final",turn:d,finalText:S,status:w,errorMessage:oe,turnUsage:ke,tokenUsage:ka}),M(!1)}}}),[_,Y]);Wt(()=>{let d=!1;return(async()=>{if(!(j||G))try{let S=ie.current;S&&await S.close();let w=await dn(Z,K);if(d){await w.close();return}ie.current=w,Ve(w),Ae(w.historyFilePath??null)}catch(S){if(d)return;ie.current=null,Ve(null),Ae(null),M(!1),y("Session",`Failed to create session: ${S.message}`,"error")}})(),()=>{d=!0}},[y,Z,G,K,j]),Wt(()=>{let d=!1;return(async()=>{let S=await ya();d||!S||y("Update",`Update available: v${S.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{d=!0}},[y]),Wt(()=>()=>{ie.current&&ie.current.close()},[]);let re=X(async()=>{let d=Xe.current;d&&(d("deny"),Xe.current=null),ne&&Be(null),ie.current&&await ie.current.close(),bt("Bye!"),setTimeout(()=>u(),250)},[u,ne]),Pe=X(()=>{if(R){y("Clear","Cancel current run before clearing timeline.","warning");return}if(ne){y("Clear","Resolve current approval request before clearing timeline.","warning");return}_({type:"clear_current_timeline"}),Se(null),A(0),Mg()},[y,R,_,ne]),On=X(()=>{if(R){y("New Session","Cancel current run before starting a new session.","warning");return}if(ne){y("New Session","Resolve current approval request before starting a new session.","warning");return}_({type:"reset_all"}),Se(null),A(0),Fe.current=null,V(d=>({...d,sessionId:Tt()})),y("New Session","Started a fresh session.")},[y,R,_,ne]),Ct=X(async d=>{try{let S=await de();await Me(S.configPath,{...S.config,current_provider:d})}catch(S){y("Config",`Failed to persist provider: ${S.message}`,"warning")}},[y]),C=X(async d=>{if(R){y("Model switch","Cancel current run before switching models.","warning");return}if(d.name===b&&d.model===B){y("Model switch",`Already using ${d.name} (${d.model}).`);return}_({type:"reset_all"}),A(0),Fe.current=null;let S=O(d);E(d.name),q(d.model),He(S),V(w=>({...w,sessionId:Tt(),providerName:d.name,maxPromptTokens:S})),await Ct(d.name),y("Model switch",`Switched to ${d.name} (${d.model}).`)},[y,R,B,b,_,Ct,O]),k=X(d=>d===U.NONE?"none (no tools)":d===U.ONCE?"once (approval required)":"full (no approval)",[]),ae=X(d=>{if(R){y("Tools","Cancel current run before changing tool permission mode.","warning");return}if(ne){y("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(d===Y){y("Tools",`Already using ${k(d)}.`);return}H(d),V(S=>({...S,sessionId:Tt(),dangerous:d===U.FULL,toolPermissionMode:d})),y("Tools",`Tool permission set to ${k(d)}.`)},[y,R,ne,k,Y]),F=X(async d=>{try{let S=await de();await Me(S.configPath,{...S.config,active_mcp_servers:d})}catch(S){y("MCP",`Failed to persist active MCP servers: ${S.message}`,"warning")}},[y]),Te=X((d,S)=>{let w=wg(g,d);z(w),Gt(!1),V(oe=>({...oe,sessionId:Tt(),activeMcpServers:w})),S&&F(w)},[g,F]),Je=X(async d=>{if(R){y("History","Cancel current run before loading session history.","warning");return}if(ne){y("History","Resolve current approval request before loading session history.","warning");return}try{let S=await Tg(d.sessionFile,"utf8"),w=pa(S);_({type:"clear_current_timeline"}),_({type:"replace_history",turns:w.turns,maxSequence:w.maxSequence}),Se(w.messages),M(!1),Ve(null),Ae(null),A(0),Fe.current=null,V(oe=>({...oe,sessionId:Tt()})),y("History",w.summary||d.input)}catch(S){y("History",`Failed to load ${d.sessionFile}: ${S.message}`,"error")}},[y,R,_,ne]),st=X(()=>{R&&D?.cancelCurrentTurn?.()},[R,D]),xt=X(async()=>{if(!D||R)return;let d=ye($.INIT);try{let S=await Xr("init_agents");te(w=>[...w,d]),M(!0),ot.current=d,await D.runTurn(S)}catch(S){M(!1),y("Init",`Failed to run init task: ${S.message}`,"error")}},[y,R,D]),Ln=X(async d=>{if(!D||R)return;if(Y===U.NONE){y("Review",'Tool permission mode is "none". Set `/tools once` or `/tools full` before running `/review`.',"warning");return}let S=`${ye($.REVIEW)} ${d}`;try{let w=await _a({cwd:s,mcpServers:o,activeMcpServerNames:ge,availableToolNames:D.listToolNames?.()??[]});if(w.kind==="unavailable"){y("Review",w.reason,"error");return}let oe=await Xr("review_pull_request",{pr_number:String(d),backend_strategy:w.strategy,backend_details:w.details,mcp_server_prefix:w.kind==="github_mcp"?w.mcpServerPrefix:"github"});te(ke=>[...ke,S]),y("Review",w.details),M(!0),ot.current=S,await D.runTurn(oe)}catch(w){M(!1),y("Review",`Failed to run review task for PR #${d}: ${w.message}`,"error")}},[ge,y,R,s,o,D,Y]),wt=X(async d=>{let S=d.trim();if(S){if(S.toLowerCase()===yi){await re();return}if(S===ye($.INIT)){await xt();return}if(!(!D||R)){te(w=>[...w,S]),M(!0);try{await D.runTurn(S)}catch(w){M(!1),y("Run",`Turn failed: ${w.message}`,"error")}}}},[y,R,re,xt,D]),wa=X(async()=>{try{let d=await de(),S=Ze(d.config),w=ut(d.config,S);ce(d.config.providers),P(d.config.model_profiles),E(S.name),q(S.model),He(w),V(oe=>({...oe,sessionId:Tt(),providerName:S.name,maxPromptTokens:w})),vt(!1),y("Setup",`Config saved to ${d.configPath}`)}catch(d){y("Setup",`Failed to reload config: ${d.message}`,"error")}},[y]);Wt(()=>{if(!D||!_e?.length)return;let d=D.history[0];d&&(D.history.splice(0,D.history.length,d,..._e),Se(null))},[_e,D]);let Ma=X(d=>{let S=Xe.current;S&&(S(d),Xe.current=null),Be(null)},[]),Ea=ni(f.turns[f.turns.length-1]?.tokenUsage),Aa=ti(Ke,rt),Pa=jt(()=>({providerName:b,model:B,cwd:s,sessionId:K.sessionId??"unknown",mcpNames:ge,version:T?.version??"unknown"}),[ge,B,b,s,T?.version,K.sessionId]);return L?qe(Sa,{children:qe(bg,{color:"green",children:L})}):j?qe(ua,{configPath:r,onComplete:wa,onExit:re}):G?qe(ia,{serverNames:g,defaultSelected:v,onConfirm:Te,onExit:()=>{re()}}):Eg(Sa,{flexDirection:"column",children:[qe(hi,{header:Pa,systemMessages:f.systemMessages,turns:f.turns,historicalTurns:f.historicalTurns}),qe(ea,{disabled:!D||!!ne,busy:R,history:I,cwd:s,sessionsDir:i,currentSessionFile:ue??void 0,providers:fe,configPath:r,providerName:b,model:B,toolPermissionMode:Y,mcpServers:o,onSubmit:d=>{wt(d)},onExit:()=>{re()},onClear:Pe,onNewSession:On,onCancelRun:st,onHistorySelect:d=>{Je(d)},onModelSelect:d=>{C(d)},onSetToolPermission:ae,onReviewPullRequest:d=>{Ln(d)},onSystemMessage:y}),ne?qe(sa,{request:ne,onDecision:Ma}):null,qe(ra,{busy:R,pendingApproval:!!ne,contextPercent:Aa,tokenLine:Ea})]})}var Ag=`
|
|
31
|
+
`):"",r="";e.mcp_servers&&Object.keys(e.mcp_servers).length>0&&(r=Object.entries(e.mcp_servers).map(([c,a])=>{if("url"in a){let y=[`[mcp_servers.${c}]`];y.push(`type = "${a.type??"streamable_http"}"`),y.push(`url = "${a.url}"`),a.bearer_token_env_var&&y.push(`bearer_token_env_var = ${JSON.stringify(a.bearer_token_env_var)}`);let b=a.http_headers??a.headers;if(b&&Object.keys(b).length>0){let U=Object.entries(b).map(([H,R])=>`${JSON.stringify(H)} = ${JSON.stringify(R)}`).join(", "),T=a.http_headers?"http_headers":"headers";y.push(`${T} = { ${U} }`)}return y.join(`
|
|
32
|
+
`)}let l=a.args?`args = ${JSON.stringify(a.args)}`:"",p=a.type?`type = "${a.type}"
|
|
33
|
+
`:"",u=a.stderr?`stderr = "${a.stderr}"
|
|
34
|
+
`:"",d=`[mcp_servers.${c}]
|
|
35
|
+
${p}command = "${a.command}"
|
|
36
|
+
${u}${l}`.trimEnd(),m=a.env?Object.entries(a.env):[];if(m.length===0)return d;let g=m.map(([y,b])=>`${JSON.stringify(y)} = ${JSON.stringify(b)}`).join(`
|
|
37
|
+
`);return`${d}
|
|
38
|
+
|
|
39
|
+
[mcp_servers.${c}.env]
|
|
40
|
+
${g}`}).join(`
|
|
41
|
+
|
|
42
|
+
`));let o=[`current_provider = "${e.current_provider}"`];Array.isArray(e.active_mcp_servers)&&o.push(`active_mcp_servers = ${JSON.stringify(e.active_mcp_servers)}`),Array.isArray(e.active_skills)&&o.push(`active_skills = ${JSON.stringify(e.active_skills)}`);let s=e.mcp_oauth_credentials_store_mode;return(s==="auto"||s==="keyring"||s==="file")&&o.push(`mcp_oauth_credentials_store_mode = ${JSON.stringify(s)}`),typeof e.mcp_oauth_callback_port=="number"&&Number.isInteger(e.mcp_oauth_callback_port)&&e.mcp_oauth_callback_port>0&&e.mcp_oauth_callback_port<=65535&&o.push(`mcp_oauth_callback_port = ${e.mcp_oauth_callback_port}`),o.push(`auto_compact_threshold_percent = ${Us(e.auto_compact_threshold_percent)}`),[o.join(`
|
|
43
|
+
`),t,n,r].filter(Boolean).join(`
|
|
44
|
+
|
|
45
|
+
`)}async function we(e,t){await hp(vp(e),{recursive:!0}),await yp(e,Pp(t),"utf-8")}async function ee(){let e=process.env.MEMO_HOME?Fs(process.env.MEMO_HOME):bp,t=it(e,"config.toml");try{await Sp(t);let n=await _p(t,"utf-8"),r=Cp(n),o=Mp(r.providers),s=Array.isArray(r.active_mcp_servers)?r.active_mcp_servers.filter(m=>typeof m=="string"&&m.trim().length>0):void 0,i=kp(r.active_skills),c=r.mcp_oauth_credentials_store_mode==="auto"||r.mcp_oauth_credentials_store_mode==="keyring"||r.mcp_oauth_credentials_store_mode==="file"?r.mcp_oauth_credentials_store_mode:Wt.mcp_oauth_credentials_store_mode,a=typeof r.mcp_oauth_callback_port=="number"&&Number.isInteger(r.mcp_oauth_callback_port)&&r.mcp_oauth_callback_port>0&&r.mcp_oauth_callback_port<=65535?r.mcp_oauth_callback_port:void 0,l=Us(r.auto_compact_threshold_percent),p=Ap(r.model_profiles),u={current_provider:r.current_provider??Wt.current_provider,mcp_oauth_credentials_store_mode:c,mcp_oauth_callback_port:a,auto_compact_threshold_percent:l,providers:o,model_profiles:p,mcp_servers:r.mcp_servers??{},active_mcp_servers:s,active_skills:i},d=!u.providers.length;return{config:d?Wt:u,home:e,configPath:t,needsSetup:d}}catch{return{config:Wt,home:e,configPath:t,needsSetup:!0}}}function at(e,t){let n=t||e.current_provider,r=e.providers.find(o=>o.name===n);return r||(e.providers?.[0]??Wt.providers[0])}function jt(e,t){let n=t.historyDir??it(e.home,xp),r=Fs(n),o=wp(t.cwd??process.cwd()),s=Tp(o).root,c=o.slice(s.length).split(/[\\/]+/).filter(Boolean);if(process.platform==="win32"){let l=/^([A-Za-z]):/.exec(s)?.[1];l&&c.unshift(l.toUpperCase())}if(c.length===0)return it(r,"-root");let a=`-${c.map(l=>l.replace(/[^A-Za-z0-9._-]/g,"_")).join("-")}`;return it(r,a)}function Hs(e,t){let n=new Date,r=String(n.getFullYear()),o=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),c=String(n.getMinutes()).padStart(2,"0"),a=String(n.getSeconds()).padStart(2,"0"),l=`${r}-${o}-${s}T${i}-${c}-${a}`,p=t.replace(/[^A-Za-z0-9._-]/g,"_"),u=`${l}-${p}.jsonl`;return it(e,u)}import{createHash as Ep}from"crypto";import{spawn as Rp}from"child_process";import{createServer as Ip}from"http";import{mkdir as Op,readFile as Lp,rename as Np,writeFile as $p}from"fs/promises";import{homedir as Mr}from"os";import{dirname as Dp,join as Pr}from"path";import{auth as Bs}from"@modelcontextprotocol/sdk/client/auth.js";var kr=1,Up="mcp-oauth.json",Fp=3e5,Hp=5e3,Ws="MCP-Protocol-Version",Bp="2024-11-05",Er="memo-code.mcp.oauth",Wp=33333;function jp(e){return{client_name:"Memo Code CLI",redirect_uris:[e],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function js(e){return e instanceof Error?e.message:String(e)}function Rr(e){return new URL(e).toString()}function Ir(e){return e==="file"||e==="keyring"||e==="auto"?e:"auto"}function zs(e){return e==="~"?Mr():e.startsWith("~/")?Pr(Mr(),e.slice(2)):e}function zp(e){return e?.memoHome?.trim()?zs(e.memoHome.trim()):process.env.MEMO_HOME?.trim()?zs(process.env.MEMO_HOME.trim()):Pr(Mr(),".memo")}function Xs(e){return Pr(zp(e),"auth",Up)}function St(e){return Ep("sha256").update(Rr(e)).digest("hex")}function Gs(){return{version:kr,credentials:{}}}async function Or(e){let t=Xs(e);try{let n=await Lp(t,"utf8"),r=JSON.parse(n);return r.version!==kr||!r.credentials?Gs():{version:kr,credentials:r.credentials}}catch{return Gs()}}async function Js(e,t){let n=Xs(e),r=`${n}.tmp`;await Op(Dp(n),{recursive:!0}),await $p(r,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),await Np(r,n)}var vn=null;async function Lr(){return vn||(vn=(async()=>{try{let t=await new Function("specifier","return import(specifier)")("keytar"),n=t.default??t;return n&&typeof n.getPassword=="function"&&typeof n.setPassword=="function"&&typeof n.deletePassword=="function"?n:null}catch{return null}})(),vn)}async function br(e,t){let n=St(e);return(await Or(t)).credentials[n]?.credential}async function xr(e,t,n){let r=St(e),o=await Or(n);o.credentials[r]={url:Rr(e),updatedAt:Date.now(),credential:t},await Js(n,o)}async function Ar(e,t){let n=St(e),r=await Or(t);return r.credentials[n]?(delete r.credentials[n],await Js(t,r),!0):!1}async function Ks(e,t){let n=St(t),r=await e.getPassword(Er,n);return r?JSON.parse(r).credential:void 0}async function qs(e,t,n){let r=St(t),o={url:Rr(t),updatedAt:Date.now(),credential:n};await e.setPassword(Er,r,JSON.stringify(o))}async function Vs(e,t){let n=St(t);return e.deletePassword(Er,n)}function Gp(e,t){return new URL(e).origin===t.origin}function Ys(e){return{...e.http_headers??e.headers??{}}}function Kp(e){let t=e.replace(/^\/+|\/+$/g,"");if(!t)return["/.well-known/oauth-authorization-server"];let n=[],r=o=>{n.includes(o)||n.push(o)};return r(`/.well-known/oauth-authorization-server/${t}`),r(`/${t}/.well-known/oauth-authorization-server`),r("/.well-known/oauth-authorization-server"),n}function qp(e){if(!e||e.length===0)return;let t=e.flatMap(n=>n.split(/[,\s]+/g)).map(n=>n.trim()).filter(Boolean);if(t.length!==0)return t.join(" ")}function Qs(e){if(e!==void 0){if(!Number.isInteger(e)||e<=0||e>65535)throw new Error(`Invalid MCP OAuth callback port "${e}". Use an integer between 1 and 65535.`);return e}}function Vp(e){return process.platform==="darwin"?{command:"open",args:[e]}:process.platform==="win32"?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]}}async function Xp(e){let{command:t,args:n}=Vp(e);await new Promise((r,o)=>{let s=Rp(t,n,{detached:!0,stdio:"ignore"}),i=!1,c=p=>{if(!i){if(i=!0,s.off("error",a),s.off("spawn",l),p){o(p);return}r()}},a=p=>{c(p)},l=()=>{c()};s.on("error",a),s.on("spawn",l),s.unref()})}function Zs(e,t){return async(n,r)=>{let o=typeof n=="string"||n instanceof URL?new URL(String(n),e):new URL(n.url),s=new Headers(r?.headers??{});if(Gp(e,o)){for(let[i,c]of Object.entries(t))s.has(i)||s.set(i,c);s.has(Ws)||s.set(Ws,Bp)}return fetch(o,{...r,headers:s})}}async function ei(e,t){let n=new URL(e),r=Zs(e,t),o=Kp(n.pathname);for(let s of o){let i=new URL(n.toString());i.pathname=s,i.search="",i.hash="";let c=new AbortController,a=setTimeout(()=>c.abort(),Hp);try{let l=await r(i,{method:"GET",signal:c.signal});if(!l.ok)continue;let p=await l.json();if(typeof p.authorization_endpoint=="string"&&typeof p.token_endpoint=="string")return!0}catch{continue}finally{clearTimeout(a)}}return!1}var Tn=class{constructor(t,n,r,o,s){this.serverUrl=t;this.settings=n;this.redirectUrlValue=r;this.handleRedirect=o;this.clientMetadata=jp(r),s&&(this.credential=s,this.loaded=!0)}loaded=!1;credential={};verifier=null;clientMetadata;get redirectUrl(){return this.redirectUrlValue}async ensureLoaded(){if(this.loaded)return;let t=await wn(this.serverUrl,this.settings);this.credential=t.credential??{},this.loaded=!0}async persist(){await Jp(this.serverUrl,this.credential,this.settings)}async clientInformation(){return await this.ensureLoaded(),this.credential.clientInformation}async saveClientInformation(t){await this.ensureLoaded(),this.credential={...this.credential,clientInformation:t},await this.persist()}async tokens(){return await this.ensureLoaded(),this.credential.tokens}async saveTokens(t){await this.ensureLoaded(),this.credential={...this.credential,tokens:t},await this.persist()}async redirectToAuthorization(t){await this.handleRedirect(t)}saveCodeVerifier(t){this.verifier=t}codeVerifier(){if(!this.verifier)throw new Error("OAuth code verifier is missing.");return this.verifier}async invalidateCredentials(t){if(await this.ensureLoaded(),t==="all")this.credential={};else if(t==="client")this.credential={...this.credential,clientInformation:void 0};else if(t==="tokens")this.credential={...this.credential,tokens:void 0};else if(t==="verifier"){this.verifier=null;return}await this.persist()}};async function wn(e,t){let n=Ir(t?.storeMode);if(n==="file")return{backend:"file",credential:await br(e,t)};let r=await Lr();if(n==="keyring"){if(!r)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return{backend:"keyring",credential:await Ks(r,e)}}if(!r)return{backend:"file",credential:await br(e,t)};try{let o=await Ks(r,e);if(o)return{backend:"keyring",credential:o}}catch{}return{backend:"file",credential:await br(e,t)}}async function Jp(e,t,n){let r=Ir(n?.storeMode);if(r==="file")return await xr(e,t,n),{backend:"file"};let o=await Lr();if(r==="keyring"){if(!o)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return await qs(o,e,t),{backend:"keyring"}}if(!o)return await xr(e,t,n),{backend:"file"};try{return await qs(o,e,t),await Ar(e,n).catch(()=>{}),{backend:"keyring"}}catch{return await xr(e,t,n),{backend:"file"}}}async function Yp(e,t){let n=Ir(t?.storeMode);if(n==="file")return{backend:"file",removed:await Ar(e,t)};let r=await Lr();if(n==="keyring"){if(!r)throw new Error('Keyring storage is not available. Set mcp_oauth_credentials_store_mode = "file".');return{backend:"keyring",removed:await Vs(r,e)}}let o=!1;if(r)try{o=await Vs(r,e)}catch{o=!1}let s=await Ar(e,t);return{backend:o?"keyring":"file",removed:o||s}}async function Nr(e,t){return"url"in e?e.bearer_token_env_var?"bearer_token":(await wn(e.url,t)).credential?.tokens?.access_token?"oauth":await ei(e.url,Ys(e))?"not_logged_in":"unsupported":"unsupported"}async function Qp(e,t){let n=Qs(e),r="127.0.0.1",o=!1,s=null,i=null,c=null,a=new Promise((d,m)=>{i=d,c=m}),l=Ip((d,m)=>{let g=new URL(d.url??"/",`http://${r}`);if(g.pathname!=="/callback"){m.writeHead(404,{"Content-Type":"text/plain"}),m.end("Not found");return}let y=g.searchParams.get("code"),b=g.searchParams.get("error"),U=g.searchParams.get("error_description");if(y){m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end("<html><body><h1>Authentication complete.</h1><p>You can close this window.</p></body></html>"),i?.(y);return}let T=U??b??"OAuth callback missing code.";m.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),m.end(`<html><body><h1>Authentication failed.</h1><p>${T}</p></body></html>`),c?.(new Error(T))});await new Promise((d,m)=>{l.once("error",m),l.listen(n??0,r,()=>{l.off("error",m),d()})});let p=l.address();if(!p||typeof p=="string")throw await new Promise(d=>l.close(()=>d())),new Error("Failed to resolve OAuth callback listener address.");s=setTimeout(()=>{c?.(new Error("Timed out waiting for OAuth callback."))},t),s.unref?.();let u=async()=>{o||(o=!0,s&&(clearTimeout(s),s=null),await new Promise(d=>l.close(()=>d())))};return{redirectUrl:`http://${r}:${p.port}/callback`,waitForCode:async()=>{try{return await a}finally{await u()}},close:u}}async function $r(e){if(e.config.bearer_token_env_var)throw new Error(`Server "${e.serverName}" is configured with bearer_token_env_var. Remove it to use OAuth login.`);let t=Ys(e.config);if(!await ei(e.config.url,t))throw new Error(`Server "${e.serverName}" does not advertise OAuth support. Configure --bearer-token-env-var instead.`);let r=await Qp(e.settings?.callbackPort,e.timeoutMs??Fp),o=Zs(e.config.url,t),s=new Tn(e.config.url,e.settings,r.redirectUrl,async i=>{let c=i.toString();e.onAuthorizationUrl?.(c);try{await Xp(c)}catch(a){e.onBrowserOpenFailure?.(new Error(js(a)),i.toString())}});try{let i=qp(e.scopes);if(await Bs(s,{serverUrl:e.config.url,scope:i,fetchFn:o})==="REDIRECT"){let l=await r.waitForCode();if(await Bs(s,{serverUrl:e.config.url,authorizationCode:l,scope:i,fetchFn:o})!=="AUTHORIZED")throw new Error("OAuth authorization did not complete.")}let a=await wn(e.config.url,e.settings);if(!a.credential?.tokens?.access_token)throw new Error("OAuth login completed but no access token was stored.");return{backend:a.backend}}catch(i){throw new Error(`OAuth login failed: ${js(i)}`)}finally{await r.close()}}async function Dr(e){return Yp(e.config.url,e.settings)}async function ti(e){if(e.config.bearer_token_env_var)return null;let t=await wn(e.config.url,e.settings);if(!t.credential?.tokens?.access_token)return null;let r=`http://127.0.0.1:${Qs(e.settings?.callbackPort)??Wp}/callback`;return new Tn(e.config.url,e.settings,r,async()=>{throw new Error(`MCP server "${e.serverName}" requires OAuth login. Run: memo mcp login ${e.serverName}`)},t.credential)}import{access as qS,mkdir as VS,readFile as XS,readdir as JS,rm as YS,writeFile as QS}from"fs/promises";import{homedir as ev}from"os";import{basename as nv,dirname as rv,join as ov,resolve as sv}from"path";import{z as He}from"zod";function D(e){let{inputSchema:t,execute:n,...r}=e,o=t.toJSONSchema?.(),{$schema:s,...i}=o??{};return{...r,source:"native",inputSchema:i,validateInput:c=>{let a=t.safeParse(c);if(!a.success){let l=a.error.issues[0]?.message??"invalid input";return{ok:!1,error:`${e.name} invalid input: ${l}`}}return{ok:!0,data:a.data}},execute:n}}function h(e,t=!1){return{content:[{type:"text",text:e}],isError:t}}import{spawn as wd}from"child_process";import{EventEmitter as Cd}from"events";import{resolve as bd}from"path";import{posix as Zp}from"path";var ni=220,ri=4096,ed=/^\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)$/i,td=/(?:^|[\s(])(?:\d?>>?|>>|>\||&>)\s*\/dev\/(?:sd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|hd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|mmcblk\d+(?:p\d+)?|disk\d+|rdisk\d+)(?:\s|$)/i,nd=new Set(["-u","--user","-g","--group","-h","--host","-p","--prompt","-C","-T","-r","--role","-t","--type","-D","--chdir"]),rd=new Set(["fdisk","sfdisk","cfdisk","parted","sgdisk","gdisk","wipefs","blkdiscard","shred"]);function Ur(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function od(e){let t=e.replace(/\s+/g," ").trim();return t.length>ni?`${t.slice(0,ni)}\u2026`:t}function oi(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return(t.split(/[\\/]/).at(-1)??t).toLowerCase()}function sd(e){let t=null,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(n){n=!1;continue}if(o==="\\"&&t!=="'"){n=!0;continue}if(t){o===t&&(t=null);continue}if(o==='"'||o==="'"){t=o;continue}if(o==="#")return e.slice(0,r)}return e}function id(e){let t=[],n="",r=null,o=!1,s=()=>{let i=sd(n).trim();i&&t.push(i),n=""};for(let i=0;i<e.length;i+=1){let c=e[i];if(o){n+=c,o=!1;continue}if(c==="\\"&&r!=="'"){n+=c,o=!0;continue}if(r){n+=c,c===r&&(r=null);continue}if(c==='"'||c==="'"){r=c,n+=c;continue}if(c===";"||c===`
|
|
46
|
+
`){s();continue}if(c==="&"){e[i+1]==="&"&&(i+=1),s();continue}if(c==="|"){e[i+1]==="|"&&(i+=1),s();continue}n+=c}return s(),t}function ad(e){let t=[],n="",r=null,o=!1,s=()=>{n&&t.push(n),n=""};for(let i=0;i<e.length;i+=1){let c=e[i];if(o){n+=c,o=!1;continue}if(c==="\\"&&r!=="'"){o=!0;continue}if(r){c===r?r=null:n+=c;continue}if(c==='"'||c==="'"){r=c;continue}if(/\s/.test(c)){s();continue}n+=c}return s(),t}function si(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function cd(e,t){let n=t;for(;n<e.length;){let r=oi(e[n]??"");if(r==="sudo"){for(n+=1;n<e.length;){let o=e[n]??"";if(!o.startsWith("-"))break;n+=1,nd.has(o)&&n<e.length&&(n+=1)}continue}if(r==="env"){for(n+=1;n<e.length;){let o=e[n]??"";if(o.startsWith("-")||si(o)){n+=1;continue}break}continue}if(r==="command"||r==="nohup"||r==="time"){n+=1;continue}break}return n}function ld(e){let t=ad(e);if(t.length===0)return null;let n=0;for(;n<t.length&&si(t[n]??"");)n+=1;if(n=cd(t,n),n>=t.length)return null;let r=oi(t[n]??"");return r?{raw:e,commandName:r,args:t.slice(n+1)}:null}function Fr(e){let t=e.trim().replace(/^['"]|['"]$/g,"");return ed.test(t)}function ud(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.toLowerCase();return n==="/"||n==="/*"||n==="/.*"||n==="~"||n==="~/"||n==="~/*"||n==="$home"||n==="$home/"||n==="$home/*"||n==="${home}"||n==="${home}/"||n==="${home}/*"?!0:t.startsWith("/")&&!/[*?[\]{}$]/.test(t)?Zp.normalize(t)==="/":!1}function pd(e){return e.startsWith("-")&&e!=="-"}function dd(e){if(e.commandName!=="rm")return null;let t=!1,n=0;for(;n<e.args.length;){let o=e.args[n]??"";if(o==="--"){n+=1;break}if(!pd(o))break;if(o==="--recursive"){t=!0,n+=1;continue}if(o.startsWith("--")){n+=1;continue}let s=o.slice(1);(s.includes("r")||s.includes("R"))&&(t=!0),n+=1}if(!t)return null;let r=e.args.slice(n);for(let o of r)if(ud(o))return{ruleId:"rm_recursive_critical_target",matchedSegment:e.raw};return null}function md(e){return e.commandName==="mkfs"||e.commandName.startsWith("mkfs.")?{ruleId:"mkfs_filesystem_create",matchedSegment:e.raw}:null}function fd(e){if(e.commandName!=="dd")return null;for(let t=0;t<e.args.length;t+=1){let n=e.args[t]??"",r=n.indexOf("=");if(r<=0)continue;let o=n.slice(0,r).toLowerCase(),s=n.slice(r+1);if(o==="of"&&Fr(s))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}for(let t=0;t<e.args.length-1;t+=1){let n=(e.args[t]??"").toLowerCase(),r=e.args[t+1]??"";if(n==="of"&&Fr(r))return{ruleId:"dd_write_block_device",matchedSegment:e.raw}}return null}function gd(e){return!rd.has(e.commandName)||!e.args.some(t=>Fr(t))?null:{ruleId:"disk_mutation_block_device",matchedSegment:e.raw}}function hd(e){return td.test(e)?{ruleId:"redirect_block_device",matchedSegment:e}:null}function yd(e){for(let t of id(e)){let n=ld(t);if(n){let o=dd(n);if(o)return o;let s=md(n);if(s)return s;let i=fd(n);if(i)return i;let c=gd(n);if(c)return c}let r=hd(t);if(r)return r}return null}function _d(e,t){let n=od(e.command),r=typeof e.sessionId=="number"?` session_id="${e.sessionId}"`:"";return`<system_hint type="tool_call_denied" tool="${Ur(e.toolName)}" reason="dangerous_command" policy="blacklist" rule="${Ur(t.ruleId)}"${r} command="${Ur(n)}">Blocked a high-risk shell command to prevent irreversible data loss. Use a safer and scoped alternative.</system_hint>`}function Hr(e){let t=yd(e.command);return t?{blocked:!0,xml:_d(e,t),match:t}:{blocked:!1}}function ii(e){let n=e.replace(/\r\n/g,`
|
|
47
|
+
`).replace(/\r/g,`
|
|
48
|
+
`).split(`
|
|
49
|
+
`),r=n.pop()??"";return{completedLines:n,remainder:r}}function Br(e){return e.length<=ri?e:e.slice(-ri)}import{AsyncLocalStorage as Sd}from"async_hooks";import{resolve as vd}from"path";var ai=new Sd;function ci(e){if(!(!e||!e.trim()))return vd(e)}function Td(){return ai.getStore()??{}}function Fe(e=process.cwd()){return ci(Td().cwd)??e}async function li(e,t){let n={cwd:ci(e.cwd)};return new Promise((r,o)=>{ai.run(n,()=>{Promise.resolve(t()).then(r,o)})})}var xd=1e4,Md=250,kd=2e3,Cn=64;function Ad(e){return Math.ceil(e.length/4)}function Pd(){return Math.random().toString(16).slice(2)||String(Date.now())}function Ed(e){let t=e.login,n=e.shell?.trim();if(process.platform==="win32"){let o=n||"powershell.exe";return o.toLowerCase().includes("powershell")?{file:o,args:["-NoProfile","-Command",e.cmd]}:{file:o,args:[t?"-lc":"-c",e.cmd]}}return{file:n||process.env.SHELL||"/bin/bash",args:[t?"-lc":"-c",e.cmd]}}function Rd(e,t){let r=(typeof t=="number"&&t>0?Math.floor(t):kd)*4,o=Ad(e);return e.length<=r?{output:e,originalTokenCount:o,deliveredChars:e.length}:{output:e.slice(0,r),originalTokenCount:o,deliveredChars:r}}function Id(e){let t=[];return t.push(`Chunk ID: ${e.chunkId}`),t.push(`Wall time: ${e.wallTimeSeconds.toFixed(4)} seconds`),e.exitCode!==null?t.push(`Process exited with code ${e.exitCode}`):t.push(`Process running with session ID ${e.sessionId}`),t.push(`Original token count: ${e.originalTokenCount}`),t.push("Output:"),t.push(e.output),t.join(`
|
|
50
|
+
`)}function ui(e,t){return typeof e!="number"||Number.isNaN(e)?t:e<0?0:Math.floor(e)}async function pi(e,t){t<=0||e.exited||await new Promise(n=>{let r=!1,o=()=>{r||(r=!0,clearTimeout(c),i(),n())},s=()=>{o()},i=()=>{e.eventBus.off("exit",s)},c=setTimeout(()=>{o()},t);c.unref?.(),e.eventBus.on("exit",s)})}async function di(e,t){e.exited||t<=0||await new Promise(n=>{let r=!1,o=()=>{r||(r=!0,clearTimeout(c),i(),n())},s=()=>{o()},i=()=>{e.eventBus.off("exit",s)},c=setTimeout(()=>{o()},t);c.unref?.(),e.eventBus.on("exit",s)})}var Wr=class{sessions=new Map;nextId=1;cleanupSessions(){if(this.sessions.size<=Cn)return;let t=Array.from(this.sessions.values()).filter(n=>n.exited).sort((n,r)=>n.startedAtMs-r.startedAtMs);for(let n of t){if(this.sessions.size<=Cn)break;this.sessions.delete(n.id)}}activeSessionCount(){let t=0;for(let n of this.sessions.values())n.exited||(t+=1);return t}async terminateForTimeout(t){if(!t.exited){try{t.proc.kill("SIGTERM")}catch{}if(await di(t,200),!t.exited){try{t.proc.kill("SIGKILL")}catch{}await di(t,200)}}}async start(t){let n=t.cmd.trim();if(!n)throw new Error("cmd must not be empty");if(this.cleanupSessions(),this.activeSessionCount()>=Cn)throw new Error(`too many active sessions (max ${Cn})`);let r=Hr({toolName:t.source_tool??"exec_command",command:n});if(r.blocked)return r.xml;let o=this.nextId++,s=Date.now(),i=Ed({cmd:n,shell:t.shell,login:t.login!==!1}),c=Fe(),a=t.workdir?.trim()?bd(c,t.workdir.trim()):c,l=wd(i.file,i.args,{cwd:a,env:process.env,stdio:["pipe","pipe","pipe"],shell:!1}),p={id:o,output:"",readOffset:0,pendingStdinInput:"",startedAtMs:s,exited:!1,exitCode:null,eventBus:new Cd,proc:l},u=(y,b)=>{let U=typeof b=="string"?b:b.toString("utf8");p.output+=y?`${y}${U}`:U,p.eventBus.emit("output")};l.stdout?.on("data",y=>u("",y)),l.stderr?.on("data",y=>u("",y)),l.on("error",y=>{p.output+=`
|
|
51
|
+
[exec error] ${y.message}`,p.eventBus.emit("output")}),l.on("close",y=>{p.exited=!0,p.exitCode=typeof y=="number"?y:-1,p.eventBus.emit("exit")}),this.sessions.set(o,p),this.cleanupSessions();let d=typeof t.execution_timeout_ms=="number"&&t.execution_timeout_ms>0?Math.floor(t.execution_timeout_ms):null,m=ui(t.yield_time_ms,xd),g=d!==null?Math.min(m,Math.max(0,d)):m;if(await pi(p,g),d!==null&&!p.exited&&Date.now()-s>=d)throw await this.terminateForTimeout(p),this.cleanupSessions(),new Error(`command timed out after ${d}ms`);return this.buildResponseText(p,t.max_output_tokens)}async write(t){let n=this.sessions.get(t.session_id);if(!n)throw new Error(`session_id ${t.session_id} not found`);if(!n.exited&&t.chars&&t.chars.length>0){let o=Br(`${n.pendingStdinInput}${t.chars}`),{completedLines:s,remainder:i}=ii(o);for(let c of s){if(!c.trim())continue;let a=Hr({toolName:t.source_tool??"write_stdin",command:c,sessionId:n.id});if(a.blocked)return n.pendingStdinInput="",a.xml}n.pendingStdinInput=Br(i);try{let c=n.proc.stdin;c&&!c.destroyed&&!c.writableEnded&&c.write(t.chars)}catch{}}let r=ui(t.yield_time_ms,Md);return await pi(n,r),this.buildResponseText(n,t.max_output_tokens)}buildResponseText(t,n){let r=t.output.slice(t.readOffset),o=Rd(r,n);t.readOffset+=o.deliveredChars;let s={sessionId:t.id,chunkId:Pd(),wallTimeSeconds:(Date.now()-t.startedAtMs)/1e3,exitCode:t.exited?t.exitCode:null,output:o.output,originalTokenCount:o.originalTokenCount};return Id(s)}},mi=new Wr;async function vt(e){return mi.start(e)}async function fi(e){return mi.write(e)}var Od=He.object({command:He.array(He.string().min(1)).min(1,"command cannot be empty"),workdir:He.string().optional(),timeout_ms:He.number().int().positive().optional(),sandbox_permissions:He.enum(["use_default","require_escalated"]).optional(),justification:He.string().optional(),prefix_rule:He.array(He.string().min(1)).optional()}).strict(),Ld=/^[A-Za-z0-9_./:@%+-]+$/;function Nd(e){return e.length===0?"''":Ld.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`}function $d(e){return e.map(t=>Nd(t)).join(" ")}var gi=D({name:"shell",description:"Runs a shell command (argv form) and returns output.",inputSchema:Od,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,timeout_ms:n})=>{try{let r=await vt({cmd:$d(e),workdir:t,login:!1,yield_time_ms:n,execution_timeout_ms:n,source_tool:"shell"});return h(r)}catch(r){return h(`shell failed: ${r.message}`,!0)}}});import{z as Be}from"zod";var Dd=Be.object({command:Be.string().min(1,"command cannot be empty"),workdir:Be.string().optional(),login:Be.boolean().optional(),timeout_ms:Be.number().int().positive().optional(),sandbox_permissions:Be.enum(["use_default","require_escalated"]).optional(),justification:Be.string().optional(),prefix_rule:Be.array(Be.string().min(1)).optional()}).strict(),hi=D({name:"shell_command",description:"Runs a shell command and returns its output. Always set workdir when possible.",inputSchema:Dd,supportsParallelToolCalls:!0,isMutating:!0,execute:async({command:e,workdir:t,login:n,timeout_ms:r})=>{try{let o=await vt({cmd:e,workdir:t,login:n,yield_time_ms:r,execution_timeout_ms:r,source_tool:"shell_command"});return h(o)}catch(o){return h(`shell_command failed: ${o.message}`,!0)}}});import{z as Me}from"zod";var Ud=Me.object({cmd:Me.string().min(1,"cmd cannot be empty"),workdir:Me.string().optional(),shell:Me.string().optional(),login:Me.boolean().optional(),tty:Me.boolean().optional(),yield_time_ms:Me.number().int().nonnegative().optional(),max_output_tokens:Me.number().int().positive().optional(),sandbox_permissions:Me.enum(["use_default","require_escalated"]).optional(),justification:Me.string().optional(),prefix_rule:Me.array(Me.string().min(1)).optional()}).strict(),jr=D({name:"exec_command",description:"Runs a command in a PTY-like managed session, returning output or a session ID for ongoing interaction.",inputSchema:Ud,supportsParallelToolCalls:!0,isMutating:!0,execute:async e=>{try{let t=await vt({...e,source_tool:"exec_command"});return h(t)}catch(t){return h(`exec_command failed: ${t.message}`,!0)}}});import{z as zt}from"zod";var Fd=zt.object({session_id:zt.number().int().positive(),chars:zt.string().optional(),yield_time_ms:zt.number().int().nonnegative().optional(),max_output_tokens:zt.number().int().positive().optional()}).strict(),zr=D({name:"write_stdin",description:"Writes characters to an existing unified exec session and returns recent output.",inputSchema:Fd,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{try{let t=await fi({...e,source_tool:"write_stdin"});return h(t)}catch(t){return h(`write_stdin failed: ${t.message}`,!0)}}});import{access as gm,readFile as hm,realpath as ym,writeFile as _m}from"fs/promises";import{z as ge}from"zod";var pm=Yo(xi(),1);import{normalize as om,resolve as sm,dirname as Kv,join as im,relative as am,isAbsolute as cm}from"path";import{homedir as lm}from"os";import{existsSync as Xv,statSync as Jv,realpathSync as um}from"fs";import{readFile as Qv}from"fs/promises";function rm(e){let t=e?.trim();if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:Math.floor(n)}function xn(){return rm(process.env.MEMO_TOOL_RESULT_MAX_CHARS)??2e4}function Mi(){let e=xn(),t=Math.max(16,Math.floor(e*.25)),n=Math.max(32,e-t),r=Math.max(32,Math.floor(e*.6));return Math.min(12e3,r,n)}function je(e){return om(sm(e))}function Mn(e){let t=je(e);try{return je(um(t))}catch{return t}}function dm(e,t){let n=am(t,e);return n===""||!n.startsWith("..")&&!cm(n)}function mm(){let e=process.env.MEMO_SANDBOX_WRITABLE_ROOTS?.trim();return e?e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>Mn(t)):[]}function ki(){let e=new Set;e.add(Mn(Fe()));let t=process.env.MEMO_HOME?.trim()||im(lm(),".memo");e.add(Mn(t));for(let n of mm())e.add(n);return Array.from(e)}function fm(e){let t=Mn(e);return ki().some(r=>dm(t,r))}function Ai(e){if(fm(e))return null;let t=ki();return`sandbox write denied: ${e} is not within allowed directories (${t.join(", ")})`}var Sm=ge.object({old_string:ge.string().min(1,"old_string cannot be empty"),new_string:ge.string(),replace_all:ge.boolean().optional()}).strict(),Pi=ge.object({file_path:ge.string().min(1),old_string:ge.string().optional(),new_string:ge.string().optional(),replace_all:ge.boolean().optional(),edits:ge.array(Sm).min(1).optional()}).superRefine((e,t)=>{let n=!!(e.edits&&e.edits.length>0),r=e.old_string!==void 0||e.new_string!==void 0||e.replace_all!==void 0;if(n&&r){t.addIssue({code:ge.ZodIssueCode.custom,message:"Use either edits or old_string/new_string fields, not both."});return}if(!n){if(typeof e.old_string!="string"||typeof e.new_string!="string"){t.addIssue({code:ge.ZodIssueCode.custom,message:"Provide old_string/new_string, or use edits."});return}e.old_string.trim()||t.addIssue({code:ge.ZodIssueCode.custom,message:"old_string cannot be empty",path:["old_string"]});return}for(let o=0;o<(e.edits?.length??0);o+=1){let s=e.edits?.[o];s&&(s.old_string.trim()||t.addIssue({code:ge.ZodIssueCode.custom,message:"old_string cannot be empty",path:["edits",o,"old_string"]}))}}).strict();function vm(e){let t=Ai(e);if(t)throw new Error(t)}function Tm(e){return e.edits&&e.edits.length>0?e.edits:[{old_string:e.old_string??"",new_string:e.new_string??"",replace_all:e.replace_all}]}var Ei=D({name:"apply_patch",description:"Edit a local file by direct string replacement. Supports single replacement fields or batch edits.",inputSchema:Pi,supportsParallelToolCalls:!1,isMutating:!0,execute:async e=>{let t=Pi.safeParse(e);if(!t.success){let o=t.error.issues[0]?.message??"invalid input";return h(`apply_patch invalid input: ${o}`,!0)}let n=t.data,r=je(n.file_path);try{await gm(r);let o=je(await ym(r));vm(o);let s=await hm(o,"utf8"),i=Tm(e),c=s,a=0;for(let l=0;l<i.length;l+=1){let p=i[l];if(!p)continue;let u=p.old_string,d=p.replace_all??!1;if(!c.includes(u))return i.length===1?h("apply_patch failed: target text not found.",!0):h(`apply_patch failed: target text not found at edit ${l+1}.`,!0);if(d){let m=c.split(u),g=m.length-1;c=m.join(p.new_string),a+=g}else c=c.replace(u,p.new_string),a+=1}return c===s?h("No changes made."):(await _m(o,c,"utf8"),h(`Success. Updated file: ${o}
|
|
52
|
+
Edits: ${i.length}
|
|
53
|
+
Replacements: ${a}`))}catch(o){return o.code==="ENOENT"?h(`apply_patch failed: file does not exist: ${r}`,!0):h(`apply_patch failed: ${o.message}`,!0)}}});import{readFile as wm}from"fs/promises";import{z as Oe}from"zod";var Ri=500,Ii=200,Cm=Oe.object({file_path:Oe.string().min(1),offset:Oe.number().int().positive().optional(),limit:Oe.number().int().positive().optional(),mode:Oe.enum(["slice","indentation"]).optional(),indentation:Oe.object({anchor_line:Oe.number().int().positive().optional(),max_levels:Oe.number().int().nonnegative().optional(),include_siblings:Oe.boolean().optional(),include_header:Oe.boolean().optional(),max_lines:Oe.number().int().positive().optional()}).strict().optional()}).strict();function bm(e){return e.length<=Ri?e:e.slice(0,Ri)}function xm(e){let t=0;for(let n of e)if(n===" ")t+=1;else if(n===" ")t+=4;else break;return t}function Mm(e){return e.split(/\r?\n/).map((n,r)=>({line:r+1,text:bm(n),indent:xm(n)}))}function km(e){return e.map(t=>`L${t.line}: ${t.text}`).join(`
|
|
54
|
+
`)}function Am(e,t,n){let r=t-1;if(r>=e.length)throw new Error("offset exceeds file length");return e.slice(r,r+n)}function Pm(e,t){let n=t.offset??1,r=t.limit??Ii,o=t.indentation,s=o?.anchor_line??n;if(s<=0||s>e.length)throw new Error("anchor_line exceeds file length");let i=e[s-1];if(!i)throw new Error("anchor_line exceeds file length");let c=o?.max_levels??0,a=o?.include_siblings??!0,l=o?.include_header??!0,p=o?.max_lines??r,u=Math.max(1,Math.min(r,p)),d=c===0?0:Math.max(0,i.indent-c*4),m=s-1,g=s-1;for(;m-1>=0;){let y=e[m-1];if(!y)break;let b=/^\s*(#|\/\/|--)/.test(y.text),U=y.text.trim().length===0;if(y.indent<d||!a&&y.indent===d&&!b&&!U||!l&&(b||U)&&y.indent<i.indent||(m-=1,g-m+1>=u))break}for(;g+1<e.length&&g-m+1<u;){let y=e[g+1];if(!y||y.indent<d||!a&&y.indent===d)break;g+=1}return e.slice(m,g+1)}var Oi=D({name:"read_file",description:"Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes.",inputSchema:Cm,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??1,n=e.limit??Ii;if(t<=0)return h("offset must be a 1-indexed line number",!0);if(n<=0)return h("limit must be greater than zero",!0);let r=e.file_path.trim();if(!r.startsWith("/"))return h("file_path must be an absolute path",!0);let o=je(r);try{let s=await wm(o,"utf8"),i=Mm(s);if(i.length===0)return h("");let a=(e.mode??"slice")==="indentation"?Pm(i,e):Am(i,t,n);return h(km(a))}catch(s){return h(`read_file failed: ${s.message}`,!0)}}});import{readdir as Em,lstat as Rm}from"fs/promises";import{join as Im}from"path";import{z as Gt}from"zod";var Om=1,Lm=25,Nm=2,$m=Gt.object({dir_path:Gt.string().min(1),offset:Gt.number().int().positive().optional(),limit:Gt.number().int().positive().optional(),depth:Gt.number().int().positive().optional()}).strict();function Dm(e){let t=" ".repeat(e.displayDepth*2),n="";e.kind==="dir"&&(n="/"),e.kind==="symlink"&&(n="@"),e.kind==="other"&&(n="?");let r=e.path.split("/"),o=r[r.length-1]??e.path;return`${t}${o}${n}`}var Li=D({name:"list_dir",description:"Lists entries in a local directory with 1-indexed entry numbers and simple type labels.",inputSchema:$m,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.offset??Om,n=e.limit??Lm,r=e.depth??Nm;if(t<=0)return h("offset must be a 1-indexed entry number",!0);if(n<=0)return h("limit must be greater than zero",!0);if(r<=0)return h("depth must be greater than zero",!0);let o=e.dir_path.trim();if(!o.startsWith("/"))return h("dir_path must be an absolute path",!0);let s=je(o);try{let i=[{absPath:s,depth:r,displayDepth:0}],c=[];for(;i.length>0;){let u=i.shift();if(!u)continue;let d=await Em(u.absPath);d.sort((m,g)=>m.localeCompare(g));for(let m of d){let g=Im(u.absPath,m),y=await Rm(g),b=y.isSymbolicLink()?"symlink":y.isDirectory()?"dir":y.isFile()?"file":"other";c.push({path:g,displayDepth:u.displayDepth,kind:b}),b==="dir"&&u.depth>1&&i.push({absPath:g,depth:u.depth-1,displayDepth:u.displayDepth+1})}}if(c.length===0)return h(`Absolute path: ${s}`);let a=t-1;if(a>=c.length)return h("offset exceeds directory entry count",!0);let l=c.slice(a,a+n),p=[`Absolute path: ${s}`,...l.map(Dm)];return a+n<c.length&&p.push(`More than ${n} entries found`),h(p.join(`
|
|
55
|
+
`))}catch(i){return h(`list_dir failed: ${i.message}`,!0)}}});import{spawn as Um}from"child_process";import{resolve as Fm}from"path";import{z as Kt}from"zod";var Hm=100,Bm=2e3,Wm=3e4,jm=Kt.object({pattern:Kt.string().min(1),include:Kt.string().optional(),path:Kt.string().optional(),limit:Kt.number().int().positive().optional()}).strict();function zm(e){return new Promise((t,n)=>{let r=["--files-with-matches","--sortr=modified","--regexp",e.pattern,"--max-count","1","--no-messages"];e.include?.trim()&&r.push("--glob",e.include.trim()),r.push("--",e.searchPath);let o=Um("rg",r,{cwd:e.cwd,stdio:["ignore","pipe","pipe"]}),s=[],i=[];o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",g=>s.push(g)),o.stderr?.on("data",g=>i.push(g));let c=!1,a=null,l=!1,p=()=>{clearTimeout(m),a&&(clearTimeout(a),a=null)},u=g=>{l||(l=!0,p(),n(g))},d=g=>{l||(l=!0,p(),t(g))},m=setTimeout(()=>{c=!0;try{o.kill("SIGTERM")}catch{}a=setTimeout(()=>{if(o.exitCode===null)try{o.kill("SIGKILL")}catch{}},500),a.unref?.()},Wm);m.unref?.(),o.on("error",g=>{u(g)}),o.on("close",g=>{if(c){u(new Error("rg timed out after 30 seconds"));return}d({exitCode:typeof g=="number"?g:-1,stdout:s.join(""),stderr:i.join("")})})})}var Ni=D({name:"grep_files",description:"Finds files whose contents match the pattern and lists them by modification time.",inputSchema:jm,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t=e.pattern.trim();if(!t)return h("pattern must not be empty",!0);let n=Math.min(e.limit??Hm,Bm),r=Fe(),o=e.path?.trim()?Fm(r,e.path.trim()):r;try{let s=await zm({pattern:t,include:e.include,searchPath:o,cwd:r,limit:n});if(s.exitCode===1)return h("No matches found.");if(s.exitCode!==0)return h(`rg failed: ${s.stderr||s.stdout}`,!0);let i=s.stdout.split(/\r?\n/).map(c=>c.trim()).filter(Boolean).slice(0,n);return i.length===0?h("No matches found."):h(i.join(`
|
|
56
|
+
`))}catch(s){return h(`grep_files failed: ${s.message}`,!0)}}});import{z as ze}from"zod";import{createHash as Gm}from"crypto";import{mkdir as Km,readFile as qm,rename as Vm,writeFile as Xm}from"fs/promises";import{homedir as Zr}from"os";import{dirname as Jm,join as no}from"path";var Ym="mcp.json",An=2,Qm=120,Zm=600*1e3,$i=1440*60*1e3;function Yr(){return process.env.MEMO_FORCE_MCP_DISK_CACHE==="1"?!0:!(process.env.MEMO_FORCE_MCP_DISK_CACHE==="0"||process.env.NODE_ENV==="test"||typeof process.env.VITEST<"u"||typeof process.env.VITEST_WORKER_ID<"u")}function ef(e){return e==="~"?Zr():e.startsWith("~/")?no(Zr(),e.slice(2)):e}function tf(){let e=process.env.MEMO_HOME?.trim();return e?ef(e):no(Zr(),".memo")}function Di(){return no(tf(),"cache",Ym)}function eo(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>eo(r)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${eo(t[r])}`).join(",")}}`}function Ui(e){return Gm("sha256").update(eo(e)).digest("hex")}function nf(e){return e instanceof Error?e.message:String(e)}function kn(){return{version:An,toolsByServer:{},responses:{}}}var to=class{data=kn();loaded=!1;loadPromise=null;persistTimer=null;persistRunning=!1;persistRequested=!1;responseInflight=new Map;pruneExpiredResponses(t=Date.now()){for(let[n,r]of Object.entries(this.data.responses))r.expiresAt<=t&&delete this.data.responses[n]}pruneExpiredTools(t=Date.now()){for(let[n,r]of Object.entries(this.data.toolsByServer))t-r.fetchedAt>$i&&delete this.data.toolsByServer[n]}async ensureLoaded(){if(!Yr()){this.loaded=!0;return}if(!this.loaded){if(this.loadPromise){await this.loadPromise;return}this.loadPromise=(async()=>{let t=Di();try{let n=await qm(t,"utf8"),r=JSON.parse(n);if(r.version===An){let o=r;this.data={version:An,toolsByServer:o.toolsByServer??{},responses:o.responses??{}}}else r.version===1&&r.entries?this.data={version:An,toolsByServer:{},responses:r.entries}:this.data=kn()}catch{this.data=kn()}finally{this.pruneExpiredResponses(),this.pruneExpiredTools(),this.loaded=!0}})(),await this.loadPromise}}async persistToDisk(){if(!Yr())return;this.pruneExpiredResponses(),this.pruneExpiredTools();let t=Di(),n=`${t}.tmp`,r=Jm(t);await Km(r,{recursive:!0}),await Xm(n,JSON.stringify(this.data,null,2),"utf8"),await Vm(n,t)}async flushPersistQueue(){if(!(!this.persistRequested||this.persistRunning)){this.persistRequested=!1,this.persistRunning=!0;try{await this.persistToDisk()}catch{}finally{this.persistRunning=!1,this.persistRequested&&this.flushPersistQueue()}}}schedulePersist(){Yr()&&(this.persistRequested=!0,!this.persistTimer&&(this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersistQueue()},Qm),this.persistTimer.unref?.()))}async getServerTools(t,n){await this.ensureLoaded();let r=this.data.toolsByServer[t];if(!r)return null;if(r.configHash!==Ui(n))return delete this.data.toolsByServer[t],this.schedulePersist(),null;let o=Date.now()-r.fetchedAt;return o>$i?(delete this.data.toolsByServer[t],this.schedulePersist(),null):{tools:r.tools,stale:o>Zm,ageMs:o}}async setServerTools(t,n,r){await this.ensureLoaded(),this.data.toolsByServer[t]={fetchedAt:Date.now(),configHash:Ui(n),tools:r},this.schedulePersist()}async withResponseCache(t,n,r){await this.ensureLoaded();let o=this.data.responses[t];if(o&&o.expiresAt>Date.now())return o.value;o&&o.expiresAt<=Date.now()&&delete this.data.responses[t];let s=this.responseInflight.get(t);if(s)return await s;let i=(async()=>{let c=await r();return this.data.responses[t]={expiresAt:Date.now()+n,value:c},this.schedulePersist(),c})();this.responseInflight.set(t,i);try{return await i}catch(c){throw new Error(nf(c))}finally{this.responseInflight.delete(t)}}async flushForTests(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.persistRequested=!0,await this.flushPersistQueue()}resetForTests(){this.data=kn(),this.loaded=!1,this.loadPromise=null,this.responseInflight.clear(),this.persistRequested=!1,this.persistRunning=!1,this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null)}},Qr=null;function Pn(){return Qr||(Qr=new to),Qr}var Fi=null,Hi=null;function ro(e){Fi=e}function Bi(){return Fi}function oo(e){Hi=e}function Wi(){return Hi}var rf=ze.object({server:ze.string().optional(),cursor:ze.string().optional()}).strict(),of=ze.object({server:ze.string().optional(),cursor:ze.string().optional()}).strict(),sf=ze.object({server:ze.string().min(1),uri:ze.string().min(1)}).strict(),En=15e3,af=6e4;function so(){let e=Bi();if(!e)throw new Error("MCP pool is not initialized");return e}function io(){return Wi()??Pn()}function Gi(e){return e instanceof Error?e.message:String(e)}function ji(e,t){return`list_resources:${e}:${t??""}`}function zi(e,t){return`list_resource_templates:${e}:${t??""}`}function cf(e,t){return`read_resource:${e}:${t}`}function ao(e,t){return typeof e.hasServer=="function"?e.hasServer(t):typeof e.get=="function"?!!e.get(t):!1}async function co(e,t){if(typeof e.get=="function"){let n=e.get(t);if(n)return n}if(typeof e.connect=="function")return e.connect(t)}async function Ki(e){if(typeof e.getKnownServerNames=="function"&&typeof e.connect=="function"){let n=e.getKnownServerNames().sort((s,i)=>s.localeCompare(i)),r=await Promise.allSettled(n.map(s=>e.connect(s))),o=[];return r.forEach((s,i)=>{if(s.status==="fulfilled"){o.push(s.value);return}let c=n[i];c&&o.push({name:c,client:null,__error:s.reason})}),o.sort((s,i)=>s.name.localeCompare(i.name))}return(typeof e.getAll=="function"?e.getAll():[]).sort((n,r)=>n.name.localeCompare(r.name))}var qi=D({name:"list_mcp_resources",description:"Lists resources provided by MCP servers. Prefer resources over web search when possible.",inputSchema:rf,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=so(),r=io(),o=e?.trim();if(o){if(!ao(n,o))return h(`MCP server not found: ${e}`,!0);let a=await co(n,o);if(!a)return h(`MCP server not found: ${e}`,!0);let l=await r.withResponseCache(ji(a.name,t),En,async()=>{let p=await a.client.listResources(t?{cursor:t}:void 0);return{server:a.name,resources:p.resources,nextCursor:p.nextCursor}});return h(JSON.stringify(l,null,2))}if(t)return h("cursor is only supported when server is specified",!0);let s=await Ki(n),i=`all:${s.map(a=>a.name).join(",")}`,c=await r.withResponseCache(ji(i),En,async()=>{let a=await Promise.allSettled(s.map(async u=>{if(!u.client)throw new Error(`MCP server '${u.name}' is not connected`);return{server:u.name,result:await u.client.listResources()}})),l=[],p=[];return a.forEach((u,d)=>{let m=s[d]?.name??"unknown";if(u.status==="rejected"){p.push({server:m,error:Gi(u.reason)});return}for(let g of u.value.result.resources)l.push({server:u.value.server,...g})}),{resources:l,...p.length>0?{errors:p}:{}}});return h(JSON.stringify(c,null,2))}catch(n){return h(`list_mcp_resources failed: ${n.message}`,!0)}}}),Vi=D({name:"list_mcp_resource_templates",description:"Lists resource templates provided by MCP servers. Prefer resource templates over web search when possible.",inputSchema:of,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,cursor:t})=>{try{let n=so(),r=io(),o=e?.trim();if(o){if(!ao(n,o))return h(`MCP server not found: ${e}`,!0);let a=await co(n,o);if(!a)return h(`MCP server not found: ${e}`,!0);let l=await r.withResponseCache(zi(a.name,t),En,async()=>{let p=await a.client.listResourceTemplates(t?{cursor:t}:void 0);return{server:a.name,resourceTemplates:p.resourceTemplates,nextCursor:p.nextCursor}});return h(JSON.stringify(l,null,2))}if(t)return h("cursor is only supported when server is specified",!0);let s=await Ki(n),i=`all:${s.map(a=>a.name).join(",")}`,c=await r.withResponseCache(zi(i),En,async()=>{let a=await Promise.allSettled(s.map(async u=>{if(!u.client)throw new Error(`MCP server '${u.name}' is not connected`);return{server:u.name,result:await u.client.listResourceTemplates()}})),l=[],p=[];return a.forEach((u,d)=>{let m=s[d]?.name??"unknown";if(u.status==="rejected"){p.push({server:m,error:Gi(u.reason)});return}for(let g of u.value.result.resourceTemplates)l.push({server:u.value.server,...g})}),{resourceTemplates:l,...p.length>0?{errors:p}:{}}});return h(JSON.stringify(c,null,2))}catch(n){return h(`list_mcp_resource_templates failed: ${n.message}`,!0)}}}),Xi=D({name:"read_mcp_resource",description:"Read a specific resource from an MCP server given the server name and resource URI.",inputSchema:sf,supportsParallelToolCalls:!0,isMutating:!1,execute:async({server:e,uri:t})=>{try{let n=so(),r=io(),o=e.trim();if(!ao(n,o))return h(`MCP server not found: ${e}`,!0);let s=await co(n,o);if(!s)return h(`MCP server not found: ${e}`,!0);let i=await r.withResponseCache(cf(o,t),af,async()=>{let c=await s.client.readResource({uri:t});return{server:o,uri:t,...c}});return h(JSON.stringify(i,null,2))}catch(n){return h(`read_mcp_resource failed: ${n.message}`,!0)}}});import{z as Tt}from"zod";var lf=Tt.object({step:Tt.string().min(1),status:Tt.enum(["pending","in_progress","completed"])}).strict(),uf=Tt.object({explanation:Tt.string().optional(),plan:Tt.array(lf).min(1)}).strict(),Ji=[],Yi=D({name:"update_plan",description:"Updates the task plan. At most one step can be in_progress at a time.",inputSchema:uf,supportsParallelToolCalls:!1,isMutating:!1,execute:async({explanation:e,plan:t})=>{if(t.filter(r=>r.status==="in_progress").length>1)return h("At most one step can be in_progress at a time",!0);if(t.length<4){let r=t[0]?.step??"";return h(`<system_hint tool="update_plan" reason="simple_task">Task "${r}" is simple (${t.length} step${t.length>1?"s":""}) - execute directly without update_plan.</system_hint>`)}return Ji=t,h(JSON.stringify({message:"Plan updated",explanation:e,plan:Ji},null,2))}});import{readFile as pf}from"fs/promises";import{homedir as df}from"os";import{join as Qi}from"path";import{z as Zi}from"zod";var mf=Zi.object({memory_id:Zi.string().min(1)}).strict();function ff(){let e=process.env.MEMO_HOME?.trim()||Qi(df(),".memo");return Qi(e,"Agents.md")}var ea=D({name:"get_memory",description:"Loads the stored memory payload for a memory_id.",inputSchema:mf,supportsParallelToolCalls:!0,isMutating:!1,execute:async({memory_id:e})=>{try{let t=ff(),n=await pf(t,"utf8");return h(JSON.stringify({memory_id:e,memory_summary:n},null,2))}catch{return h(`memory not found for memory_id=${e}`,!0)}}});import{z as ta}from"zod";var gf=ta.object({url:ta.string().min(1)}).strict(),na=1e4,qt=512e3,hf=new Set(["http:","https:"]),yf=/<\/\s*(p|div|section|article|header|footer|aside|main|h[1-6]|li|tr|table|blockquote)\s*>/gi,_f=/<\s*(br|hr)\s*\/?>/gi,Sf=/<\s*li[^>]*>/gi,vf=/<[^>]+>/g,Tf=/<(script|style)[^>]*>[\s\S]*?<\/\s*\1>/gi,wf=e=>e.replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/g,"'").replace(/&#(x?[0-9a-fA-F]+);/g,(r,o)=>{try{let s=o.startsWith("x")||o.startsWith("X")?parseInt(o.slice(1),16):parseInt(o,10);return Number.isFinite(s)?String.fromCharCode(s):""}catch{return""}}),Cf=e=>{let r=e.replace(Tf," ").replace(Sf,"- ").replace(_f,`
|
|
57
|
+
`).replace(yf,`
|
|
58
|
+
`).replace(vf," "),s=wf(r).replace(/\r/g,"").split(`
|
|
59
|
+
`).map(c=>c.trim().replace(/[ \t]{2,}/g," "));return s.filter((c,a)=>c.length>0||a>0&&(s[a-1]?.length??0)>0).join(`
|
|
60
|
+
`).trim()},bf=e=>e.replace(/\s+/g," ").trim(),ra=D({name:"webfetch",description:"HTTP GET request, returns processed plain text body (automatically strips HTML tags)",inputSchema:gf,supportsParallelToolCalls:!0,isMutating:!1,execute:async e=>{let t;try{t=new URL(e.url)}catch{return h(`Invalid URL: ${e.url}`,!0)}if(!hf.has(t.protocol))return h(`Unsupported protocol: ${t.protocol}`,!0);let n=new AbortController,r=setTimeout(()=>n.abort(),na);try{let o=await globalThis.fetch(t,{signal:n.signal}),s=o.headers.get("content-length"),i=s?Number(s):void 0;if(i&&i>qt)return h(`Request rejected: response body too large (${i} bytes)`,!0);let c=0,a="";if(o.body&&o.body.getReader){let U=o.body.getReader(),T=[];for(;;){let{done:I,value:G}=await U.read();if(I)break;if(G){if(c+=G.byteLength,c>qt)return n.abort(),h(`Request aborted: response body exceeds ${qt} bytes`,!0);T.push(G)}}let H=new Uint8Array(c),R=0;for(let I of T)H.set(I,R),R+=I.byteLength;a=new TextDecoder().decode(H)}else if(a=await o.text(),c=new TextEncoder().encode(a).byteLength,c>qt)return h(`Request rejected: response body exceeds ${qt} bytes`,!0);let l=o.headers.get("content-type")||"",p=/text\/html/i.test(l)||/^\s*<!doctype html/i.test(a)||/^\s*<html[\s>]/i.test(a),u=p?Cf(a):a.trim(),d=bf(u),m=Mi(),g=d.length>m?`${d.slice(0,m)}...`:d,y=d.length>m?" text_truncated=true":"",b=p?" source=html_stripped":"";return h(`status=${o.status} bytes=${c} text_chars=${d.length} text="${g}"${y}${b}`)}catch(o){return o.name==="AbortError"?h(`Request timeout or aborted (${na}ms)`,!0):h(`Request failed: ${o.message}`,!0)}finally{clearTimeout(r)}}});import{spawn as xf}from"child_process";import{existsSync as Mf}from"fs";import{resolve as kf}from"path";import{z as me}from"zod";var Af=3e4,Pf=1e4,Ef=3e5,oa=4,Rf=1500,sa=2e3,Xe=new Map,If=me.object({message:me.string().min(1),agent_type:me.string().optional()}).strict(),Of=me.object({id:me.string().min(1),message:me.string().min(1),interrupt:me.boolean().optional()}).strict(),Lf=me.object({id:me.string().min(1)}).strict(),Nf=me.object({ids:me.array(me.string().min(1)).min(1),timeout_ms:me.number().int().positive().optional()}).strict(),$f=me.object({id:me.string().min(1)}).strict();function wt(){return new Date().toISOString()}function lo(e){return h(`agent not found: ${e}`,!0)}function Df(){let e=process.env.MEMO_SUBAGENT_MAX_AGENTS?.trim();if(!e)return oa;let t=Number(e);return!Number.isFinite(t)||t<=0?oa:Math.floor(t)}function Uf(){let e=0;for(let t of Xe.values())t.running&&(e+=1);return e}function Ff(){let e=process.env.MEMO_SUBAGENT_COMMAND?.trim();if(e)return e;let t=kf(Fe(),"dist/index.js");return Mf(t)?`node ${JSON.stringify(t)} --dangerous`:"memo --dangerous"}function Hf(e){return e!=="running"}function Bf(e){return new Promise(t=>{setTimeout(t,e)})}function Wf(e){return e===void 0?Af:e<=0?null:Math.max(Pf,Math.min(Ef,e))}function jf(e){return e.length<=sa?e:`${e.slice(0,sa)}
|
|
61
|
+
...[truncated]`}function zf(e,t){let n=[],r=e.trim(),o=t.trim();return r&&n.push(r),o&&n.push(`stderr:
|
|
62
|
+
${o}`),jf(n.join(`
|
|
63
|
+
|
|
64
|
+
`))}async function ia(e){let t=e.running;if(!t)return;t.interrupted=!0;let n=t.process;n.exitCode!==null||n.killed||await new Promise(r=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(i),n.off("close",s),r())},i=setTimeout(()=>{if(n.exitCode===null)try{n.kill("SIGKILL")}catch{s()}},Rf);n.on("close",s);try{n.kill("SIGTERM")}catch{s()}})}function Gf(e){let t=Xe.get(e);return t?t.status:"not_found"}function Kf(e){let t=Xe.get(e);return t?{status:t.status,last_message:t.lastMessage,last_output:t.lastOutput,last_error:t.lastError,last_submission_id:t.lastSubmissionId,updated_at:t.updatedAt}:{status:"not_found",last_message:null,last_output:null,last_error:null,last_submission_id:null,updated_at:null}}function qf(e){return{agent_id:e.id,status:e.status,created_at:e.createdAt,updated_at:e.updatedAt,last_message:e.lastMessage,last_submission_id:e.lastSubmissionId,has_last_output:!!e.lastOutput,has_last_error:!!e.lastError}}function Vf(e){let{record:t,submissionId:n,stdout:r,stderr:o,exitCode:s,interrupted:i}=e;if(!(!t.running||t.running.id!==n)&&(t.running=null,t.updatedAt=wt(),t.lastOutput=zf(r,o)||null,t.lastError=null,t.status!=="closed")){if(i){t.status="errored",t.lastError="interrupted",t.statusBeforeClose="errored";return}if(s===0){t.status="completed",t.statusBeforeClose="completed";return}t.status="errored",t.lastError=`submission failed with exit code ${s}`,t.statusBeforeClose="errored"}}async function aa(e,t){let n=Df();if(Uf()>=n)throw new Error(`subagent concurrency limit reached (${n})`);let r=crypto.randomUUID(),o=Ff(),s=xf(o,{cwd:Fe(),env:{...process.env},shell:!0,stdio:["pipe","pipe","pipe"]}),i=[],c=[];s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",a=>i.push(a)),s.stderr?.on("data",a=>c.push(a)),s.on("error",a=>{c.push(`[spawn error] ${a.message}`)}),e.running={id:r,message:t,process:s,startedAt:wt(),interrupted:!1},e.status="running",e.lastMessage=t,e.lastSubmissionId=r,e.updatedAt=wt(),s.on("close",a=>{let l=typeof a=="number"?a:-1,p=!!(e.running?.id===r&&e.running.interrupted);Vf({record:e,submissionId:r,stdout:i.join(""),stderr:c.join(""),exitCode:l,interrupted:p})});try{s.stdin?.write(`${t.trim()}
|
|
65
|
+
`)}catch{}try{s.stdin?.end()}catch{}return r}var ca=D({name:"spawn_agent",description:"Spawn a sub-agent for a well-scoped task and return the agent id.",inputSchema:If,supportsParallelToolCalls:!1,isMutating:!0,execute:async({message:e})=>{let t=e.trim();if(!t)return h("spawn_agent failed: message must not be empty",!0);let n=crypto.randomUUID(),r=wt(),o={id:n,createdAt:r,updatedAt:r,status:"running",statusBeforeClose:"completed",lastMessage:t,lastSubmissionId:null,lastOutput:null,lastError:null,running:null};Xe.set(n,o);try{let s=await aa(o,t);return h(JSON.stringify({...qf(o),submission_id:s},null,2))}catch(s){return Xe.delete(n),h(`spawn_agent failed: ${s.message}`,!0)}}}),la=D({name:"send_input",description:"Send a message to an existing agent.",inputSchema:Of,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e,message:t,interrupt:n})=>{let r=Xe.get(e);if(!r)return lo(e);let o=t.trim();if(!o)return h("send_input failed: message must not be empty",!0);if(r.status==="closed")return h(`send_input failed: agent ${e} is closed; run resume_agent first`,!0);if(r.running){if(!n)return h(`send_input failed: agent ${e} is busy; set interrupt=true to cancel current submission`,!0);await ia(r)}try{let s=await aa(r,o);return h(JSON.stringify({agent_id:r.id,status:r.status,submission_id:s},null,2))}catch(s){return h(`send_input failed: ${s.message}`,!0)}}}),ua=D({name:"resume_agent",description:"Resume a previously closed agent by id.",inputSchema:Lf,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=Xe.get(e);return t?(t.status==="closed"&&(t.status=t.statusBeforeClose,t.updatedAt=wt()),h(JSON.stringify({agent_id:e,status:t.status},null,2))):lo(e)}}),pa=D({name:"wait",description:"Wait for agent statuses and return current snapshots.",inputSchema:Nf,supportsParallelToolCalls:!1,isMutating:!1,execute:async({ids:e,timeout_ms:t})=>{let n=Wf(t);if(n===null)return h("wait failed: timeout_ms must be greater than zero",!0);let r=()=>{let i={},c={};for(let a of e){let l=Gf(a);Hf(l)&&(i[a]=l,c[a]=Kf(a))}return{status:i,details:c}},o=r();if(Object.keys(o.status).length>0)return h(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));let s=Date.now()+n;for(;Date.now()<s;)if(await Bf(100),o=r(),Object.keys(o.status).length>0)return h(JSON.stringify({status:o.status,details:o.details,timed_out:!1},null,2));return h(JSON.stringify({status:{},details:{},timed_out:!0},null,2))}}),da=D({name:"close_agent",description:"Close an agent and return its last known status.",inputSchema:$f,supportsParallelToolCalls:!1,isMutating:!0,execute:async({id:e})=>{let t=Xe.get(e);return t?t.status==="closed"?h(JSON.stringify({agent_id:e,status:"closed"},null,2)):(t.statusBeforeClose=t.running?"completed":t.status,t.status="closed",t.updatedAt=wt(),await ia(t),h(JSON.stringify({agent_id:e,status:"closed"},null,2))):lo(e)}});var uo={list_mcp_resources:"read",list_mcp_resource_templates:"read",read_mcp_resource:"read",update_plan:"read",get_memory:"read",webfetch:"read",read_file:"read",list_dir:"read",grep_files:"read",wait:"read",spawn_agent:"read",send_input:"read",resume_agent:"read",close_agent:"read",apply_patch:"write",shell:"execute",shell_command:"execute",exec_command:"execute",write_stdin:"execute"},ma=new Set(["spawn_agent","send_input","resume_agent","wait","close_agent"]),Rn={read:0,write:1,execute:2},fa=["exec","run","shell","command","stdin"],ga=["write","patch","create","delete","modify","update"],ha=["read","get","fetch","search","list","find"],ya=new Set(["write","execute"]);function mo(e){let t={...uo,...e?.customLevels};return{getRiskLevel(n){if(n in t)return t[n];let r=n.toLowerCase();return po(r,fa)?"execute":po(r,ga)?"write":po(r,ha)?"read":"write"},compareRisk(n,r){return Rn[n]-Rn[r]},needsApproval(n,r){return r==="strict"?!0:ya.has(n)}}}function po(e,t){return t.some(n=>e.includes(n))}import{createHash as Xf}from"crypto";function In(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>In(n)).join(",")+"]":`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${In(r)}`).join(",")}}`}function fo(e,t){let n=In(t),r=`${e}:${n}`;return Xf("sha256").update(r).digest("hex").slice(0,16)}function Jf(e){return`Tool "${e}" requires approval.`}function go(e){let{mode:t="auto",dangerous:n=!1,toolRiskLevels:r}=e||{},o=t==="strict"?"strict":"auto";if(n)return{isDangerousMode:!0,getRiskLevel:()=>"read",check:()=>({needApproval:!1,decision:"auto-execute"}),recordDecision:()=>{},isGranted:()=>!0,clearOnceApprovals:()=>{},dispose:()=>{}};let s=mo({customLevels:r}),i={sessionTools:new Set,onceTools:new Set,deniedTools:new Set,toolByFingerprint:new Map};return{get isDangerousMode(){return!1},getRiskLevel(c){return s.getRiskLevel(c)},check(c,a){if(ma.has(c))return{needApproval:!1,decision:"auto-execute"};let l=s.getRiskLevel(c);if(!s.needsApproval(l,o))return{needApproval:!1,decision:"auto-execute"};let p=fo(c,a);return i.toolByFingerprint.set(p,c),i.sessionTools.has(c)||i.onceTools.has(c)?{needApproval:!1,decision:"auto-execute"}:i.deniedTools.has(c)?{needApproval:!0,fingerprint:p,riskLevel:l,reason:"This request was previously denied.",toolName:c,params:a}:{needApproval:!0,fingerprint:p,riskLevel:l,reason:Jf(c),toolName:c,params:a}},recordDecision(c,a){let l=i.toolByFingerprint.get(c);if(l)switch(i.sessionTools.delete(l),i.onceTools.delete(l),i.deniedTools.delete(l),a){case"session":i.sessionTools.add(l);break;case"once":i.onceTools.add(l);break;case"deny":i.deniedTools.add(l);break}},isGranted(c){let a=i.toolByFingerprint.get(c);return a?i.sessionTools.has(a)||i.onceTools.has(a):!1},clearOnceApprovals(){i.onceTools.clear()},dispose(){i.sessionTools.clear(),i.onceTools.clear(),i.deniedTools.clear(),i.toolByFingerprint.clear()}}}var _a=1e5;function Yf(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Qf(e){let t=0;for(let n of e.content??[]){if(n.type==="text"){t+=n.text.length;continue}try{t+=JSON.stringify(n).length}catch{t+=100}}return t}function Zf(e,t,n){return`<system_hint type="tool_output_omitted" tool="${Yf(e)}" reason="too_long" actual_chars="${t}" max_chars="${n}">Tool output too long, automatically omitted. Please narrow the scope or add limit parameters and try again.</system_hint>`}function eg(e,t){let n=xn(),r=Qf(t);return r<=n?t:{content:[{type:"text",text:Zf(e,r,n)}],isError:!1}}function tg(e){return(e.content?.flatMap(n=>n.type==="text"?[n.text]:[])??[]).join(`
|
|
66
|
+
`)}function Sa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ng(e,t){let n=t;if(typeof t=="string"){if(t.length>_a)return{ok:!1,error:`${e.name} invalid input: input string too large (max ${_a} chars)`};let r=t.trim();if(r)try{n=JSON.parse(r)}catch{n=r}else n={}}if(!Sa(n))return{ok:!1,error:`${e.name} invalid input: expected object`};if(typeof e.validateInput=="function"){let r=e.validateInput(n);return r.ok?Sa(r.data)?{ok:!0,data:r.data}:{ok:!1,error:`${e.name} invalid input: expected object`}:r}return{ok:!0,data:n}}function rg(e){let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();return t.includes("sandbox")||t.includes("permission denied")||t.includes("operation not permitted")||t.includes("eacces")?"sandbox_denied":"execution_failed"}var ho=class{constructor(t){this.config=t;this.approvalManager=go(t.approval)}approvalManager;async executeAction(t,n){let r=Date.now(),o=t.id??`${t.name}:${r}`,s=this.approvalManager.check(t.name,t.input);if(s.needApproval){let c={toolName:s.toolName,params:s.params,fingerprint:s.fingerprint,riskLevel:s.riskLevel,reason:s.reason};await n?.onApprovalRequest?.(c);let a=n?.requestApproval?await n.requestApproval(c):"deny";if(this.approvalManager.recordDecision(s.fingerprint,a),await n?.onApprovalResponse?.({fingerprint:s.fingerprint,decision:a}),a==="deny")return{actionId:o,tool:t.name,status:"approval_denied",errorType:"approval_denied",success:!1,observation:`User denied tool execution: ${t.name}`,durationMs:Date.now()-r,rejected:!0}}let i=this.config.tools[t.name];if(!i)return{actionId:o,tool:t.name,status:"tool_not_found",errorType:"tool_not_found",success:!1,observation:`Unknown tool: ${t.name}`,durationMs:Date.now()-r};try{let c=ng(i,t.input);if(!c.ok)return{actionId:o,tool:t.name,status:"input_invalid",errorType:"input_invalid",success:!1,observation:c.error,durationMs:Date.now()-r};let a=await i.execute(c.data),l=eg(t.name,a);return{actionId:o,tool:t.name,status:"success",success:!0,observation:tg(l)||"(no tool output)",durationMs:Date.now()-r}}catch(c){let a=rg(c);return{actionId:o,tool:t.name,status:a,errorType:a,success:!1,observation:`Tool execution failed: ${c.message}`,durationMs:Date.now()-r}}}async executeActions(t,n={}){let r=n.executionMode??"sequential",o=n.failurePolicy??(n.stopOnRejection===!1?"collect_all":"fail_fast"),s=[];if(r==="parallel"){let a=await Promise.all(t.map(l=>this.executeAction(l,n)));if(o==="fail_fast"){let l=a.findIndex(p=>p.rejected);s=l>=0?a.slice(0,l+1):a}else s=a}else for(let a of t){let l=await this.executeAction(a,n);if(s.push(l),l.rejected&&o==="fail_fast")break}let i=s.some(a=>a.rejected),c=s.map(a=>`[${a.tool}]: ${a.observation}`).join(`
|
|
67
|
+
|
|
68
|
+
`);return{results:s,combinedObservation:c,hasRejection:i,executionMode:r,failurePolicy:o}}clearOnceApprovals(){this.approvalManager.clearOnceApprovals()}dispose(){this.approvalManager.dispose()}};function va(e){return new ho(e)}var On=class{tools=new Map;register(t){this.tools.set(t.name,t)}registerMany(t){for(let n of t)this.register(n)}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}};import{Client as og}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as sg}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{StdioClientTransport as ig}from"@modelcontextprotocol/sdk/client/stdio.js";import{UnauthorizedError as ag}from"@modelcontextprotocol/sdk/client/auth.js";import{StreamableHTTPError as cg}from"@modelcontextprotocol/sdk/client/streamableHttp.js";function lg(e){if(!e)return;let t={...process.env,...e},n=Object.entries(t).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function Ta(){return new og({name:"memo-code-cli-client",version:"1.0.0"},{capabilities:{}})}function ug(e){if(!(!e||Object.keys(e).length===0))return{headers:e}}function pg(e){let t={...e.http_headers??e.headers??{}};if(e.bearer_token_env_var){let n=process.env[e.bearer_token_env_var];n&&!t.Authorization&&(t.Authorization=`Bearer ${n}`)}return t}async function dg(e,t,n){let r=new URL(t.url),o=ug(pg(t)),s=await ti({serverName:e,config:t,settings:n});try{let i=Ta(),c=new sg(r,{requestInit:o,...s?{authProvider:s}:{}});return await i.connect(c),{client:i,transport:c}}catch(i){let c=fg(i)?` Run "memo mcp login ${e}".`:"",a=`Failed to connect via streamable_http (${i.message}).${c}`,l=new Error(a);throw l.cause=i,l}}async function mg(e,t,n){if("url"in t)return dg(e,t,n);let r={command:t.command,args:t.args,env:lg(t.env),stderr:t.stderr??(process.stdout.isTTY&&process.stdin.isTTY?"ignore":void 0)},o=new ig(r),s=Ta();return await s.connect(o),{client:s,transport:o}}var Ln=class{connections=new Map;pendingConnections=new Map;serverConfigs=new Map;oauthSettings;setServerConfigs(t,n){this.serverConfigs=new Map(Object.entries(t)),this.oauthSettings=n}hasServer(t){return this.connections.has(t)||this.serverConfigs.has(t)}async connect(t,n){n&&this.serverConfigs.set(t,n);let r=this.connections.get(t);if(r)return r;let o=this.pendingConnections.get(t);if(o)return o;let s=n??this.serverConfigs.get(t);if(!s)throw new Error(`MCP server config not found: ${t}`);let i=(async()=>{let{client:c,transport:a}=await mg(t,s,this.oauthSettings);try{let l=await c.listTools(),p={name:t,client:c,transport:a,tools:(l.tools||[]).map(u=>({name:`${t}_${u.name}`,description:u.description||`Tool from ${t}: ${u.name}`,source:"mcp",serverName:t,originalName:u.name,inputSchema:u.inputSchema,execute:async()=>({content:[]})}))};return this.connections.set(t,p),p}catch(l){try{await c.close()}catch{}throw l}})();this.pendingConnections.set(t,i);try{return await i}finally{this.pendingConnections.delete(t)}}get(t){return this.connections.get(t)}getAll(){return Array.from(this.connections.values())}getKnownServerNames(){let t=new Set([...Array.from(this.serverConfigs.keys()),...Array.from(this.connections.keys())]);return Array.from(t.values())}getAllTools(){let t=[];for(let n of this.connections.values())for(let r of n.tools)t.push({name:r.name,description:r.description,serverName:r.serverName,originalName:r.originalName,inputSchema:r.inputSchema,client:n.client});return t}async closeAll(){let t=Array.from(this.connections.values()).map(async n=>{try{await n.client.close()}catch(r){console.error(`[MCP] Error closing client ${n.name}:`,r)}});await Promise.all(t),this.connections.clear(),this.pendingConnections.clear()}get size(){return this.connections.size}};function fg(e){if(e instanceof ag)return!0;if(e instanceof cg)return e.code===401||e.code===403;let t=e?.message?.toLowerCase()??"";return t.includes("unauthorized")||t.includes("401")||t.includes("403")||t.includes("oauth")}var Nn=class{pool;serverToolNames=new Map;refreshPromises=new Map;tools=new Map;cacheStore=Pn();shouldLog;constructor(){this.pool=new Ln,ro(this.pool),oo(this.cacheStore),this.shouldLog=!(process.stdout.isTTY&&process.stdin.isTTY)}buildTool(t,n,r){return{name:`${t}_${r.originalName}`,description:r.description||`Tool from ${t}: ${r.originalName}`,source:"mcp",serverName:t,originalName:r.originalName,inputSchema:r.inputSchema??{},execute:async o=>(await this.pool.connect(t,n)).client.callTool({name:r.originalName,arguments:o})}}replaceServerTools(t,n){let r=this.serverToolNames.get(t);if(r)for(let s of r)this.tools.delete(s);let o=new Set;for(let s of n)this.tools.set(s.name,s),o.add(s.name);this.serverToolNames.set(t,o)}connectionToDescriptors(t,n){return n.tools.map(r=>({originalName:r.originalName,description:r.description||`Tool from ${t}: ${r.originalName}`,inputSchema:r.inputSchema}))}async refreshServer(t,n,r){let o=this.refreshPromises.get(t);if(o){r==="sync"&&await o;return}let s=(async()=>{try{let i=await this.pool.connect(t,n),c=this.connectionToDescriptors(t,i);await this.cacheStore.setServerTools(t,n,c);let a=c.map(l=>this.buildTool(t,n,l));this.replaceServerTools(t,a),this.shouldLog&&r==="background"&&console.log(`[MCP] Refreshed '${t}' tools in background (${a.length})`)}catch(i){this.shouldLog&&console.error(`[MCP] Failed to refresh server '${t}':`,i)}})();this.refreshPromises.set(t,s),s.finally(()=>{this.refreshPromises.delete(t)}),r==="sync"&&await s}removeToolsForMissingServers(t){for(let[n,r]of this.serverToolNames.entries())if(!t.has(n)){for(let o of r)this.tools.delete(o);this.serverToolNames.delete(n)}}async loadServers(t){return this.loadServersWithOptions(t)}async loadServersWithOptions(t,n){if(!t||Object.keys(t).length===0)return 0;let r=Object.entries(t);this.pool.setServerConfigs(t,n),this.removeToolsForMissingServers(new Set(r.map(([s])=>s)));let o=[];for(let[s,i]of r){let c=await this.cacheStore.getServerTools(s,i);if(c){let a=c.tools.map(l=>this.buildTool(s,i,l));this.replaceServerTools(s,a),this.shouldLog&&console.log(`[MCP] Loaded ${a.length} cached tools for '${s}' (${c.stale?"stale":"fresh"})`),c.stale&&this.refreshServer(s,i,"background");continue}o.push(this.refreshServer(s,i,"sync"))}return await Promise.all(o),this.tools.size}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}toRegistry(){let t={};for(let[n,r]of this.tools)t[n]=r;return t}has(t){return this.tools.has(t)}get size(){return this.tools.size}async dispose(){await this.pool.closeAll(),this.tools.clear(),this.serverToolNames.clear(),this.refreshPromises.clear(),ro(null),oo(null)}getPool(){return this.pool}};var $n=class{nativeRegistry;mcpRegistry;constructor(){this.nativeRegistry=new On,this.mcpRegistry=new Nn}registerNativeTool(t){this.nativeRegistry.register(t)}registerNativeTools(t){for(let n of t)this.registerNativeTool(n)}async loadMcpServers(t,n){return this.mcpRegistry.loadServersWithOptions(t,n)}getTool(t){return this.nativeRegistry.get(t)??this.mcpRegistry.get(t)}getAllTools(){return[...this.nativeRegistry.getAll(),...this.mcpRegistry.getAll()]}toRegistry(){return{...this.nativeRegistry.toRegistry(),...this.mcpRegistry.toRegistry()}}hasTool(t){return this.nativeRegistry.has(t)||this.mcpRegistry.has(t)}getToolCount(){let t=this.nativeRegistry.size,n=this.mcpRegistry.size;return{native:t,mcp:n,total:t+n}}async execute(t,n){let r=this.getTool(t);if(!r)throw new Error(`Tool '${t}' not found`);return r.execute(n)}generateToolDefinitions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema||{type:"object",properties:{}}}))}generateToolDescriptions(){let t=this.getAllTools();if(t.length===0)return"";let n=[];n.push("## Available Tools"),n.push("");let r=t.filter(s=>s.source==="native"),o=t.filter(s=>s.source==="mcp");if(r.length>0){n.push("### Built-in Tools"),n.push("");for(let s of r)n.push(this.formatToolDescription(s));n.push("")}if(o.length>0){n.push("### External MCP Tools"),n.push("");let s=this.groupByServer(o);for(let[i,c]of Object.entries(s)){n.push(`**Server: ${i}**`),n.push("");for(let a of c)n.push(this.formatToolDescription(a));n.push("")}}return n.join(`
|
|
69
|
+
`)}formatToolDescription(t){let n=[];return n.push(`#### ${t.name}`),n.push(`- **Description**: ${t.description}`),t.inputSchema&&Object.keys(t.inputSchema).length>0&&n.push(`- **Input Schema**: ${JSON.stringify(t.inputSchema)}`),n.join(`
|
|
70
|
+
`)}groupByServer(t){let n={};for(let r of t)if(r.source==="mcp"){let o=r.serverName;n[o]||(n[o]=[]),n[o].push(r)}return n}getToolDescriptions(){return this.getAllTools().map(t=>({name:t.name,description:t.description,source:t.source,serverName:t.source==="mcp"?t.serverName:void 0,inputSchema:t.inputSchema}))}async dispose(){await this.mcpRegistry.dispose()}};function gg(e){let t=process.env[e]?.trim();return t?new Set(t.split(",").map(n=>n.trim()).filter(Boolean)):new Set}function hg(){let e=[],t=process.env.MEMO_SHELL_TOOL_TYPE?.trim()||"unified_exec",n=gg("MEMO_EXPERIMENTAL_TOOLS"),r=n.size===0,o=process.env.MEMO_ENABLE_COLLAB_TOOLS!=="0",s=process.env.MEMO_ENABLE_MEMORY_TOOL!=="0";return t==="shell"?e.push(gi):t==="shell_command"?e.push(hi):t==="unified_exec"?e.push(jr,zr):t!=="disabled"&&e.push(jr,zr),e.push(qi,Vi,Xi),e.push(Yi),e.push(Ei),(r||n.has("grep_files"))&&e.push(Ni),(r||n.has("read_file"))&&e.push(Oi),(r||n.has("list_dir"))&&e.push(Li),s&&e.push(ea),e.push(ra),o&&e.push(ca,la,ua,pa,da),e}function yg(e){let t={};for(let n of e)t[n.name]=n;return t}var _g=yg(hg()),Sg=Object.values(_g),wa=Sg;import Ag from"openai";import{encoding_for_model as vg,get_encoding as Tg}from"@dqbd/tiktoken";var Ca="cl100k_base";function wg(e){let t=e?.trim()||Ca;try{let n=()=>vg(t);return n().free(),{model:t,factory:n}}catch{let n=Ca,r=()=>Tg(n);return r().free(),{model:n,factory:r}}}function Cg(e){if(e.role==="assistant"){let t=e.reasoning_content?`
|
|
71
|
+
${e.reasoning_content}`:"";return e.tool_calls?.length?`${e.content}${t}
|
|
72
|
+
${JSON.stringify(e.tool_calls)}`:`${e.content}${t}`}return e.role==="tool"?`${e.content}
|
|
73
|
+
${e.tool_call_id}
|
|
74
|
+
${e.name??""}`:e.content}function ba(e){let{model:t,factory:n}=wg(e),r=n(),o=4,s=2,i=1,c=l=>l?r.encode(l).length:0;return{model:t,countText:c,countMessages:l=>{if(!l.length)return 0;let p=0;for(let u of l)p+=o,p+=c(Cg(u)),u.name&&(p+=i);return p+=s,p},dispose:()=>r.free()}}import"openai";var bg={supportsParallelToolCalls:!1,supportsReasoningContent:!1};function yo(e){return e.trim().toLowerCase()}function xg(e,t,n){if(!n)return;let r=new Map;for(let[s,i]of Object.entries(n))r.set(yo(s),i);let o=r.get(`${e}:${t}`);return o||r.get(t)}function Mg(e,t){if(!t)return{capabilities:e,usedOverride:!1};let n={...e},r=!1;return typeof t.supports_parallel_tool_calls=="boolean"&&(n.supportsParallelToolCalls=t.supports_parallel_tool_calls,r=!0),typeof t.supports_reasoning_content=="boolean"&&(n.supportsReasoningContent=t.supports_reasoning_content,r=!0),typeof t.context_window=="number"&&Number.isFinite(t.context_window)&&t.context_window>0&&(n.contextWindow=Math.floor(t.context_window),r=!0),{capabilities:n,usedOverride:r}}function xa(e,t){let n=yo(e.name),r=yo(e.model),{capabilities:o,usedOverride:s}=Mg(bg,xg(n,r,t));return{profile:{wireApi:"chat_completions",...o,isFallback:!s}}}function kg(e){if(e.length!==0)return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.input_schema}}))}function Ma(e){let t=kg(e.toolDefinitions),n={model:e.model,messages:e.messages,tools:t,tool_choice:t?"auto":void 0};return t&&e.profile.supportsParallelToolCalls&&(n.parallel_tool_calls=!0),n}function Pg(e,t){if(!e||!t)return e;let n=new Set(t.map(o=>o.trim()).filter(Boolean));if(n.size===0)return{};let r={};for(let[o,s]of Object.entries(e))n.has(o)&&(r[o]=s);return r}function Eg(e){try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,raw:e,error:t.message}}}function Rg(e){if(e.role==="assistant"){let t={role:"assistant",content:e.content,tool_calls:e.tool_calls?.map(n=>({id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}))};return e.reasoning_content&&(t.reasoning_content=e.reasoning_content),t}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:e.tool_call_id}:{role:e.role,content:e.content}}function Ig(e){let t=e?.reasoning_content;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function Og(e){return!e||typeof e!="object"?!1:Array.isArray(e.choices)}async function ka(e,t,n){let r=await ee(),o=r.config,s=new $n;if(s.registerNativeTools(wa),await s.loadMcpServers(Pg(o.mcp_servers,t.activeMcpServers),{memoHome:r.home,storeMode:o.mcp_oauth_credentials_store_mode,callbackPort:o.mcp_oauth_callback_port}),e.tools)for(let[d,m]of Object.entries(e.tools))s.registerNativeTool({name:d,description:m.description,source:"native",inputSchema:{type:"object"},execute:m.execute});let i=s.toRegistry(),c=async()=>{let d=e.loadPrompt?await e.loadPrompt():await as({cwd:t.cwd,memoHome:r.home,activeSkillPaths:o.active_skills}),m=s.generateToolDescriptions();return m&&(d+=`
|
|
75
|
+
|
|
76
|
+
${m}`),d},a=s.generateToolDefinitions(),l=jt(r,t),p=Hs(l,n),u=new ln(p);return{tools:i,dispose:async()=>{e.dispose&&await e.dispose(),await s.dispose()},callLLM:e.callLLM??(async(d,m,g)=>{let y=at(o,t.providerName),b=process.env[y.env_api_key]??process.env.OPENAI_API_KEY??process.env.DEEPSEEK_API_KEY;if(!b)throw new Error(`Missing env var ${y.env_api_key} (or OPENAI_API_KEY/DEEPSEEK_API_KEY)`);let U=new Ag({apiKey:b,baseURL:y.base_url}),T=d.map(Rg),{profile:H}=xa(y,o.model_profiles),R=g?.tools??a,I=Ma({model:y.model,messages:T,toolDefinitions:R,profile:H}),G=await U.chat.completions.create(I,{signal:g?.signal});if(!Og(G))throw new Error("Streaming response is not supported in core callLLM");let se=G.choices?.[0]?.message,Re=Ig(se);if(se?.tool_calls&&se.tool_calls.length>0){let z=[];se.content&&z.push({type:"text",text:se.content});for(let P of se.tool_calls)if(P.type==="function"){let te=Eg(P.function.arguments);te.ok?z.push({type:"tool_use",id:P.id,name:P.function.name,input:te.data}):z.push({type:"text",text:`[tool_use parse error] ${te.error}; raw: ${te.raw}`})}let M=z.some(P=>P.type==="tool_use");return{content:z,reasoning_content:Re,stop_reason:M?"tool_use":"end_turn",usage:{prompt:G.usage?.prompt_tokens??void 0,completion:G.usage?.completion_tokens??void 0,total:G.usage?.total_tokens??void 0}}}let ie=se?.content;if(typeof ie!="string")throw new Error("OpenAI-compatible API returned empty content");return{content:[{type:"text",text:ie}],reasoning_content:Re,stop_reason:"end_turn",usage:{prompt:G.usage?.prompt_tokens??void 0,completion:G.usage?.completion_tokens??void 0,total:G.usage?.total_tokens??void 0}}}),loadPrompt:c,historySinks:e.historySinks??[u],tokenCounter:e.tokenCounter??ba(t.tokenizerModel),historyFilePath:p}}function Lg(e){let t=[],n=/<\s*(think|thinking)\s*>([\s\S]*?)<\/\s*\1\s*>/gi,r=e.replace(n,(o,s,i)=>{let c=(i??"").trim();return c&&t.push(c),c});return{thinkingParts:t,cleaned:r.trim()}}function Aa(e){if(e.length===0)return;let t=e.join(`
|
|
77
|
+
`),{thinkingParts:n,cleaned:r}=Lg(t);return n.length>0?n.join(`
|
|
78
|
+
|
|
79
|
+
`):r||void 0}import{randomUUID as Gg}from"crypto";var Dn="interactive";var So="success",Ct="Tool usage is disabled in the current permission mode. Switch to /tools once or /tools full to enable tools.";var Ng="Skipped tool execution after previous rejection.",Pa="Tool execution skipped: tools are disabled in current permission mode.";function $g(e){process.stderr.write(`${JSON.stringify(e)}
|
|
80
|
+
`)}function Ea(e){if(e.toolPermissionMode==="none")return{mode:"none",toolsDisabled:!0,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="once")return{mode:"once",toolsDisabled:!1,dangerous:!1,approvalMode:"auto"};if(e.toolPermissionMode==="full")return{mode:"full",toolsDisabled:!1,dangerous:!0,approvalMode:"auto"};let t=e.dangerous??!1;return{mode:t?"full":"auto",toolsDisabled:!1,dangerous:t,approvalMode:"auto"}}function vo(){return{prompt:0,completion:0,total:0}}function To(e,t){if(!t)return;let n=t.prompt??0,r=t.completion??0,o=t.total??n+r;e.prompt+=n,e.completion+=r,e.total+=o}function wo(e){let t=e.content.filter(r=>r.type==="text"),n=e.content.filter(r=>r.type==="tool_use");return{textContent:t.map(r=>r.text).join(`
|
|
81
|
+
`),toolUseBlocks:n.map(r=>({id:r.id,name:r.name,input:r.input})),reasoningContent:typeof e.reasoning_content=="string"&&e.reasoning_content.trim().length>0?e.reasoning_content:void 0,stopReason:e.stop_reason,usage:e.usage}}async function Ra(e,t){for(let n of t)try{await n.append(e)}catch(r){$g({level:"error",event:"history_sink_append_failed",sink:n.constructor?.name||"anonymous_sink",message:r.message})}}function Ia(e){if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;let t=e.message?.toLowerCase?.()??"";return t.includes("request was aborted")||t.includes("operation was aborted")||t.includes("aborted")}function Un(e){return _o(e,new WeakSet,0)}var Dg=100;function _o(e,t,n){if(n>Dg)return JSON.stringify("[MaxDepthExceeded]");if(typeof e=="bigint")return JSON.stringify(e.toString());if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(t.has(e))return JSON.stringify("[Circular]");if(t.add(e),Array.isArray(e)){let s=`[${e.map(i=>_o(i,t,n+1)).join(",")}]`;return t.delete(e),s}let o=`{${Object.entries(e).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${JSON.stringify(s)}:${_o(i,t,n+1)}`).join(",")}}`;return t.delete(e),o}function Oa(e){return e.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:Un(t.input)}}))}function La(e,t){let n=e.trim();if(!n)return null;let r=[n],o=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);o?.[1]&&r.push(o[1].trim());for(let s of r)if(!(!s.startsWith("{")||!s.endsWith("}")))try{let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,a=typeof c.tool=="string"?c.tool.trim():"";if(!a||!Object.prototype.hasOwnProperty.call(t,a))continue;return{tool:a,input:c.input??{}}}catch{}return null}function Ug(e){return e.length<=60?e:`${e.slice(0,57).trimEnd()}...`}function Na(e){let t=e.replace(/\s+/g," ").trim();if(!t)return"New Session";if(!t.includes(" "))return t.length<=20?t:`${t.slice(0,20).trimEnd()}...`;let r=t.split(" ").filter(Boolean).slice(0,8).join(" ");return Ug(r||t)}function Co(e){return{role:"tool",content:e.observation,tool_call_id:e.actionId,name:e.tool}}function $a(e,t,n){let r=new Map(t.map(o=>[o.actionId,o]));return e.map(o=>{let s=r.get(o.id);return s||{actionId:o.id,tool:o.name,status:n?"approval_denied":"execution_failed",errorType:n?"approval_denied":"execution_failed",success:!1,observation:n?`${Ng} ${o.name}`:`Tool result missing for ${o.name}; execution aborted before producing output.`,durationMs:0,rejected:n?!0:void 0}})}import{randomUUID as Wg}from"crypto";var Da=`You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
|
|
82
|
+
|
|
83
|
+
Include:
|
|
84
|
+
- Current progress and key decisions made
|
|
85
|
+
- Important context, constraints, or user preferences
|
|
86
|
+
- What remains to be done (clear next steps)
|
|
87
|
+
- Any critical data, examples, or references needed to continue
|
|
88
|
+
|
|
89
|
+
Be concise, structured, and focused on helping the next LLM seamlessly continue the work.`,xo="Another language model started to solve this problem and produced a summary of its thinking process. Use this summary to continue the task without redoing completed work.";function bo(e){let t=e.replace(/\r\n/g,`
|
|
90
|
+
`).trim();return t.length<=4e3?t:`${t.slice(0,4e3)}...`}function Fg(e,t){let n=e.role.toUpperCase();if(e.role==="assistant"&&e.tool_calls?.length){let r=e.tool_calls.map(o=>o.function.name).join(", ");return`[${t}] ${n} (tool_calls: ${r})
|
|
91
|
+
${bo(e.content)}`}if(e.role==="tool"){let r=e.name?` (${e.name})`:"";return`[${t}] ${n}${r}
|
|
92
|
+
${bo(e.content)}`}return`[${t}] ${n}
|
|
93
|
+
${bo(e.content)}`}function Ua(e){return e.role!=="user"?!1:e.content.startsWith(`${xo}
|
|
94
|
+
`)}function Fa(e){return["Conversation history to summarize:",e.length?e.map((n,r)=>Fg(n,r)).join(`
|
|
95
|
+
|
|
96
|
+
`):"(empty)","","Return only the summary body in plain text. Do not add markdown fences."].join(`
|
|
97
|
+
`)}function Hg(){return{onTurnStart:[],onContextUsage:[],onContextCompacted:[],onAction:[],onObservation:[],onFinal:[],onApprovalRequest:[],onApprovalResponse:[],onTitleGenerated:[]}}function Ha(e,t){t&&(t.onTurnStart&&e.onTurnStart.push(t.onTurnStart),t.onContextUsage&&e.onContextUsage.push(t.onContextUsage),t.onContextCompacted&&e.onContextCompacted.push(t.onContextCompacted),t.onAction&&e.onAction.push(t.onAction),t.onObservation&&e.onObservation.push(t.onObservation),t.onFinal&&e.onFinal.push(t.onFinal),t.onApprovalRequest&&e.onApprovalRequest.push(t.onApprovalRequest),t.onApprovalResponse&&e.onApprovalResponse.push(t.onApprovalResponse),t.onTitleGenerated&&e.onTitleGenerated.push(t.onTitleGenerated))}function Ba(e){let t=Hg();if(Ha(t,e.hooks),Array.isArray(e.middlewares))for(let n of e.middlewares)Ha(t,n);return t}async function V(e,t,n){let r=e[t];if(r.length)for(let o of r)try{await o(n)}catch(s){console.warn(`Hook ${t} failed: ${s.message}`)}}function bt(e){return e.map(t=>t.role==="assistant"&&t.tool_calls?.length?{...t,tool_calls:t.tool_calls.map(n=>({...n,function:{...n.function}}))}:{...t})}var jg=80,zg=2e4,Fn=class{constructor(t,n,r,o,s){this.deps=t;this.options=n;this.id=n.sessionId||Wg(),this.mode=n.mode||Dn,this.history=[{role:"system",content:r}],this.tokenCounter=o,this.sinks=t.historySinks??[],this.hooks=Ba(t),this.historyFilePath=s;let i=Ea(n);this.toolsDisabled=i.toolsDisabled,this.toolPermissionMode=i.mode,this.toolOrchestrator=va({tools:t.tools,approval:{dangerous:i.dangerous,mode:i.approvalMode}})}title;id;mode;history;historyFilePath;turnIndex=0;tokenCounter;sinks;sessionUsage=vo();startedAt=Date.now();hooks;closed=!1;sessionStartEmitted=!1;currentAbortController=null;cancelling=!1;lastActionSignature=null;repeatedActionCount=0;toolOrchestrator;toolsDisabled=!1;toolPermissionMode="auto";async init(){}resetActionRepetition(){this.lastActionSignature=null,this.repeatedActionCount=0}maybeWarnRepeatedAction(t,n){let r=`${t}:${Un(n)}`;if(this.lastActionSignature===r?this.repeatedActionCount+=1:(this.lastActionSignature=r,this.repeatedActionCount=1),this.repeatedActionCount===3){let o=Un(n).slice(0,200),s=`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4F60\u5DF2\u8FDE\u7EED3\u6B21\u8C03\u7528\u540C\u4E00\u5DE5\u5177\u300C${t}\u300D\u4E14\u53C2\u6570\u76F8\u540C\uFF08${o}${o.length>=200?"\u2026":""}\uFF09\u3002\u8BF7\u786E\u8BA4\u662F\u5426\u9677\u5165\u5FAA\u73AF\uFF0C\u5FC5\u8981\u65F6\u76F4\u63A5\u7ED9\u51FA\u6700\u7EC8\u56DE\u7B54\u6216\u8C03\u6574\u53C2\u6570\u3002`;this.history.push({role:"system",content:s})}}resolveContextWindow(){let t=this.options.contextWindow;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):12e4}resolveSessionCwd(){let t=this.options.cwd?.trim();return t||process.cwd()}resolveAutoCompactThresholdPercent(){let t=this.options.autoCompactThresholdPercent;return typeof t=="number"&&Number.isInteger(t)&&Number.isFinite(t)&&t>=1&&t<=100?t:jg}resolveThresholdTokens(t){let n=Math.floor(t*this.resolveAutoCompactThresholdPercent()/100);return Math.max(1,n)}calculateUsagePercent(t,n){return t<=0||n<=0?0:Math.round(t/n*1e4)/100}async emitContextUsage(t,n,r,o,s,i){let c=this.calculateUsagePercent(r,o);await this.emitEvent("context_usage",{turn:t,step:n,meta:{phase:i,prompt_tokens:r,context_window:o,threshold_tokens:s,usage_percent:c}}),await V(this.hooks,"onContextUsage",{sessionId:this.id,turn:t,step:n,promptTokens:r,contextWindow:o,thresholdTokens:s,usagePercent:c,phase:i})}async emitContextCompacted(t,n,r){await this.emitEvent("context_compact",{turn:t,step:n,content:r.summary,meta:{reason:r.reason,status:r.status,before_tokens:r.beforeTokens,after_tokens:r.afterTokens,threshold_tokens:r.thresholdTokens,reduction_percent:r.reductionPercent,error_message:r.errorMessage}}),await V(this.hooks,"onContextCompacted",{sessionId:this.id,turn:t,step:n,reason:r.reason,status:r.status,beforeTokens:r.beforeTokens,afterTokens:r.afterTokens,thresholdTokens:r.thresholdTokens,reductionPercent:r.reductionPercent,summary:r.summary,errorMessage:r.errorMessage})}buildCompactedHistory(t){let n=this.history[0]?.role==="system"?this.history[0]:void 0,o=(n?this.history.slice(1):this.history).filter(c=>c.role==="user"&&!Ua(c)).map(c=>c.content),s=this.selectCompactionUserMessages(o).map(c=>({role:"user",content:c})),i={role:"user",content:`${xo}
|
|
98
|
+
${t}`};return n?[n,...s,i]:[...s,i]}selectCompactionUserMessages(t){if(!t.length)return[];let n=[],r=zg;for(let o=t.length-1;o>=0;o-=1){let s=t[o];if(!s)continue;let i=this.tokenCounter.countText(s);if(i<=r){if(n.push(s),r=Math.max(0,r-i),r===0)break;continue}r>0&&n.push(s.slice(0,r));break}return n.reverse(),n}normalizeCompactionSummary(t){return(t.replace(/<think>[\s\S]*?<\/think>/gi,"").trim()||t).replace(/\n{3,}/g,`
|
|
99
|
+
|
|
100
|
+
`).trim()}async compactHistoryInternal(t,n,r){let o=this.resolveContextWindow(),s=this.resolveThresholdTokens(o),i=this.tokenCounter.countMessages(this.history),a=(this.history[0]?.role==="system"?this.history[0]:void 0)?this.history.slice(1):this.history.slice();if(!a.length){let l={reason:t,status:"skipped",beforeTokens:i,afterTokens:i,thresholdTokens:s,reductionPercent:0};return await this.emitContextCompacted(n,r,l),l}try{let l=await this.deps.callLLM([{role:"system",content:Da},{role:"user",content:Fa(a)}],void 0,{tools:[]}),p=wo(l),u=this.normalizeCompactionSummary(p.textContent);if(!u)throw new Error("Compaction model returned an empty summary.");let d=this.buildCompactedHistory(u),m=this.tokenCounter.countMessages(d);this.history.splice(0,this.history.length,...d);let g=i>0?Math.max(0,Math.round((i-m)/i*1e4)/100):0,y={reason:t,status:"success",beforeTokens:i,afterTokens:m,thresholdTokens:s,reductionPercent:g,summary:u};return await this.emitContextCompacted(n,r,y),y}catch(l){let p={reason:t,status:"failed",beforeTokens:i,afterTokens:i,thresholdTokens:s,reductionPercent:0,errorMessage:l.message};return await this.emitContextCompacted(n,r,p),p}}buildToolApprovalHooks(t,n){return{onApprovalRequest:async r=>{await V(this.hooks,"onApprovalRequest",{sessionId:this.id,turn:t,step:n,request:r})},requestApproval:async r=>this.deps.requestApproval?this.deps.requestApproval(r):"deny",onApprovalResponse:async({fingerprint:r,decision:o})=>{await V(this.hooks,"onApprovalResponse",{sessionId:this.id,turn:t,step:n,fingerprint:r,decision:o})}}}async executeToolAction(t,n,r,o,s){return this.toolOrchestrator.executeAction({id:t,name:n,input:r},this.buildToolApprovalHooks(o,s))}async maybeGenerateSessionTitle(t,n){if(t!==1||this.title)return;let r=Na(n);this.title=r,await this.emitEvent("session_title",{turn:t,content:r,meta:{source:"first_prompt",original_prompt:n}}),await V(this.hooks,"onTitleGenerated",{sessionId:this.id,turn:t,title:r,originalPrompt:n})}async runTurn(t){return li({cwd:this.resolveSessionCwd()},async()=>{let n=new AbortController;this.currentAbortController=n,this.cancelling=!1,this.turnIndex+=1;let r=this.turnIndex,o=[],s=vo(),i=Date.now(),c=this.resolveContextWindow(),a=this.resolveThresholdTokens(c),l=this.resolveAutoCompactThresholdPercent(),p=!1;if(!this.sessionStartEmitted){let u=this.history[0]?.role==="system"?this.history[0].content:void 0;await this.emitEvent("session_start",{content:u,role:u?"system":void 0,meta:{mode:this.mode,cwd:this.resolveSessionCwd(),tokenizer:this.tokenCounter.model,warnPromptTokens:this.options.warnPromptTokens,contextWindow:c,autoCompactThresholdPercent:l,toolPermissionMode:this.toolPermissionMode}}),this.sessionStartEmitted=!0}this.history.push({role:"user",content:t});try{let u=this.tokenCounter.countMessages(this.history);await this.emitEvent("turn_start",{turn:r,content:t,meta:{tokens:{prompt:u}}}),await V(this.hooks,"onTurnStart",{sessionId:this.id,turn:r,input:t,promptTokens:u,history:bt(this.history)}),await this.emitContextUsage(r,0,u,c,a,"turn_start"),await this.maybeGenerateSessionTitle(r,t);let d="",m="ok",g,y=0,b=null,U=-1;for(let T=0;;T++){let H=this.tokenCounter.countMessages(this.history);if(await this.emitContextUsage(r,T,H,c,a,"step_start"),!p&&H>=a&&(p=!0,await this.compactHistoryInternal("auto",r,T),H=this.tokenCounter.countMessages(this.history),await this.emitContextUsage(r,T,H,c,a,"post_compact")),H>c){let A=`Context tokens (${H}) exceed the limit. Please shorten the input or restart the session.`;this.history.push({role:"assistant",content:A}),m="prompt_limit",d=A,g=A,await this.emitEvent("final",{turn:r,step:T,content:A,role:"assistant",meta:{tokens:{prompt:H}}}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:A,status:m,errorMessage:g,turnUsage:{...s},steps:o});break}this.options.warnPromptTokens&&H>this.options.warnPromptTokens&&console.warn(`Prompt tokens are near the limit: ${H}`);let R="",I=[],G,se,Re,ie=!1;try{let A=await this.deps.callLLM(this.history,ne=>{ne&&(ie=!0),this.deps.onAssistantStep?.(ne,T)},{signal:n.signal}),O=wo(A);R=O.textContent,I=O.toolUseBlocks,se=O.stopReason,G=O.usage,Re=O.reasoningContent,R.trim().length>0&&(b=R,U=T)}catch(A){if(this.cancelling&&Ia(A)){m="cancelled",d="",g="Turn cancelled",await this.emitEvent("final",{turn:r,step:T,content:"",role:"assistant",meta:{cancelled:!0}}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:d,status:m,errorMessage:g,turnUsage:{...s},steps:o});break}let O=`LLM call failed: ${A.message}`;this.history.push({role:"assistant",content:O}),m="error",d=O,g=O,await this.emitEvent("final",{turn:r,content:O,role:"assistant"}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:d,status:m,errorMessage:g,turnUsage:{...s},steps:o});break}!ie&&R&&this.deps.onAssistantStep?.(R,T);let z=I.length===0&&R?La(R,this.deps.tools):null,M,P=null;if(I.length>0){let A=I[0];if(A){let O=R?Aa([R]):void 0;M={action:{tool:A.name,input:A.input},thinking:O},P={role:"assistant",content:R,reasoning_content:Re,tool_calls:Oa(I)}}else M={}}else R?(M={final:R},P={role:"assistant",content:R,reasoning_content:Re}):M={};let te=this.tokenCounter.countText(R),ae=G?.prompt??H,F=G?.completion??te,ce=G?.total??ae+F,J={prompt:ae,completion:F,total:ce};if(To(s,J),To(this.sessionUsage,J),o.push({index:T,assistantText:R,parsed:M,tokenUsage:J}),await this.emitEvent("assistant",{turn:r,step:T,content:R,role:"assistant",meta:{tokens:J,protocol_violation:!!z,protocol_violation_count:z?y+1:y||void 0}}),z){y+=1;let A=`Model protocol error: returned plain-text tool JSON for "${z.tool}" ${y} times. Structured tool calls are required.`;m="error",d=A,g=A,this.history.push({role:"assistant",content:A}),await this.emitEvent("final",{turn:r,step:T,content:A,role:"assistant",meta:{error_type:"model_protocol_error",tool:z.tool,protocol_violation:!0,protocol_violation_count:y,tokens:J}}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:d,status:m,errorMessage:g,tokenUsage:J,turnUsage:{...s},steps:o});break}if(P&&this.history.push(P),I.length>0&&this.toolsDisabled){for(let A of I)this.history.push({role:"tool",content:Pa,tool_call_id:A.id,name:A.name});m="error",d=Ct,g=Ct,this.history.push({role:"assistant",content:Ct}),await this.emitEvent("final",{turn:r,step:T,content:Ct,role:"assistant",meta:{error_type:"tool_disabled",tool_count:I.length,tools:I.map(A=>A.name).join(","),tokens:J}}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:Ct,status:m,errorMessage:g,tokenUsage:J,turnUsage:{...s},steps:o});break}if(I.length>1){for(let k of I)this.maybeWarnRepeatedAction(k.name,k.input);await this.emitEvent("action",{turn:r,step:T,meta:{tools:I.map(k=>k.name),action_ids:I.map(k=>k.id),action_id:I[0]?.id,parallel:!0,phase:"dispatch",thinking:M.thinking,toolBlocks:I.map(k=>({id:k.id,name:k.name,input:k.input}))}});let A=I[0];A&&await V(this.hooks,"onAction",{sessionId:this.id,turn:r,step:T,action:{tool:A.name,input:A.input},parallelActions:I.map(k=>({tool:k.name,input:k.input})),thinking:M.thinking,history:bt(this.history)});let O=I.every(k=>!!this.deps.tools[k.name]?.supportsParallelToolCalls),ne=I.some(k=>!!this.deps.tools[k.name]?.isMutating),Se=O&&!ne?"parallel":"sequential",fe=await this.toolOrchestrator.executeActions(I.map(k=>({id:k.id,name:k.name,input:k.input})),{...this.buildToolApprovalHooks(r,T),executionMode:Se,failurePolicy:"fail_fast"}),Ke=$a(I,fe.results,fe.hasRejection);for(let[k,L]of Ke.entries())this.history.push(Co(L)),await this.emitEvent("observation",{turn:r,step:T,content:L.observation,meta:{tool:L.tool,index:k,action_id:L.actionId,phase:"result",status:L.status,error_type:L.errorType,duration_ms:L.durationMs,execution_mode:Se}});let $e=Ke.map(k=>`[${k.tool}]: ${k.observation}`).join(`
|
|
101
|
+
|
|
102
|
+
`),tt=Ke.map(k=>k.status),ve=tt.find(k=>k!==So)??So,be=o[o.length-1];if(be&&(be.observation=$e),await V(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:T,tool:I.map(k=>k.name).join(", "),observation:$e,resultStatus:ve,parallelResultStatuses:tt,history:bt(this.history)}),fe.hasRejection){let k=Ke.find(L=>L.rejected);m="cancelled",d="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:r,step:T,content:d,role:"assistant",meta:{rejected:!0,phase:"result",action_id:k?.actionId,error_type:k?.errorType??"approval_denied",duration_ms:k?.durationMs}}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:d,status:m,tokenUsage:J,turnUsage:{...s},steps:o});break}continue}else if(M.action){this.maybeWarnRepeatedAction(M.action.tool,M.action.input);let A=I[0]?.id??`${r}:${T}:single:${M.action.tool}`;await this.emitEvent("action",{turn:r,step:T,meta:{tool:M.action.tool,input:M.action.input,action_id:A,phase:"dispatch",thinking:M.thinking}}),await V(this.hooks,"onAction",{sessionId:this.id,turn:r,step:T,action:M.action,thinking:M.thinking,history:bt(this.history)});let O=await this.executeToolAction(A,M.action.tool,M.action.input,r,T);if(O.rejected){this.history.push(Co({...O,observation:O.observation||`User denied tool execution: ${M.action.tool}`})),m="cancelled",d="\u7528\u6237\u62D2\u7EDD\u4E86\u5DE5\u5177\u6267\u884C\uFF0C\u5DF2\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u3002",await this.emitEvent("final",{turn:r,step:T,content:d,role:"assistant",meta:{rejected:!0,phase:"result",action_id:O.actionId,error_type:O.errorType??"approval_denied",duration_ms:O.durationMs}}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:d,status:m,tokenUsage:J,turnUsage:{...s},steps:o});break}let ne=O.observation;this.history.push({role:"tool",content:ne,tool_call_id:O.actionId,name:M.action.tool});let Se=o[o.length-1];Se&&(Se.observation=ne),await this.emitEvent("observation",{turn:r,step:T,content:ne,meta:{tool:M.action.tool,action_id:O.actionId,phase:"result",status:O.status,error_type:O.errorType,duration_ms:O.durationMs}}),await V(this.hooks,"onObservation",{sessionId:this.id,turn:r,step:T,tool:M.action.tool,observation:ne,resultStatus:O.status,history:bt(this.history)});continue}if(se==="end_turn"||M.final){this.resetActionRepetition();let A=se==="end_turn"&&!M.final&&R.trim().length===0&&!!b&&U===T-1;d=A?b??"":M.final||R,M.final&&(M.final=d),await this.emitEvent("final",{turn:r,step:T,content:d,role:"assistant",meta:{tokens:J,fallback_from_previous_text:A||void 0}}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,step:T,finalText:d,status:m,tokenUsage:J,turnUsage:{...s},steps:o});break}this.resetActionRepetition();break}return!d&&m!=="cancelled"&&(m==="ok"&&(m="error"),d="Unable to produce a final answer. Please retry or adjust the request.",g=d,this.history.push({role:"assistant",content:d}),await this.emitEvent("final",{turn:r,content:d,role:"assistant"}),await V(this.hooks,"onFinal",{sessionId:this.id,turn:r,finalText:d,status:m,errorMessage:g,turnUsage:{...s},steps:o})),await this.emitEvent("turn_end",{turn:r,meta:{status:m,stepCount:o.length,durationMs:Date.now()-i,tokens:s,protocol_violation_count:y||void 0}}),{finalText:d,steps:o,status:m,errorMessage:g,tokenUsage:s}}finally{this.currentAbortController=null,this.cancelling=!1,this.toolOrchestrator.clearOnceApprovals()}})}cancelCurrentTurn(){this.currentAbortController&&(this.cancelling=!0,this.currentAbortController.abort())}async compactHistory(t="manual"){return this.compactHistoryInternal(t,this.turnIndex,0)}listToolNames(){return Object.keys(this.deps.tools)}async close(){if(this.closed)return;if(this.closed=!0,this.sessionStartEmitted||this.turnIndex>=0){await this.emitEvent("session_end",{meta:{durationMs:Date.now()-this.startedAt,tokens:this.sessionUsage}});for(let n of this.sinks)try{n.close?await n.close():n.flush&&await n.flush()}catch(r){console.error(`History flush failed: ${r.message}`)}}this.tokenCounter.dispose(),this.toolOrchestrator.dispose(),this.deps.dispose&&await this.deps.dispose()}async emitEvent(t,n){if(!this.sinks.length)return;let r=cs({sessionId:this.id,type:t,turn:n.turn,step:n.step,content:n.content,role:n.role,meta:n.meta});await Ra(r,this.sinks)}};async function Hn(e,t={}){let n=t.sessionId||Gg(),r=await ka(e,{...t,sessionId:n},n),o=await r.loadPrompt(),s=new Fn({...e,...r},{...t,sessionId:n,mode:t.mode??Dn},o,r.tokenCounter,r.historyFilePath);return await s.init(),s}import{randomUUID as Rt}from"crypto";import{readFile as n_}from"fs/promises";import{useCallback as X,useEffect as It,useMemo as nn,useReducer as r_,useRef as rr,useState as Z}from"react";import{Box as Kc,Text as o_,useApp as s_}from"ink";import{memo as uh,useMemo as tc,useRef as nc,useEffect as ph}from"react";import{Box as Za,Static as dh,Text as Bn}from"ink";import{memo as Po}from"react";import{Box as Je,Text as oe}from"ink";var ke={PENDING:"pending",EXECUTING:"executing",SUCCESS:"success",ERROR:"error"};import xt from"path";var Kg="success",Vt=".";function Mo(e){return e?e===Kg?ke.SUCCESS:ke.ERROR:ke.SUCCESS}function Wa(e){if(e?.length)return e.map(t=>Mo(t))}function ja(e,t){return!t||t<=0||!e||e<=0?0:Math.min(100,e/t*100)}function Xt(e,t=80){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function za(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function ko(e,t){let n=e.trim();if(!n)return e;if(n===Vt)return Vt;if(xt.isAbsolute(n)){let r=xt.relative(xt.resolve(t),n);return r?xt.normalize(r):Vt}if(n.startsWith("./")||n.startsWith("../")){let r=xt.normalize(n);return!r||r==="."||r==="./"?Vt:r}return n}function Ga(e){return e?e===Vt||xt.isAbsolute(e)?!0:e.startsWith("./")||e.startsWith("../"):!1}import{memo as Zg,useMemo as eh}from"react";import{Box as Le,Text as Ce}from"ink";import{marked as qg}from"marked";var Vg=/(`[^`\n]+`|\[[^\]]+\]\((?:\\.|[^)])+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\n]+\*|_[^_\n]+_)/g;function Jt(e){return e.map(t=>{let n=t;return typeof n.text=="string"?n.text:typeof n.raw=="string"?n.raw:Array.isArray(n.tokens)?Jt(n.tokens):Array.isArray(n.items)?n.items.map(r=>typeof r.text=="string"?r.text:Array.isArray(r.tokens)?Jt(r.tokens):"").filter(Boolean).join(`
|
|
103
|
+
`):""}).join("")}function Xg(e){let t=[],n=e.replace(/<think>([\s\S]*?)<\/think>/gi,(r,o)=>{let s=o.trim();return s&&t.push(s),""});return{think:t,cleaned:n}}function Jg(e){if(e.startsWith("`")&&e.endsWith("`"))return{type:"inlineCode",content:e.slice(1,-1)};if(e.startsWith("**")&&e.endsWith("**")||e.startsWith("__")&&e.endsWith("__"))return{type:"bold",content:e.slice(2,-2)};if(e.startsWith("*")&&e.endsWith("*")||e.startsWith("_")&&e.endsWith("_"))return{type:"italic",content:e.slice(1,-1)};let t=e.match(/^\[([^\]]+)\]\((.+)\)$/);return t?{type:"link",label:t[1]??"",href:t[2]??""}:{type:"text",content:e}}function qa(e){if(!e)return[];let t=[],n=0;for(let r of e.matchAll(Vg)){let o=r[0];if(!o)continue;let s=r.index??0;s>n&&t.push({type:"text",content:e.slice(n,s)}),t.push(Jg(o)),n=s+o.length}return n<e.length&&t.push({type:"text",content:e.slice(n)}),t.filter(r=>r.type==="link"?r.label.length>0||r.href.length>0:r.content.length>0)}function Yg(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Jt(e.tokens):""}function Qg(e){return typeof e.text=="string"&&e.text.length>0?e.text:Array.isArray(e.tokens)?Jt(e.tokens):typeof e.raw=="string"?e.raw.split(`
|
|
104
|
+
`).map(t=>t.replace(/^>\s?/,"")).join(`
|
|
105
|
+
`).trim():""}function Ka(e){return typeof e.text=="string"?e.text:Array.isArray(e.tokens)?Jt(e.tokens):typeof e.raw=="string"?e.raw:""}function Va(e){let{think:t,cleaned:n}=Xg(e),r=[];t.length>0&&r.push({type:"think",content:t.join(`
|
|
106
|
+
|
|
107
|
+
`)});let o=qg.lexer(n);for(let s of o)switch(s.type){case"html":{r.push({type:"html",content:s.text??s.raw??""});break}case"hr":{r.push({type:"hr"});break}case"heading":{r.push({type:"heading",level:typeof s.depth=="number"?s.depth:1,content:s.text??Ka(s)});break}case"paragraph":case"text":{let i=Ka(s);i.trim().length>0&&r.push({type:"paragraph",content:i});break}case"code":{r.push({type:"code",language:s.lang,content:s.text??""});break}case"blockquote":{let i=Qg(s);i.trim().length>0&&r.push({type:"blockquote",content:i});break}case"list":{let i=Array.isArray(s.items)?s.items.map(c=>Yg(c)).filter(c=>c.trim().length>0):[];i.length>0&&r.push({type:"list",items:i,ordered:!!s.ordered});break}default:break}return r}import{Fragment as ch,jsx as j,jsxs as Mt}from"react/jsx-runtime";var th="\u2014\u2014\u2014";function nh(e,t){return e.repeat(Math.max(0,t))}function rh(e){let t=e.split(`
|
|
108
|
+
`);if(t.length===0)return["Think:"];let n=t.findIndex(r=>r.trim().length>0);return n<0&&(n=0),t.map((r,o)=>o===n?`Think: ${r}`:r)}function oh(e){return e.split(`
|
|
109
|
+
`)}function sh({content:e}){let t=oh(e);return j(Le,{flexDirection:"column",marginY:1,children:t.map((n,r)=>j(Ce,{children:n},r))})}function ih({node:e}){switch(e.type){case"bold":return j(Ce,{bold:!0,children:e.content});case"italic":return j(Ce,{italic:!0,children:e.content});case"inlineCode":return j(Ce,{color:"cyan",children:e.content});case"link":return Mt(ch,{children:[j(Ce,{color:"blue",underline:!0,children:e.label}),Mt(Ce,{color:"gray",children:[" (",e.href,")"]})]});case"text":return j(Ce,{children:e.content});default:return null}}function Ao({content:e}){let t=qa(e);return j(Le,{flexWrap:"wrap",children:t.map((n,r)=>j(ih,{node:n},r))})}function ah(e,t){switch(e.type){case"html":return j(Le,{children:j(Ce,{color:"gray",dimColor:!0,children:e.content})},t);case"hr":return j(Le,{marginY:1,children:j(Ce,{color:"gray",dimColor:!0,children:th})},t);case"think":return j(Le,{flexDirection:"column",marginY:1,children:rh(e.content).map((n,r)=>j(Ce,{color:"gray",dimColor:!0,children:n},r))},t);case"heading":return j(Le,{children:Mt(Ce,{bold:!0,color:"cyan",children:[nh("#",e.level)," ",e.content]})},t);case"paragraph":return j(Ao,{content:e.content},t);case"code":return j(sh,{content:e.content},t);case"blockquote":return j(Le,{flexDirection:"column",children:e.content.split(`
|
|
110
|
+
`).map((n,r)=>Mt(Le,{children:[j(Ce,{color:"gray",dimColor:!0,children:"> "}),j(Ao,{content:n})]},r))},t);case"list":return j(Le,{flexDirection:"column",children:e.items.map((n,r)=>Mt(Le,{children:[Mt(Ce,{color:"gray",children:[e.ordered?`${r+1}.`:"\u2022"," "]}),j(Ao,{content:n})]},r))},t);default:return null}}var Xa=Zg(function({content:t}){let n=eh(()=>Va(t),[t]);return j(Le,{flexDirection:"column",children:n.map((r,o)=>ah(r,`${r.type}-${o}`))})});import{jsx as he,jsxs as Ae}from"react/jsx-runtime";function Ja(e){return e===ke.ERROR?"red":e===ke.EXECUTING?"yellow":"green"}function Ya(e,t){if(e==null)return null;if(typeof e=="string"){let s=Ga(e)?ko(e,t):e;return Xt(s,70)}if(typeof e!="object"||Array.isArray(e))return Xt(String(e),70);let n=e,r=["cmd","path","file_path","dir_path","query","pattern","url","content"],o=new Set(["path","file_path","dir_path"]);for(let s of r){let i=n[s];if(i==null||i==="")continue;let c=String(i),a=o.has(s)?ko(c,t):c;return Xt(a,70)}return Xt(za(n),70)}var Qa=Po(function({message:t}){let n=t.tone==="error"?"red":t.tone==="warning"?"yellow":"cyan";return Ae(Je,{flexDirection:"column",children:[Ae(oe,{color:n,children:["\u25CF ",t.title]}),he(oe,{color:"gray",children:t.content})]})}),lh=Po(function({step:t,cwd:n}){let r=!!(t.parallelActions&&t.parallelActions.length>1),o=!r&&t.action?Ya(t.action.input,n):null;return Ae(Je,{flexDirection:"column",children:[t.thinking?Ae(Je,{children:[he(oe,{color:"gray",children:"\u25CF "}),he(oe,{color:"gray",children:t.thinking})]}):null,r?t.parallelActions?.map((s,i)=>{let c=Ya(s.input,n);return Ae(Je,{children:[Ae(oe,{color:Ja(t.parallelToolStatuses?.[i]??t.toolStatus),children:["\u25CF"," "]}),he(oe,{color:"gray",children:"Used "}),he(oe,{color:"cyan",children:s.tool}),c?Ae(oe,{color:"gray",children:[" (",c,")"]}):null]},`${s.tool}-${i}`)}):null,!r&&t.action?Ae(Je,{children:[he(oe,{color:Ja(t.toolStatus),children:"\u25CF "}),he(oe,{color:"gray",children:"Used "}),he(oe,{color:"cyan",children:t.action.tool}),o?Ae(oe,{color:"gray",children:[" (",o,")"]}):null]}):null]})}),Eo=Po(function({turn:t,cwd:n}){return Ae(Je,{flexDirection:"column",children:[Ae(Je,{marginY:.5,children:[he(oe,{color:"gray",children:"\u203A "}),he(oe,{children:t.userInput})]}),t.steps.map(r=>he(lh,{step:r,cwd:n},`${t.index}-${r.index}`)),t.finalText?he(Je,{marginTop:0,children:he(Xa,{content:t.finalText})}):null,t.status&&t.status!=="ok"?Ae(oe,{color:"red",children:["Status: ",t.status]}):null,t.errorMessage?he(oe,{color:"red",children:t.errorMessage}):null]})});import{jsx as Yt,jsxs as Qt}from"react/jsx-runtime";function ec(e){return e.sequence??0}function mh(e){return e.type==="header"}function fh(e){return e.id!==void 0}function gh(e){let t=nc("");return tc(()=>{let n=`${e.sessionId}-${e.providerName}-${e.model}-${e.version}`;return n!==t.current&&(t.current=n),t.current},[e.sessionId,e.providerName,e.model,e.version])}var rc=uh(function({header:t,systemMessages:n,turns:r,historicalTurns:o}){let s=gh(t),i=nc(t.cwd);ph(()=>{i.current=t.cwd},[t.cwd]);let{completedTurns:c,inProgressTurn:a,staticItems:l}=tc(()=>{let u=[...o,...r],d=u.length>0?u[u.length-1]:void 0,m=d&&!!(d.finalText||d.status&&d.status!=="ok"),g=m?u:u.slice(0,-1),y=m?void 0:d,b={type:"header",data:t},U=[...n,...g];U.sort((H,R)=>ec(H)-ec(R));let T=[b,...U];return{completedTurns:g,inProgressTurn:y,staticItems:T}},[t,o,r,n]),p=i.current;return Qt(Za,{flexDirection:"column",children:[Yt(dh,{items:l,children:u=>mh(u)?Qt(Za,{borderStyle:"round",borderColor:"blue",paddingX:1,flexDirection:"column",children:[Yt(Bn,{bold:!0,children:"Memo Code CLI"}),Qt(Bn,{color:"gray",children:[u.data.providerName," / ",u.data.model," \u2022 v",u.data.version]}),Qt(Bn,{color:"gray",children:["cwd: ",u.data.cwd]}),Qt(Bn,{color:"gray",children:["mcp: ",u.data.mcpNames.join(", ")||"none"]})]},`header-${s}`):fh(u)?Yt(Qa,{message:u},u.id):Yt(Eo,{turn:u,cwd:p},`turn-${u.sequence??u.index}`)}),a?Yt(Eo,{turn:a,cwd:p}):null]})});import{memo as Oh,useCallback as ut,useEffect as Vn,useMemo as xc,useRef as en,useState as Qe}from"react";import{Box as Lo,Text as Xn,useInput as Lh,useStdout as Nh}from"ink";async function oc(e){return Es(e)}import{basename as hh,resolve as Ro}from"path";var sc=new Map;function ic(e){let t=Ro(e);return process.platform==="win32"?t.toLowerCase():t}function ac(e){return Ro(e)}function yh(e){let t=Ro(e),n=sc.get(t);if(n)return n;let r=new mn({sessionsDir:t});return sc.set(t,r),r}function _h(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Sh(e){let t=e.title?.trim();return t||hh(e.filePath).replace(/\.jsonl$/i,"")}async function Wn(e){let t=e.limit??10;if(t<=0)return[];let r=await yh(e.sessionsDir).getAllSummaries(),o=ic(e.cwd),s=e.activeSessionFile?ac(e.activeSessionFile):null,i=e.keyword?.trim().toLowerCase(),c=new Set,a=[],l=[...r].sort((p,u)=>u.date.updatedAt.localeCompare(p.date.updatedAt));for(let p of l){if(a.length>=t)break;if(ic(p.cwd)!==o)continue;let u=ac(p.filePath);if(s&&u===s||c.has(u))continue;let d=Sh(p);i&&!d.toLowerCase().includes(i)||(c.add(u),a.push({id:u,cwd:e.cwd,input:d,ts:_h(p.date.updatedAt),sessionFile:u}))}return a}import{memo as vh}from"react";import{Box as jn,Text as zn}from"ink";import{jsx as ct,jsxs as wh}from"react/jsx-runtime";var Th="#3a3a3a",Gn="#262626",cc=vh(function({items:t,activeIndex:n,loading:r}){return r?ct(jn,{paddingX:1,backgroundColor:Gn,children:ct(zn,{color:"gray",children:"Loading..."})}):t.length?ct(jn,{flexDirection:"column",backgroundColor:Gn,children:t.map((o,s)=>{let i=s===n;return wh(jn,{paddingX:1,gap:2,backgroundColor:i?Th:Gn,children:[ct(zn,{color:i?"cyan":"white",bold:i,children:o.title}),o.subtitle?ct(zn,{color:"gray",children:o.subtitle}):null]},o.id)})}):ct(jn,{paddingX:1,backgroundColor:Gn,children:ct(zn,{color:"gray",children:"No matches"})})});import Ch from"string-width";var bh=55296,xh=56319,Mh=56320,kh=57343;function lc(e){return e>=bh&&e<=xh}function uc(e){return e>=Mh&&e<=kh}function Pe(e,t){if(!Number.isFinite(t)||t<=0)return 0;if(t>=e.length)return e.length;if(e.length===0)return 0;let n=Math.floor(t);if(n<=0)return 0;if(n>=e.length)return e.length;let r=e.charCodeAt(n),o=e.charCodeAt(n-1);return uc(r)&&lc(o)?n-1:n}function pc(e,t){let n=Pe(e,t);if(n>=e.length)return e.length;let r=e.codePointAt(n);return r===void 0?Math.min(e.length,n+1):Math.min(e.length,n+(r>65535?2:1))}function lt(e,t){let n=Pe(e,t);if(n<=0)return 0;let r=n-1;if(r<=0)return r;let o=e.charCodeAt(r),s=e.charCodeAt(r-1);return uc(o)&&lc(s)?r-1:r}function Kn(e,t){let n=Pe(e,t),r=e.lastIndexOf(`
|
|
111
|
+
`,Math.max(0,n-1));return r===-1?0:r+1}function qn(e,t){let n=Pe(e,t),r=e.indexOf(`
|
|
112
|
+
`,n);return r===-1?e.length:r}function Ah(e){return/[\p{L}\p{N}_]/u.test(e)}function dc(e,t,n){let r=Pe(e,t);if(!n)return{value:e,cursor:r};let o=n.replace(/\r\n?/g,`
|
|
113
|
+
`);return o?{value:`${e.slice(0,r)}${o}${e.slice(r)}`,cursor:r+o.length}:{value:e,cursor:r}}function mc(e,t){let n=Pe(e,t);if(n<=0)return{value:e,cursor:n};let r=lt(e,n);return{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function Io(e,t){let n=Pe(e,t);if(n>=e.length)return{value:e,cursor:n};let r=pc(e,n);return{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function fc(e,t){let n=Pe(e,t);if(n<=0)return{value:e,cursor:n};let r=n;for(;r>0;){let s=lt(e,r);if(e.slice(s,r).trim().length>0)break;r=s}for(;r>0;){let s=lt(e,r),i=e.slice(s,r);if(!Ah(i))break;r=s}return r===n&&(r=lt(e,n)),{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function gc(e,t){let n=Pe(e,t),r=Kn(e,n);return r>=n?{value:e,cursor:n}:{value:`${e.slice(0,r)}${e.slice(n)}`,cursor:r}}function hc(e,t){let n=Pe(e,t),r=qn(e,n);return r<=n?{value:e,cursor:n}:{value:`${e.slice(0,n)}${e.slice(r)}`,cursor:n}}function yc(e,t){return lt(e,t)}function _c(e,t){return pc(e,t)}function Sc(e,t){return Kn(e,t)}function vc(e,t){return qn(e,t)}function Oo(e,t,n,r){let o=Pe(e,t),s=Kn(e,o),i=qn(e,o),c=o-s,a=r??c;if(n==="up"){if(s===0)return{cursor:o,preferredColumn:a,changed:!1};let d=s-1,m=Kn(e,d),g=Math.min(m+a,d);return{cursor:g,preferredColumn:a,changed:g!==o}}if(i>=e.length)return{cursor:o,preferredColumn:a,changed:!1};let l=i+1,p=qn(e,l),u=Math.min(l+a,p);return{cursor:u,preferredColumn:a,changed:u!==o}}function Tc(e,t,n){let r=Pe(e,t),o=Number.isFinite(n)?Math.max(1,Math.floor(n)):1,s=[],i=0,c=0,a="",l=0,p=()=>{s.push({text:a,start:i,end:c})},u=0;for(let g of e){let y=u;if(u+=g.length,g===`
|
|
114
|
+
`){c=y,p(),i=u,c=u,a="",l=0;continue}let b=Math.max(0,Ch(g));a.length>0&&l+b>o&&(p(),i=y,c=y,a="",l=0),a+=g,c=u,l+=b}if(p(),s.length===0)return{lines:[{text:"",start:0,end:0}],row:0,cursorInRow:0};let d=Math.max(0,s.length-1),m=(s[d]?.text??"").length;for(let g=0;g<s.length;g+=1){let y=s[g];if(y&&!(r<y.start)&&r<=y.end){d=g,m=r-y.start;break}}return{lines:s,row:d,cursorInRow:m}}function wc(e,t){let n=e==="\b"||e==="\x7F",r=!!t.ctrl&&e.toLowerCase()==="h";return t.backspace||n||r||t.delete&&!(t.ctrl||t.meta)?"backspace":t.delete?"delete":"none"}var Ph=3,Cc=8,Eh=120,Rh=process.platform==="win32"?60:8,Zt=class{lastPlainCharAtMs=null;consecutivePlainChars=0;burstWindowUntilMs=null;buffer="";active=!1;pendingFirstChar=null;minChars;charIntervalMs;enterSuppressWindowMs;activeIdleTimeoutMs;constructor(t={}){this.minChars=t.minChars??Ph,this.charIntervalMs=t.charIntervalMs??Cc,this.enterSuppressWindowMs=t.enterSuppressWindowMs??Eh,this.activeIdleTimeoutMs=t.activeIdleTimeoutMs??Rh}static recommendedFlushDelayMs(){return Cc+1}recommendedActiveFlushDelayMs(){return this.activeIdleTimeoutMs+1}onPlainChar(t,n){let r=Array.from(t)[0]??"";return this.notePlainChar(n),this.active?(this.extendWindow(n),{type:"buffer_append"}):this.pendingFirstChar&&n-this.pendingFirstChar.atMs<=this.charIntervalMs?(this.active=!0,this.buffer+=this.pendingFirstChar.ch,this.pendingFirstChar=null,this.extendWindow(n),{type:"begin_buffer_from_pending"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:r?(this.pendingFirstChar={ch:r,atMs:n},{type:"retain_first_char"}):{type:"retain_first_char"}}onPlainCharNoHold(t){return this.notePlainChar(t),this.active?(this.extendWindow(t),{type:"buffer_append"}):this.consecutivePlainChars>=this.minChars?{type:"begin_buffer",retroChars:Math.max(0,this.consecutivePlainChars-1)}:null}flushIfDue(t){let n=this.isActiveInternal()?this.activeIdleTimeoutMs:this.charIntervalMs;if(!(this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs>n))return{type:"none"};if(this.isActiveInternal()){this.active=!1;let o=this.buffer;return this.buffer="",{type:"paste",text:o}}if(this.pendingFirstChar){let o=this.pendingFirstChar.ch;return this.pendingFirstChar=null,{type:"typed",text:o}}return{type:"none"}}appendNewlineIfActive(t){return this.isActiveInternal()?(this.buffer+=`
|
|
115
|
+
`,this.extendWindow(t),!0):!1}newlineShouldInsertInsteadOfSubmit(t){let n=this.burstWindowUntilMs!==null&&t<=this.burstWindowUntilMs;return this.isActiveInternal()||n}extendWindow(t){this.burstWindowUntilMs=t+this.enterSuppressWindowMs}beginWithRetroGrabbed(t,n){t&&(this.buffer+=t),this.active=!0,this.extendWindow(n)}appendCharToBuffer(t,n){t&&(this.buffer+=t,this.extendWindow(n))}decideBeginBuffer(t,n,r){let o=Ih(n,r),s=n.slice(o);return/\s/u.test(s)||Array.from(s).length>=16?(this.beginWithRetroGrabbed(s,t),{start:o,grabbed:s}):null}flushBeforeModifiedInput(){if(!this.isActive())return null;this.active=!1;let t=this.buffer;return this.buffer="",this.pendingFirstChar&&(t+=this.pendingFirstChar.ch,this.pendingFirstChar=null),t}clearWindowAfterNonChar(){this.consecutivePlainChars=0,this.lastPlainCharAtMs=null,this.burstWindowUntilMs=null,this.active=!1,this.pendingFirstChar=null}isActive(){return this.isActiveInternal()||this.pendingFirstChar!==null}isBuffering(){return this.isActiveInternal()}hasPendingFirstChar(){return this.pendingFirstChar!==null}clearAfterExplicitPaste(){this.lastPlainCharAtMs=null,this.consecutivePlainChars=0,this.burstWindowUntilMs=null,this.active=!1,this.buffer="",this.pendingFirstChar=null}notePlainChar(t){this.lastPlainCharAtMs!==null&&t-this.lastPlainCharAtMs<=this.charIntervalMs?this.consecutivePlainChars+=1:this.consecutivePlainChars=1,this.lastPlainCharAtMs=t}isActiveInternal(){return this.active||this.buffer.length>0}};function Ih(e,t){if(t<=0)return e.length;let n=e.length,r=t;for(;r>0&&n>0;)n=lt(e,n),r-=1;return n}var Ne={HELP:"help",EXIT:"exit",NEW:"new",RESUME:"resume",REVIEW:"review",MODELS:"models",TOOLS:"tools",COMPACT:"compact",MCP:"mcp",INIT:"init"},ye={NONE:"none",ONCE:"once",FULL:"full"};function Ye(e){return`/${e}`}var bc="exit";import{jsx as kt,jsxs as Mc}from"react/jsx-runtime";var $h=400,No=Ye(Ne.MODELS),$o=Ye(Ne.TOOLS),Dh=Ye(Ne.INIT),Uh=[{mode:ye.NONE,description:"Disable all tool calls"},{mode:ye.ONCE,description:"Require approval when needed"},{mode:ye.FULL,description:"Run tools without approval"}];function Fh(e){let t=e.lastIndexOf("@");if(t===-1)return null;if(t>0){let r=e[t-1];if(r&&!/\s/.test(r))return null}let n=e.slice(t+1);return/\s/.test(n)?null:{type:"file",query:n,tokenStart:t+1}}function Hh(e){let t=e.trimStart(),n=e.length-t.length;if(!t.length)return null;let r=t;if(r.startsWith("/")&&(r=r.slice(1)),!r.toLowerCase().startsWith(Ne.RESUME)||e.slice(0,n).trim().length>0)return null;let s=r.slice(Ne.RESUME.length);return s&&!s.startsWith(" ")?null:{type:"history",keyword:s.trim()}}function Bh(e){let t=e.trimStart();if(!t.startsWith("/"))return null;let n=t.slice(1);return n.includes(" ")?null:n.length?/^[a-zA-Z-]+$/.test(n)?{type:"slash",keyword:n.toLowerCase()}:null:{type:"slash",keyword:""}}function Wh(e){let t=e.trimStart();if(!t.startsWith(No))return null;let n=t.slice(No.length);return n&&!n.startsWith(" ")?null:{type:"models",keyword:n.trim().toLowerCase()}}function jh(e){let t=e.trimStart();if(!t.startsWith($o))return null;let n=t.slice($o.length);return n&&!n.startsWith(" ")?null:{type:"tools"}}function zh(e){return jh(e)??Wh(e)??Bh(e)??Fh(e)??Hh(e)}function Gh(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";let n=String(t.getFullYear()),r=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${s}:${i}`}function Kh(e,t){return{mode:"model",items:e.filter(r=>{if(!t)return!0;let o=r.name.toLowerCase(),s=r.model.toLowerCase();return o.includes(t)||s.includes(t)}).map(r=>({id:r.name,title:`${r.name}: ${r.model}`,subtitle:r.base_url,kind:"model",value:`${No} ${r.name}`,meta:{type:"model",provider:r}}))}}function qh(e){return{mode:"tools",items:Uh.map(n=>({id:n.mode,title:n.mode,subtitle:n.mode===e?`Current \xB7 ${n.description}`:n.description,kind:"tools",value:`${$o} ${n.mode}`,meta:{type:"tools",mode:n.mode}}))}}function Vh(e){return{mode:"slash",items:Bt.filter(n=>n.name.startsWith(e)).map(n=>({id:n.name,title:`/${n.name}`,subtitle:n.description,kind:"slash",value:`/${n.name}`,meta:{type:"slash"}}))}}async function Xh({trigger:e,cwd:t,sessionsDir:n,currentSessionFile:r,providers:o,toolPermissionMode:s}){switch(e.type){case"file":return{mode:"file",items:(await oc({cwd:t,query:e.query,limit:8,respectGitIgnore:!0})).map(a=>({id:a.id,title:a.isDir?`${a.path}/`:a.path,kind:"file",value:a.isDir?`${a.path}/`:a.path,meta:{type:"file",isDir:a.isDir}}))};case"history":return{mode:"history",items:(await Wn({sessionsDir:n,cwd:t,keyword:e.keyword,activeSessionFile:r})).map(a=>({id:a.id,title:a.input,subtitle:Gh(a.ts),kind:"history",value:a.input,meta:{type:"history",entry:a}}))};case"models":return Kh(o,e.keyword);case"tools":return qh(s);case"slash":return Vh(e.keyword)}}var kc=Oh(function({disabled:t,busy:n,history:r,cwd:o,sessionsDir:s,currentSessionFile:i,providers:c,configPath:a,providerName:l,model:p,toolPermissionMode:u,mcpServers:d,onSubmit:m,onExit:g,onClear:y,onNewSession:b,onCancelRun:U,onCompact:T,onHistorySelect:H,onModelSelect:R,onSetToolPermission:I,onReviewPullRequest:G,onSystemMessage:se}){let{stdout:Re}=Nh(),[ie,z]=Qe({value:"",cursor:0}),M=en(ie),P=en(null),[te,ae]=Qe(null),[F,ce]=Qe(""),[J,A]=Qe("none"),[O,ne]=Qe([]),[Se,fe]=Qe(0),[Ke,$e]=Qe(!1),[tt,ve]=Qe(!1),be=en(0),k=en(0),L=en(new Zt);Vn(()=>{M.current=ie,ve(!1)},[ie]);let rn=xc(()=>({configPath:a,providerName:l,model:p,mcpServers:d,providers:c,toolPermissionMode:u}),[a,l,p,d,c,u]),Te=xc(()=>t||tt?null:zh(ie.value),[t,ie.value,tt]),K=ut((w=!0)=>{w&&ve(!0),A("none"),ne([]),fe(0),$e(!1)},[]),$=ut((w,S=!1)=>{M.current=w,z(w),S&&(ae(null),ce(""))},[]),Lt=ut(()=>{$({value:"",cursor:0},!0)},[$]),N=ut((w,S=!0)=>{if(!w)return;let _=M.current;P.current=null;let Q=dc(_.value,_.cursor,w);$(Q,S),w.includes(`
|
|
116
|
+
`)&&K(!1)},[$,K]),nt=ut(w=>w.type==="none"?!1:w.type==="paste"?(w.text&&N(w.text,!0),!0):(N(w.text,!0),!0),[N]),le=ut((w=!0)=>{let S=L.current.flushBeforeModifiedInput();return S&&N(S,!0),w&&L.current.clearWindowAfterNonChar(),!!S},[N]);Vn(()=>{let w=setInterval(()=>{let S=L.current.flushIfDue(Date.now());nt(S)},Zt.recommendedFlushDelayMs());return()=>{clearInterval(w)}},[nt]),Vn(()=>{t&&K(!1)},[t,K]),Vn(()=>{if(!Te){K(!1);return}let w=!1,S=++be.current;return $e(!0),(async()=>{try{let{mode:_,items:Q}=await Xh({trigger:Te,cwd:o,sessionsDir:s,currentSessionFile:i,providers:c,toolPermissionMode:u});if(w||S!==be.current)return;A(_),ne(Q),fe(re=>Q.length?Math.min(re,Q.length-1):0)}finally{!w&&S===be.current&&$e(!1)}})(),()=>{w=!0}},[Te,o,s,i,c,u,K]);let qe=ut(w=>{if(w){if(J==="file"&&Te?.type==="file"){let S=M.current.value,_=S.slice(0,Te.tokenStart),Q=S.slice(Te.tokenStart+Te.query.length),re=`${_}${w.value}${Q}`,De=_.length+w.value.length;$({value:re,cursor:De},!0),w.meta?.type==="file"&&w.meta.isDir||K();return}switch(w.meta?.type){case"history":H(w.meta.entry),$({value:w.value,cursor:w.value.length},!1),K();return;case"model":R(w.meta.provider),Lt(),K();return;case"tools":I(w.meta.mode),Lt(),K();return;case"slash":$({value:`${w.value} `,cursor:`${w.value} `.length},!0),K(!1);return;default:$({value:w.value,cursor:w.value.length},!0),K()}}},[$,J,Te,K,Lt,H,R,I]);Lh((w,S)=>{if(S.ctrl&&w==="c"){g();return}if(t)return;let _=Date.now();nt(L.current.flushIfDue(_));let Q=J!=="none",re=Q&&O.length>0,De=wc(w,S),ar=!!(S.ctrl||S.meta),Nt=!!w&&!ar&&!S.return&&!S.tab&&De==="none"&&!S.escape&&!S.upArrow&&!S.downArrow&&!S.leftArrow&&!S.rightArrow;if(!Nt&&!S.return&&le(!0),S.ctrl&&w==="a"){let x=M.current,E=Sc(x.value,x.cursor);P.current=null,$({value:x.value,cursor:E},!1);return}if(S.ctrl&&w==="e"){let x=M.current,E=vc(x.value,x.cursor);P.current=null,$({value:x.value,cursor:E},!1);return}if(S.ctrl&&w==="u"){let x=M.current,E=gc(x.value,x.cursor);P.current=null,$(E,!0);return}if(S.ctrl&&w==="k"){let x=M.current,E=hc(x.value,x.cursor);P.current=null,$(E,!0);return}if(S.ctrl&&w==="w"){let x=M.current,E=fc(x.value,x.cursor);P.current=null,$(E,!0);return}if(S.ctrl&&w==="d"){let x=M.current;if(!x.value){g();return}let E=Io(x.value,x.cursor);P.current=null,$(E,!0);return}if(S.ctrl&&w==="l"){$({value:"",cursor:0},!0),K(),y(),b();return}if(S.escape){if(_-k.current<=$h){k.current=0,n?U():(P.current=null,$({value:"",cursor:0},!0),K());return}k.current=_,Q&&K();return}if(S.upArrow){if(re){fe(B=>B<=0?O.length-1:B-1);return}let x=M.current;if(x.value.includes(`
|
|
117
|
+
`)){let B=Oo(x.value,x.cursor,"up",P.current??void 0);if(B.changed){P.current=B.preferredColumn,$({value:x.value,cursor:B.cursor},!1);return}}if(!r.length)return;if(te===null){ce(x.value);let B=r.length-1;ae(B);let xe=r[B]??"";P.current=null,$({value:xe,cursor:xe.length},!1);return}let E=Math.max(0,te-1);ae(E);let ue=r[E]??"";P.current=null,$({value:ue,cursor:ue.length},!1);return}if(S.downArrow){if(re){fe(B=>(B+1)%O.length);return}let x=M.current;if(x.value.includes(`
|
|
118
|
+
`)){let B=Oo(x.value,x.cursor,"down",P.current??void 0);if(B.changed){P.current=B.preferredColumn,$({value:x.value,cursor:B.cursor},!1);return}}if(te===null)return;let E=te+1;if(E>=r.length){ae(null),P.current=null,$({value:F,cursor:F.length},!1),ce("");return}ae(E);let ue=r[E]??"";P.current=null,$({value:ue,cursor:ue.length},!1);return}if(S.leftArrow){let x=M.current,E=yc(x.value,x.cursor);P.current=null,$({value:x.value,cursor:E},!1);return}if(S.rightArrow){let x=M.current,E=_c(x.value,x.cursor);P.current=null,$({value:x.value,cursor:E},!1);return}if(S.tab&&re){qe(O[Se]);return}if(S.return){if(re){qe(O[Se]);return}L.current.hasPendingFirstChar()&&!L.current.isBuffering()&&le(!1);let x=M.current.value.trimStart().startsWith("/");if(!S.shift&&!x){if(L.current.appendNewlineIfActive(_))return;if(L.current.newlineShouldInsertInsteadOfSubmit(_)){le(!1),N(`
|
|
119
|
+
`,!0),L.current.extendWindow(_);return}}if(le(!0),S.shift){N(`
|
|
120
|
+
`,!0);return}let ue=M.current.value.trim();if(!ue)return;if(ue.startsWith("/")){let B=wr(ue,rn);switch(B.kind){case"message":se(B.title,B.content);break;case"new":b();break;case"exit":g();break;case"switch_model":R(B.provider);break;case"set_tool_permission":I(B.mode);break;case"compact":T();break;case"review_pr":G(B.prNumber);break;case"init_agents_md":m(Dh);break;default:{let xe=B}}P.current=null,$({value:"",cursor:0},!0),K(!1);return}m(ue),P.current=null,$({value:"",cursor:0},!0),K(!1);return}if(De!=="none"){let x=M.current,E=De==="backspace"?mc(x.value,x.cursor):Io(x.value,x.cursor);P.current=null,$(E,!0);return}if(w&&Nt){let x=Array.from(w);if(x.length!==1){le(!1),N(w,!0),L.current.clearAfterExplicitPaste();return}let E=x[0]??"";if(!E)return;let ue=ot=>{let mt=M.current,on=mt.value.slice(0,mt.cursor),sn=mt.value.slice(mt.cursor),$t=L.current.decideBeginBuffer(_,on,ot);return $t?(P.current=null,$({value:`${on.slice(0,$t.start)}${sn}`,cursor:$t.start},!0),L.current.appendCharToBuffer(E,_),!0):!1};if(!((E.codePointAt(0)??0)<=127)){let ot=L.current.onPlainCharNoHold(_);if(ot?.type==="buffer_append"){L.current.appendCharToBuffer(E,_);return}if(ot?.type==="begin_buffer"&&ue(ot.retroChars))return;le(!1),N(E,!0);return}let xe=L.current.onPlainChar(E,_);if(xe.type==="retain_first_char")return;if(xe.type==="buffer_append"||xe.type==="begin_buffer_from_pending"){L.current.appendCharToBuffer(E,_);return}if(xe.type==="begin_buffer"&&ue(xe.retroChars))return;le(!1),N(E,!0);return}w&&(N(w,!0),L.current.clearWindowAfterNonChar())});let dt=Re?.columns??process.stdout?.columns??80,Y=Math.max(1,dt-3),Ve=Tc(ie.value,ie.cursor,Y),rt=Ve.lines;return Mc(Lo,{flexDirection:"column",gap:1,children:[kt(Lo,{flexDirection:"column",paddingY:1,children:rt.map((w,S)=>{let _=w.text,Q=!t&&S===Ve.row,re=Q?_.slice(0,Ve.cursorInRow):_,De=Q?_.slice(Ve.cursorInRow):"";return Mc(Lo,{children:[kt(Xn,{color:"gray",children:S===0?"\u203A ":" "}),kt(Xn,{children:re}),Q?kt(Xn,{color:"cyan",children:"\u258A"}):null,Q?kt(Xn,{children:De}):null]},`line-${S}`)})}),J!=="none"?kt(cc,{items:O.map(({value:w,meta:S,..._})=>_),activeIndex:Se,loading:Ke}):null]})});import{memo as Jh}from"react";import{Box as Ac,Text as Do}from"ink";import{jsx as Uo,jsxs as Pc}from"react/jsx-runtime";var Ec=Jh(function({busy:t,pendingApproval:n=!1,contextPercent:r}){let o=`${r.toFixed(1)}%`;return Pc(Ac,{justifyContent:"space-between",children:[Uo(Ac,{children:t?Uo(Do,{color:"yellow",children:"Working..."}):Uo(Do,{color:"gray",children:n?"Approval pending \u2022 Enter confirm \u2022 Esc deny":"Enter send \u2022 Shift+Enter newline \u2022 /help"})}),Pc(Do,{color:"gray",children:["context: ",o]})]})});import{memo as Yh}from"react";import{Box as Jn,Text as Fo,useInput as Qh}from"ink";import{Select as Zh,StatusMessage as ey}from"@inkjs/ui";import{jsx as pt,jsxs as Rc}from"react/jsx-runtime";var ty=[{label:"Allow once",decision:"once"},{label:"Allow for this session",decision:"session"},{label:"Deny",decision:"deny"}];function ny(e){if(!e)return"";if(typeof e!="object")return String(e);let t=Object.entries(e);if(!t.length)return"";let[n,r]=t[0]??[];if(!n)return"";let o=typeof r=="string"?r:JSON.stringify(r);return`${n}=${o?.slice(0,60)??""}${o&&o.length>60?"...":""}`}var Ic=Yh(function({request:t,onDecision:n}){Qh((o,s)=>{(s.escape||s.ctrl&&o==="c")&&n("deny")});let r=ny(t.params);return Rc(Jn,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",paddingX:1,children:[pt(Fo,{bold:!0,color:"yellow",children:"Tool Approval Required"}),Rc(Fo,{children:[t.toolName,r?` (${r})`:""]}),pt(Jn,{marginTop:1,children:pt(ey,{variant:"warning",children:t.reason})}),pt(Jn,{marginTop:1,flexDirection:"column",children:pt(Zh,{options:ty.map(o=>({label:o.label,value:o.decision})),onChange:o=>{n(o)}})}),pt(Jn,{marginTop:1,children:pt(Fo,{color:"gray",children:"Enter confirm \u2022 Esc deny"})})]})});import{memo as ry,useMemo as oy,useState as sy}from"react";import{Box as Ho,Text as Yn,useInput as iy}from"ink";import{MultiSelect as ay}from"@inkjs/ui";import{jsx as tn,jsxs as Bo}from"react/jsx-runtime";function cy(e,t){let n=new Set(e);return t.filter(r=>n.has(r))}var Oc=ry(function({serverNames:t,defaultSelected:n,onConfirm:r,onExit:o}){let s=oy(()=>{let l=cy(t,n);return n.length===0?[]:l.length>0?l:[...t]},[n,t]),[i,c]=sy(s),a=i.length===t.length;return iy((l,p)=>{if(p.ctrl&&l==="c"){o();return}p.escape&&r(i,!1)}),Bo(Ho,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[tn(Yn,{bold:!0,color:"cyan",children:"Activate MCP Servers"}),tn(Yn,{color:"gray",children:"Select servers to load for this run."}),tn(Ho,{marginTop:1,flexDirection:"column",children:tn(ay,{options:t.map(l=>({label:l,value:l})),defaultValue:s,onChange:c,onSubmit:l=>{r(l,!0)}})}),Bo(Ho,{marginTop:1,flexDirection:"column",children:[Bo(Yn,{color:"gray",children:["Selected: ",i.length,"/",t.length,a?" (all)":""]}),tn(Yn,{color:"gray",children:"Controls: \u2191/\u2193 move, Space toggle, Enter confirm"})]})]})});import{spawn as ly}from"child_process";var Wo="\x07",uy="Memo: Approval required",py="Memo CLI",dy=2e3;function my(e){return e.replace(/\s+/g," ").trim()}function fy(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-3))}...`}function gy(e){let t=my(e.reason),n=`Tool ${e.toolName} is waiting for your approval.`;return t?fy(`${n} ${t}`,220):n}function Lc(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function hy(e,t=process.platform){let n=uy,r=gy(e);return t==="darwin"?{command:"osascript",args:["-e",`display notification "${Lc(r)}" with title "${Lc(n)}"`]}:t==="linux"?{command:"notify-send",args:["--app-name",py,n,r]}:null}async function yy(e,t){await new Promise((n,r)=>{let o=ly(e,t,{stdio:"ignore"}),s=!1,i=a=>{if(!s){if(s=!0,a){r(a);return}n()}},c=setTimeout(()=>{try{o.kill()}catch{}i()},dy);o.once("error",a=>{clearTimeout(c),i(a)}),o.once("exit",a=>{if(clearTimeout(c),a===0||a===null){i();return}i(new Error(`${e} exited with code ${a}`))})})}function _y(e){if(e){e(Wo);return}try{if(process.stdout?.isTTY){process.stdout.write(Wo);return}process.stderr?.isTTY&&process.stderr.write(Wo)}catch{}}async function Nc(e,t={}){_y(t.writeBell);let n=hy(e,t.platform??process.platform);if(!n)return;let r=t.runCommand??yy;try{await r(n.command,n.args)}catch{}}import{Box as At,Text as Ge,useInput as Sy}from"ink";import{Spinner as vy,StatusMessage as Ty,TextInput as wy}from"@inkjs/ui";import{memo as Cy,useCallback as $c,useMemo as by,useState as Qn}from"react";import{jsx as Ee,jsxs as Pt}from"react/jsx-runtime";var Ze=[{key:"name",label:"Provider name",hint:"Used for /models switching",defaultValue:"deepseek"},{key:"envKey",label:"API key env var",hint:"Read at runtime from environment variables",defaultValue:"DEEPSEEK_API_KEY"},{key:"model",label:"Model name",defaultValue:"deepseek-chat"},{key:"baseUrl",label:"Base URL",defaultValue:"https://api.deepseek.com"}],Dc=Cy(function({configPath:t,onComplete:n,onExit:r}){let[o,s]=Qn(0),[i,c]=Qn({}),[a,l]=Qn(!1),[p,u]=Qn(null),d=Ze[o]??Ze[0],m=$c(async b=>{l(!0),u(null);try{let U={current_provider:b.name,providers:[{name:b.name,env_api_key:b.envKey,model:b.model,base_url:b.baseUrl||void 0}]};await we(t,U),n()}catch(U){u(U.message),l(!1)}},[t,n]),g=$c(async b=>{if(!d)return;let U=b.trim()||d.defaultValue,T={...i,[d.key]:U};if(c(T),o<Ze.length-1){s(o+1);return}let H={name:T.name||Ze[0].defaultValue,envKey:T.envKey||Ze[1].defaultValue,model:T.model||Ze[2].defaultValue,baseUrl:T.baseUrl||Ze[3].defaultValue};await m(H)},[m,d,o,i]);Sy((b,U)=>{U.ctrl&&b==="c"&&r()});let y=by(()=>`Step ${o+1}/${Ze.length}`,[o]);return d?Pt(At,{flexDirection:"column",children:[Ee(Ge,{bold:!0,children:"Memo setup"}),Ee(Ge,{color:"gray",children:"No provider config found. Complete setup to continue."}),Pt(Ge,{color:"gray",children:["Config path: ",t]}),Pt(At,{marginTop:1,flexDirection:"column",children:[Ee(Ge,{color:"cyan",children:y}),Ee(Ge,{children:d.label}),Pt(Ge,{color:"gray",children:["Default: ",d.defaultValue]}),d.hint?Ee(Ge,{color:"gray",children:d.hint}):null]}),Pt(At,{marginTop:1,children:[Ee(Ge,{color:"gray",children:"> "}),Ee(wy,{isDisabled:a,defaultValue:i[d.key]??"",placeholder:d.defaultValue,onSubmit:b=>{g(b)}},d.key)]}),Ee(At,{marginTop:1,children:Ee(Ge,{color:"gray",children:"Enter to continue, Ctrl+C to exit"})}),a?Ee(At,{marginTop:1,children:Ee(vy,{label:"Saving config..."})}):null,p?Ee(At,{marginTop:1,children:Pt(Ty,{variant:"error",children:["Failed to save config: ",p]})}):null]}):null});function Uc(e){let t=e.finalText?.trim();return t||e.steps.map(n=>n.assistantText??"").join("").trim()}function xy(e){return e==="ok"||e==="error"||e==="cancelled"?e:void 0}function My(e){if(e.resultStatus)return e.resultStatus==="success"?ke.SUCCESS:ke.ERROR}function ky(e,t,n){return{index:-(n+1),userInput:e.input??"",steps:(e.steps??[]).map(r=>({index:r.step,assistantText:r.assistantText??"",thinking:r.thinking,action:r.action,parallelActions:r.parallelActions,observation:r.observation,toolStatus:My(r)})),status:xy(e.status),errorMessage:e.errorMessage,tokenUsage:e.tokenUsage,finalText:Uc(e),sequence:t}}function Zn(e){let t=dn(e,"history.log"),n=[...t.turns].sort((i,c)=>i.turn-c.turn),r=[];for(let i of n){let c=(i.input??"").trim();c&&r.push({role:"user",content:c});let a=Uc(i);a&&r.push({role:"assistant",content:a})}let o=0,s=n.map((i,c)=>(o+=1,ky(i,o,c)));return{summary:t.summary,messages:r,turns:s,maxSequence:o}}function jo(){return{turns:[],historicalTurns:[],systemMessages:[],sequence:0}}function Ay(e,t){return{index:e,userInput:"",steps:[],sequence:t}}function er(e,t){if(e.length>t)return e;let n=e.slice();for(;n.length<=t;)n.push({index:n.length,assistantText:""});return n}function Et(e,t,n){let r=e.turns.slice(),o=r.findIndex(i=>i.index===t);if(o===-1){let i=e.sequence+1;return r.push(n(Ay(t,i))),{turns:r,sequence:i}}let s=r[o];return s?(r[o]=n(s),{turns:r,sequence:e.sequence}):{turns:r,sequence:e.sequence}}function Py(e){return{id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,title:e.title,content:e.content,tone:e.tone??"info",sequence:e.sequence}}function Fc(e,t){switch(t.type){case"append_system_message":{let n=e.sequence+1;return{...e,sequence:n,systemMessages:[...e.systemMessages,Py({title:t.title,content:t.content,tone:t.tone,sequence:n})]}}case"turn_start":{let n=Et(e,t.turn,r=>({...r,index:t.turn,userInput:t.input,steps:[],finalText:void 0,status:void 0,errorMessage:void 0,tokenUsage:void 0,startedAt:Date.now(),durationMs:void 0,contextPromptTokens:t.promptTokens??r.contextPromptTokens}));return{...e,turns:n.turns,sequence:n.sequence}}case"context_usage":{let n=Et(e,t.turn,r=>{let o=er(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,contextPromptTokens:t.promptTokens},{...r,contextPromptTokens:t.promptTokens,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"assistant_chunk":{let n=Et(e,t.turn,r=>{let o=er(r.steps,t.step),s=o[t.step];if(!s)return r;let i=`${s.assistantText}${t.chunk}`;return i===s.assistantText?r:(o[t.step]={...s,assistantText:i},{...r,steps:o})});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_action":{let n=Et(e,t.turn,r=>{let o=er(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,action:t.action,thinking:t.thinking,parallelActions:t.parallelActions&&t.parallelActions.length>1?t.parallelActions:void 0,toolStatus:ke.EXECUTING},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"tool_observation":{let n=Et(e,t.turn,r=>{let o=er(r.steps,t.step),s=o[t.step];return s?(o[t.step]={...s,observation:t.observation,toolStatus:t.toolStatus,parallelToolStatuses:t.parallelToolStatuses},{...r,steps:o}):r});return{...e,turns:n.turns,sequence:n.sequence}}case"turn_final":{let n=Et(e,t.turn,r=>{let o=r.startedAt??Date.now(),s=Math.max(0,Date.now()-o),i=t.tokenUsage?.prompt??r.contextPromptTokens;return{...r,finalText:t.finalText,status:t.status,errorMessage:t.errorMessage,tokenUsage:t.turnUsage,contextPromptTokens:i,startedAt:o,durationMs:s}});return{...e,turns:n.turns,sequence:n.sequence}}case"replace_history":return{...e,historicalTurns:t.turns,sequence:Math.max(e.sequence,t.maxSequence)};case"clear_current_timeline":return{...e,turns:[],systemMessages:[]};case"reset_all":return jo();default:return e}}import{dirname as tr,join as Bc,resolve as Ey}from"path";import{statSync as Ry,existsSync as Wc,readFileSync as Iy}from"fs";import{readFile as Oy}from"fs/promises";import{get as Ly}from"https";import{fileURLToPath as Ny}from"url";function Hc(e){let t=e.trim().replace(/^v/i,""),[n="",r]=t.split("-",2),o=n.split(".").map(s=>Number(s));return o.length<3||o.some(s=>!Number.isFinite(s))?null:{major:o[0]??0,minor:o[1]??0,patch:o[2]??0,prerelease:r??null}}function $y(e,t){let n=Hc(e),r=Hc(t);return!n||!r?!1:n.major!==r.major?n.major>r.major:n.minor!==r.minor?n.minor>r.minor:n.patch!==r.patch?n.patch>r.patch:n.prerelease&&!r.prerelease?!1:!n.prerelease&&r.prerelease?!0:n.prerelease&&r.prerelease?n.prerelease>r.prerelease:!1}function jc(){try{let t=Ny(import.meta.url);return tr(t)}catch{}let e=Ey(process.argv[1]??process.cwd());try{return Ry(e).isFile()?tr(e):e}catch{return process.cwd()}}async function Dy(e){let t=Bc(e,"package.json");if(!Wc(t))return null;let n=await Oy(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}function Uy(e){let t=Bc(e,"package.json");if(!Wc(t))return null;try{let n=Iy(t,"utf8"),r=JSON.parse(n);return!r.name||!r.version?null:{name:r.name,version:r.version}}catch{return null}}async function Fy(){let e=jc();for(;;){let t=await Dy(e);if(t&&t.name==="@memo-code/memo")return t;let n=tr(e);if(n===e)break;e=n}return null}function nr(){let e=jc();for(;;){let t=Uy(e);if(t&&t.name==="@memo-code/memo")return t;let n=tr(e);if(n===e)break;e=n}return null}async function Hy(e,t=1500){let r=`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`;return new Promise(o=>{let s=Ly(r,{timeout:t},i=>{if(i.statusCode&&i.statusCode>=400){i.resume(),o(null);return}let c=[];i.on("data",a=>c.push(a)),i.on("end",()=>{try{let a=JSON.parse(Buffer.concat(c).toString("utf8"));o(a.version??null)}catch{o(null)}})});s.on("timeout",()=>{s.destroy(),o(null)}),s.on("error",()=>o(null))})}async function zc(){let e=await Fy();if(!e)return null;let t=await Hy(e.name);return!t||!$y(t,e.version)?null:{current:e.version,latest:t}}import{readFile as By}from"fs/promises";import{dirname as Wy,join as jy}from"path";import{fileURLToPath as zy}from"url";var Gy=/{{\s*([\w.-]+)\s*}}/g;function Ky(e,t){return e.replace(Gy,(n,r)=>t[r]??"")}async function zo(e,t={}){let n=Wy(zy(import.meta.url)),r=jy(n,"task-prompts",`${e}.md`),o=await By(r,"utf-8");return Ky(o,t)}import{spawn as qy}from"child_process";var Vy=12e3,Xy=new Set(["WRITE","MAINTAIN","ADMIN"]),Jy=["pull_request_read","list_pull_requests","search_pull_requests","add_issue_comment","add_comment_to_pending_review","issue_read","get_me"];function Yy(e){return e.replace(/\\/g,"/").toLowerCase()}function Qy(e,t){if(e.toLowerCase().includes("github"))return!0;if("command"in t){let o=Yy(t.command),s=(t.args??[]).join(" ").toLowerCase();return!!(o.includes("github")||o.includes("gh-")||s.includes("github")||s.includes("gh-"))}let r=t.url.toLowerCase();return r.includes("github")||r.includes("api.github.com")}function Zy(e,t){let n=new Set(t),r=Object.entries(e).filter(([i,c])=>Qy(i,c)).map(([i])=>i),o=r.find(i=>n.has(i))??null,s=r.filter(i=>!n.has(i));return{active:o,inactiveCandidates:s}}function e_(e){let t=new Map;for(let n of e)for(let r of Jy){let o=`_${r}`;if(!n.endsWith(o))continue;let s=n.slice(0,-o.length);s&&t.set(s,(t.get(s)??0)+1)}return Array.from(t.entries()).filter(([,n])=>n>=2).sort((n,r)=>r[1]-n[1]).map(([n])=>n)}async function Go(e,t,n,r=Vy){return new Promise(o=>{let s=qy(e,t,{cwd:n,env:process.env,stdio:["ignore","pipe","pipe"]}),i="",c="",a=!1,l=u=>{a||(a=!0,clearTimeout(p),o(u))},p=setTimeout(()=>{s.kill("SIGTERM"),l({ok:!1,stdout:i,stderr:c,code:null,errorMessage:`${e} ${t.join(" ")} timed out after ${r}ms`})},r);s.stdout.on("data",u=>{i+=u.toString()}),s.stderr.on("data",u=>{c+=u.toString()}),s.on("error",u=>{l({ok:!1,stdout:i,stderr:c,code:null,errorMessage:u.message})}),s.on("close",u=>{l({ok:u===0,stdout:i,stderr:c,code:u})})})}async function t_(e){if(!(await Go("gh",["--version"],e)).ok)return{ok:!1,reason:"GitHub MCP not available, and GitHub CLI (gh) is not installed or not executable. Install gh: https://cli.github.com/"};let n=await Go("gh",["auth","status","-h","github.com"],e);if(!n.ok)return{ok:!1,reason:`GitHub CLI is installed but not authenticated for github.com. Run: gh auth login -h github.com (detail: ${n.stderr.trim()||n.stdout.trim()||n.errorMessage||"unknown error"})`};let r=await Go("gh",["repo","view","--json","nameWithOwner,viewerPermission"],e);if(!r.ok)return{ok:!1,reason:`GitHub CLI authentication works, but this directory is not a readable GitHub repo for gh (detail: ${r.stderr.trim()||r.stdout.trim()||r.errorMessage||"unknown error"})`};let o;try{o=JSON.parse(r.stdout)}catch{return{ok:!1,reason:"Failed to parse `gh repo view` output. Try upgrading gh and retry."}}let s=o.nameWithOwner?.trim(),i=o.viewerPermission?.trim().toUpperCase();return!s||!i?{ok:!1,reason:"GitHub CLI did not return repository or permission info from `gh repo view`."}:Xy.has(i)?{ok:!0,repository:s,viewerPermission:i}:{ok:!1,reason:`GitHub CLI connected to ${s}, but permission is ${i}. PR review comments require WRITE/MAINTAIN/ADMIN permission.`}}async function Gc(e){let t=e_(e.availableToolNames??[]),n=e.activeMcpServerNames.find(l=>t.includes(l))??null,r=l=>{let p=e.availableToolNames;if(!p||p.length===0)return!0;let u=`${l}_`;return p.some(d=>d.startsWith(u))};if(n&&r(n))return{kind:"github_mcp",strategy:"github_mcp",details:`Using active GitHub MCP server \`${n}\` (detected from loaded MCP tool signatures).`,mcpServerPrefix:n};let{active:o,inactiveCandidates:s}=Zy(e.mcpServers,e.activeMcpServerNames);if(o&&r(o))return{kind:"github_mcp",strategy:"github_mcp",details:`Using active GitHub MCP server \`${o}\`.`,mcpServerPrefix:o};let i=await t_(e.cwd);if(i.ok){let l=s.length?` GitHub MCP server(s) configured but inactive in this session: ${s.join(", ")}.`:"";return{kind:"gh_cli",strategy:"gh_cli",details:`Using gh CLI on repo \`${i.repository}\` with permission \`${i.viewerPermission}\`.${l}`,repository:i.repository,viewerPermission:i.viewerPermission}}let c=s.length?` Also found configured but inactive GitHub MCP server(s): ${s.join(", ")}. Start a new session and activate one of them, or fix gh CLI access.`:"",a=o&&!r(o)?` Active MCP server \`${o}\` is configured, but no tools with prefix \`${o}_\` are currently loaded in this session.`:"";return{kind:"unavailable",reason:`${i.reason}${a}${c}`}}import{jsx as et,jsxs as l_}from"react/jsx-runtime";function i_(e,t){if(e.length===0)return[];if(t===void 0)return[...e];if(t.length===0)return[];let n=new Set(e),r=t.filter(o=>n.has(o));return r.length>0?r:[...e]}function a_(e,t){if(e.length===0)return[];if(t.length===0)return[];let n=new Set(e);return t.filter(r=>n.has(r))}function c_(){try{process.stdout?.isTTY&&process.stdout.write("\x1Bc")}catch{}}function qc({sessionOptions:e,providerName:t,model:n,configPath:r,mcpServers:o,cwd:s,sessionsDir:i,providers:c,modelProfiles:a,dangerous:l=!1,needsSetup:p=!1,initialHistory:u}){let{exit:d}=s_(),m=nn(()=>Object.keys(o??{}).sort(),[o]),g=nn(()=>i_(m,e.activeMcpServers),[m,e.activeMcpServers]),y=e.toolPermissionMode??(l?ye.FULL:ye.ONCE),[b,U]=r_(Fc,void 0,jo),[T,H]=Z(t),[R,I]=Z(n),[G,se]=Z(c),[Re,ie]=Z(a),[z,M]=Z(y),P=X(f=>_t({model_profiles:Re},f),[Re]),[te,ae]=Z({...e,providerName:t,contextWindow:P({name:t,model:n}),dangerous:y===ye.FULL,toolPermissionMode:y}),[F,ce]=Z(!1),[J,A]=Z([]),[O,ne]=Z(null),[Se,fe]=Z(null),[Ke,$e]=Z(P({name:t,model:n})),[tt,ve]=Z(0),[be,k]=Z(p),[L,rn]=Z(!p&&m.length>0),[Te,K]=Z(g),[$,Lt]=Z(null),[N,nt]=Z(null),le=rr(null),qe=rr(null),dt=rr(null),[Y,Ve]=Z(null),rt=rr(null),w=nn(()=>nr(),[]),S=X(f=>{U(f)},[]);It(()=>{u&&(S({type:"clear_current_timeline"}),S({type:"replace_history",turns:u.turns,maxSequence:u.maxSequence}),fe(u.messages),u.summary.trim()&&S({type:"append_system_message",title:"History",content:u.summary,tone:"info"}))},[S,u]),It(()=>{be||(K(g),rn(m.length>0))},[be,g,m.length]);let _=X((f,v,C="info")=>{S({type:"append_system_message",title:f,content:v,tone:C})},[S]),Q=nn(()=>({onAssistantStep:(f,v)=>{let C=qe.current;C&&S({type:"assistant_chunk",turn:C,step:v,chunk:f})},requestApproval:z===ye.FULL||z===ye.NONE?void 0:f=>new Promise(v=>{Nc(f),Ve(f),rt.current=v}),hooks:{onTurnStart:({turn:f,input:v,promptTokens:C})=>{qe.current=f;let q=dt.current;q&&(dt.current=null);let Ie=q??v;C&&C>0&&ve(C),S({type:"turn_start",turn:f,input:Ie,promptTokens:C})},onContextUsage:({turn:f,step:v,promptTokens:C,phase:q})=>{ve(C),S({type:"context_usage",turn:f,step:v,promptTokens:C,phase:q})},onContextCompacted:({reason:f,status:v,beforeTokens:C,afterTokens:q,reductionPercent:Ie,errorMessage:cr})=>{v==="success"&&ve(q);let lr=f==="manual"?"manual command":"auto trigger";if(v==="success"){_("Context compacted",`Compacted by ${lr}: ${C} -> ${q} tokens (${Ie.toFixed(2)}% reduced).`);return}if(v==="skipped"){_("Context compacted",`Skipped (${lr}): nothing to compact.`,"warning");return}_("Context compacted",`Failed (${lr}): ${cr??"unknown error"}`,"warning")},onAction:({turn:f,step:v,action:C,thinking:q,parallelActions:Ie})=>{S({type:"tool_action",turn:f,step:v,action:C,thinking:q,parallelActions:Ie})},onObservation:({turn:f,step:v,observation:C,resultStatus:q,parallelResultStatuses:Ie})=>{S({type:"tool_observation",turn:f,step:v,observation:C,toolStatus:Mo(q),parallelToolStatuses:Wa(Ie)})},onFinal:({turn:f,finalText:v,status:C,errorMessage:q,turnUsage:Ie,tokenUsage:cr})=>{S({type:"turn_final",turn:f,finalText:v,status:C,errorMessage:q,turnUsage:Ie,tokenUsage:cr}),ce(!1)}}}),[_,S,z]);It(()=>{let f=!1;return(async()=>{if(!(be||L))try{let v=le.current;v&&await v.close();let C=await Hn(Q,te);if(f){await C.close();return}le.current=C,nt(C),ne(C.historyFilePath??null)}catch(v){if(f)return;le.current=null,nt(null),ne(null),ce(!1),_("Session",`Failed to create session: ${v.message}`,"error")}})(),()=>{f=!0}},[_,Q,L,te,be]),It(()=>{let f=!1;return(async()=>{let v=await zc();f||!v||_("Update",`Update available: v${v.latest}. Run: npm install -g @memo-code/memo@latest`)})(),()=>{f=!0}},[_]),It(()=>()=>{le.current&&le.current.close()},[]);let re=X(async()=>{let f=rt.current;f&&(f("deny"),rt.current=null),Y&&Ve(null),le.current&&await le.current.close(),Lt("Bye!"),setTimeout(()=>d(),250)},[d,Y]),De=X(()=>{if(F){_("Clear","Cancel current run before clearing timeline.","warning");return}if(Y){_("Clear","Resolve current approval request before clearing timeline.","warning");return}S({type:"clear_current_timeline"}),fe(null),ve(0),c_()},[_,F,S,Y]),ar=X(()=>{if(F){_("New Session","Cancel current run before starting a new session.","warning");return}if(Y){_("New Session","Resolve current approval request before starting a new session.","warning");return}S({type:"reset_all"}),fe(null),ve(0),qe.current=null,ae(f=>({...f,sessionId:Rt()})),_("New Session","Started a fresh session.")},[_,F,S,Y]),Nt=X(async f=>{try{let v=await ee();await we(v.configPath,{...v.config,current_provider:f})}catch(v){_("Config",`Failed to persist provider: ${v.message}`,"warning")}},[_]),x=X(async f=>{if(F){_("Model switch","Cancel current run before switching models.","warning");return}if(f.name===T&&f.model===R){_("Model switch",`Already using ${f.name} (${f.model}).`);return}S({type:"reset_all"}),ve(0),qe.current=null;let v=P(f);H(f.name),I(f.model),$e(v),ae(C=>({...C,sessionId:Rt(),providerName:f.name,contextWindow:v})),await Nt(f.name),_("Model switch",`Switched to ${f.name} (${f.model}).`)},[_,F,R,T,S,Nt,P]),E=X(f=>f===ye.NONE?"none (no tools)":f===ye.ONCE?"once (approval required)":"full (no approval)",[]),ue=X(f=>{if(F){_("Tools","Cancel current run before changing tool permission mode.","warning");return}if(Y){_("Tools","Resolve current approval request before changing tool permission mode.","warning");return}if(f===z){_("Tools",`Already using ${E(f)}.`);return}M(f),ae(v=>({...v,sessionId:Rt(),dangerous:f===ye.FULL,toolPermissionMode:f})),_("Tools",`Tool permission set to ${E(f)}.`)},[_,F,Y,E,z]),B=X(async f=>{try{let v=await ee();await we(v.configPath,{...v.config,active_mcp_servers:f})}catch(v){_("MCP",`Failed to persist active MCP servers: ${v.message}`,"warning")}},[_]),xe=X((f,v)=>{let C=a_(m,f);K(C),rn(!1),ae(q=>({...q,sessionId:Rt(),activeMcpServers:C})),v&&B(C)},[m,B]),ot=X(async f=>{if(F){_("History","Cancel current run before loading session history.","warning");return}if(Y){_("History","Resolve current approval request before loading session history.","warning");return}try{let v=await n_(f.sessionFile,"utf8"),C=Zn(v);S({type:"clear_current_timeline"}),S({type:"replace_history",turns:C.turns,maxSequence:C.maxSequence}),fe(C.messages),ce(!1),nt(null),ne(null),ve(0),qe.current=null,ae(q=>({...q,sessionId:Rt()})),_("History",C.summary||f.input)}catch(v){_("History",`Failed to load ${f.sessionFile}: ${v.message}`,"error")}},[_,F,S,Y]),mt=X(()=>{F&&N?.cancelCurrentTurn?.()},[F,N]),on=X(async()=>{if(F){_("Compact","Cancel current run before compacting context.","warning");return}if(Y){_("Compact","Resolve current approval request before compacting context.","warning");return}if(N)try{let f=await N.compactHistory("manual");ve(f.afterTokens)}catch(f){_("Compact",`Failed to compact context: ${f.message}`,"error")}},[_,F,Y,N]),sn=X(async()=>{if(!N||F)return;let f=Ye(Ne.INIT);try{let v=await zo("init_agents");A(C=>[...C,f]),ce(!0),dt.current=f,await N.runTurn(v)}catch(v){ce(!1),_("Init",`Failed to run init task: ${v.message}`,"error")}},[_,F,N]),$t=X(async f=>{if(!N||F)return;if(z===ye.NONE){_("Review",'Tool permission mode is "none". Set `/tools once` or `/tools full` before running `/review`.',"warning");return}let v=`${Ye(Ne.REVIEW)} ${f}`;try{let C=await Gc({cwd:s,mcpServers:o,activeMcpServerNames:Te,availableToolNames:N.listToolNames?.()??[]});if(C.kind==="unavailable"){_("Review",C.reason,"error");return}let q=await zo("review_pull_request",{pr_number:String(f),backend_strategy:C.strategy,backend_details:C.details,mcp_server_prefix:C.kind==="github_mcp"?C.mcpServerPrefix:"github"});A(Ie=>[...Ie,v]),_("Review",C.details),ce(!0),dt.current=v,await N.runTurn(q)}catch(C){ce(!1),_("Review",`Failed to run review task for PR #${f}: ${C.message}`,"error")}},[Te,_,F,s,o,N,z]),ul=X(async f=>{let v=f.trim();if(v){if(v.toLowerCase()===bc){await re();return}if(v===Ye(Ne.INIT)){await sn();return}if(!(!N||F)){A(C=>[...C,v]),ce(!0);try{await N.runTurn(v)}catch(C){ce(!1),_("Run",`Turn failed: ${C.message}`,"error")}}}},[_,F,re,sn,N]),pl=X(async()=>{try{let f=await ee(),v=at(f.config),C=_t(f.config,v);se(f.config.providers),ie(f.config.model_profiles),H(v.name),I(v.model),$e(C),ae(q=>({...q,sessionId:Rt(),providerName:v.name,contextWindow:C,autoCompactThresholdPercent:f.config.auto_compact_threshold_percent})),k(!1),_("Setup",`Config saved to ${f.configPath}`)}catch(f){_("Setup",`Failed to reload config: ${f.message}`,"error")}},[_]);It(()=>{if(!N||!Se?.length)return;let f=N.history[0];f&&(N.history.splice(0,N.history.length,f,...Se),fe(null))},[Se,N]);let dl=X(f=>{let v=rt.current;v&&(v(f),rt.current=null),Ve(null)},[]),ml=ja(tt,Ke),fl=nn(()=>({providerName:T,model:R,cwd:s,sessionId:te.sessionId??"unknown",mcpNames:Te,version:w?.version??"unknown"}),[Te,R,T,s,w?.version,te.sessionId]);return $?et(Kc,{children:et(o_,{color:"green",children:$})}):be?et(Dc,{configPath:r,onComplete:pl,onExit:re}):L?et(Oc,{serverNames:m,defaultSelected:g,onConfirm:xe,onExit:()=>{re()}}):l_(Kc,{flexDirection:"column",children:[et(rc,{header:fl,systemMessages:b.systemMessages,turns:b.turns,historicalTurns:b.historicalTurns}),et(kc,{disabled:!N||!!Y,busy:F,history:J,cwd:s,sessionsDir:i,currentSessionFile:O??void 0,providers:G,configPath:r,providerName:T,model:R,toolPermissionMode:z,mcpServers:o,onSubmit:f=>{ul(f)},onExit:()=>{re()},onClear:De,onNewSession:ar,onCancelRun:mt,onCompact:()=>{on()},onHistorySelect:f=>{ot(f)},onModelSelect:f=>{x(f)},onSetToolPermission:ue,onReviewPullRequest:f=>{$t(f)},onSystemMessage:_}),Y?et(Ic,{request:Y,onDecision:dl}):null,et(Ec,{busy:F,pendingApproval:!!Y,contextPercent:ml})]})}var u_=`
|
|
107
121
|
Usage:
|
|
108
122
|
memo mcp list [--json]
|
|
109
123
|
memo mcp get <name> [--json]
|
|
@@ -112,13 +126,14 @@ Usage:
|
|
|
112
126
|
memo mcp remove <name>
|
|
113
127
|
memo mcp login <name> [--scopes scope1,scope2]
|
|
114
128
|
memo mcp logout <name>
|
|
115
|
-
`;function
|
|
116
|
-
`)}function
|
|
117
|
-
`),{
|
|
118
|
-
[
|
|
119
|
-
[
|
|
120
|
-
`);let
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
`))
|
|
129
|
+
`;function or(){console.log(u_.trim())}function Vc(e){return e instanceof Error?e.message:String(e)}function p_(e){let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+1);return n?{key:n,value:r}:null}function Xc(e,t,n){let r=[];if(r.push(`${e}`),n&&r.push(` auth_status: ${n}`),"url"in t){r.push(` type: ${t.type??"streamable_http"}`),r.push(` url: ${t.url}`),t.bearer_token_env_var&&r.push(` bearer_token_env_var: ${t.bearer_token_env_var}`);let o=t.http_headers??t.headers;o&&Object.keys(o).length>0&&r.push(` headers: ${Object.entries(o).map(([s,i])=>`${s}=${i}`).join(", ")}`)}else r.push(` type: ${t.type??"stdio"}`),r.push(` command: ${t.command}`),t.args&&t.args.length>0&&r.push(` args: ${t.args.join(" ")}`),t.env&&Object.keys(t.env).length>0&&r.push(` env: ${Object.entries(t.env).map(([o,s])=>`${o}=${s}`).join(", ")}`);return r.join(`
|
|
130
|
+
`)}function d_(e){let t=e.shift();if(!t)return{error:"Missing server name."};let n,r,o={},s=[];for(let i=0;i<e.length;i+=1){let c=e[i];if(c){if(c==="--"){s=e.slice(i+1);break}if(c==="--url"){let a=e[i+1];if(!a)return{error:"Missing value for --url."};n=a,i+=1;continue}if(c==="--bearer-token-env-var"){let a=e[i+1];if(!a)return{error:"Missing value for --bearer-token-env-var."};r=a,i+=1;continue}if(c==="--env"){let a=e[i+1];if(!a)return{error:"Missing value for --env (KEY=VALUE)."};let l=p_(a);if(!l)return{error:"Invalid --env format. Use KEY=VALUE."};o[l.key]=l.value,i+=1;continue}return c==="--help"||c==="-h"?{error:""}:{error:`Unknown option: ${c}`}}}return n?s.length>0?{error:"Use either --url or a stdio command, not both."}:Object.keys(o).length>0?{error:"--env is only supported with stdio servers."}:{options:{name:t,url:n,bearerTokenEnvVar:r}}:r?{error:"--bearer-token-env-var is only supported with HTTP servers."}:s.length===0?{error:"Missing stdio command. Use `-- <command...>`."}:{options:{name:t,command:s[0],args:s.slice(1),env:Object.keys(o).length>0?o:void 0}}}function m_(e){let[t,...n]=e;return!t||t==="--help"||t==="-h"||t==="help"?{command:"help",rest:[]}:{command:t,rest:n}}function Ko(e,t=[]){let n=new Set(t);for(let r=0;r<e.length;r+=1){let o=e[r];if(o){if(o.startsWith("--")){n.has(o)&&(r+=1);continue}return o}}return null}function f_(e){return e.split(/[,\s]+/g).map(t=>t.trim()).filter(Boolean)}function g_(e){let t,n;for(let r=0;r<e.length;r+=1){let o=e[r];if(o){if(o==="--help"||o==="-h")return{showHelp:!0};if(o==="--scopes"){let s=e[r+1];if(!s)return{error:"Missing value for --scopes."};let i=f_(s);if(i.length===0)return{error:"Invalid --scopes value. Use comma-separated scopes."};n=i,r+=1;continue}if(o.startsWith("--"))return{error:`Unknown option: ${o}`};if(!t){t=o;continue}return{error:`Unexpected argument: ${o}`}}}return{name:t,scopes:n}}function qo(e){return{memoHome:e.home,storeMode:e.config.mcp_oauth_credentials_store_mode,callbackPort:e.config.mcp_oauth_callback_port}}async function Jc(e){let{command:t,rest:n}=m_(e);if(t==="help"){or();return}if(t==="list"){let r=n.includes("--json"),o=await ee(),s=o.config.mcp_servers??{},i=Object.keys(s),c=qo(o),a=new Map;if(await Promise.all(i.map(async l=>{let p=s[l];if(p)try{let u=await Nr(p,c);a.set(l,u)}catch{a.set(l,"unsupported")}})),r){let l={};for(let p of i){let u=s[p];u&&(l[p]={...u,auth_status:a.get(p)??"unsupported"})}console.log(JSON.stringify(l,null,2));return}if(i.length===0){console.log('No MCP servers configured. Add one with "memo mcp add".');return}console.log(`MCP servers (${i.length}):`);for(let l of i){let p=s[l];p&&console.log(Xc(l,p,a.get(l)??"unsupported"))}return}if(t==="get"){let r=n.includes("--json"),o=Ko(n);if(!o){console.error("Missing server name."),process.exitCode=1;return}let i=(await ee()).config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(r){console.log(JSON.stringify(i,null,2));return}console.log(Xc(o,i));return}if(t==="add"){let r=d_(n);if(r.error!==void 0){r.error&&(console.error(r.error),process.exitCode=1),or();return}let o=r.options;if(!o)return;if(o.url)try{new URL(o.url)}catch{console.error("Invalid URL."),process.exitCode=1;return}let s=await ee(),i={...s.config.mcp_servers??{}};if(i[o.name]){console.error(`MCP server "${o.name}" already exists.`),process.exitCode=1;return}let c;o.url?c={type:"streamable_http",url:o.url,...o.bearerTokenEnvVar?{bearer_token_env_var:o.bearerTokenEnvVar}:{}}:c={command:o.command,args:o.args&&o.args.length>0?o.args:void 0,env:o.env},i[o.name]=c,await we(s.configPath,{...s.config,mcp_servers:i}),console.log(`Added MCP server "${o.name}".`);return}if(t==="remove"){let r=Ko(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await ee(),s={...o.config.mcp_servers??{}};if(!s[r]){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}delete s[r],await we(o.configPath,{...o.config,mcp_servers:s}),console.log(`Removed MCP server "${r}".`);return}if(t==="login"){let r=g_(n);if(r.showHelp){or();return}if(r.error){console.error(r.error),process.exitCode=1;return}let o=r.name;if(!o){console.error("Missing server name."),process.exitCode=1;return}let s=await ee(),i=s.config.mcp_servers?.[o];if(!i){console.error(`Unknown MCP server "${o}".`),process.exitCode=1;return}if(!("url"in i)){console.error("OAuth login only applies to streamable HTTP servers."),process.exitCode=1;return}console.log(`Starting OAuth login for "${o}"...`);try{let c=await $r({serverName:o,config:i,scopes:r.scopes,settings:qo(s),onAuthorizationUrl:a=>{console.log(`Open this URL to authorize:
|
|
131
|
+
${a}`)},onBrowserOpenFailure:()=>{console.log("Browser launch failed. Open the URL above manually.")}});console.log(`OAuth login completed for "${o}" (credentials stored in ${c.backend}).`)}catch(c){console.error(Vc(c)),process.exitCode=1}return}if(t==="logout"){let r=Ko(n);if(!r){console.error("Missing server name."),process.exitCode=1;return}let o=await ee(),s=o.config.mcp_servers?.[r];if(!s){console.error(`Unknown MCP server "${r}".`),process.exitCode=1;return}if(!("url"in s)){console.error("OAuth logout only applies to streamable HTTP servers."),process.exitCode=1;return}try{(await Dr({config:s,settings:qo(o)})).removed?console.log(`Removed OAuth credentials for "${r}".`):console.log(`No OAuth credentials stored for "${r}".`)}catch(i){console.error(Vc(i)),process.exitCode=1}return}console.error(`Unknown subcommand: ${t}`),or(),process.exitCode=1}function Yc(e){let t={dangerous:!1,showVersion:!1,once:!1,prev:!1},n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o!==void 0){if(o==="--version"||o==="-v"){t.showVersion=!0;continue}if(o==="--once"||o==="-once"){t.once=!0;continue}if(o==="--prev"||o==="-prev"){t.prev=!0;continue}if(o==="--dangerous"||o==="-d"){t.dangerous=!0;continue}n.push(o)}}return{question:n.join(" "),options:t}}var h_=["mcp","web"];function y_(e){return e.length===0?{token:null,offset:0}:e[0]==="--"?{token:e[1]??null,offset:2}:{token:e[0]??null,offset:1}}function __(e){return h_.includes(e)}function Qc(e){let{token:t,offset:n}=y_(e);return t&&__(t)?{kind:"subcommand",name:t,args:e.slice(n)}:{kind:"default",args:e}}import{jsx as W_}from"react/jsx-runtime";async function cl(e){let t=await ee();if(!t.needsSetup)return t;let n=t.config.providers[0],o=[n?.env_api_key,"OPENAI_API_KEY","DEEPSEEK_API_KEY"].filter(Boolean).some(c=>!!process.env[c]);if(n&&o)return await we(t.configPath,t.config),console.log(`Detected API key in env. Wrote default provider (${n.name}) to ${t.configPath}`),{...t,needsSetup:!1};if(e==="tui")return t;let s=O_({input:L_,output:N_}),i=async(c,a)=>(await s.question(c)).trim()||a;try{console.log("No provider config found. Please answer the prompts:");let c=await i("Provider name [deepseek]: ","deepseek"),a=await i("API key env var [DEEPSEEK_API_KEY]: ","DEEPSEEK_API_KEY"),l=await i("Model name [deepseek-chat]: ","deepseek-chat"),p=await i("Base URL [https://api.deepseek.com]: ","https://api.deepseek.com"),u={current_provider:c,providers:[{name:c,env_api_key:a,model:l,base_url:p||void 0}]};return await we(t.configPath,u),console.log(`Config written to ${t.configPath}
|
|
132
|
+
`),{...t,config:u,needsSetup:!1}}finally{s.close()}}async function ll(e,t){let r=(await Wn({sessionsDir:e,cwd:t,limit:1}))[0];if(!r)return null;let o=await I_(r.sessionFile,"utf8");return Zn(o)}function D_(e,t){if(!t.length)return;let n=e.history[0];n&&e.history.splice(0,e.history.length,n,...t)}async function U_(e){let t=await cl("plain"),n=at(t.config),r=_t(t.config,n),s={sessionId:al(),mode:"interactive",contextWindow:r,autoCompactThresholdPercent:t.config.auto_compact_threshold_percent,activeMcpServers:t.config.active_mcp_servers,dangerous:e.options.dangerous},i=jt(t,s),c=e.options.prev?await ll(i,process.cwd()):null;if(e.options.prev&&!c){console.error("No previous session found for current directory."),process.exitCode=1;return}e.options.dangerous&&console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!");let a={requestApproval:e.options.dangerous?void 0:u=>(console.log(`
|
|
133
|
+
[approval required] ${u.toolName}: ${u.reason}`),console.log("[approval] Run with --dangerous to bypass approval"),Promise.resolve("deny")),hooks:{onAction:({action:u})=>{console.log(`
|
|
134
|
+
[tool] ${u.tool}`),u.input!==void 0&&console.log(`[input] ${JSON.stringify(u.input)}`)},onObservation:()=>{}}},l=await Hn(a,s);c&&(D_(l,c.messages),console.log("[session] Continued from previous session context."));let p=e.question;if(!p&&!process.stdin.isTTY&&(p=await B_()),!p){console.error("No input provided. Pass a question or use stdin."),await l.close();return}try{console.log(`User: ${p}
|
|
135
|
+
`);let u=await l.runTurn(p);console.log(`
|
|
136
|
+
${u.finalText}`),console.log(`
|
|
137
|
+
[tokens] prompt=${u.tokenUsage.prompt} completion=${u.tokenUsage.completion} total=${u.tokenUsage.total}`),console.log(`
|
|
138
|
+
provider=${n.name} model=${n.model}`)}catch(u){console.error(`Run failed: ${u.message}`)}finally{await l.close()}}async function F_(e){let t=await cl("tui"),n=at(t.config),r=_t(t.config,n),s={sessionId:al(),mode:"interactive",contextWindow:r,autoCompactThresholdPercent:t.config.auto_compact_threshold_percent,activeMcpServers:t.config.active_mcp_servers,dangerous:e.options.dangerous},i=jt(t,s),c=e.options.prev?await ll(i,process.cwd()):null;if(e.options.prev&&!c){console.error("No previous session found for current directory."),process.exitCode=1;return}e.options.dangerous&&(console.log("\u26A0\uFE0F DANGEROUS MODE: All tool approvals are bypassed!"),console.log(` Use with caution.
|
|
139
|
+
`)),await $_(W_(qc,{sessionOptions:s,providerName:n.name,model:n.model,configPath:t.configPath,mcpServers:t.config.mcp_servers??{},cwd:process.cwd(),sessionsDir:i,providers:t.config.providers,modelProfiles:t.config.model_profiles,dangerous:e.options.dangerous,needsSetup:t.needsSetup,initialHistory:c??void 0}),{exitOnCtrlC:!1,patchConsole:!1}).waitUntilExit()}async function H_(){let e=process.argv.slice(2),t=Qc(e);if(t.kind==="subcommand"){if(t.name==="mcp"){await Jc(t.args);return}if(t.name==="web"){let{runWebCommand:o}=await Promise.resolve().then(()=>(il(),sl));await o(t.args);return}}let n=Yc(t.args);if(n.options.showVersion){let s=nr()?.version??"unknown";console.log(s);return}let r=process.stdin.isTTY&&process.stdout.isTTY;if(n.options.once||!r){await U_(n);return}await F_(n)}H_();async function B_(){return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim())}),process.stdin.resume()})}
|