@ashx-j/lunr 0.2.17 → 0.2.19
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/CHANGELOG.md +26 -1
- package/README.md +2 -1
- package/dist/builtin-extensions/ashxj-thinking.d.ts +1 -0
- package/dist/builtin-extensions/ashxj-thinking.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-thinking.js +44 -19
- package/dist/builtin-extensions/ashxj-thinking.js.map +1 -1
- package/dist/builtin-extensions/index.d.ts.map +1 -1
- package/dist/builtin-extensions/index.js +2 -1
- package/dist/builtin-extensions/index.js.map +1 -1
- package/dist/builtin-extensions/pi-lsp-extension/src/index.d.ts +4 -0
- package/dist/builtin-extensions/pi-lsp-extension/src/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-lsp-extension/src/index.js +172 -171
- package/dist/builtin-extensions/pi-lsp-extension/src/index.js.map +1 -1
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts +50 -0
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js +131 -0
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js.map +1 -0
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.d.ts +7 -0
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.js +211 -0
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.js.map +1 -0
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts +0 -5
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js +0 -202
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.js +276 -109
- package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/init.d.ts +4 -1
- package/dist/builtin-extensions/pi-mcp-adapter/init.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/init.js +10 -3
- package/dist/builtin-extensions/pi-mcp-adapter/init.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.js +6 -1
- package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.d.ts +6 -1
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.js +33 -8
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.js.map +1 -1
- package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.js +2 -1
- package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.js.map +1 -1
- package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.d.ts +1 -1
- package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.js +1 -1
- package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js +68 -15
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js +5 -2
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +2 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js +72 -31
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/review.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/review.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/review.js +2 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/review.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/extract.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-web-access/extract.js +105 -54
- package/dist/builtin-extensions/pi-web-access/extract.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/gemini-search.d.ts +1 -1
- package/dist/builtin-extensions/pi-web-access/gemini-search.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-web-access/gemini-search.js +82 -65
- package/dist/builtin-extensions/pi-web-access/gemini-search.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/github-extract.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-web-access/github-extract.js +2 -0
- package/dist/builtin-extensions/pi-web-access/github-extract.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-web-access/index.js +259 -168
- package/dist/builtin-extensions/pi-web-access/index.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/lazy.d.ts +18 -0
- package/dist/builtin-extensions/pi-web-access/lazy.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-web-access/lazy.js +19 -0
- package/dist/builtin-extensions/pi-web-access/lazy.js.map +1 -0
- package/dist/builtin-extensions/pi-web-access/session-cleanup.d.ts +6 -0
- package/dist/builtin-extensions/pi-web-access/session-cleanup.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-web-access/session-cleanup.js +17 -0
- package/dist/builtin-extensions/pi-web-access/session-cleanup.js.map +1 -0
- package/dist/cli-runtime.d.ts +3 -0
- package/dist/cli-runtime.d.ts.map +1 -0
- package/dist/cli-runtime.js +72 -0
- package/dist/cli-runtime.js.map +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +11 -60
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +1 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +6 -3
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/host-static.d.ts.map +1 -1
- package/dist/core/extensions/host-static.js +34 -12
- package/dist/core/extensions/host-static.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +1 -2
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +10 -64
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/keybindings.d.ts +2 -2
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +2 -2
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +1 -1
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/timings.d.ts +2 -1
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/timings.js +17 -2
- package/dist/core/timings.js.map +1 -1
- package/dist/gateway/agent-bridge.d.ts +6 -1
- package/dist/gateway/agent-bridge.d.ts.map +1 -1
- package/dist/gateway/agent-bridge.js +23 -6
- package/dist/gateway/agent-bridge.js.map +1 -1
- package/dist/gateway/cron.d.ts +1 -1
- package/dist/gateway/cron.d.ts.map +1 -1
- package/dist/gateway/cron.js +3 -1
- package/dist/gateway/cron.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +20 -14
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +10 -8
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/thinking-level-slash.d.ts +4 -0
- package/dist/modes/interactive/thinking-level-slash.d.ts.map +1 -0
- package/dist/modes/interactive/thinking-level-slash.js +23 -0
- package/dist/modes/interactive/thinking-level-slash.js.map +1 -0
- package/dist/node-runtime/agent-session-services-35WNVGMR.js +36 -0
- package/dist/node-runtime/benchmark-request-UC7PD3V3.js +57 -0
- package/dist/node-runtime/brave-UWDA3I22.js +143 -0
- package/dist/node-runtime/builtin-extensions-322XDDEM.js +28 -0
- package/dist/node-runtime/chunk-2SJB2AWP.js +47 -0
- package/dist/node-runtime/chunk-3NMWLTPV.js +64 -0
- package/dist/node-runtime/chunk-3WFAEVKS.js +115 -0
- package/dist/node-runtime/chunk-3X3KZKMI.js +49 -0
- package/dist/node-runtime/chunk-4CSFRBCN.js +7558 -0
- package/dist/node-runtime/chunk-4DJ6HEGH.js +296 -0
- package/dist/node-runtime/chunk-4FX25LWP.js +1345 -0
- package/dist/node-runtime/chunk-4HXHDDCF.js +16 -0
- package/dist/node-runtime/chunk-4I23VTC4.js +429 -0
- package/dist/node-runtime/chunk-4TLO4PO2.js +3427 -0
- package/dist/node-runtime/chunk-4ZWGEEAS.js +69 -0
- package/dist/node-runtime/chunk-53YJI7JU.js +137 -0
- package/dist/node-runtime/chunk-5EFIU3OM.js +295 -0
- package/dist/node-runtime/chunk-6BEIBLQ3.js +53 -0
- package/dist/node-runtime/chunk-6KDIOJL3.js +72 -0
- package/dist/node-runtime/chunk-7N3YHTYF.js +26 -0
- package/dist/node-runtime/chunk-7NBZ5P7I.js +24 -0
- package/dist/node-runtime/chunk-AD6VXAO7.js +342 -0
- package/dist/node-runtime/chunk-ARC4KOTI.js +11178 -0
- package/dist/node-runtime/chunk-AROOY4BB.js +173 -0
- package/dist/node-runtime/chunk-ATGA2WLC.js +5646 -0
- package/dist/node-runtime/chunk-AUXVGBO4.js +19 -0
- package/dist/node-runtime/chunk-AY6CAJSL.js +30 -0
- package/dist/node-runtime/chunk-BHO7O6E5.js +296 -0
- package/dist/node-runtime/chunk-BI3DHYCN.js +8845 -0
- package/dist/node-runtime/chunk-BOHIDQT4.js +21 -0
- package/dist/node-runtime/chunk-BRJX2PRC.js +53 -0
- package/dist/node-runtime/chunk-CBGB57XT.js +20211 -0
- package/dist/node-runtime/chunk-CCZJ3PYY.js +17 -0
- package/dist/node-runtime/chunk-CGBXPL3E.js +1171 -0
- package/dist/node-runtime/chunk-CJECDQKP.js +19 -0
- package/dist/node-runtime/chunk-CSFI6YXL.js +130 -0
- package/dist/node-runtime/chunk-DAPBPCBP.js +53 -0
- package/dist/node-runtime/chunk-DDWHZ633.js +37 -0
- package/dist/node-runtime/chunk-DMMTJQMQ.js +43 -0
- package/dist/node-runtime/chunk-DVGWF6A2.js +1180 -0
- package/dist/node-runtime/chunk-FQMM2EZ2.js +248 -0
- package/dist/node-runtime/chunk-FVDOXRUD.js +96 -0
- package/dist/node-runtime/chunk-G6LRAP36.js +105 -0
- package/dist/node-runtime/chunk-GKLEQ3I4.js +860 -0
- package/dist/node-runtime/chunk-H2EOZYMP.js +57 -0
- package/dist/node-runtime/chunk-HQCKFM2O.js +56 -0
- package/dist/node-runtime/chunk-HYHJIRDW.js +19 -0
- package/dist/node-runtime/chunk-I6R76AG7.js +22 -0
- package/dist/node-runtime/chunk-IRPJXI6U.js +1269 -0
- package/dist/node-runtime/chunk-J26TSGDL.js +633 -0
- package/dist/node-runtime/chunk-JHYKXIMM.js +378 -0
- package/dist/node-runtime/chunk-JZQ7F36T.js +610 -0
- package/dist/node-runtime/chunk-KBKMCJDU.js +126 -0
- package/dist/node-runtime/chunk-KWA4OC2J.js +100 -0
- package/dist/node-runtime/chunk-M3LZLQW2.js +98 -0
- package/dist/node-runtime/chunk-MCUNIRD5.js +8388 -0
- package/dist/node-runtime/chunk-NUIFPZWX.js +209 -0
- package/dist/node-runtime/chunk-OBMWP3I5.js +68 -0
- package/dist/node-runtime/chunk-OCVIXVTZ.js +88 -0
- package/dist/node-runtime/chunk-OPEK5RRY.js +466 -0
- package/dist/node-runtime/chunk-OR4L3IB2.js +42 -0
- package/dist/node-runtime/chunk-PL6JKXWI.js +3622 -0
- package/dist/node-runtime/chunk-PNJSG3IZ.js +807 -0
- package/dist/node-runtime/chunk-PVCDKGR6.js +55 -0
- package/dist/node-runtime/chunk-Q4Q6D4IY.js +364 -0
- package/dist/node-runtime/chunk-Q5ZU2VRT.js +83 -0
- package/dist/node-runtime/chunk-QFWG2RVL.js +5477 -0
- package/dist/node-runtime/chunk-QZMODZQ2.js +305 -0
- package/dist/node-runtime/chunk-RNBHABBA.js +986 -0
- package/dist/node-runtime/chunk-RQ2Q5IYR.js +72 -0
- package/dist/node-runtime/chunk-RRIZE6QQ.js +17 -0
- package/dist/node-runtime/chunk-SN6G4OU6.js +4753 -0
- package/dist/node-runtime/chunk-STERBGUB.js +949 -0
- package/dist/node-runtime/chunk-TFBIJTM3.js +966 -0
- package/dist/node-runtime/chunk-TXHKBRHZ.js +9450 -0
- package/dist/node-runtime/chunk-UWQYRSYQ.js +8973 -0
- package/dist/node-runtime/chunk-VRB2IYGG.js +53 -0
- package/dist/node-runtime/chunk-VSELYKWU.js +772 -0
- package/dist/node-runtime/chunk-W3CVH5RX.js +62 -0
- package/dist/node-runtime/chunk-WJVFOIB5.js +24921 -0
- package/dist/node-runtime/chunk-WKDK4C5P.js +2834 -0
- package/dist/node-runtime/chunk-XATUM2HK.js +46 -0
- package/dist/node-runtime/chunk-XBWPBZBN.js +125 -0
- package/dist/node-runtime/chunk-XTHQ7XR7.js +509 -0
- package/dist/node-runtime/chunk-ZRCBN365.js +1734 -0
- package/dist/node-runtime/cli-runtime.js +80 -0
- package/dist/node-runtime/clipboard-OZ63BBC6.js +12 -0
- package/dist/node-runtime/clipboard-image-7QR6GXVA.js +13 -0
- package/dist/node-runtime/command-DWUM5X3U.js +13 -0
- package/dist/node-runtime/commands-MV5KOZ64.js +291 -0
- package/dist/node-runtime/config-QDD5PUE2.js +73 -0
- package/dist/node-runtime/curator-server-XCM43VEF.js +3816 -0
- package/dist/node-runtime/customize-XEXL2DGQ.js +12 -0
- package/dist/node-runtime/direct-tool-executor-BK7CLEBX.js +188 -0
- package/dist/node-runtime/exa-LL64QZR2.js +329 -0
- package/dist/node-runtime/export-html-TEXVV5RP.js +150 -0
- package/dist/node-runtime/extension-input-O4HSAEM4.js +14 -0
- package/dist/node-runtime/extension-selector-X5FCX43D.js +14 -0
- package/dist/node-runtime/extract-XLQSJN4V.js +17 -0
- package/dist/node-runtime/file-sync-HCOP2QVF.js +117 -0
- package/dist/node-runtime/gateway-UZXMFGWY.js +2137 -0
- package/dist/node-runtime/gemini-api-QE7ANVDZ.js +29 -0
- package/dist/node-runtime/gemini-search-U7SUMPQA.js +330 -0
- package/dist/node-runtime/gemini-url-context-PXWCBQHK.js +103 -0
- package/dist/node-runtime/gemini-web-MM446SEH.js +14 -0
- package/dist/node-runtime/github-extract-F64RZOEA.js +619 -0
- package/dist/node-runtime/goal-NJEE5CTU.js +1831 -0
- package/dist/node-runtime/index.js +859 -0
- package/dist/node-runtime/init-3C7Z24OI.js +28 -0
- package/dist/node-runtime/install-cli-EXMJQESX.js +308 -0
- package/dist/node-runtime/interactive-mode-QT5IKGQ5.js +56 -0
- package/dist/node-runtime/interactive-view-ILS6TAN5.js +247 -0
- package/dist/node-runtime/lsp-manager-3ASUSO4T.js +1104 -0
- package/dist/node-runtime/lunr-cron-QPBTKBGI.js +272 -0
- package/dist/node-runtime/main.js +54 -0
- package/dist/node-runtime/mcp-auth-flow-QIXHW6QN.js +32 -0
- package/dist/node-runtime/mcp-panel-IIGMXQGP.js +501 -0
- package/dist/node-runtime/mcp-setup-panel-FEK7663I.js +355 -0
- package/dist/node-runtime/memory-cap-3S4XRLNP.js +20 -0
- package/dist/node-runtime/model-tiers-NJLHUEGK.js +20 -0
- package/dist/node-runtime/openai-search-B3MSNCQA.js +288 -0
- package/dist/node-runtime/package-manager-cli-7RKSZGEN.js +749 -0
- package/dist/node-runtime/parallel-AI2MNSCU.js +265 -0
- package/dist/node-runtime/parser-manager-TQHWYDH7.js +152 -0
- package/dist/node-runtime/pdf-extract-IPE6H4HP.js +57 -0
- package/dist/node-runtime/perplexity-QVJW3I35.js +12 -0
- package/dist/node-runtime/pi-intercom-EEMBGQID.js +2215 -0
- package/dist/node-runtime/pi-mcp-adapter-GUFZWW54.js +428 -0
- package/dist/node-runtime/pi-ollama-cloud-2F3Y2QNM.js +1440 -0
- package/dist/node-runtime/pi-prompt-template-model-QWTCGLJU.js +3946 -0
- package/dist/node-runtime/pi-subagents-7YJ3I4VE.js +6048 -0
- package/dist/node-runtime/pi-web-access-2CQGFLT2.js +1867 -0
- package/dist/node-runtime/print-mode-XSFM26EL.js +12 -0
- package/dist/node-runtime/proxy-modes-V6YVFH3C.js +685 -0
- package/dist/node-runtime/rpc-entry.js +62 -0
- package/dist/node-runtime/rpc-mode-W5ZTLTMZ.js +13 -0
- package/dist/node-runtime/runtime-bridges-3RKBDLNA.js +14 -0
- package/dist/node-runtime/session-manager-E7AREDTV.js +33 -0
- package/dist/node-runtime/session-selector-FJ7M2AIX.js +14 -0
- package/dist/node-runtime/settings-manager-GHPTUN7R.js +21 -0
- package/dist/node-runtime/src-BPQFJR76.js +2427 -0
- package/dist/node-runtime/subagent-executor-5Q5A4HJ2.js +8499 -0
- package/dist/node-runtime/summary-review-YSMXKITO.js +228 -0
- package/dist/node-runtime/tavily-WEZFVFP7.js +154 -0
- package/dist/node-runtime/timings-UAD5BEAS.js +16 -0
- package/dist/node-runtime/tool-renderer-MV5O452K.js +204 -0
- package/dist/node-runtime/update-cli-L3JIBH2U.js +70 -0
- package/dist/node-runtime/v4-5MNC3H7G.js +424 -0
- package/dist/node-runtime/video-extract-OYT5WKS5.js +304 -0
- package/dist/node-runtime/workspace-index-6DBXSTJ6.js +163 -0
- package/dist/node-runtime/youtube-extract-TQYKGFGS.js +264 -0
- package/dist/rpc.d.ts +3 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +18 -0
- package/dist/rpc.js.map +1 -0
- package/dist/startup/benchmark-request.d.ts +3 -0
- package/dist/startup/benchmark-request.d.ts.map +1 -0
- package/dist/startup/benchmark-request.js +65 -0
- package/dist/startup/benchmark-request.js.map +1 -0
- package/dist/startup/interactive-view.d.ts.map +1 -1
- package/dist/startup/interactive-view.js +1 -2
- package/dist/startup/interactive-view.js.map +1 -1
- package/dist/startup/startup-milestones.d.ts +1 -1
- package/dist/startup/startup-milestones.d.ts.map +1 -1
- package/dist/startup/startup-milestones.js.map +1 -1
- package/dist/utils/await-with-abort.d.ts +2 -0
- package/dist/utils/await-with-abort.d.ts.map +1 -0
- package/dist/utils/await-with-abort.js +19 -0
- package/dist/utils/await-with-abort.js.map +1 -0
- package/docs/development.md +5 -1
- package/docs/features.md +2 -2
- package/docs/interactive-startup.md +95 -48
- package/docs/keybindings.md +2 -2
- package/docs/terminal-setup.md +1 -1
- package/docs/usage.md +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/hidden-thinking-label.ts +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/builtin-extensions/pi-lsp-extension/src/index.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AA8EpE,MAAM,CAAC,OAAO,UAAU,YAAY,CAAC,EAAE,EAAE,YAAY,QAyfpD","sourcesContent":["// @ts-nocheck\n/**\n * pi-lsp-extension — Pi coding agent extension for LSP integration.\n *\n * Exposes Language Server Protocol capabilities as tools the LLM can call:\n * - lsp_diagnostics: compilation errors and warnings\n * - lsp_hover: type info and docs at a position\n * - lsp_definition: go to definition\n * - lsp_references: find all references\n * - lsp_symbols: file/workspace symbol search\n * - lsp_rename: preview rename refactoring\n * - lsp_completions: code completion suggestions at a position\n * - lsp_code_actions: quick fixes, refactorings, and source actions\n *\n * Position-based tools (hover, definition, references, rename, code_actions)\n * accept an optional `query` parameter as an alternative to line/character,\n * resolving a symbol name to its position automatically.\n *\n * Usage:\n * 1. npm install in this directory\n * 2. Add to pi via settings.json extensions, or: pi -e ./src/index.ts\n * 3. LSP servers start lazily when you first use a tool on a file\n */\n\nimport type { ExtensionAPI } from \"@ashx-j/lunr\";\nimport {\n isReadToolResult,\n isWriteToolResult,\n isEditToolResult,\n} from \"@ashx-j/lunr\";\nimport { DiagnosticSeverity, type Diagnostic } from \"vscode-languageserver-protocol\";\n\nimport { LspManager, type ServerConfig, type LspManagerCallbacks } from \"./lsp-manager.js\";\nimport { FileSync } from \"./file-sync.js\";\nimport { TreeSitterManager } from \"./tree-sitter/parser-manager.js\";\nimport { WorkspaceIndex } from \"./tree-sitter/workspace-index.js\";\nimport { type WorkspaceProvider, DefaultWorkspaceProvider } from \"./workspace-provider.js\";\nimport { createDiagnosticsTool } from \"./tools/diagnostics.js\";\nimport { createHoverTool } from \"./tools/hover.js\";\nimport { createDefinitionTool } from \"./tools/definition.js\";\nimport { createReferencesTool } from \"./tools/references.js\";\nimport { createSymbolsTool } from \"./tools/symbols.js\";\nimport { createRenameTool } from \"./tools/rename.js\";\nimport { createCodeOverviewTool } from \"./tools/code-overview.js\";\nimport { createCompletionsTool } from \"./tools/completions.js\";\nimport { createCodeSearchTool } from \"./tools/code-search.js\";\nimport { createCodeRewriteTool } from \"./tools/code-rewrite.js\";\nimport { createCodeActionsTool } from \"./tools/code-actions.js\";\nimport { syntheticDotLocks } from \"./tools/completions.js\";\nimport { relative } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { DIAGNOSTIC_SETTLE_DELAY_MS } from \"./shared/timing.js\";\n\n/**\n * Project-level LSP config — loaded from `.pi-lsp.json` in the workspace root.\n *\n * Example:\n * ```json\n * {\n * \"autoStart\": [\"java\", \"typescript\"],\n * \"lombokJar\": \"env/Lombok-1.18.x/runtime/lib/lombok-1.18.42.jar\",\n * \"servers\": {\n * \"python\": { \"command\": \"pylsp\", \"args\": [] }\n * }\n * }\n * ```\n */\ninterface ProjectLspConfig {\n /** Languages to start eagerly on session_start (e.g. [\"java\", \"typescript\"]) */\n autoStart?: string[];\n /** Path to Lombok jar (absolute or relative to project root). \"auto\" to auto-detect. */\n lombokJar?: string;\n /** Custom server configs keyed by language ID */\n servers?: Record<string, { command: string; args?: string[]; env?: Record<string, string>; initializationOptions?: Record<string, unknown>; settings?: Record<string, unknown> }>;\n /**\n * Auto-inject LSP error diagnostics into write/edit tool results.\n * Set to false to disable, or provide an array of language IDs to enable selectively.\n * Default: true (all languages).\n *\n * Examples:\n * true — inject for all languages\n * false — never inject\n * [\"typescript\"] — only inject for TypeScript files\n */\n autoInjectDiagnostics?: boolean | string[];\n}\n\n/** Load .pi-lsp.json from a directory. Returns null if not found or invalid. */\nfunction loadProjectConfig(dir: string): ProjectLspConfig | null {\n const configPath = join(dir, \".pi-lsp.json\");\n try {\n if (!existsSync(configPath)) return null;\n const raw = readFileSync(configPath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (typeof parsed !== \"object\" || parsed === null) return null;\n return parsed as ProjectLspConfig;\n } catch {\n return null;\n }\n}\n\nexport default function lspExtension(pi: ExtensionAPI) {\n // Prevent EPIPE errors from LSP server exits from crashing the host process.\n // When an LSP server exits unexpectedly, in-flight writes to its stdin pipe\n // can produce EPIPE errors that escape all connection-level error handlers.\n const origListeners = process.listeners(\"uncaughtException\");\n process.on(\"uncaughtException\", (err: any) => {\n if (err?.code === \"EPIPE\") return; // swallow — LSP server exited, harmless\n // Re-throw for other handlers\n for (const listener of origListeners) (listener as any)(err);\n if (origListeners.length === 0) {\n console.error(\"[LSP] Uncaught exception:\", err);\n }\n });\n\n let manager: LspManager | null = null;\n let fileSync: FileSync | null = null;\n let treeSitter: TreeSitterManager | null = null;\n let workspaceIndex: WorkspaceIndex | null = null;\n let pendingProvider: WorkspaceProvider | null = null;\n // Store latest ctx for lifecycle callbacks (updated on each event)\n let latestCtx: any = null;\n // Project config — loaded on session_start, used by auto-injection guard\n let projectConfig: ProjectLspConfig | null = null;\n\n /**\n * Run `fn` with the currently captured ctx, swallowing stale-ctx errors.\n *\n * Lifecycle callbacks from LspManager (server ready, workspace setup, etc.)\n * and `pi.events` listeners can fire AFTER the session is replaced or reloaded,\n * at which point the captured ctx has been invalidated and any property access\n * throws via ExtensionRunner.assertActive(). We can't use optional chaining to\n * dodge it because the `ui` / `theme` getters themselves run assertActive().\n */\n const withLatestCtx = (fn: (ctx: any) => void) => {\n const ctx = latestCtx;\n if (!ctx) return;\n try {\n fn(ctx);\n } catch (err: any) {\n if (typeof err?.message === \"string\" && err.message.includes(\"stale after session\")) {\n // Session was replaced/reloaded — drop the stale ctx and move on.\n latestCtx = null;\n return;\n }\n throw err;\n }\n };\n\n // Listen for external workspace providers (e.g. bemol extension).\n // Also check if one was already registered before we loaded (load order varies).\n // Store as pendingProvider so it's available when the manager is created later.\n const applyProvider = (data: unknown) => {\n const provider = data as WorkspaceProvider;\n pendingProvider = provider;\n if (manager) {\n manager.setWorkspaceProvider(provider);\n }\n // Update status if we have a UI context\n const statusText = provider.getStatusText();\n if (!statusText) return;\n withLatestCtx((ctx) => {\n if (!ctx.ui?.theme) return;\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", `LSP: ${statusText}`));\n });\n };\n\n pi.events.on(\"lsp:register-workspace-provider\", applyProvider);\n\n // Check for provider registered before our listener existed\n const existing = (pi.events as any)[\"lsp:workspace-provider\"];\n if (existing) applyProvider(existing);\n\n /** Build lifecycle callbacks that update UI status */\n const setLspStatus = (color: string, text: string) => {\n withLatestCtx((ctx) => {\n if (!ctx.ui?.theme) return;\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(color, text));\n });\n };\n\n const makeCallbacks = (): LspManagerCallbacks => ({\n onWorkspaceSetupStart: () => {\n setLspStatus(\"warning\", \"LSP: workspace setup...\");\n },\n onWorkspaceSetupEnd: (success: boolean, duration: number) => {\n const secs = (duration / 1000).toFixed(1);\n if (success) {\n setLspStatus(\"accent\", `LSP: workspace ready (${secs}s)`);\n } else {\n setLspStatus(\"warning\", `LSP: workspace setup failed (${secs}s)`);\n }\n },\n onServerStart: (languageId: string, command: string) => {\n setLspStatus(\"warning\", `LSP: starting ${languageId} (${command})...`);\n },\n onServerReady: (languageId: string) => {\n setLspStatus(\"accent\", `LSP: ${languageId} ready`);\n },\n onServerError: (languageId: string, _error: string) => {\n setLspStatus(\"error\", `LSP: ${languageId} failed`);\n },\n onServerCrash: (languageId: string, restarting: boolean, attempt: number) => {\n if (restarting) {\n setLspStatus(\"warning\", `LSP: restarting ${languageId}... (attempt ${attempt}/3)`);\n } else {\n setLspStatus(\"error\", `LSP: ${languageId} crashed — auto-restart exhausted`);\n }\n },\n });\n\n // Create manager eagerly so tools can reference it, but servers start lazily\n const getManager = (): LspManager => {\n if (!manager) {\n manager = new LspManager(process.cwd(), undefined, makeCallbacks(), undefined, pendingProvider ?? undefined);\n fileSync = new FileSync(manager);\n fileSync.setSyntheticDotChecker((uri) => syntheticDotLocks.has(uri));\n treeSitter = new TreeSitterManager();\n workspaceIndex = new WorkspaceIndex(process.cwd(), treeSitter);\n fileSync.setTreeSitter(treeSitter, workspaceIndex);\n }\n return manager;\n };\n\n const getFileSync = (): FileSync => {\n if (!fileSync) {\n getManager(); // ensures fileSync is created\n }\n return fileSync!;\n };\n\n const getTreeSitter = (): TreeSitterManager => {\n if (!treeSitter) {\n getManager(); // ensures treeSitter is created\n }\n return treeSitter!;\n };\n\n const getWorkspaceIndex = (): WorkspaceIndex => {\n if (!workspaceIndex) {\n getManager(); // ensures workspaceIndex is created\n }\n return workspaceIndex!;\n };\n\n // Initialize manager (uses cwd at session start time)\n pi.on(\"session_start\", async (_event, ctx) => {\n latestCtx = ctx;\n\n // If manager was already created eagerly (e.g. by a tool before session_start),\n // shut it down so we can re-create with the correct ctx.cwd.\n if (manager) {\n await manager.shutdownAll().catch(() => {});\n if (treeSitter) treeSitter.shutdown();\n }\n\n manager = new LspManager(ctx.cwd, undefined, makeCallbacks(), undefined, pendingProvider ?? undefined);\n fileSync = new FileSync(manager);\n fileSync.setSyntheticDotChecker((uri) => syntheticDotLocks.has(uri));\n treeSitter = new TreeSitterManager();\n workspaceIndex = new WorkspaceIndex(ctx.cwd, treeSitter);\n fileSync.setTreeSitter(treeSitter, workspaceIndex);\n\n // Initialize tree-sitter in the background (don't block session start)\n treeSitter.init().catch((err) => {\n console.error(`[pi-lsp-extension] tree-sitter WASM init failed: ${err?.message ?? err}`);\n });\n\n // Show workspace provider status\n const wsProvider = manager.workspace;\n const statusText = wsProvider.getStatusText();\n if (statusText) {\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", `LSP: ${statusText}`));\n } else {\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"dim\", \"LSP: idle\"));\n }\n\n // Load project config and apply settings\n projectConfig = loadProjectConfig(ctx.cwd);\n if (projectConfig) {\n // Apply custom server configs\n if (projectConfig.servers) {\n for (const [lang, serverConf] of Object.entries(projectConfig.servers)) {\n manager.setServerConfig(lang, {\n command: serverConf.command,\n args: serverConf.args ?? [],\n env: serverConf.env,\n initializationOptions: serverConf.initializationOptions,\n settings: serverConf.settings,\n });\n }\n }\n\n // Set Lombok jar path (explicit path or \"auto\" for auto-detection)\n if (projectConfig.lombokJar) {\n if (projectConfig.lombokJar !== \"auto\") {\n manager.setLombokJar(projectConfig.lombokJar);\n }\n // \"auto\" is the default behavior — findLombokJar() already auto-detects.\n // Setting it explicitly just confirms the user wants Lombok support.\n }\n\n // Auto-start configured languages in the background\n if (projectConfig.autoStart && projectConfig.autoStart.length > 0) {\n const langs = projectConfig.autoStart;\n const lombokNote = langs.includes(\"java\") && manager.getLombokJar()\n ? ` (lombok: ${manager.getLombokJar()?.split(\"/\").pop()})` : \"\";\n setLspStatus(\"warning\", `LSP: auto-starting ${langs.join(\", \")}${lombokNote}...`);\n manager.startEagerly(langs);\n }\n }\n });\n\n // Register all LSP tools\n // Tools call getManager() lazily so they work even if session_start hasn't fired\n const managerProxy = new Proxy({} as LspManager, {\n get(_target, prop) {\n return (getManager() as any)[prop];\n },\n });\n\n const treeSitterProxy = new Proxy({} as TreeSitterManager, {\n get(_target, prop) {\n return (getTreeSitter() as any)[prop];\n },\n });\n\n const workspaceIndexProxy = new Proxy({} as WorkspaceIndex, {\n get(_target, prop) {\n return (getWorkspaceIndex() as any)[prop];\n },\n });\n\n pi.registerTool(createDiagnosticsTool(managerProxy, treeSitterProxy));\n pi.registerTool(createHoverTool(managerProxy, treeSitterProxy));\n pi.registerTool(createDefinitionTool(managerProxy, treeSitterProxy, workspaceIndexProxy));\n pi.registerTool(createReferencesTool(managerProxy, treeSitterProxy));\n pi.registerTool(createSymbolsTool(managerProxy, treeSitterProxy, workspaceIndexProxy));\n pi.registerTool(createRenameTool(managerProxy, treeSitterProxy));\n pi.registerTool(createCodeActionsTool(managerProxy, treeSitterProxy));\n pi.registerTool(createCompletionsTool(managerProxy, {\n getTrackedVersion: (uri) => getFileSync().getTrackedVersion(uri),\n setTrackedVersion: (uri, v) => getFileSync().setTrackedVersion(uri, v),\n isSyntheticDotActive: (uri) => syntheticDotLocks.has(uri),\n }, treeSitterProxy));\n const getRootDir = () => manager?.resolvePath(\".\") ?? process.cwd();\n pi.registerTool(createCodeOverviewTool(getRootDir, treeSitterProxy, workspaceIndexProxy));\n pi.registerTool(createCodeSearchTool(getRootDir, treeSitterProxy));\n pi.registerTool(createCodeRewriteTool(getRootDir, treeSitterProxy, {\n onFileModified: (filePath: string) => {\n getFileSync().handleFileWrite(filePath).catch(() => {});\n },\n }));\n pi.registerTool(createCodeActionsTool(managerProxy, treeSitterProxy));\n\n // File sync: track file reads/writes/edits\n // After writes/edits, append file-scoped error diagnostics to the tool result\n pi.on(\"tool_result\", async (event) => {\n const sync = getFileSync();\n\n try {\n if (isReadToolResult(event) && !event.isError) {\n const path = (event.input as any)?.path;\n if (path) await sync.handleFileRead(path);\n }\n\n if (isWriteToolResult(event) && !event.isError) {\n const path = (event.input as any)?.path;\n if (path) await sync.handleFileWrite(path);\n }\n\n if (isEditToolResult(event) && !event.isError) {\n const path = (event.input as any)?.path;\n if (path) await sync.handleFileWrite(path);\n }\n } catch {\n // File sync errors are non-fatal\n }\n\n // Auto-append diagnostics for the changed file (write/edit only)\n if ((isWriteToolResult(event) || isEditToolResult(event)) && !event.isError && manager) {\n const path = (event.input as any)?.path;\n if (!path) return;\n\n const languageId = manager.getLanguageId(path);\n if (!languageId) return;\n\n // Check autoInjectDiagnostics config\n const inject = projectConfig?.autoInjectDiagnostics;\n if (inject === false) return;\n if (Array.isArray(inject) && !inject.includes(languageId)) return;\n\n const client = manager.getRunningClient(languageId);\n if (!client) return;\n\n // Wait briefly for the LSP to publish updated diagnostics\n await new Promise((r) => setTimeout(r, DIAGNOSTIC_SETTLE_DELAY_MS));\n\n const uri = manager.getFileUri(path);\n const diagnostics = client.getDiagnostics(uri);\n const errors = diagnostics.filter((d) => d.severity === DiagnosticSeverity.Error);\n\n if (errors.length === 0) return;\n\n // Build a compact summary — just errors, max 10 lines\n const relPath = relative(manager.resolvePath(\".\"), manager.resolvePath(path));\n const lines = errors.slice(0, 10).map((d) => {\n const line = d.range.start.line + 1;\n const col = d.range.start.character + 1;\n const source = d.source ? ` [${d.source}]` : \"\";\n return `${relPath}:${line}:${col} error: ${d.message}${source}`;\n });\n if (errors.length > 10) {\n lines.push(`... and ${errors.length - 10} more error(s)`);\n }\n\n const summary = `\\n\\n⚠ LSP: ${errors.length} error(s) in ${relPath}:\\n${lines.join(\"\\n\")}`;\n\n return {\n content: [\n ...event.content,\n { type: \"text\" as const, text: summary },\n ],\n };\n }\n });\n\n // Update status after tool execution ends\n pi.on(\"tool_execution_end\", async (_event, ctx) => {\n latestCtx = ctx;\n if (!manager) return;\n const statuses = manager.getStatus();\n const running = statuses.filter((s) => s.running);\n if (running.length === 0) {\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"dim\", \"LSP: idle\"));\n } else {\n const totalDiags = running.reduce((n, s) => n + s.diagnosticsCount, 0);\n const langs = running.map((s) => s.languageId).join(\", \");\n let status = `LSP: ${langs}`;\n if (totalDiags > 0) {\n status += ` (${totalDiags} diagnostic${totalDiags !== 1 ? \"s\" : \"\"})`;\n }\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", status));\n }\n });\n\n // /lsp command — show server status\n pi.registerCommand(\"lsp\", {\n description: \"Show LSP server status\",\n handler: async (_args, ctx) => {\n if (!manager) {\n ctx.ui.notify(\"LSP manager not initialized\", \"warning\");\n return;\n }\n\n const statuses = manager.getStatus();\n if (statuses.length === 0) {\n ctx.ui.notify(\"No LSP servers configured\", \"info\");\n return;\n }\n\n const lines = statuses.map((s) => {\n const icon = s.running ? \"🟢\" : \"⚪\";\n const diags =\n s.diagnosticsCount > 0 ? ` (${s.diagnosticsCount} diagnostics)` : \"\";\n const shared = s.shared ? \" [shared]\" : \"\";\n return `${icon} ${s.languageId}: ${s.command}${diags}${shared}`;\n });\n\n ctx.ui.notify(lines.join(\"\\n\"), \"info\");\n },\n });\n\n // /lsp-restart command — restart a specific language server\n pi.registerCommand(\"lsp-restart\", {\n description: \"Restart an LSP server: /lsp-restart <language> (e.g. java, typescript)\",\n handler: async (args, ctx) => {\n if (!manager) {\n ctx.ui.notify(\"LSP manager not initialized\", \"warning\");\n return;\n }\n\n const languageId = args?.trim().toLowerCase();\n if (!languageId) {\n // Show running servers and usage\n const statuses = manager.getStatus().filter((s) => s.running);\n if (statuses.length === 0) {\n ctx.ui.notify(\"No LSP servers are running.\\n\\nUsage: /lsp-restart <language>\", \"info\");\n } else {\n const langs = statuses.map((s) => s.languageId).join(\", \");\n ctx.ui.notify(\n `Running servers: ${langs}\\n\\nUsage: /lsp-restart <language>\\nExample: /lsp-restart java`,\n \"info\"\n );\n }\n return;\n }\n\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"warning\", `LSP: restarting ${languageId}...`));\n ctx.ui.notify(`Restarting ${languageId} server (kills daemon if shared)...`, \"info\");\n\n try {\n await manager.restartServer(languageId);\n const lombokJar = languageId === \"java\" ? manager.getLombokJar() : null;\n const lombokNote = lombokJar ? `\\nLombok: ${lombokJar}` : \"\";\n ctx.ui.notify(`${languageId} server restarted successfully.${lombokNote}`, \"info\");\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", `LSP: ${languageId} ready`));\n } catch (err: any) {\n ctx.ui.notify(`Failed to restart ${languageId}: ${err.message}`, \"error\");\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"error\", `LSP: ${languageId} restart failed`));\n }\n },\n });\n\n // /lsp-config command — add or override server configuration\n pi.registerCommand(\"lsp-config\", {\n description:\n \"Configure an LSP server: /lsp-config <language> <command> [args...]\",\n handler: async (args, ctx) => {\n if (!args?.trim()) {\n ctx.ui.notify(\n \"Usage: /lsp-config <language> <command> [args...]\\nExample: /lsp-config python pylsp\",\n \"info\"\n );\n return;\n }\n\n const parts = args.trim().split(/\\s+/);\n if (parts.length < 2) {\n ctx.ui.notify(\n \"Usage: /lsp-config <language> <command> [args...]\",\n \"warning\"\n );\n return;\n }\n\n const [languageId, command, ...serverArgs] = parts;\n const config: ServerConfig = { command, args: serverArgs };\n\n getManager().setServerConfig(languageId, config);\n ctx.ui.notify(\n `Configured LSP for ${languageId}: ${command} ${serverArgs.join(\" \")}`,\n \"info\"\n );\n },\n });\n\n // /lsp-lombok command — set Lombok jar path for Java\n pi.registerCommand(\"lsp-lombok\", {\n description:\n \"Set Lombok jar path for Java: /lsp-lombok <path-to-lombok.jar>\",\n handler: async (args, ctx) => {\n const mgr = getManager();\n\n if (!args?.trim()) {\n const current = mgr.getLombokJar();\n if (current) {\n ctx.ui.notify(`Lombok jar: ${current}`, \"info\");\n } else {\n ctx.ui.notify(\n \"No Lombok jar configured or detected.\\n\\n\" +\n \"Usage: /lsp-lombok <path-to-lombok.jar>\\n\" +\n \"Or set LOMBOK_JAR environment variable.\\n\\n\" +\n \"Download from: https://projectlombok.org/download\",\n \"info\"\n );\n }\n return;\n }\n\n const jarPath = args.trim();\n const { existsSync } = await import(\"node:fs\");\n const { resolve } = await import(\"node:path\");\n const resolved = resolve(ctx.cwd, jarPath);\n\n if (!existsSync(resolved)) {\n ctx.ui.notify(`File not found: ${resolved}`, \"error\");\n return;\n }\n\n if (!resolved.endsWith(\".jar\")) {\n ctx.ui.notify(`Warning: ${resolved} doesn't end in .jar — setting anyway`, \"warning\");\n }\n\n mgr.setLombokJar(resolved);\n ctx.ui.notify(`Lombok jar set: ${resolved}`, \"info\");\n },\n });\n\n // Clean shutdown (includes workspace provider, all LSP servers, and tree-sitter)\n pi.on(\"session_shutdown\", async () => {\n // Drop the captured ctx immediately — once shutdown fires, any late\n // LSP manager callback that reaches setLspStatus/applyProvider would\n // otherwise hit an invalidated ctx and throw an uncaught exception.\n latestCtx = null;\n if (manager) {\n await manager.shutdownAll();\n manager = null;\n fileSync = null;\n }\n if (treeSitter) {\n treeSitter.shutdown();\n treeSitter = null;\n }\n workspaceIndex = null;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/builtin-extensions/pi-lsp-extension/src/index.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,iCAAiC,CAAC;AAmHpF,MAAM,CAAC,OAAO,UAAU,YAAY,CAAC,EAAE,EAAE,YAAY,QAgepD;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC","sourcesContent":["// @ts-nocheck\n/**\n * pi-lsp-extension — Pi coding agent extension for LSP integration.\n *\n * Exposes Language Server Protocol capabilities as tools the LLM can call:\n * - lsp_diagnostics: compilation errors and warnings\n * - lsp_hover: type info and docs at a position\n * - lsp_definition: go to definition\n * - lsp_references: find all references\n * - lsp_symbols: file/workspace symbol search\n * - lsp_rename: preview rename refactoring\n * - lsp_completions: code completion suggestions at a position\n * - lsp_code_actions: quick fixes, refactorings, and source actions\n *\n * Position-based tools (hover, definition, references, rename, code_actions)\n * accept an optional `query` parameter as an alternative to line/character,\n * resolving a symbol name to its position automatically.\n *\n * Tool schemas, commands, and hooks register immediately. Heavy managers\n * (LspManager, FileSync, Tree-sitter/WASM, WorkspaceIndex) load on first use.\n *\n * Usage:\n * 1. npm install in this directory\n * 2. Add to pi via settings.json extensions, or: pi -e ./src/index.ts\n * 3. LSP servers start lazily when you first use a tool on a file\n */\n\nimport type { ExtensionAPI, ToolDefinition } from \"@ashx-j/lunr\";\nimport type { TSchema } from \"typebox\";\nimport { awaitWithAbort } from \"../../../utils/await-with-abort.ts\";\nimport {\n isReadToolResult,\n isWriteToolResult,\n isEditToolResult,\n} from \"../../../core/extensions/types.js\";\nimport { DiagnosticSeverity } from \"vscode-languageserver-protocol\";\n\nimport type { WorkspaceProvider } from \"./workspace-provider.js\";\nimport { LspRuntimeHost, type LspRuntimeCallbacks } from \"./runtime.js\";\nimport { createDiagnosticsTool } from \"./tools/diagnostics.js\";\nimport { createHoverTool } from \"./tools/hover.js\";\nimport { createDefinitionTool } from \"./tools/definition.js\";\nimport { createReferencesTool } from \"./tools/references.js\";\nimport { createSymbolsTool } from \"./tools/symbols.js\";\nimport { createRenameTool } from \"./tools/rename.js\";\nimport { createCodeOverviewTool } from \"./tools/code-overview.js\";\nimport { createCompletionsTool } from \"./tools/completions.js\";\nimport { createCodeSearchTool } from \"./tools/code-search.js\";\nimport { createCodeRewriteTool } from \"./tools/code-rewrite.js\";\nimport { createCodeActionsTool } from \"./tools/code-actions.js\";\nimport { syntheticDotLocks } from \"./tools/completions.js\";\nimport { relative } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { DIAGNOSTIC_SETTLE_DELAY_MS } from \"./shared/timing.js\";\n\n/**\n * Project-level LSP config — loaded from `.pi-lsp.json` in the workspace root.\n *\n * Example:\n * ```json\n * {\n * \"autoStart\": [\"java\", \"typescript\"],\n * \"lombokJar\": \"env/Lombok-1.18.x/runtime/lib/lombok-1.18.42.jar\",\n * \"servers\": {\n * \"python\": { \"command\": \"pylsp\", \"args\": [] }\n * }\n * }\n * ```\n */\ninterface ProjectLspConfig {\n /** Languages to start eagerly on session_start (e.g. [\"java\", \"typescript\"]) */\n autoStart?: string[];\n /** Path to Lombok jar (absolute or relative to project root). \"auto\" to auto-detect. */\n lombokJar?: string;\n /** Custom server configs keyed by language ID */\n servers?: Record<string, { command: string; args?: string[]; env?: Record<string, string>; initializationOptions?: Record<string, unknown>; settings?: Record<string, unknown> }>;\n /**\n * Auto-inject LSP error diagnostics into write/edit tool results.\n * Set to false to disable, or provide an array of language IDs to enable selectively.\n * Default: true (all languages).\n *\n * Examples:\n * true — inject for all languages\n * false — never inject\n * [\"typescript\"] — only inject for TypeScript files\n */\n autoInjectDiagnostics?: boolean | string[];\n}\n\ninterface ServerConfig {\n command: string;\n args: string[];\n env?: Record<string, string>;\n initializationOptions?: Record<string, unknown>;\n settings?: Record<string, unknown>;\n}\n\n/** Load .pi-lsp.json from a directory. Returns null if not found or invalid. */\nfunction loadProjectConfig(dir: string): ProjectLspConfig | null {\n const configPath = join(dir, \".pi-lsp.json\");\n try {\n if (!existsSync(configPath)) return null;\n const raw = readFileSync(configPath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (typeof parsed !== \"object\" || parsed === null) return null;\n return parsed as ProjectLspConfig;\n } catch {\n return null;\n }\n}\n\nfunction createServiceProxy<T extends object>(getTarget: () => T | null, label: string): T {\n return new Proxy({} as T, {\n get(_target, prop, receiver) {\n const service = getTarget();\n if (!service) {\n throw new Error(`${label} is not initialized`);\n }\n const value = Reflect.get(service, prop, service);\n if (typeof value === \"function\") {\n return value.bind(service);\n }\n return value;\n },\n });\n}\n\nfunction registerToolWithRuntime<T extends TSchema, D>(pi: ExtensionAPI, tool: ToolDefinition<T, D>, ensure: () => Promise<unknown>, host: LspRuntimeHost) {\n pi.registerTool({\n ...tool,\n async execute(id, params, signal, onUpdate, ctx) {\n const generation = host.getGeneration();\n signal?.throwIfAborted();\n await awaitWithAbort(ensure(), signal);\n signal?.throwIfAborted();\n if (host.getGeneration() !== generation) throw new Error(\"LSP session changed before execution\");\n return tool.execute(id, params, signal, onUpdate, ctx);\n },\n });\n}\n\nexport default function lspExtension(pi: ExtensionAPI) {\n // Prevent EPIPE errors from LSP server exits from crashing the host process.\n // When an LSP server exits unexpectedly, in-flight writes to its stdin pipe\n // can produce EPIPE errors that escape all connection-level error handlers.\n const origListeners = process.listeners(\"uncaughtException\");\n process.on(\"uncaughtException\", (err: any) => {\n if (err?.code === \"EPIPE\") return; // swallow — LSP server exited, harmless\n // Re-throw for other handlers\n for (const listener of origListeners) (listener as any)(err);\n if (origListeners.length === 0) {\n console.error(\"[LSP] Uncaught exception:\", err);\n }\n });\n\n const host = new LspRuntimeHost();\n let pendingProvider: WorkspaceProvider | null = null;\n let latestCtx: any = null;\n let projectConfig: ProjectLspConfig | null = null;\n let sessionCwd = process.cwd();\n\n /**\n * Run `fn` with the currently captured ctx, swallowing stale-ctx errors.\n *\n * Lifecycle callbacks from LspManager (server ready, workspace setup, etc.)\n * and `pi.events` listeners can fire AFTER the session is replaced or reloaded,\n * at which point the captured ctx has been invalidated and any property access\n * throws via ExtensionRunner.assertActive(). We can't use optional chaining to\n * dodge it because the `ui` / `theme` getters themselves run assertActive().\n */\n const withLatestCtx = (fn: (ctx: any) => void) => {\n const ctx = latestCtx;\n if (!ctx) return;\n try {\n fn(ctx);\n } catch (err: any) {\n if (typeof err?.message === \"string\" && err.message.includes(\"stale after session\")) {\n // Session was replaced/reloaded — drop the stale ctx and move on.\n latestCtx = null;\n return;\n }\n throw err;\n }\n };\n\n const applyProvider = (data: unknown) => {\n const provider = data as WorkspaceProvider;\n pendingProvider = provider;\n host.setPendingProvider(provider);\n const statusText = provider.getStatusText();\n if (!statusText) return;\n withLatestCtx((ctx) => {\n if (!ctx.ui?.theme) return;\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", `LSP: ${statusText}`));\n });\n };\n\n pi.events.on(\"lsp:register-workspace-provider\", applyProvider);\n\n // Check for provider registered before our listener existed\n const existing = (pi.events as any)[\"lsp:workspace-provider\"];\n if (existing) applyProvider(existing);\n\n const setLspStatus = (color: string, text: string) => {\n withLatestCtx((ctx) => {\n if (!ctx.ui?.theme) return;\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(color, text));\n });\n };\n\n const makeCallbacks = (): LspRuntimeCallbacks => ({\n onWorkspaceSetupStart: () => {\n setLspStatus(\"warning\", \"LSP: workspace setup...\");\n },\n onWorkspaceSetupEnd: (success: boolean, duration: number) => {\n const secs = (duration / 1000).toFixed(1);\n if (success) {\n setLspStatus(\"accent\", `LSP: workspace ready (${secs}s)`);\n } else {\n setLspStatus(\"warning\", `LSP: workspace setup failed (${secs}s)`);\n }\n },\n onServerStart: (languageId: string, command: string) => {\n setLspStatus(\"warning\", `LSP: starting ${languageId} (${command})...`);\n },\n onServerReady: (languageId: string) => {\n setLspStatus(\"accent\", `LSP: ${languageId} ready`);\n },\n onServerError: (languageId: string, _error: string) => {\n setLspStatus(\"error\", `LSP: ${languageId} failed`);\n },\n onServerCrash: (languageId: string, restarting: boolean, attempt: number) => {\n if (restarting) {\n setLspStatus(\"warning\", `LSP: restarting ${languageId}... (attempt ${attempt}/3)`);\n } else {\n setLspStatus(\"error\", `LSP: ${languageId} crashed — auto-restart exhausted`);\n }\n },\n });\n\n const applyProjectConfigToManager = (manager: { setServerConfig: Function; setLombokJar: Function }, config: ProjectLspConfig | null) => {\n if (!config) return;\n if (config.servers) {\n for (const [lang, serverConf] of Object.entries(config.servers)) {\n manager.setServerConfig(lang, {\n command: serverConf.command,\n args: serverConf.args ?? [],\n env: serverConf.env,\n initializationOptions: serverConf.initializationOptions,\n settings: serverConf.settings,\n });\n }\n }\n if (config.lombokJar && config.lombokJar !== \"auto\") {\n manager.setLombokJar(config.lombokJar);\n }\n };\n\n const buildBindOptions = (cwd: string) => ({\n cwd,\n callbacks: makeCallbacks(),\n pendingProvider,\n syntheticDotChecker: (uri: string) => syntheticDotLocks.has(uri),\n configureManager: (manager) => {\n applyProjectConfigToManager(manager, projectConfig);\n },\n });\n\n const ensureRuntime = async () => {\n return host.ensureServices(\n buildBindOptions(sessionCwd || process.cwd()),\n );\n };\n\n // session_start binds cwd/config only. Heavy managers load on first use,\n // unless autoStart is configured (then ensure + startEagerly).\n pi.on(\"session_start\", async (_event, ctx) => {\n latestCtx = ctx;\n sessionCwd = ctx.cwd;\n\n projectConfig = loadProjectConfig(ctx.cwd);\n await host.bindSession(buildBindOptions(ctx.cwd));\n\n const statusText = pendingProvider?.getStatusText?.() ?? \"\";\n if (statusText) {\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", `LSP: ${statusText}`));\n } else {\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"dim\", \"LSP: idle\"));\n }\n\n if (projectConfig?.autoStart && projectConfig.autoStart.length > 0) {\n const langs = projectConfig.autoStart;\n const generation = host.getGeneration();\n void ensureRuntime().then((services) => {\n if (host.getGeneration() !== generation) return;\n const lombokJar = services.manager.getLombokJar?.() ?? null;\n const lombokNote = langs.includes(\"java\") && lombokJar\n ? ` (lombok: ${String(lombokJar).split(/[/\\\\]/).pop()})`\n : \"\";\n setLspStatus(\"warning\", `LSP: auto-starting ${langs.join(\", \")}${lombokNote}...`);\n services.manager.startEagerly(langs);\n }).catch((error) => {\n if (host.getGeneration() === generation) setLspStatus(\"error\", `LSP startup failed: ${String(error)}`);\n });\n }\n });\n\n const managerProxy = createServiceProxy(\n () => host.getServicesIfReady()?.manager ?? null,\n \"LSP manager\",\n );\n const treeSitterProxy = createServiceProxy(\n () => host.getServicesIfReady()?.treeSitter ?? null,\n \"Tree-sitter manager\",\n );\n const workspaceIndexProxy = createServiceProxy(\n () => host.getServicesIfReady()?.workspaceIndex ?? null,\n \"Workspace index\",\n );\n\n registerToolWithRuntime(pi, createDiagnosticsTool(managerProxy, treeSitterProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createHoverTool(managerProxy, treeSitterProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createDefinitionTool(managerProxy, treeSitterProxy, workspaceIndexProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createReferencesTool(managerProxy, treeSitterProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createSymbolsTool(managerProxy, treeSitterProxy, workspaceIndexProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createRenameTool(managerProxy, treeSitterProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createCodeActionsTool(managerProxy, treeSitterProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createCompletionsTool(\n managerProxy,\n {\n getTrackedVersion: (uri) => {\n const services = host.getServicesIfReady();\n if (!services) return null;\n return services.fileSync.getTrackedVersion(uri);\n },\n setTrackedVersion: (uri, v) => {\n host.getServicesIfReady()?.fileSync.setTrackedVersion(uri, v);\n },\n isSyntheticDotActive: (uri) => syntheticDotLocks.has(uri),\n },\n treeSitterProxy,\n ), ensureRuntime, host);\n const getRootDir = () => {\n const manager = host.getServicesIfReady()?.manager;\n if (manager) return manager.resolvePath(\".\");\n return sessionCwd || process.cwd();\n };\n registerToolWithRuntime(pi, createCodeOverviewTool(getRootDir, treeSitterProxy, workspaceIndexProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createCodeSearchTool(getRootDir, treeSitterProxy), ensureRuntime, host);\n registerToolWithRuntime(pi, createCodeRewriteTool(getRootDir, treeSitterProxy, {\n onFileModified: (filePath: string) => {\n const services = host.getServicesIfReady();\n if (!services) return;\n services.fileSync.handleFileWrite(filePath).catch(() => {});\n },\n }), ensureRuntime, host);\n\n // File sync: track file reads/writes/edits without loading runtime on plain reads\n // when LSP was never used. Writes may start a server (existing behavior) so they\n // ensure runtime. After writes/edits, append file-scoped error diagnostics.\n pi.on(\"tool_result\", async (event) => {\n const generation = host.getGeneration();\n try {\n if (isReadToolResult(event) && !event.isError) {\n const services = host.getServicesIfReady();\n if (services) {\n const path = (event.input as any)?.path;\n if (path) await services.fileSync.handleFileRead(path);\n if (host.getGeneration() !== generation) return;\n }\n }\n\n if ((isWriteToolResult(event) || isEditToolResult(event)) && !event.isError) {\n const path = (event.input as any)?.path;\n if (path) {\n const services = await ensureRuntime();\n if (host.getGeneration() !== generation) return;\n await services.fileSync.handleFileWrite(path);\n }\n }\n } catch {\n // File sync errors are non-fatal\n }\n\n if (host.getGeneration() !== generation) return;\n // Auto-append diagnostics for the changed file (write/edit only)\n const services = host.getServicesIfReady();\n if ((isWriteToolResult(event) || isEditToolResult(event)) && !event.isError && services) {\n const path = (event.input as any)?.path;\n if (!path) return;\n\n const manager = services.manager;\n const languageId = manager.getLanguageId(path);\n if (!languageId) return;\n\n // Check autoInjectDiagnostics config\n const inject = projectConfig?.autoInjectDiagnostics;\n if (inject === false) return;\n if (Array.isArray(inject) && !inject.includes(languageId)) return;\n\n const client = manager.getRunningClient(languageId);\n if (!client) return;\n\n // Wait briefly for the LSP to publish updated diagnostics\n await new Promise((r) => setTimeout(r, DIAGNOSTIC_SETTLE_DELAY_MS));\n if (host.getGeneration() !== generation) return;\n\n const uri = manager.getFileUri(path);\n const diagnostics = client.getDiagnostics(uri);\n const errors = diagnostics.filter((d) => d.severity === DiagnosticSeverity.Error);\n\n if (errors.length === 0) return;\n\n // Build a compact summary — just errors, max 10 lines\n const relPath = relative(manager.resolvePath(\".\"), manager.resolvePath(path));\n const lines = errors.slice(0, 10).map((d) => {\n const line = d.range.start.line + 1;\n const col = d.range.start.character + 1;\n const source = d.source ? ` [${d.source}]` : \"\";\n return `${relPath}:${line}:${col} error: ${d.message}${source}`;\n });\n if (errors.length > 10) {\n lines.push(`... and ${errors.length - 10} more error(s)`);\n }\n\n const summary = `\\n\\n⚠ LSP: ${errors.length} error(s) in ${relPath}:\\n${lines.join(\"\\n\")}`;\n\n return {\n content: [\n ...event.content,\n { type: \"text\" as const, text: summary },\n ],\n };\n }\n });\n\n // Update status after tool execution ends\n pi.on(\"tool_execution_end\", async (_event, ctx) => {\n latestCtx = ctx;\n const services = host.getServicesIfReady();\n if (!services) return;\n const statuses = services.manager.getStatus();\n const running = statuses.filter((s) => s.running);\n if (running.length === 0) {\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"dim\", \"LSP: idle\"));\n } else {\n const totalDiags = running.reduce((n, s) => n + s.diagnosticsCount, 0);\n const langs = running.map((s) => s.languageId).join(\", \");\n let status = `LSP: ${langs}`;\n if (totalDiags > 0) {\n status += ` (${totalDiags} diagnostic${totalDiags !== 1 ? \"s\" : \"\"})`;\n }\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", status));\n }\n });\n\n // /lsp command — show server status\n pi.registerCommand(\"lsp\", {\n description: \"Show LSP server status\",\n handler: async (_args, ctx) => {\n const services = host.getServicesIfReady();\n if (!services) {\n ctx.ui.notify(\n host.isInitializing() ? \"LSP runtime is starting\" : \"LSP runtime is idle (not started)\",\n \"info\",\n );\n return;\n }\n\n const statuses = services.manager.getStatus();\n if (statuses.length === 0) {\n ctx.ui.notify(\"No LSP servers configured\", \"info\");\n return;\n }\n\n const lines = statuses.map((s) => {\n const icon = s.running ? \"🟢\" : \"⚪\";\n const diags =\n s.diagnosticsCount > 0 ? ` (${s.diagnosticsCount} diagnostics)` : \"\";\n const shared = s.shared ? \" [shared]\" : \"\";\n return `${icon} ${s.languageId}: ${s.command}${diags}${shared}`;\n });\n\n ctx.ui.notify(lines.join(\"\\n\"), \"info\");\n },\n });\n\n // /lsp-restart command — restart a specific language server\n pi.registerCommand(\"lsp-restart\", {\n description: \"Restart an LSP server: /lsp-restart <language> (e.g. java, typescript)\",\n handler: async (args, ctx) => {\n const services = host.getServicesIfReady();\n if (!services) {\n if (args?.trim()) {\n ctx.ui.notify(\n host.isInitializing()\n ? \"LSP runtime is starting\"\n : \"LSP runtime is idle. Run an LSP tool before restarting a server.\",\n \"info\",\n );\n } else {\n ctx.ui.notify(\"No LSP servers are running.\\n\\nUsage: /lsp-restart <language>\", \"info\");\n }\n return;\n }\n\n const languageId = args?.trim().toLowerCase();\n if (!languageId) {\n // Show running servers and usage\n const statuses = services.manager.getStatus().filter((s) => s.running);\n if (statuses.length === 0) {\n ctx.ui.notify(\"No LSP servers are running.\\n\\nUsage: /lsp-restart <language>\", \"info\");\n } else {\n const langs = statuses.map((s) => s.languageId).join(\", \");\n ctx.ui.notify(\n `Running servers: ${langs}\\n\\nUsage: /lsp-restart <language>\\nExample: /lsp-restart java`,\n \"info\"\n );\n }\n return;\n }\n\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"warning\", `LSP: restarting ${languageId}...`));\n ctx.ui.notify(`Restarting ${languageId} server (kills daemon if shared)...`, \"info\");\n\n try {\n await services.manager.restartServer(languageId);\n const lombokJar = languageId === \"java\" ? services.manager.getLombokJar() : null;\n const lombokNote = lombokJar ? `\\nLombok: ${lombokJar}` : \"\";\n ctx.ui.notify(`${languageId} server restarted successfully.${lombokNote}`, \"info\");\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"accent\", `LSP: ${languageId} ready`));\n } catch (err: any) {\n ctx.ui.notify(`Failed to restart ${languageId}: ${err.message}`, \"error\");\n ctx.ui.setStatus(\"lsp\", ctx.ui.theme.fg(\"error\", `LSP: ${languageId} restart failed`));\n }\n },\n });\n\n // /lsp-config command — add or override server configuration\n pi.registerCommand(\"lsp-config\", {\n description:\n \"Configure an LSP server: /lsp-config <language> <command> [args...]\",\n handler: async (args, ctx) => {\n if (!args?.trim()) {\n ctx.ui.notify(\n \"Usage: /lsp-config <language> <command> [args...]\\nExample: /lsp-config python pylsp\",\n \"info\"\n );\n return;\n }\n\n const parts = args.trim().split(/\\s+/);\n if (parts.length < 2) {\n ctx.ui.notify(\n \"Usage: /lsp-config <language> <command> [args...]\",\n \"warning\"\n );\n return;\n }\n\n const [languageId, command, ...serverArgs] = parts;\n const config: ServerConfig = { command, args: serverArgs };\n\n const services = await ensureRuntime();\n services.manager.setServerConfig(languageId, config);\n ctx.ui.notify(\n `Configured LSP for ${languageId}: ${command} ${serverArgs.join(\" \")}`,\n \"info\"\n );\n },\n });\n\n // /lsp-lombok command — set Lombok jar path for Java\n pi.registerCommand(\"lsp-lombok\", {\n description:\n \"Set Lombok jar path for Java: /lsp-lombok <path-to-lombok.jar>\",\n handler: async (args, ctx) => {\n const services = await ensureRuntime();\n const mgr = services.manager;\n\n if (!args?.trim()) {\n const current = mgr.getLombokJar();\n if (current) {\n ctx.ui.notify(`Lombok jar: ${current}`, \"info\");\n } else {\n ctx.ui.notify(\n \"No Lombok jar configured or detected.\\n\\n\" +\n \"Usage: /lsp-lombok <path-to-lombok.jar>\\n\" +\n \"Or set LOMBOK_JAR environment variable.\\n\\n\" +\n \"Download from: https://projectlombok.org/download\",\n \"info\"\n );\n }\n return;\n }\n\n const jarPath = args.trim();\n const resolved = resolve(ctx.cwd, jarPath);\n\n if (!existsSync(resolved)) {\n ctx.ui.notify(`File not found: ${resolved}`, \"error\");\n return;\n }\n\n if (!resolved.endsWith(\".jar\")) {\n ctx.ui.notify(`Warning: ${resolved} doesn't end in .jar — setting anyway`, \"warning\");\n }\n\n mgr.setLombokJar(resolved);\n ctx.ui.notify(`Lombok jar set: ${resolved}`, \"info\");\n },\n });\n\n // Clean shutdown — never loads heavy modules if they were unused\n pi.on(\"session_shutdown\", async () => {\n // Drop the captured ctx immediately — once shutdown fires, any late\n // LSP manager callback that reaches setLspStatus/applyProvider would\n // otherwise hit an invalidated ctx and throw an uncaught exception.\n latestCtx = null;\n await host.shutdown();\n });\n}\n\nexport { LspRuntimeHost } from \"./runtime.js\";\n"]}
|
|
@@ -16,18 +16,18 @@
|
|
|
16
16
|
* accept an optional `query` parameter as an alternative to line/character,
|
|
17
17
|
* resolving a symbol name to its position automatically.
|
|
18
18
|
*
|
|
19
|
+
* Tool schemas, commands, and hooks register immediately. Heavy managers
|
|
20
|
+
* (LspManager, FileSync, Tree-sitter/WASM, WorkspaceIndex) load on first use.
|
|
21
|
+
*
|
|
19
22
|
* Usage:
|
|
20
23
|
* 1. npm install in this directory
|
|
21
24
|
* 2. Add to pi via settings.json extensions, or: pi -e ./src/index.ts
|
|
22
25
|
* 3. LSP servers start lazily when you first use a tool on a file
|
|
23
26
|
*/
|
|
24
|
-
import {
|
|
27
|
+
import { awaitWithAbort } from "../../../utils/await-with-abort.js";
|
|
28
|
+
import { isReadToolResult, isWriteToolResult, isEditToolResult, } from "../../../core/extensions/types.js";
|
|
25
29
|
import { DiagnosticSeverity } from "vscode-languageserver-protocol";
|
|
26
|
-
import {
|
|
27
|
-
import { FileSync } from "./file-sync.js";
|
|
28
|
-
import { TreeSitterManager } from "./tree-sitter/parser-manager.js";
|
|
29
|
-
import { WorkspaceIndex } from "./tree-sitter/workspace-index.js";
|
|
30
|
-
import "./workspace-provider.js";
|
|
30
|
+
import { LspRuntimeHost } from "./runtime.js";
|
|
31
31
|
import { createDiagnosticsTool } from "./tools/diagnostics.js";
|
|
32
32
|
import { createHoverTool } from "./tools/hover.js";
|
|
33
33
|
import { createDefinitionTool } from "./tools/definition.js";
|
|
@@ -42,7 +42,7 @@ import { createCodeActionsTool } from "./tools/code-actions.js";
|
|
|
42
42
|
import { syntheticDotLocks } from "./tools/completions.js";
|
|
43
43
|
import { relative } from "node:path";
|
|
44
44
|
import { existsSync, readFileSync } from "node:fs";
|
|
45
|
-
import { join } from "node:path";
|
|
45
|
+
import { join, resolve } from "node:path";
|
|
46
46
|
import { DIAGNOSTIC_SETTLE_DELAY_MS } from "./shared/timing.js";
|
|
47
47
|
/** Load .pi-lsp.json from a directory. Returns null if not found or invalid. */
|
|
48
48
|
function loadProjectConfig(dir) {
|
|
@@ -60,6 +60,35 @@ function loadProjectConfig(dir) {
|
|
|
60
60
|
return null;
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
|
+
function createServiceProxy(getTarget, label) {
|
|
64
|
+
return new Proxy({}, {
|
|
65
|
+
get(_target, prop, receiver) {
|
|
66
|
+
const service = getTarget();
|
|
67
|
+
if (!service) {
|
|
68
|
+
throw new Error(`${label} is not initialized`);
|
|
69
|
+
}
|
|
70
|
+
const value = Reflect.get(service, prop, service);
|
|
71
|
+
if (typeof value === "function") {
|
|
72
|
+
return value.bind(service);
|
|
73
|
+
}
|
|
74
|
+
return value;
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
function registerToolWithRuntime(pi, tool, ensure, host) {
|
|
79
|
+
pi.registerTool({
|
|
80
|
+
...tool,
|
|
81
|
+
async execute(id, params, signal, onUpdate, ctx) {
|
|
82
|
+
const generation = host.getGeneration();
|
|
83
|
+
signal?.throwIfAborted();
|
|
84
|
+
await awaitWithAbort(ensure(), signal);
|
|
85
|
+
signal?.throwIfAborted();
|
|
86
|
+
if (host.getGeneration() !== generation)
|
|
87
|
+
throw new Error("LSP session changed before execution");
|
|
88
|
+
return tool.execute(id, params, signal, onUpdate, ctx);
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
63
92
|
export default function lspExtension(pi) {
|
|
64
93
|
// Prevent EPIPE errors from LSP server exits from crashing the host process.
|
|
65
94
|
// When an LSP server exits unexpectedly, in-flight writes to its stdin pipe
|
|
@@ -75,15 +104,11 @@ export default function lspExtension(pi) {
|
|
|
75
104
|
console.error("[LSP] Uncaught exception:", err);
|
|
76
105
|
}
|
|
77
106
|
});
|
|
78
|
-
|
|
79
|
-
let fileSync = null;
|
|
80
|
-
let treeSitter = null;
|
|
81
|
-
let workspaceIndex = null;
|
|
107
|
+
const host = new LspRuntimeHost();
|
|
82
108
|
let pendingProvider = null;
|
|
83
|
-
// Store latest ctx for lifecycle callbacks (updated on each event)
|
|
84
109
|
let latestCtx = null;
|
|
85
|
-
// Project config — loaded on session_start, used by auto-injection guard
|
|
86
110
|
let projectConfig = null;
|
|
111
|
+
let sessionCwd = process.cwd();
|
|
87
112
|
/**
|
|
88
113
|
* Run `fn` with the currently captured ctx, swallowing stale-ctx errors.
|
|
89
114
|
*
|
|
@@ -109,16 +134,10 @@ export default function lspExtension(pi) {
|
|
|
109
134
|
throw err;
|
|
110
135
|
}
|
|
111
136
|
};
|
|
112
|
-
// Listen for external workspace providers (e.g. bemol extension).
|
|
113
|
-
// Also check if one was already registered before we loaded (load order varies).
|
|
114
|
-
// Store as pendingProvider so it's available when the manager is created later.
|
|
115
137
|
const applyProvider = (data) => {
|
|
116
138
|
const provider = data;
|
|
117
139
|
pendingProvider = provider;
|
|
118
|
-
|
|
119
|
-
manager.setWorkspaceProvider(provider);
|
|
120
|
-
}
|
|
121
|
-
// Update status if we have a UI context
|
|
140
|
+
host.setPendingProvider(provider);
|
|
122
141
|
const statusText = provider.getStatusText();
|
|
123
142
|
if (!statusText)
|
|
124
143
|
return;
|
|
@@ -133,7 +152,6 @@ export default function lspExtension(pi) {
|
|
|
133
152
|
const existing = pi.events["lsp:workspace-provider"];
|
|
134
153
|
if (existing)
|
|
135
154
|
applyProvider(existing);
|
|
136
|
-
/** Build lifecycle callbacks that update UI status */
|
|
137
155
|
const setLspStatus = (color, text) => {
|
|
138
156
|
withLatestCtx((ctx) => {
|
|
139
157
|
if (!ctx.ui?.theme)
|
|
@@ -172,165 +190,144 @@ export default function lspExtension(pi) {
|
|
|
172
190
|
}
|
|
173
191
|
},
|
|
174
192
|
});
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
if (!fileSync) {
|
|
189
|
-
getManager(); // ensures fileSync is created
|
|
193
|
+
const applyProjectConfigToManager = (manager, config) => {
|
|
194
|
+
if (!config)
|
|
195
|
+
return;
|
|
196
|
+
if (config.servers) {
|
|
197
|
+
for (const [lang, serverConf] of Object.entries(config.servers)) {
|
|
198
|
+
manager.setServerConfig(lang, {
|
|
199
|
+
command: serverConf.command,
|
|
200
|
+
args: serverConf.args ?? [],
|
|
201
|
+
env: serverConf.env,
|
|
202
|
+
initializationOptions: serverConf.initializationOptions,
|
|
203
|
+
settings: serverConf.settings,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
190
206
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
const getTreeSitter = () => {
|
|
194
|
-
if (!treeSitter) {
|
|
195
|
-
getManager(); // ensures treeSitter is created
|
|
207
|
+
if (config.lombokJar && config.lombokJar !== "auto") {
|
|
208
|
+
manager.setLombokJar(config.lombokJar);
|
|
196
209
|
}
|
|
197
|
-
return treeSitter;
|
|
198
210
|
};
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
211
|
+
const buildBindOptions = (cwd) => ({
|
|
212
|
+
cwd,
|
|
213
|
+
callbacks: makeCallbacks(),
|
|
214
|
+
pendingProvider,
|
|
215
|
+
syntheticDotChecker: (uri) => syntheticDotLocks.has(uri),
|
|
216
|
+
configureManager: (manager) => {
|
|
217
|
+
applyProjectConfigToManager(manager, projectConfig);
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
const ensureRuntime = async () => {
|
|
221
|
+
return host.ensureServices(buildBindOptions(sessionCwd || process.cwd()));
|
|
204
222
|
};
|
|
205
|
-
//
|
|
223
|
+
// session_start binds cwd/config only. Heavy managers load on first use,
|
|
224
|
+
// unless autoStart is configured (then ensure + startEagerly).
|
|
206
225
|
pi.on("session_start", async (_event, ctx) => {
|
|
207
226
|
latestCtx = ctx;
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
if (treeSitter)
|
|
213
|
-
treeSitter.shutdown();
|
|
214
|
-
}
|
|
215
|
-
manager = new LspManager(ctx.cwd, undefined, makeCallbacks(), undefined, pendingProvider ?? undefined);
|
|
216
|
-
fileSync = new FileSync(manager);
|
|
217
|
-
fileSync.setSyntheticDotChecker((uri) => syntheticDotLocks.has(uri));
|
|
218
|
-
treeSitter = new TreeSitterManager();
|
|
219
|
-
workspaceIndex = new WorkspaceIndex(ctx.cwd, treeSitter);
|
|
220
|
-
fileSync.setTreeSitter(treeSitter, workspaceIndex);
|
|
221
|
-
// Initialize tree-sitter in the background (don't block session start)
|
|
222
|
-
treeSitter.init().catch((err) => {
|
|
223
|
-
console.error(`[pi-lsp-extension] tree-sitter WASM init failed: ${err?.message ?? err}`);
|
|
224
|
-
});
|
|
225
|
-
// Show workspace provider status
|
|
226
|
-
const wsProvider = manager.workspace;
|
|
227
|
-
const statusText = wsProvider.getStatusText();
|
|
227
|
+
sessionCwd = ctx.cwd;
|
|
228
|
+
projectConfig = loadProjectConfig(ctx.cwd);
|
|
229
|
+
await host.bindSession(buildBindOptions(ctx.cwd));
|
|
230
|
+
const statusText = pendingProvider?.getStatusText?.() ?? "";
|
|
228
231
|
if (statusText) {
|
|
229
232
|
ctx.ui.setStatus("lsp", ctx.ui.theme.fg("accent", `LSP: ${statusText}`));
|
|
230
233
|
}
|
|
231
234
|
else {
|
|
232
235
|
ctx.ui.setStatus("lsp", ctx.ui.theme.fg("dim", "LSP: idle"));
|
|
233
236
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
initializationOptions: serverConf.initializationOptions,
|
|
245
|
-
settings: serverConf.settings,
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
// Set Lombok jar path (explicit path or "auto" for auto-detection)
|
|
250
|
-
if (projectConfig.lombokJar) {
|
|
251
|
-
if (projectConfig.lombokJar !== "auto") {
|
|
252
|
-
manager.setLombokJar(projectConfig.lombokJar);
|
|
253
|
-
}
|
|
254
|
-
// "auto" is the default behavior — findLombokJar() already auto-detects.
|
|
255
|
-
// Setting it explicitly just confirms the user wants Lombok support.
|
|
256
|
-
}
|
|
257
|
-
// Auto-start configured languages in the background
|
|
258
|
-
if (projectConfig.autoStart && projectConfig.autoStart.length > 0) {
|
|
259
|
-
const langs = projectConfig.autoStart;
|
|
260
|
-
const lombokNote = langs.includes("java") && manager.getLombokJar()
|
|
261
|
-
? ` (lombok: ${manager.getLombokJar()?.split("/").pop()})` : "";
|
|
237
|
+
if (projectConfig?.autoStart && projectConfig.autoStart.length > 0) {
|
|
238
|
+
const langs = projectConfig.autoStart;
|
|
239
|
+
const generation = host.getGeneration();
|
|
240
|
+
void ensureRuntime().then((services) => {
|
|
241
|
+
if (host.getGeneration() !== generation)
|
|
242
|
+
return;
|
|
243
|
+
const lombokJar = services.manager.getLombokJar?.() ?? null;
|
|
244
|
+
const lombokNote = langs.includes("java") && lombokJar
|
|
245
|
+
? ` (lombok: ${String(lombokJar).split(/[/\\]/).pop()})`
|
|
246
|
+
: "";
|
|
262
247
|
setLspStatus("warning", `LSP: auto-starting ${langs.join(", ")}${lombokNote}...`);
|
|
263
|
-
manager.startEagerly(langs);
|
|
264
|
-
}
|
|
248
|
+
services.manager.startEagerly(langs);
|
|
249
|
+
}).catch((error) => {
|
|
250
|
+
if (host.getGeneration() === generation)
|
|
251
|
+
setLspStatus("error", `LSP startup failed: ${String(error)}`);
|
|
252
|
+
});
|
|
265
253
|
}
|
|
266
254
|
});
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
255
|
+
const managerProxy = createServiceProxy(() => host.getServicesIfReady()?.manager ?? null, "LSP manager");
|
|
256
|
+
const treeSitterProxy = createServiceProxy(() => host.getServicesIfReady()?.treeSitter ?? null, "Tree-sitter manager");
|
|
257
|
+
const workspaceIndexProxy = createServiceProxy(() => host.getServicesIfReady()?.workspaceIndex ?? null, "Workspace index");
|
|
258
|
+
registerToolWithRuntime(pi, createDiagnosticsTool(managerProxy, treeSitterProxy), ensureRuntime, host);
|
|
259
|
+
registerToolWithRuntime(pi, createHoverTool(managerProxy, treeSitterProxy), ensureRuntime, host);
|
|
260
|
+
registerToolWithRuntime(pi, createDefinitionTool(managerProxy, treeSitterProxy, workspaceIndexProxy), ensureRuntime, host);
|
|
261
|
+
registerToolWithRuntime(pi, createReferencesTool(managerProxy, treeSitterProxy), ensureRuntime, host);
|
|
262
|
+
registerToolWithRuntime(pi, createSymbolsTool(managerProxy, treeSitterProxy, workspaceIndexProxy), ensureRuntime, host);
|
|
263
|
+
registerToolWithRuntime(pi, createRenameTool(managerProxy, treeSitterProxy), ensureRuntime, host);
|
|
264
|
+
registerToolWithRuntime(pi, createCodeActionsTool(managerProxy, treeSitterProxy), ensureRuntime, host);
|
|
265
|
+
registerToolWithRuntime(pi, createCompletionsTool(managerProxy, {
|
|
266
|
+
getTrackedVersion: (uri) => {
|
|
267
|
+
const services = host.getServicesIfReady();
|
|
268
|
+
if (!services)
|
|
269
|
+
return null;
|
|
270
|
+
return services.fileSync.getTrackedVersion(uri);
|
|
277
271
|
},
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
get(_target, prop) {
|
|
281
|
-
return getWorkspaceIndex()[prop];
|
|
272
|
+
setTrackedVersion: (uri, v) => {
|
|
273
|
+
host.getServicesIfReady()?.fileSync.setTrackedVersion(uri, v);
|
|
282
274
|
},
|
|
283
|
-
});
|
|
284
|
-
pi.registerTool(createDiagnosticsTool(managerProxy, treeSitterProxy));
|
|
285
|
-
pi.registerTool(createHoverTool(managerProxy, treeSitterProxy));
|
|
286
|
-
pi.registerTool(createDefinitionTool(managerProxy, treeSitterProxy, workspaceIndexProxy));
|
|
287
|
-
pi.registerTool(createReferencesTool(managerProxy, treeSitterProxy));
|
|
288
|
-
pi.registerTool(createSymbolsTool(managerProxy, treeSitterProxy, workspaceIndexProxy));
|
|
289
|
-
pi.registerTool(createRenameTool(managerProxy, treeSitterProxy));
|
|
290
|
-
pi.registerTool(createCodeActionsTool(managerProxy, treeSitterProxy));
|
|
291
|
-
pi.registerTool(createCompletionsTool(managerProxy, {
|
|
292
|
-
getTrackedVersion: (uri) => getFileSync().getTrackedVersion(uri),
|
|
293
|
-
setTrackedVersion: (uri, v) => getFileSync().setTrackedVersion(uri, v),
|
|
294
275
|
isSyntheticDotActive: (uri) => syntheticDotLocks.has(uri),
|
|
295
|
-
}, treeSitterProxy));
|
|
296
|
-
const getRootDir = () =>
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
276
|
+
}, treeSitterProxy), ensureRuntime, host);
|
|
277
|
+
const getRootDir = () => {
|
|
278
|
+
const manager = host.getServicesIfReady()?.manager;
|
|
279
|
+
if (manager)
|
|
280
|
+
return manager.resolvePath(".");
|
|
281
|
+
return sessionCwd || process.cwd();
|
|
282
|
+
};
|
|
283
|
+
registerToolWithRuntime(pi, createCodeOverviewTool(getRootDir, treeSitterProxy, workspaceIndexProxy), ensureRuntime, host);
|
|
284
|
+
registerToolWithRuntime(pi, createCodeSearchTool(getRootDir, treeSitterProxy), ensureRuntime, host);
|
|
285
|
+
registerToolWithRuntime(pi, createCodeRewriteTool(getRootDir, treeSitterProxy, {
|
|
300
286
|
onFileModified: (filePath) => {
|
|
301
|
-
|
|
287
|
+
const services = host.getServicesIfReady();
|
|
288
|
+
if (!services)
|
|
289
|
+
return;
|
|
290
|
+
services.fileSync.handleFileWrite(filePath).catch(() => { });
|
|
302
291
|
},
|
|
303
|
-
}));
|
|
304
|
-
|
|
305
|
-
//
|
|
306
|
-
// After writes/edits, append file-scoped error diagnostics
|
|
292
|
+
}), ensureRuntime, host);
|
|
293
|
+
// File sync: track file reads/writes/edits without loading runtime on plain reads
|
|
294
|
+
// when LSP was never used. Writes may start a server (existing behavior) so they
|
|
295
|
+
// ensure runtime. After writes/edits, append file-scoped error diagnostics.
|
|
307
296
|
pi.on("tool_result", async (event) => {
|
|
308
|
-
const
|
|
297
|
+
const generation = host.getGeneration();
|
|
309
298
|
try {
|
|
310
299
|
if (isReadToolResult(event) && !event.isError) {
|
|
311
|
-
const
|
|
312
|
-
if (
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
300
|
+
const services = host.getServicesIfReady();
|
|
301
|
+
if (services) {
|
|
302
|
+
const path = event.input?.path;
|
|
303
|
+
if (path)
|
|
304
|
+
await services.fileSync.handleFileRead(path);
|
|
305
|
+
if (host.getGeneration() !== generation)
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
319
308
|
}
|
|
320
|
-
if (isEditToolResult(event) && !event.isError) {
|
|
309
|
+
if ((isWriteToolResult(event) || isEditToolResult(event)) && !event.isError) {
|
|
321
310
|
const path = event.input?.path;
|
|
322
|
-
if (path)
|
|
323
|
-
await
|
|
311
|
+
if (path) {
|
|
312
|
+
const services = await ensureRuntime();
|
|
313
|
+
if (host.getGeneration() !== generation)
|
|
314
|
+
return;
|
|
315
|
+
await services.fileSync.handleFileWrite(path);
|
|
316
|
+
}
|
|
324
317
|
}
|
|
325
318
|
}
|
|
326
319
|
catch {
|
|
327
320
|
// File sync errors are non-fatal
|
|
328
321
|
}
|
|
322
|
+
if (host.getGeneration() !== generation)
|
|
323
|
+
return;
|
|
329
324
|
// Auto-append diagnostics for the changed file (write/edit only)
|
|
330
|
-
|
|
325
|
+
const services = host.getServicesIfReady();
|
|
326
|
+
if ((isWriteToolResult(event) || isEditToolResult(event)) && !event.isError && services) {
|
|
331
327
|
const path = event.input?.path;
|
|
332
328
|
if (!path)
|
|
333
329
|
return;
|
|
330
|
+
const manager = services.manager;
|
|
334
331
|
const languageId = manager.getLanguageId(path);
|
|
335
332
|
if (!languageId)
|
|
336
333
|
return;
|
|
@@ -345,6 +342,8 @@ export default function lspExtension(pi) {
|
|
|
345
342
|
return;
|
|
346
343
|
// Wait briefly for the LSP to publish updated diagnostics
|
|
347
344
|
await new Promise((r) => setTimeout(r, DIAGNOSTIC_SETTLE_DELAY_MS));
|
|
345
|
+
if (host.getGeneration() !== generation)
|
|
346
|
+
return;
|
|
348
347
|
const uri = manager.getFileUri(path);
|
|
349
348
|
const diagnostics = client.getDiagnostics(uri);
|
|
350
349
|
const errors = diagnostics.filter((d) => d.severity === DiagnosticSeverity.Error);
|
|
@@ -373,9 +372,10 @@ export default function lspExtension(pi) {
|
|
|
373
372
|
// Update status after tool execution ends
|
|
374
373
|
pi.on("tool_execution_end", async (_event, ctx) => {
|
|
375
374
|
latestCtx = ctx;
|
|
376
|
-
|
|
375
|
+
const services = host.getServicesIfReady();
|
|
376
|
+
if (!services)
|
|
377
377
|
return;
|
|
378
|
-
const statuses = manager.getStatus();
|
|
378
|
+
const statuses = services.manager.getStatus();
|
|
379
379
|
const running = statuses.filter((s) => s.running);
|
|
380
380
|
if (running.length === 0) {
|
|
381
381
|
ctx.ui.setStatus("lsp", ctx.ui.theme.fg("dim", "LSP: idle"));
|
|
@@ -394,11 +394,12 @@ export default function lspExtension(pi) {
|
|
|
394
394
|
pi.registerCommand("lsp", {
|
|
395
395
|
description: "Show LSP server status",
|
|
396
396
|
handler: async (_args, ctx) => {
|
|
397
|
-
|
|
398
|
-
|
|
397
|
+
const services = host.getServicesIfReady();
|
|
398
|
+
if (!services) {
|
|
399
|
+
ctx.ui.notify(host.isInitializing() ? "LSP runtime is starting" : "LSP runtime is idle (not started)", "info");
|
|
399
400
|
return;
|
|
400
401
|
}
|
|
401
|
-
const statuses = manager.getStatus();
|
|
402
|
+
const statuses = services.manager.getStatus();
|
|
402
403
|
if (statuses.length === 0) {
|
|
403
404
|
ctx.ui.notify("No LSP servers configured", "info");
|
|
404
405
|
return;
|
|
@@ -416,14 +417,22 @@ export default function lspExtension(pi) {
|
|
|
416
417
|
pi.registerCommand("lsp-restart", {
|
|
417
418
|
description: "Restart an LSP server: /lsp-restart <language> (e.g. java, typescript)",
|
|
418
419
|
handler: async (args, ctx) => {
|
|
419
|
-
|
|
420
|
-
|
|
420
|
+
const services = host.getServicesIfReady();
|
|
421
|
+
if (!services) {
|
|
422
|
+
if (args?.trim()) {
|
|
423
|
+
ctx.ui.notify(host.isInitializing()
|
|
424
|
+
? "LSP runtime is starting"
|
|
425
|
+
: "LSP runtime is idle. Run an LSP tool before restarting a server.", "info");
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
ctx.ui.notify("No LSP servers are running.\n\nUsage: /lsp-restart <language>", "info");
|
|
429
|
+
}
|
|
421
430
|
return;
|
|
422
431
|
}
|
|
423
432
|
const languageId = args?.trim().toLowerCase();
|
|
424
433
|
if (!languageId) {
|
|
425
434
|
// Show running servers and usage
|
|
426
|
-
const statuses = manager.getStatus().filter((s) => s.running);
|
|
435
|
+
const statuses = services.manager.getStatus().filter((s) => s.running);
|
|
427
436
|
if (statuses.length === 0) {
|
|
428
437
|
ctx.ui.notify("No LSP servers are running.\n\nUsage: /lsp-restart <language>", "info");
|
|
429
438
|
}
|
|
@@ -436,8 +445,8 @@ export default function lspExtension(pi) {
|
|
|
436
445
|
ctx.ui.setStatus("lsp", ctx.ui.theme.fg("warning", `LSP: restarting ${languageId}...`));
|
|
437
446
|
ctx.ui.notify(`Restarting ${languageId} server (kills daemon if shared)...`, "info");
|
|
438
447
|
try {
|
|
439
|
-
await manager.restartServer(languageId);
|
|
440
|
-
const lombokJar = languageId === "java" ? manager.getLombokJar() : null;
|
|
448
|
+
await services.manager.restartServer(languageId);
|
|
449
|
+
const lombokJar = languageId === "java" ? services.manager.getLombokJar() : null;
|
|
441
450
|
const lombokNote = lombokJar ? `\nLombok: ${lombokJar}` : "";
|
|
442
451
|
ctx.ui.notify(`${languageId} server restarted successfully.${lombokNote}`, "info");
|
|
443
452
|
ctx.ui.setStatus("lsp", ctx.ui.theme.fg("accent", `LSP: ${languageId} ready`));
|
|
@@ -463,7 +472,8 @@ export default function lspExtension(pi) {
|
|
|
463
472
|
}
|
|
464
473
|
const [languageId, command, ...serverArgs] = parts;
|
|
465
474
|
const config = { command, args: serverArgs };
|
|
466
|
-
|
|
475
|
+
const services = await ensureRuntime();
|
|
476
|
+
services.manager.setServerConfig(languageId, config);
|
|
467
477
|
ctx.ui.notify(`Configured LSP for ${languageId}: ${command} ${serverArgs.join(" ")}`, "info");
|
|
468
478
|
},
|
|
469
479
|
});
|
|
@@ -471,7 +481,8 @@ export default function lspExtension(pi) {
|
|
|
471
481
|
pi.registerCommand("lsp-lombok", {
|
|
472
482
|
description: "Set Lombok jar path for Java: /lsp-lombok <path-to-lombok.jar>",
|
|
473
483
|
handler: async (args, ctx) => {
|
|
474
|
-
const
|
|
484
|
+
const services = await ensureRuntime();
|
|
485
|
+
const mgr = services.manager;
|
|
475
486
|
if (!args?.trim()) {
|
|
476
487
|
const current = mgr.getLombokJar();
|
|
477
488
|
if (current) {
|
|
@@ -486,8 +497,6 @@ export default function lspExtension(pi) {
|
|
|
486
497
|
return;
|
|
487
498
|
}
|
|
488
499
|
const jarPath = args.trim();
|
|
489
|
-
const { existsSync } = await import("node:fs");
|
|
490
|
-
const { resolve } = await import("node:path");
|
|
491
500
|
const resolved = resolve(ctx.cwd, jarPath);
|
|
492
501
|
if (!existsSync(resolved)) {
|
|
493
502
|
ctx.ui.notify(`File not found: ${resolved}`, "error");
|
|
@@ -500,22 +509,14 @@ export default function lspExtension(pi) {
|
|
|
500
509
|
ctx.ui.notify(`Lombok jar set: ${resolved}`, "info");
|
|
501
510
|
},
|
|
502
511
|
});
|
|
503
|
-
// Clean shutdown
|
|
512
|
+
// Clean shutdown — never loads heavy modules if they were unused
|
|
504
513
|
pi.on("session_shutdown", async () => {
|
|
505
514
|
// Drop the captured ctx immediately — once shutdown fires, any late
|
|
506
515
|
// LSP manager callback that reaches setLspStatus/applyProvider would
|
|
507
516
|
// otherwise hit an invalidated ctx and throw an uncaught exception.
|
|
508
517
|
latestCtx = null;
|
|
509
|
-
|
|
510
|
-
await manager.shutdownAll();
|
|
511
|
-
manager = null;
|
|
512
|
-
fileSync = null;
|
|
513
|
-
}
|
|
514
|
-
if (treeSitter) {
|
|
515
|
-
treeSitter.shutdown();
|
|
516
|
-
treeSitter = null;
|
|
517
|
-
}
|
|
518
|
-
workspaceIndex = null;
|
|
518
|
+
await host.shutdown();
|
|
519
519
|
});
|
|
520
520
|
}
|
|
521
|
+
export { LspRuntimeHost } from "./runtime.js";
|
|
521
522
|
//# sourceMappingURL=index.js.map
|