pi-agent-ide 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +65 -17
- package/dist/{chunk-KOVPDKSJ.js → chunk-2K65BSXS.js} +1 -1
- package/dist/chunk-3G54ZL2L.js +1 -0
- package/dist/chunk-3ZGDMTMD.js +25 -0
- package/dist/{chunk-ZIWPKIBZ.js → chunk-4OYVLXWD.js} +1 -1
- package/dist/chunk-4W7GH3T7.js +10 -0
- package/dist/chunk-4XPUN4QN.js +2 -0
- package/dist/chunk-5KFVDYCI.js +1 -0
- package/dist/chunk-6EDOLYOV.js +1 -0
- package/dist/chunk-756K3LJY.js +1 -0
- package/dist/chunk-75SWXD2Z.js +9 -0
- package/dist/chunk-7HDK3NRQ.js +1 -0
- package/dist/chunk-7JV4VN73.js +1 -0
- package/dist/chunk-7NS3QUIE.js +9 -0
- package/dist/chunk-7TJ6DWW3.js +2 -0
- package/dist/chunk-ABFCAOU5.js +1 -0
- package/dist/chunk-BIG45IPN.js +2 -0
- package/dist/chunk-BQ67M4NC.js +3 -0
- package/dist/chunk-BXGMMZT3.js +1 -0
- package/dist/chunk-CPZJPGLG.js +1 -0
- package/dist/chunk-CSXHCSTH.js +9 -0
- package/dist/chunk-CTJV77FR.js +1 -0
- package/dist/chunk-DUUOCBS3.js +3 -0
- package/dist/chunk-E4HPRLRB.js +1 -0
- package/dist/chunk-EY65TFHJ.js +1 -0
- package/dist/chunk-GW6NZQTQ.js +1 -0
- package/dist/chunk-HCN5W76B.js +1 -0
- package/dist/chunk-ICDI27GZ.js +1 -0
- package/dist/{chunk-SNF7PDDX.js → chunk-IH5NW5JX.js} +1 -1
- package/dist/chunk-IMGIDBCC.js +1 -0
- package/dist/chunk-IUSLSROY.js +1 -0
- package/dist/chunk-KL776TGR.js +1 -0
- package/dist/chunk-L2B4DTVS.js +1 -0
- package/dist/chunk-LEKC4GQK.js +5 -0
- package/dist/chunk-MKEC3U2M.js +4 -0
- package/dist/chunk-MOJ5RR35.js +1 -0
- package/dist/{chunk-H445SHSJ.js → chunk-MZXX353D.js} +1 -1
- package/dist/{chunk-ZTYWHL2F.js → chunk-N7LMRL64.js} +1 -1
- package/dist/chunk-NULNW6GK.js +1 -0
- package/dist/chunk-O36UC74T.js +1 -0
- package/dist/chunk-OFILFO6D.js +1 -0
- package/dist/chunk-OJX3RJ5A.js +1 -0
- package/dist/chunk-OLI3JPHJ.js +28 -0
- package/dist/{chunk-S6QRG3TQ.js → chunk-OM4LYD3S.js} +1 -1
- package/dist/chunk-PNP2KNGP.js +5 -0
- package/dist/chunk-QP2QSQ4U.js +2 -0
- package/dist/chunk-R2U5WXYR.js +1 -0
- package/dist/chunk-R5XJSEOE.js +3 -0
- package/dist/{chunk-7UGNGK7Y.js → chunk-RAZP42IQ.js} +1 -1
- package/dist/chunk-S72FVLUX.js +1 -0
- package/dist/chunk-SBLKPTL3.js +1 -0
- package/dist/chunk-SBNR4WZF.js +1 -0
- package/dist/chunk-SSWUUBIR.js +1 -0
- package/dist/chunk-T4FTT3U4.js +1 -0
- package/dist/chunk-TOYN4W4F.js +1 -0
- package/dist/chunk-TWWND6NI.js +1 -0
- package/dist/chunk-UBH6X3D3.js +1 -0
- package/dist/{chunk-QFTBY67N.js → chunk-UEVGZUII.js} +3 -3
- package/dist/chunk-UUJJRXHG.js +29 -0
- package/dist/chunk-VDP5CQHM.js +3 -0
- package/dist/chunk-WE42GBGU.js +4 -0
- package/dist/chunk-XZDOVPRC.js +1 -0
- package/dist/chunk-YJ6T3PEP.js +1 -0
- package/dist/chunk-Z3PGADVA.js +3 -0
- package/dist/{chunk-QDLTO5PH.js → chunk-ZAWRSA7N.js} +1 -1
- package/dist/entry-0.js +1 -1
- package/dist/entry-1.js +1 -1
- package/dist/entry-10.js +1 -1
- package/dist/entry-11.js +1 -1
- package/dist/entry-13.js +1 -1
- package/dist/entry-14.js +1 -1
- package/dist/entry-15.js +1 -1
- package/dist/entry-17.js +1 -1
- package/dist/entry-2.js +1 -1
- package/dist/entry-20.js +1 -1
- package/dist/entry-21.js +1 -1
- package/dist/entry-22.js +1 -1
- package/dist/entry-23.js +1 -1
- package/dist/entry-24.js +1 -1
- package/dist/entry-25.js +1 -2
- package/dist/entry-26.js +2 -1
- package/dist/entry-27.js +1 -2
- package/dist/entry-28.js +4 -1
- package/dist/entry-29.js +1 -1
- package/dist/entry-30.js +1 -1
- package/dist/entry-31.js +1 -17
- package/dist/entry-32.js +18 -1
- package/dist/entry-33.js +1 -2
- package/dist/entry-34.js +1 -1
- package/dist/entry-35.js +1 -1
- package/dist/entry-36.js +1 -4
- package/dist/entry-37.js +1 -9
- package/dist/entry-38.js +1 -1
- package/dist/entry-39.js +1 -1
- package/dist/entry-4.js +1 -1
- package/dist/entry-40.js +1 -1
- package/dist/entry-41.js +1 -1
- package/dist/entry-42.js +1 -1
- package/dist/entry-43.js +1 -1
- package/dist/entry-44.js +1 -1
- package/dist/entry-45.js +1 -25
- package/dist/entry-46.js +25 -1
- package/dist/entry-47.js +1 -1
- package/dist/entry-48.js +1 -1
- package/dist/entry-49.js +1 -1
- package/dist/entry-50.js +1 -3
- package/dist/entry-51.js +3 -13
- package/dist/entry-52.js +13 -1
- package/dist/entry-53.js +1 -1
- package/dist/entry-54.js +1 -1
- package/dist/entry-55.js +1 -1
- package/dist/entry-56.js +1 -1
- package/dist/entry-57.js +1 -1
- package/dist/entry-58.js +1 -1
- package/dist/entry-59.js +1 -1
- package/dist/entry-60.js +1 -1
- package/dist/entry-61.js +1 -0
- package/dist/entry-62.js +0 -1
- package/dist/entry-63.js +1 -0
- package/dist/entry-64.js +0 -1
- package/dist/entry-65.js +1 -1
- package/dist/entry-66.js +1 -1
- package/dist/entry-67.js +1 -1
- package/dist/entry-68.js +1 -1
- package/dist/entry-69.js +1 -1
- package/dist/entry-70.js +1 -1
- package/dist/entry-71.js +1 -0
- package/dist/entry-72.js +0 -1
- package/dist/entry-73.js +1 -0
- package/dist/entry-74.js +0 -1
- package/dist/entry-75.js +1 -1
- package/dist/entry-76.js +1 -1
- package/dist/entry-77.js +1 -75
- package/dist/entry-78.js +76 -14
- package/dist/entry-79.js +21 -2
- package/dist/entry-8.js +1 -1
- package/dist/entry-80.js +2 -1
- package/dist/entry-81.js +1 -1
- package/dist/entry-82.js +1 -5
- package/dist/entry-83.js +1 -3
- package/dist/entry-84.js +3 -1
- package/dist/entry-85.js +1 -1
- package/dist/entry-86.js +1 -1
- package/dist/entry-87.js +1 -0
- package/dist/pi-agent-ide.js +21 -21
- package/docs/agent-guides/debugger.md +2 -0
- package/docs/agent-guides/editing.md +10 -3
- package/docs/agent-guides/search-code.md +4 -1
- package/docs/agent-guides/ssh.md +58 -0
- package/docs/agent-guides/vision.md +6 -0
- package/docs/configuration.md +55 -0
- package/docs/development.md +4 -0
- package/docs/directory-operations.md +45 -0
- package/docs/releases.md +8 -0
- package/docs/research/codemode-write-context.md +56 -0
- package/docs/tools.md +21 -14
- package/docs/user-hooks.md +29 -1
- package/node_modules/pi-agent-doctor/package.json +6 -2
- package/node_modules/pi-agent-doctor/src/evidence.ts +49 -4
- package/node_modules/pi-agent-doctor/src/executable.ts +46 -16
- package/node_modules/pi-agent-doctor/src/fixtures/executable-probe.ts +78 -0
- package/node_modules/pi-agent-doctor/src/fixtures/probe-executable-wait.mjs +10 -0
- package/node_modules/pi-agent-doctor/src/plugin-protocol.ts +6 -0
- package/node_modules/pi-agent-doctor/src/project-probes.ts +73 -0
- package/node_modules/pi-agent-doctor/src/workspace.ts +106 -0
- package/node_modules/pi-agent-documentation/package.json +2 -2
- package/node_modules/pi-agent-documentation/runtime/entry-25.js +1 -0
- package/node_modules/pi-agent-filesystem/package.json +8 -8
- package/node_modules/pi-agent-filesystem/src/resolver.ts +23 -7
- package/node_modules/pi-agent-filesystem-image/package.json +4 -4
- package/node_modules/pi-agent-filesystem-jq/index.ts +33 -6
- package/node_modules/pi-agent-filesystem-jq/package.json +6 -6
- package/node_modules/pi-agent-filesystem-jq/src/jq.ts +67 -0
- package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
- package/node_modules/pi-agent-filesystem-text/package.json +4 -4
- package/node_modules/pi-agent-filesystem-text/runtime/entry-30.js +2 -0
- package/node_modules/pi-agent-ide-ast/package.json +15 -15
- package/node_modules/pi-agent-ide-ast/runtime/entry-31.js +0 -1
- package/node_modules/pi-agent-ide-ast/runtime/entry-32.js +2 -0
- package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +2 -1
- package/node_modules/pi-agent-ide-ast/src/ast/outline.ts +10 -3
- package/node_modules/pi-agent-ide-ast/src/ast/read-text.ts +4 -1
- package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +3 -3
- package/node_modules/pi-agent-ide-ast/src/doctor-plugin.ts +13 -10
- package/node_modules/pi-agent-ide-ast/src/extension.ts +20 -2
- package/node_modules/pi-agent-ide-ast/src/outline-resolver.ts +32 -4
- package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +9 -4
- package/node_modules/pi-agent-ide-ast/src/scope-handler.ts +1 -1
- package/node_modules/pi-agent-ide-ast/src/search-presentation.ts +4 -3
- package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +100 -42
- package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +3 -2
- package/node_modules/pi-agent-ide-ast/src/tool-select.ts +2 -1
- package/node_modules/pi-agent-ide-changes/index.ts +10 -2
- package/node_modules/pi-agent-ide-changes/package.json +11 -10
- package/node_modules/pi-agent-ide-changes/runtime/entry-33.js +0 -1
- package/node_modules/pi-agent-ide-changes/src/change-anchor.ts +7 -2
- package/node_modules/pi-agent-ide-changes/src/changes/change-service.ts +18 -1
- package/node_modules/pi-agent-ide-changes/src/changes/change-types.ts +3 -0
- package/node_modules/pi-agent-ide-changes/src/changes/git-changes-backend.ts +59 -7
- package/node_modules/pi-agent-ide-changes/src/changes/git-paths.ts +49 -0
- package/node_modules/pi-agent-ide-changes/src/current-change-presenter.ts +10 -2
- package/node_modules/pi-agent-ide-changes/src/doctor-plugin.ts +13 -14
- package/node_modules/pi-agent-ide-changes/src/last-text-transaction-store.ts +2 -1
- package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +63 -11
- package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +6 -1
- package/node_modules/pi-agent-ide-formatter/index.ts +14 -2
- package/node_modules/pi-agent-ide-formatter/package.json +4 -4
- package/node_modules/pi-agent-ide-formatter/src/doctor-plugin.ts +47 -35
- package/node_modules/pi-agent-ide-formatter/src/formatter.ts +41 -11
- package/node_modules/pi-agent-ide-formatter/src/registry.ts +9 -28
- package/node_modules/pi-agent-ide-languages/package.json +3 -3
- package/node_modules/pi-agent-ide-lint/index.ts +35 -4
- package/node_modules/pi-agent-ide-lint/package.json +8 -8
- package/node_modules/pi-agent-ide-lint/src/command-linter.ts +14 -10
- package/node_modules/pi-agent-ide-lint/src/doctor-plugin.ts +47 -39
- package/node_modules/pi-agent-ide-lint/src/registry.ts +9 -25
- package/node_modules/pi-agent-ide-lsp/index.ts +108 -26
- package/node_modules/pi-agent-ide-lsp/package.json +10 -10
- package/node_modules/pi-agent-ide-lsp/runtime/entry-38.js +2 -0
- package/node_modules/pi-agent-ide-lsp/src/code-view-resolvers.ts +6 -2
- package/node_modules/pi-agent-ide-lsp/src/declaration-targets.ts +7 -2
- package/node_modules/pi-agent-ide-lsp/src/diagnostic-source.ts +5 -3
- package/node_modules/pi-agent-ide-lsp/src/doctor-plugin.ts +27 -11
- package/node_modules/pi-agent-ide-lsp/src/lsp/abort.ts +62 -0
- package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +245 -103
- package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +26 -45
- package/node_modules/pi-agent-ide-lsp/src/lsp/diagnostic-adapters.ts +1 -1
- package/node_modules/pi-agent-ide-lsp/src/lsp/document-uri.ts +40 -0
- package/node_modules/pi-agent-ide-lsp/src/lsp/file-watchers.ts +8 -1
- package/node_modules/pi-agent-ide-lsp/src/lsp/lsp-compiler.ts +24 -17
- package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +255 -56
- package/node_modules/pi-agent-ide-lsp/src/lsp/navigation.ts +51 -11
- package/node_modules/pi-agent-ide-lsp/src/lsp/owner-transport.ts +67 -0
- package/node_modules/pi-agent-ide-lsp/src/lsp/registry.ts +149 -18
- package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +79 -31
- package/node_modules/pi-agent-ide-lsp/src/lsp/symbols.ts +15 -12
- package/node_modules/pi-agent-ide-lsp/src/lsp/workspace-owner.ts +16 -0
- package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +67 -46
- package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +50 -19
- package/node_modules/pi-agent-image/package.json +3 -3
- package/node_modules/pi-agent-invariant/package.json +2 -2
- package/node_modules/pi-agent-pdf/package.json +3 -3
- package/node_modules/pi-agent-read/package.json +12 -12
- package/node_modules/pi-agent-read/runtime/entry-45.js +0 -1
- package/node_modules/pi-agent-read/runtime/entry-46.js +2 -0
- package/node_modules/pi-agent-read/src/api/tools/read.ts +4 -2
- package/node_modules/pi-agent-read/src/core/extension.ts +4 -1
- package/node_modules/pi-agent-read/src/core/tools/read/raw-read.ts +143 -69
- package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +25 -1
- package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +67 -44
- package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +8 -3
- package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +20 -5
- package/node_modules/pi-agent-resource/package.json +2 -2
- package/node_modules/pi-agent-resource/src/content-conversion/content-host.ts +75 -16
- package/node_modules/pi-agent-resource/src/index.ts +3 -0
- package/node_modules/pi-agent-resource/src/resource-error.ts +17 -0
- package/node_modules/pi-agent-resource/src/resource.ts +23 -0
- package/node_modules/pi-agent-resource/src/result-targets.ts +16 -2
- package/node_modules/pi-agent-resource/src/validation.ts +2 -1
- package/node_modules/pi-agent-search/package.json +9 -9
- package/node_modules/pi-agent-search/runtime/entry-50.js +0 -1
- package/node_modules/pi-agent-search/src/api/plugin-protocol.ts +1 -1
- package/node_modules/pi-agent-search/src/api/search-parameters.ts +6 -2
- package/node_modules/pi-agent-search/src/api/search.ts +44 -2
- package/node_modules/pi-agent-search/src/core/extension.ts +2 -3
- package/node_modules/pi-agent-search/src/core/search-core.ts +78 -8
- package/node_modules/pi-agent-search-text/index.ts +35 -1
- package/node_modules/pi-agent-search-text/package.json +14 -12
- package/node_modules/pi-agent-search-text/runtime/entry-52.js +1 -0
- package/node_modules/pi-agent-search-text/src/doctor-plugin.ts +10 -5
- package/node_modules/pi-agent-search-text/src/file-search.ts +26 -3
- package/node_modules/pi-agent-search-text/src/fuzzy-search.ts +54 -3
- package/node_modules/pi-agent-search-text/src/resolvers.ts +22 -5
- package/node_modules/pi-agent-search-text/src/scoped-search.ts +4 -5
- package/node_modules/pi-agent-search-text/src/search-backend.ts +110 -12
- package/node_modules/pi-agent-search-text/src/search-recipe.ts +5 -1
- package/node_modules/pi-agent-search-text/src/search-result.ts +1 -0
- package/node_modules/pi-agent-search-text/src/search-session.ts +100 -24
- package/node_modules/pi-agent-text/package.json +3 -3
- package/node_modules/pi-agent-text/runtime/entry-56.js +1 -0
- package/node_modules/pi-agent-text/src/text-document.ts +2 -0
- package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
- package/node_modules/pi-agent-text-anchor-constant/runtime/entry-57.js +2 -0
- package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
- package/node_modules/pi-agent-text-anchor-exact/runtime/entry-58.js +0 -1
- package/node_modules/pi-agent-text-anchor-exact/runtime/entry-59.js +2 -0
- package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
- package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-60.js +0 -1
- package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-61.js +2 -0
- package/node_modules/pi-agent-text-anchor-line-hash/src/read-handler.ts +3 -1
- package/node_modules/pi-agent-text-editor/package.json +26 -26
- package/node_modules/pi-agent-text-editor/runtime/entry-77.js +0 -1
- package/node_modules/pi-agent-text-editor/src/api/delete-guard.ts +51 -0
- package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +3 -0
- package/node_modules/pi-agent-text-editor/src/api/file-operations.ts +55 -0
- package/node_modules/pi-agent-text-editor/src/api/file-transfers.ts +41 -0
- package/node_modules/pi-agent-text-editor/src/api/mutation-guard.ts +3 -0
- package/node_modules/pi-agent-text-editor/src/api/native-files.ts +127 -0
- package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +23 -1
- package/node_modules/pi-agent-text-editor/src/api/post-edit.ts +1 -0
- package/node_modules/pi-agent-text-editor/src/core/delete-policy.ts +298 -0
- package/node_modules/pi-agent-text-editor/src/core/extension.ts +14 -2
- package/node_modules/pi-agent-text-editor/src/core/file-operation-guards.ts +81 -0
- package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +51 -5
- package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +143 -57
- package/node_modules/pi-agent-text-editor/src/core/file-result-targets.ts +31 -2
- package/node_modules/pi-agent-text-editor/src/core/file-transfers.ts +206 -0
- package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +1 -6
- package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +9 -1
- package/node_modules/pi-agent-text-editor/src/core/mutation-result-targets.ts +91 -14
- package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +125 -17
- package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +39 -9
- package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +7 -1
- package/node_modules/pi-agent-text-editor/src/core/temporary-directories.ts +116 -0
- package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +7 -3
- package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +350 -25
- package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +132 -31
- package/node_modules/pi-agent-text-editor/src/core/write-agent-result.ts +69 -0
- package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +2 -2
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -4
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +2 -2
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +6 -4
- package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
- package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +128 -23
- package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
- package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +2 -0
- package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
- package/node_modules/pi-agent-tool-ui/package.json +2 -2
- package/node_modules/pi-agent-tool-ui/runtime/entry-82.js +1 -0
- package/node_modules/pi-agent-web/index.ts +28 -4
- package/node_modules/pi-agent-web/package.json +8 -8
- package/node_modules/pi-agent-web/src/doctor-plugin.ts +21 -6
- package/node_modules/pi-agent-web/src/resolver.ts +12 -2
- package/node_modules/pi-agent-web/src/search.ts +2 -1
- package/node_modules/pi-agent-web-html/package.json +3 -3
- package/node_modules/pi-agent-web-image/package.json +4 -4
- package/node_modules/pi-agent-web-pdf/package.json +4 -4
- package/node_modules/pi-agent-web-text/package.json +4 -4
- package/node_modules/pi-agent-web-text/runtime/entry-87.js +2 -0
- package/package.json +36 -35
- package/src/api/doctor-runtime.ts +80 -0
- package/src/api/doctor.ts +6 -0
- package/src/api/hooks.ts +27 -0
- package/src/api/plugin-protocol.ts +11 -1
- package/src/api/tool-config.ts +143 -24
- package/src/backend/config.ts +85 -0
- package/src/backend/configured-process.ts +59 -0
- package/src/backend/dap-java-transport.ts +112 -0
- package/src/backend/dap-java-worker.py +218 -0
- package/src/backend/dap-node-transport.ts +112 -0
- package/src/backend/dap-powershell-worker.py +44 -0
- package/src/backend/dap-r-worker.py +210 -0
- package/src/backend/dap-tcp-transport.ts +42 -0
- package/src/backend/dap-tcp-worker.py +125 -0
- package/src/backend/dap-transport.ts +69 -0
- package/src/backend/dap-unix-worker.py +63 -0
- package/src/backend/debugger-registration.ts +62 -0
- package/src/backend/debugger-workspace-owner.ts +413 -0
- package/src/backend/doctor-inventory-worker.py +54 -0
- package/src/backend/doctor-probe-worker.py +140 -0
- package/src/backend/doctor-registration.ts +18 -0
- package/src/backend/doctor-workspace.ts +381 -0
- package/src/backend/file-operation-resolver.ts +58 -0
- package/src/backend/file-revision.ts +13 -0
- package/src/backend/file-transfer.ts +302 -0
- package/src/backend/file-watch-worker.py +119 -0
- package/src/backend/formatter-registration.ts +114 -0
- package/src/backend/git-registration.ts +60 -0
- package/src/backend/identity.ts +47 -0
- package/src/backend/index.ts +12 -0
- package/src/backend/lint-registration.ts +102 -0
- package/src/backend/lsp-file-watchers.ts +220 -0
- package/src/backend/lsp-registration.ts +83 -0
- package/src/backend/lsp-transport.ts +87 -0
- package/src/backend/lsp-workspace-owner.ts +50 -0
- package/src/backend/object-transfer.ts +299 -0
- package/src/backend/owned-command.ts +105 -0
- package/src/backend/owned-process-stop.ts +36 -0
- package/src/backend/owned-read-command.ts +20 -0
- package/src/backend/process-environment.ts +77 -0
- package/src/backend/process-metadata-worker.py +98 -0
- package/src/backend/process-metadata.ts +99 -0
- package/src/backend/recipe-evidence-worker.py +26 -0
- package/src/backend/recipe-evidence.ts +77 -0
- package/src/backend/registration.ts +124 -0
- package/src/backend/registry.ts +29 -0
- package/src/backend/resource-resolver.ts +147 -0
- package/src/backend/search-environment.ts +100 -0
- package/src/backend/ssh-channel-worker.py +306 -0
- package/src/backend/ssh-channel.ts +376 -0
- package/src/backend/ssh-transfer-worker.py +99 -0
- package/src/backend/ssh-transport.ts +54 -0
- package/src/backend/ssh-worker.py +730 -0
- package/src/backend/ssh.ts +610 -0
- package/src/backend/tool-config-access.ts +63 -0
- package/src/backend/tool-project.ts +71 -0
- package/src/backend/vision-capture-worker.py +319 -0
- package/src/backend/vision-capture.ts +165 -0
- package/src/backend/vision-registration.ts +104 -0
- package/src/backend/web-browser-worker.mjs +182 -0
- package/src/backend/web-browser.ts +128 -0
- package/src/backend/web-http-worker.py +62 -0
- package/src/backend/web-http.ts +79 -0
- package/src/backend/web-owner.ts +68 -0
- package/src/backend/web-registration.ts +14 -0
- package/src/code-view/diagnostic-view.ts +2 -2
- package/src/code-view/reference.ts +9 -0
- package/src/composite/builtin-extensions.ts +9 -14
- package/src/composite/module-labels.ts +1 -0
- package/src/composite/nested-tool-rendering.ts +130 -72
- package/src/core/diagnostic-store.ts +32 -10
- package/src/core/ide-core.ts +22 -2
- package/src/doctor/arguments.ts +19 -0
- package/src/doctor/config-writer.ts +72 -29
- package/src/doctor/discovery.ts +53 -15
- package/src/doctor/extension.ts +27 -10
- package/src/doctor/run.ts +42 -7
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +8 -8
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +33 -6
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +6 -6
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts +67 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-30.js +2 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-26.js +2 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/src/resolver.ts +23 -7
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +28 -4
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-87.js +2 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-83.js +2 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/doctor-plugin.ts +21 -6
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +12 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/search.ts +2 -1
- package/src/extensions/pi-agent-read/package.json +12 -12
- package/src/extensions/pi-agent-read/runtime/entry-45.js +0 -1
- package/src/extensions/pi-agent-read/runtime/entry-46.js +2 -0
- package/src/extensions/pi-agent-read/src/api/tools/read.ts +4 -2
- package/src/extensions/pi-agent-read/src/core/extension.ts +4 -1
- package/src/extensions/pi-agent-read/src/core/tools/read/raw-read.ts +143 -69
- package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +25 -1
- package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +67 -44
- package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +8 -3
- package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +20 -5
- package/src/extensions/pi-agent-search/package.json +9 -9
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +35 -1
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +14 -12
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-52.js +1 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-55.js +1 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/doctor-plugin.ts +10 -5
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +26 -3
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/fuzzy-search.ts +54 -3
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +22 -5
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +4 -5
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +110 -12
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +5 -1
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +1 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +100 -24
- package/src/extensions/pi-agent-search/runtime/entry-50.js +0 -1
- package/src/extensions/pi-agent-search/runtime/entry-51.js +2 -0
- package/src/extensions/pi-agent-search/src/api/plugin-protocol.ts +1 -1
- package/src/extensions/pi-agent-search/src/api/search-parameters.ts +6 -2
- package/src/extensions/pi-agent-search/src/api/search.ts +44 -2
- package/src/extensions/pi-agent-search/src/core/extension.ts +2 -3
- package/src/extensions/pi-agent-search/src/core/search-core.ts +78 -8
- package/src/extensions/pi-agent-text-editor/package.json +26 -26
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-57.js +2 -0
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-58.js +0 -1
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-59.js +2 -0
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-60.js +0 -1
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-61.js +2 -0
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/src/read-handler.ts +3 -1
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +128 -23
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +2 -0
- package/src/extensions/pi-agent-text-editor/runtime/entry-77.js +0 -1
- package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +2 -0
- package/src/extensions/pi-agent-text-editor/src/api/delete-guard.ts +51 -0
- package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +3 -0
- package/src/extensions/pi-agent-text-editor/src/api/file-operations.ts +55 -0
- package/src/extensions/pi-agent-text-editor/src/api/file-transfers.ts +41 -0
- package/src/extensions/pi-agent-text-editor/src/api/mutation-guard.ts +3 -0
- package/src/extensions/pi-agent-text-editor/src/api/native-files.ts +127 -0
- package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +23 -1
- package/src/extensions/pi-agent-text-editor/src/api/post-edit.ts +1 -0
- package/src/extensions/pi-agent-text-editor/src/core/delete-policy.ts +298 -0
- package/src/extensions/pi-agent-text-editor/src/core/extension.ts +14 -2
- package/src/extensions/pi-agent-text-editor/src/core/file-operation-guards.ts +81 -0
- package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +51 -5
- package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +143 -57
- package/src/extensions/pi-agent-text-editor/src/core/file-result-targets.ts +31 -2
- package/src/extensions/pi-agent-text-editor/src/core/file-transfers.ts +206 -0
- package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +1 -6
- package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +9 -1
- package/src/extensions/pi-agent-text-editor/src/core/mutation-result-targets.ts +91 -14
- package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +125 -17
- package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +39 -9
- package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +7 -1
- package/src/extensions/pi-agent-text-editor/src/core/temporary-directories.ts +116 -0
- package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +7 -3
- package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +350 -25
- package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +132 -31
- package/src/extensions/pi-agent-text-editor/src/core/write-agent-result.ts +69 -0
- package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +2 -2
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +6 -4
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +2 -2
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +6 -4
- package/src/plugins/pi-agent-ide-ast/package.json +15 -15
- package/src/plugins/pi-agent-ide-ast/runtime/entry-31.js +0 -1
- package/src/plugins/pi-agent-ide-ast/runtime/entry-32.js +2 -0
- package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +2 -1
- package/src/plugins/pi-agent-ide-ast/src/ast/outline.ts +10 -3
- package/src/plugins/pi-agent-ide-ast/src/ast/read-text.ts +4 -1
- package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +3 -3
- package/src/plugins/pi-agent-ide-ast/src/doctor-plugin.ts +13 -10
- package/src/plugins/pi-agent-ide-ast/src/extension.ts +20 -2
- package/src/plugins/pi-agent-ide-ast/src/outline-resolver.ts +32 -4
- package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +9 -4
- package/src/plugins/pi-agent-ide-ast/src/scope-handler.ts +1 -1
- package/src/plugins/pi-agent-ide-ast/src/search-presentation.ts +4 -3
- package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +100 -42
- package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +3 -2
- package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +2 -1
- package/src/plugins/pi-agent-ide-changes/index.ts +10 -2
- package/src/plugins/pi-agent-ide-changes/package.json +11 -10
- package/src/plugins/pi-agent-ide-changes/runtime/entry-33.js +0 -1
- package/src/plugins/pi-agent-ide-changes/src/change-anchor.ts +7 -2
- package/src/plugins/pi-agent-ide-changes/src/changes/change-service.ts +18 -1
- package/src/plugins/pi-agent-ide-changes/src/changes/change-types.ts +3 -0
- package/src/plugins/pi-agent-ide-changes/src/changes/git-changes-backend.ts +59 -7
- package/src/plugins/pi-agent-ide-changes/src/changes/git-paths.ts +49 -0
- package/src/plugins/pi-agent-ide-changes/src/current-change-presenter.ts +10 -2
- package/src/plugins/pi-agent-ide-changes/src/doctor-plugin.ts +13 -14
- package/src/plugins/pi-agent-ide-changes/src/last-text-transaction-store.ts +2 -1
- package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +63 -11
- package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +6 -1
- package/src/plugins/pi-agent-ide-debugger/index.ts +65 -26
- package/src/plugins/pi-agent-ide-debugger/src/adapter-executables.ts +3 -1
- package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +33 -0
- package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +150 -171
- package/src/plugins/pi-agent-ide-debugger/src/process-provider.ts +2 -0
- package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +152 -58
- package/src/plugins/pi-agent-ide-debugger/src/workspace-owner.ts +28 -0
- package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +4 -1
- package/src/plugins/pi-agent-ide-formatter/index.ts +14 -2
- package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
- package/src/plugins/pi-agent-ide-formatter/src/doctor-plugin.ts +47 -35
- package/src/plugins/pi-agent-ide-formatter/src/formatter.ts +41 -11
- package/src/plugins/pi-agent-ide-formatter/src/registry.ts +9 -28
- package/src/plugins/pi-agent-ide-languages/package.json +3 -3
- package/src/plugins/pi-agent-ide-lint/index.ts +35 -4
- package/src/plugins/pi-agent-ide-lint/package.json +8 -8
- package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +14 -10
- package/src/plugins/pi-agent-ide-lint/src/doctor-plugin.ts +47 -39
- package/src/plugins/pi-agent-ide-lint/src/registry.ts +9 -25
- package/src/plugins/pi-agent-ide-lsp/index.ts +108 -26
- package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
- package/src/plugins/pi-agent-ide-lsp/runtime/entry-38.js +2 -0
- package/src/plugins/pi-agent-ide-lsp/src/code-view-resolvers.ts +6 -2
- package/src/plugins/pi-agent-ide-lsp/src/declaration-targets.ts +7 -2
- package/src/plugins/pi-agent-ide-lsp/src/diagnostic-source.ts +5 -3
- package/src/plugins/pi-agent-ide-lsp/src/doctor-plugin.ts +27 -11
- package/src/plugins/pi-agent-ide-lsp/src/lsp/abort.ts +62 -0
- package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +245 -103
- package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +26 -45
- package/src/plugins/pi-agent-ide-lsp/src/lsp/diagnostic-adapters.ts +1 -1
- package/src/plugins/pi-agent-ide-lsp/src/lsp/document-uri.ts +40 -0
- package/src/plugins/pi-agent-ide-lsp/src/lsp/file-watchers.ts +8 -1
- package/src/plugins/pi-agent-ide-lsp/src/lsp/lsp-compiler.ts +24 -17
- package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +255 -56
- package/src/plugins/pi-agent-ide-lsp/src/lsp/navigation.ts +51 -11
- package/src/plugins/pi-agent-ide-lsp/src/lsp/owner-transport.ts +67 -0
- package/src/plugins/pi-agent-ide-lsp/src/lsp/registry.ts +149 -18
- package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +79 -31
- package/src/plugins/pi-agent-ide-lsp/src/lsp/symbols.ts +15 -12
- package/src/plugins/pi-agent-ide-lsp/src/lsp/workspace-owner.ts +16 -0
- package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +67 -46
- package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +50 -19
- package/src/plugins/pi-agent-ide-processes/src/registry.ts +8 -1
- package/src/plugins/pi-agent-ide-terminal/index.ts +7 -0
- package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +5 -1
- package/src/plugins/pi-agent-ide-terminal/src/resources.ts +5 -2
- package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +161 -42
- package/src/plugins/pi-agent-ide-terminal/src/shell-profile.ts +7 -0
- package/src/plugins/pi-agent-ide-terminal/src/shell-result.ts +11 -0
- package/src/plugins/pi-agent-ide-terminal/src/tools.ts +33 -8
- package/src/plugins/pi-agent-ide-terminal/src/types.ts +5 -0
- package/src/plugins/pi-agent-ide-vision/index.ts +170 -9
- package/src/plugins/pi-agent-ide-vision/src/doctor-plugin.ts +47 -0
- package/src/plugins/pi-agent-ide-vision/src/vision.ts +42 -1
- package/src/post-edit/gate.ts +4 -1
- package/src/toolchain/types.ts +2 -0
- package/dist/chunk-3YK4XMWB.js +0 -0
- package/dist/chunk-5JELU6RV.js +0 -7
- package/dist/chunk-6U5OU77O.js +0 -3
- package/dist/chunk-7LD2OQH3.js +0 -14
- package/dist/chunk-EURHXLN3.js +0 -2
- package/dist/chunk-F6IWZKOG.js +0 -25
- package/dist/chunk-IG56UGSO.js +0 -2
- package/dist/chunk-KVHDMIZS.js +0 -3
- package/dist/chunk-M5IVSCR2.js +0 -1
- package/dist/chunk-M5MJP7Z2.js +0 -1
- package/dist/chunk-MGCHOGQD.js +0 -1
- package/dist/chunk-N34ATN52.js +0 -1
- package/dist/chunk-OB46OPMZ.js +0 -1
- package/dist/chunk-PKSQT6TC.js +0 -1
- package/dist/chunk-Q6CZ6GBR.js +0 -3
- package/dist/chunk-QIK2E64R.js +0 -1
- package/dist/chunk-SBP3ABH4.js +0 -5
- package/dist/chunk-SJ4UZ4GU.js +0 -1
- package/dist/chunk-STBJO3Z3.js +0 -2
- package/dist/chunk-T6LX2RX5.js +0 -1
- package/dist/chunk-TQGE7RH6.js +0 -28
- package/dist/chunk-WZI4YC2O.js +0 -1
- package/dist/chunk-XDG7EQRN.js +0 -28
- package/dist/chunk-YWQS33DF.js +0 -1
- package/node_modules/pi-agent-filesystem/runtime/entry-25.js +0 -2
- package/node_modules/pi-agent-ide-ast/runtime/entry-30.js +0 -1
- package/node_modules/pi-agent-ide-changes/runtime/entry-32.js +0 -1
- package/node_modules/pi-agent-image/runtime/entry-38.js +0 -1
- package/node_modules/pi-agent-resource/runtime/entry-46.js +0 -1
- package/node_modules/pi-agent-text-anchor-constant/runtime/entry-56.js +0 -2
- package/node_modules/pi-agent-text-anchor-exact/runtime/entry-57.js +0 -1
- package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-59.js +0 -1
- package/node_modules/pi-agent-text-editor/runtime/entry-61.js +0 -1
- package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +0 -1
- package/node_modules/pi-agent-web/runtime/entry-82.js +0 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-26.js +0 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-25.js +0 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-83.js +0 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-82.js +0 -2
- package/src/extensions/pi-agent-read/runtime/entry-41.js +0 -1
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-51.js +0 -2
- package/src/extensions/pi-agent-search/runtime/entry-47.js +0 -1
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-56.js +0 -2
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-57.js +0 -1
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-59.js +0 -1
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +0 -2
- package/src/extensions/pi-agent-text-editor/runtime/entry-61.js +0 -1
- package/src/plugins/pi-agent-ide-ast/runtime/entry-30.js +0 -1
- package/src/plugins/pi-agent-ide-changes/runtime/entry-32.js +0 -1
- /package/node_modules/{pi-agent-documentation → pi-agent-doctor}/runtime/entry-24.js +0 -0
- /package/node_modules/{pi-agent-filesystem-image → pi-agent-filesystem}/runtime/entry-26.js +0 -0
- /package/node_modules/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-27.js +0 -0
- /package/node_modules/{pi-agent-filesystem-pdf → pi-agent-filesystem-jq}/runtime/entry-28.js +0 -0
- /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-29.js +0 -0
- /package/node_modules/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-34.js +0 -0
- /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-35.js +0 -0
- /package/node_modules/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-36.js +0 -0
- /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-37.js +0 -0
- /package/node_modules/{pi-agent-invariant → pi-agent-image}/runtime/entry-39.js +0 -0
- /package/node_modules/{pi-agent-pdf → pi-agent-invariant}/runtime/entry-40.js +0 -0
- /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-41.js +0 -0
- /package/node_modules/{pi-agent-search → pi-agent-resource}/runtime/entry-47.js +0 -0
- /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-51.js +0 -0
- /package/node_modules/{pi-agent-text → pi-agent-search-text}/runtime/entry-55.js +0 -0
- /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor}/runtime/entry-78.js +0 -0
- /package/node_modules/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-79.js +0 -0
- /package/node_modules/{pi-agent-tool-ui → pi-agent-tool-call-interception}/runtime/entry-81.js +0 -0
- /package/node_modules/{pi-agent-web-html → pi-agent-web}/runtime/entry-83.js +0 -0
- /package/node_modules/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-84.js +0 -0
- /package/node_modules/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-85.js +0 -0
- /package/node_modules/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-86.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-jq → pi-agent-filesystem-image}/runtime/entry-27.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-pdf → pi-agent-filesystem-jq}/runtime/entry-28.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/{pi-agent-filesystem-text → pi-agent-filesystem-pdf}/runtime/entry-29.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-html}/runtime/entry-84.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-image}/runtime/entry-85.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-text → pi-agent-web-pdf}/runtime/entry-86.js +0 -0
- /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-stale-anchor → pi-agent-text-editor-renderer}/runtime/entry-79.js +0 -0
- /package/src/plugins/{pi-agent-ide-formatter → pi-agent-ide-changes}/runtime/entry-34.js +0 -0
- /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-formatter}/runtime/entry-35.js +0 -0
- /package/src/plugins/{pi-agent-ide-lint → pi-agent-ide-languages}/runtime/entry-36.js +0 -0
- /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-lint}/runtime/entry-37.js +0 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as ze,c as He}from"./chunk-TOYN4W4F.js";import{a as Ge}from"./chunk-YJ6T3PEP.js";import{b as Fe,c as Ve}from"./chunk-S72FVLUX.js";import{a as et}from"./chunk-2K65BSXS.js";import{c as Qe,d as Ye,f as Ze}from"./chunk-ICDI27GZ.js";import{d as Xe}from"./chunk-IICJXZBU.js";import{a as Ke}from"./chunk-BU7IZLKB.js";import{a as Be,b as Je}from"./chunk-S5PL5DFQ.js";import{a as nt}from"./chunk-N7LMRL64.js";import{a as tt,b as rt}from"./chunk-RAZP42IQ.js";import{a as ot,b as st}from"./chunk-BIG45IPN.js";import{e as it}from"./chunk-SSWUUBIR.js";import{J as F}from"./chunk-R5XJSEOE.js";import{f as Ie,g as De,h as Ae}from"./chunk-DUUOCBS3.js";import{a as q,b as E,c as J,d as M}from"./chunk-T4FTT3U4.js";import{m as Ee}from"./chunk-ZPT5D4VP.js";import{a as Oe}from"./chunk-ZAWRSA7N.js";import{a as je,b as Te}from"./chunk-OFILFO6D.js";import{b as $e,c as We,g as Ue,j as Ne,p as qe}from"./chunk-IMGIDBCC.js";import{a as Me}from"./chunk-BXGMMZT3.js";import{a as _}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Dr from"node:path";var V=[{id:"vue-typescript-language-server",name:"vue-typescript-language-server",kind:"lsp",languages:["vue"],executables:["typescript-language-server"],dependencies:["typescript-language-server","@vue/typescript-plugin"],configFiles:["tsconfig.json"],documentation:"https://github.com/vuejs/language-tools/tree/master/packages/typescript-plugin",lsp:{command:["typescript-language-server","--stdio"],rootMarkers:["tsconfig.json","package.json"],languageIds:{vue:[".vue"]},initializationOptions:{plugins:[{name:"@vue/typescript-plugin",location:"{project}/node_modules/@vue/typescript-plugin",languages:["vue"]}]}}},b("elixir-ls",["elixir"],["elixir-ls"],["mix.exs"],{elixir:[".ex",".exs"]},["elixir-ls"],"https://github.com/elixir-lsp/elixir-ls",void 0,void 0,{elixirLS:{mcpEnabled:!1}}),b("metals",["scala"],["metals"],["build.sbt","project.scala",".bsp"],{scala:[".scala",".sc"]},["metals"],"https://scalameta.org/metals/"),{id:"angular-language-server",name:"angular-language-server",kind:"lsp",languages:["typescript","html"],executables:["ngserver"],dependencies:["@angular/language-server"],configFiles:["angular.json"],documentation:"https://github.com/angular/vscode-ng-language-service",lsp:{command:["ngserver","--stdio","--tsProbeLocations",".","--ngProbeLocations","."],rootMarkers:["angular.json"],requireRootMarker:!0,languageIds:{typescript:[".ts"],html:[".html"]}}},b("svelte-language-server",["svelte"],["svelteserver"],["svelte.config.js","package.json"],{svelte:[".svelte"]},["svelteserver","--stdio"],"https://github.com/sveltejs/language-tools/tree/master/packages/language-server",["svelte-language-server"]),b("dart-language-server",["dart"],["dart"],["pubspec.yaml","analysis_options.yaml"],{dart:[".dart"]},["dart","language-server","--protocol=lsp"],"https://dart.dev/tools/dart-language-server"),b("r-language-server",["r"],["Rscript"],["DESCRIPTION",".lintr",".Rprofile"],{r:[".r"]},["Rscript","-e","languageserver::run()"],"https://github.com/REditorSupport/languageserver"),b("zls",["zig"],["zls"],["build.zig","build.zig.zon","zls.json"],{zig:[".zig",".zon"]},["zls"],"https://zigtools.org/zls/"),b("clangd",["c","cpp"],["clangd"],[".clangd","compile_commands.json","CMakeLists.txt"],{c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hh",".hpp",".hxx"]},["clangd"],"https://clangd.llvm.org/"),b("typescript-language-server",["javascript","typescript"],["typescript-language-server"],["tsconfig.json","jsconfig.json","package.json"],{javascript:[".js",".mjs",".cjs"],javascriptreact:[".jsx"],typescript:[".ts",".mts",".cts"],typescriptreact:[".tsx"]},["typescript-language-server","--stdio"],"https://github.com/typescript-language-server/typescript-language-server",["typescript-language-server"]),b("basedpyright",["python"],["basedpyright-langserver","pyright-langserver"],["pyproject.toml","pyrightconfig.json"],{python:[".py",".pyi"]},["basedpyright-langserver","--stdio"],"https://docs.basedpyright.com/",["basedpyright"]),b("gopls",["go"],["gopls"],["go.mod","go.work"],{go:[".go"]},["gopls"],"https://go.dev/gopls/"),b("rust-analyzer",["rust"],["rust-analyzer"],["Cargo.toml","rust-project.json"],{rust:[".rs"]},["rust-analyzer"],"https://rust-analyzer.github.io/"),b("csharp-ls",["csharp"],["csharp-ls"],[".sln",".csproj"],{csharp:[".cs"]},["csharp-ls"],"https://github.com/razzmatazz/csharp-language-server"),b("jdtls",["java"],["jdtls"],["pom.xml","build.gradle",".project"],{java:[".java"]},["jdtls"],"https://projects.eclipse.org/projects/eclipse.jdt.ls"),b("kotlin-language-server",["kotlin"],["kotlin-language-server"],["build.gradle.kts","pom.xml"],{kotlin:[".kt",".kts"]},["kotlin-language-server"],"https://github.com/fwcd/kotlin-language-server"),b("solargraph",["ruby"],["solargraph"],["Gemfile",".solargraph.yml"],{ruby:[".rb",".rake"]},["solargraph","stdio"],"https://solargraph.org/"),b("intelephense",["php"],["intelephense"],["composer.json"],{php:[".php"]},["intelephense","--stdio"],"https://intelephense.com/"),b("sourcekit-lsp",["swift"],["sourcekit-lsp"],["Package.swift"],{swift:[".swift"]},["sourcekit-lsp"],"https://github.com/swiftlang/sourcekit-lsp"),b("lua-language-server",["lua"],["lua-language-server"],[".luarc.json",".luarc.jsonc"],{lua:[".lua"]},["lua-language-server"],"https://luals.github.io/"),b("bash-language-server",["shell"],["bash-language-server"],[".shellcheckrc"],{shell:[".sh",".bash"]},["bash-language-server","start"],"https://github.com/bash-lsp/bash-language-server"),b("vscode-css-language-server",["css"],["vscode-css-language-server"],["package.json"],{css:[".css",".scss",".less"]},["vscode-css-language-server","--stdio"],"https://github.com/microsoft/vscode-css-languageservice",void 0,void 0,{css:{},scss:{},less:{}}),b("vscode-html-language-server",["html"],["vscode-html-language-server"],["package.json"],{html:[".html",".htm"]},["vscode-html-language-server","--stdio"],"https://github.com/microsoft/vscode-html-languageservice"),b("yaml-language-server",["yaml"],["yaml-language-server"],[".yamllint","package.json"],{yaml:[".yaml",".yml"]},["yaml-language-server","--stdio"],"https://github.com/redhat-developer/yaml-language-server"),b("taplo-lsp",["toml"],["taplo"],["taplo.toml"],{toml:[".toml"]},["taplo","lsp","stdio"],"https://taplo.tamasfe.dev/"),b("marksman",["markdown"],["marksman"],[".marksman.toml"],{markdown:[".md",".mdx"]},["marksman","server"],"https://github.com/artempyanykh/marksman"),b("terraform-ls",["terraform"],["terraform-ls"],[".terraform.lock.hcl"],{terraform:[".tf",".tfvars"]},["terraform-ls","serve"],"https://github.com/hashicorp/terraform-ls"),b("kotlin-lsp",["kotlin"],["intellij-server"],["build.gradle.kts","build.gradle","pom.xml","settings.gradle.kts"],{kotlin:[".kt",".kts"]},["intellij-server","--stdio"],"https://github.com/Kotlin/kotlin-lsp"),b("julia-language-server",["julia"],["julia"],["Project.toml","JuliaProject.toml"],{julia:[".jl"]},["julia","--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],"https://github.com/julia-vscode/LanguageServer.jl"),b("powershell-editor-services",["powershell"],["pwsh"],["PSScriptAnalyzerSettings.psd1"],{powershell:[".ps1",".psm1",".psd1"]},["pwsh","-NoProfile","-NonInteractive","-Command",'$ErrorActionPreference="Stop";Import-Module PowerShellEditorServices;$d=Join-Path (Get-Location) ".agents/tmp/powershell-lsp-$PID";[IO.Directory]::CreateDirectory($d)|Out-Null;Start-EditorServices -HostName Pi -HostProfileId Pi -HostVersion 1.0.0 -Stdio -LanguageServiceOnly -LogPath (Join-Path $d "server.log") -SessionDetailsPath (Join-Path $d "session.json")'],"https://github.com/PowerShell/PowerShellEditorServices"),b("neocmakelsp",["cmake"],["neocmakelsp"],["CMakeLists.txt",".neocmake.toml",".neocmakelint.toml"],{cmake:[".cmake"]},["neocmakelsp","stdio"],"https://github.com/neocmakelsp/neocmakelsp",void 0,{cmake:["CMakeLists.txt"]}),b("vscode-json-language-server",["json"],["vscode-json-language-server"],["package.json"],{json:[".json",".jsonc"]},["vscode-json-language-server","--stdio"],"https://github.com/microsoft/vscode-json-languageservice"),b("lemminx",["xml"],["lemminx"],[".lemminx.json"],{xml:[".xml",".xsd",".xsl"]},["lemminx"],"https://github.com/eclipse-lemminx/lemminx"),b("sqls",["sql"],["sqls"],[".sqls.yml"],{sql:[".sql"]},["sqls"],"https://github.com/sqls-server/sqls"),b("docker-langserver",["dockerfile"],["docker-langserver"],["Dockerfile"],{dockerfile:[".dockerfile"]},["docker-langserver","--stdio"],"https://github.com/rcjsuen/dockerfile-language-server-nodejs",void 0,{dockerfile:["Dockerfile","Containerfile"]})];function b(n,e,t,r,o,s,i,l,c,p){return{id:n,name:n,kind:"lsp",languages:e,executables:t,configFiles:r,documentation:i,...l&&{dependencies:l},lsp:{command:s,rootMarkers:r,languageIds:o,...c&&{fileNames:c},...p&&{settings:p}}}}a(b,"recipe");import Jt from"node:path";import Kt from"cross-spawn";import{createMessageConnection as Xt,CancellationTokenSource as Qt,StreamMessageReader as Yt}from"vscode-jsonrpc/node";import{URI as ct}from"vscode-uri";import{watch as Nt}from"node:fs";import{readdir as qt,stat as Ft}from"node:fs/promises";import z from"node:path";import{URI as le}from"vscode-uri";var ne=class{constructor(e,t,r){this.root=e;this.changed=t;this.failed=r}static{a(this,"LspFileWatchers")}registrations=new Map;disposed=!1;async register(e,t){let r=[];try{for(let o of t){let s=o.globPattern,i=typeof s=="string"?this.root:le.parse(typeof s.baseUri=="string"?s.baseUri:s.baseUri.uri).fsPath,l=typeof s=="string"?s:s.pattern,c=a(g=>z.matchesGlob(z.isAbsolute(l)?z.join(i,g):g,l),"matches"),p=new Set((await qt(i,{recursive:!0})).filter(c));if(this.disposed)throw new Error("Language server file watchers are disposed");let d=Nt(i,{recursive:!0},(g,u)=>{!u||!c(u)||Ft(z.join(i,u)).then(()=>{if(!this.registrations.get(e)?.includes(d))return;let m=p.has(u)?2:1;p.add(u),(o.kind??7)&(m===1?1:2)&&this.changed({uri:le.file(z.join(i,u)).toString(),type:m})},m=>{if(this.registrations.get(e)?.includes(d)){if(m.code!=="ENOENT"){this.failed(m);return}p.delete(u)&&(o.kind??7)&4&&this.changed({uri:le.file(z.join(i,u)).toString(),type:3})}})});d.on("error",this.failed),r.push(d)}}catch(o){for(let s of r)s.close();throw o}this.unregister(e),this.registrations.set(e,r)}unregister(e){for(let t of this.registrations.get(e)??[])t.close();this.registrations.delete(e)}dispose(){this.disposed=!0;for(let e of this.registrations.keys())this.unregister(e)}};import{StreamMessageWriter as Vt}from"vscode-jsonrpc/node";var oe=class extends Vt{constructor(t,r){super(t);this.fail=r}static{a(this,"TransportWriter")}async write(t){try{await super.write(t)}catch(r){this.fail(r)}}};import zt from"node:path";import{URI as Ht}from"vscode-uri";function k(n,e){if(e.startsWith("ssh://")){let t=at(e);if(n.includes("://")){let o=at(n);if(o.host!==t.host)throw new Error("Document belongs to another language server owner");return o.href}let r=zt.posix.resolve(decodeURIComponent(t.pathname),n);return t.pathname=r.split("/").map(encodeURIComponent).join("/"),t.href}if(n.startsWith("ssh://")||n.includes("://")&&!n.startsWith("file://"))throw new Error("Document belongs to another language server owner");return n.startsWith("file://")?n:Ht.file(n).toString()}a(k,"documentUri");function at(n){let e=new URL(n);if(e.protocol!=="ssh:"||!e.hostname||e.username||e.password||e.port||e.search||e.hash)throw new Error("Invalid language server resource owner");return decodeURIComponent(e.pathname),e}a(at,"checkedRemote");async function A(n,e){if(e?.aborted)throw n.catch(()=>{}),e.reason;if(!e)return n;let t;try{return await Promise.race([n,new Promise((r,o)=>{t=a(()=>o(e.reason),"onAbort"),e.addEventListener("abort",t,{once:!0})})])}finally{t&&e.removeEventListener("abort",t)}}a(A,"waitWithSignal");var H=class{static{a(this,"SharedStartup")}controller=new AbortController;promise;settled=!1;waiters=0;constructor(e){this.promise=e(this.controller.signal);let t=a(()=>{this.settled=!0},"settled");this.promise.then(t,t)}async wait(e){this.waiters+=1;let t=await A(this.promise,e).then(r=>({value:r}),r=>({error:r}));if(this.waiters-=1,!this.settled&&this.waiters===0){this.controller.abort(e?.reason);try{await this.promise}catch(r){if(r!==this.controller.signal.reason)throw new AggregateError([this.controller.signal.reason,r],"Startup cancellation and cleanup failed",{cause:r})}}if("error"in t)throw t.error;return t.value}};var Gt=new Set(["uri","targetUri","target","oldUri","newUri","rootUri","documentUri","scopeUri","baseUri"]),Bt=new Set(["changes","relatedDocuments"]);function j(n,e){return Array.isArray(n)?n.map(t=>j(t,e)):typeof n!="object"||n===null?n:Object.fromEntries(Object.entries(n).map(([t,r])=>Gt.has(t)&&typeof r=="string"?[t,e(r)]:Bt.has(t)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?[t,Object.fromEntries(Object.entries(r).map(([o,s])=>[e(o),j(s,e)]))]:[t,j(r,e)]))}a(j,"mapLspUris");var $=class{static{a(this,"LspClient")}_process=null;_ownedProcess=null;_ownedStartup;_ownerTransport;_connection=null;_initialized=!1;_serverCapabilities=null;_disposed=!1;_shutdownPromise;_crashed=!1;_stderr="";_fileWatchers;_fileWatcherCleanup=Promise.resolve();_handlers=new Map;_documentVersions=new Map;_documentContents=new Map;_diagnosticPublications=new Map;_diagnosticMode="unknown";_activeDiagnosticRequests=new Set;serverId;rootUri;_command;_args;_env;_initOptions;_settings;_timeoutMs;constructor(e){this.serverId=e.serverId,this.rootUri=e.rootUri,this._command=e.command,this._args=e.command.slice(1),this._env=e.env??{},this._initOptions=e.initOptions,this._settings=e.settings,this._timeoutMs=e.timeoutMs??3e4,this._ownerTransport=e.ownerTransport}get ready(){return this._initialized&&!this._disposed}get crashed(){return this._crashed}get pid(){return this._process?.pid??null}get remote(){return this._ownedProcess?.remote}get commandName(){return $e(this._command)}get diagnosticMode(){return this._diagnosticMode}setDiagnosticMode(e){this._diagnosticMode=e}get timeoutMs(){return this._timeoutMs}supportsCommand(e){let t=this._serverCapabilities?.executeCommandProvider;return Array.isArray(t?.commands)&&t.commands.includes(e)}get hasWorkspaceSymbolCapability(){let e=this._serverCapabilities?.workspaceSymbolProvider;return e===!0||typeof e=="object"&&e!==null}get hasFoldingRangeCapability(){let e=this._serverCapabilities?.foldingRangeProvider;return e===!0||typeof e=="object"&&e!==null}documentContent(e){return this._documentContents.get(e)}documentVersion(e){return this._documentVersions.get(e)}diagnosticPublication(e){return this._diagnosticPublications.get(e)}beginDiagnosticRequest(e){this._activeDiagnosticRequests.add(e)}endDiagnosticRequest(e){this._activeDiagnosticRequests.delete(e)}hasActiveDiagnosticRequest(e){return this._activeDiagnosticRequests.has(e)}async start(e){e?.throwIfAborted();try{await this._start(e)}catch(t){try{await this.shutdown()}catch(r){throw new AggregateError([e?.aborted?e.reason:t,r],`[lsp] ${this.serverId}: startup and cleanup failed`,{cause:r})}throw e?.throwIfAborted(),t}}async _start(e){if(this._initialized)return;if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(!this.rootUri.startsWith("file://")&&!this._ownerTransport)throw Object.assign(new Error("No language server process transport for this resource owner"),{code:"UNSUPPORTED_SOURCE"});if(await this._closeFileWatchers(),e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let t=_(this._command[0]),r=this._ownerTransport?decodeURIComponent(new URL(this.rootUri).pathname):ct.parse(this.rootUri).fsPath,o=[{uri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,name:Jt.basename(r)||r}];this._ownedStartup=this._ownerTransport?.start({rootUri:this.rootUri,command:this._command,env:this._env,signal:e});let s=await this._ownedStartup;if(this._ownedProcess=s??null,e?.throwIfAborted(),this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);let i=s?void 0:Kt(t,this._args,{stdio:["pipe","pipe","pipe"],...e&&{signal:e},cwd:r,env:qe({command:this._command,env:this._env},r,process.env)});this._process=i??null;let l=i?Zt(i):Promise.resolve(),c=_(s?.stdin??i?.stdin),p=_(s?.stdout??i?.stdout),d=_(s?.stderr??i?.stderr);c.on("error",()=>{}),p.on("error",()=>{}),d.on("error",()=>{}),this._stderr="",d.setEncoding("utf8"),d.on("data",h=>{this._stderr=(this._stderr+h).slice(-4096)}),i?.on("error",h=>{("code"in h?h.code:void 0)!=="ENOENT"&&console.error(`[lsp] ${this.serverId}: spawn failed:`,h),this._crashed=!0,this._connection?.dispose(),this._connection=null,this._process=null});let g=a(h=>{(s?this._ownedProcess!==s:this._process!==i)||(this._closeFileWatchers(),!this._disposed&&h!==0&&h!==null&&(this._crashed=!0),this._connection?.dispose(),this._connection=null,this._diagnosticPublications.clear(),this._activeDiagnosticRequests.clear(),this._diagnosticMode="unknown",this._process=null,this._initialized=!1)},"onExit");i?.on("exit",g),s?.completion.then(({exitCode:h})=>g(h),()=>{this._ownedProcess===s&&(this._crashed=!0,g(null))}),await A(l,e);let u=Xt(new Yt(p),new oe(c,h=>{this._connection!==u||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),u.dispose(),console.error(`[lsp] ${this.serverId}: transport write failed:`,h))}));this._connection=u,this._connection.onError(h=>{console.error(`[lsp] ${this.serverId}: connection error:`,h)});let m=a(h=>{this._sendNotification("workspace/didChangeWatchedFiles",{changes:[h]})},"changed"),y=a(h=>console.error(`[lsp] ${this.serverId}: file watcher failed:`,h),"failed");this._fileWatchers=this._ownerTransport?this._ownerTransport.fileWatchers?.(this.rootUri,m,y):new ne(r,m,y),this._connection.onRequest("client/registerCapability",async h=>{for(let w of h.registrations)if(w.method!=="workspace/didChangeConfiguration"){if(w.method!=="workspace/didChangeWatchedFiles")throw new Error(`Unsupported dynamic capability: ${w.method}`);if(!this._fileWatchers)throw new Error("File watching is unavailable for this server owner");await this._fileWatchers.register(w.id,w.registerOptions?.watchers??[])}return null}),this._connection.onRequest("client/unregisterCapability",async h=>{for(let w of h.unregisterations)await this._fileWatchers?.unregister(w.id);return null}),this._connection.onRequest("window/workDoneProgress/create",()=>null),this._connection.onRequest("workspace/configuration",h=>h.items.map(w=>{let S=this._settings??null;for(let R of w.section?.split(".").filter(Boolean)??[])S=typeof S=="object"&&S!==null?S[R]??null:null;return S})),this._connection.listen(),this._connection.onNotification((h,...w)=>{let S=this._ownerTransport,R=S?j(w[0],v=>S.fromServerUri(v)):w[0];if(h==="textDocument/publishDiagnostics"){let v=R;v&&typeof v.uri=="string"&&Array.isArray(v.diagnostics)&&this._documentVersions.has(v.uri)&&(v.version===void 0||v.version===this.documentVersion(v.uri))&&this._diagnosticPublications.set(v.uri,{diagnostics:v.diagnostics,...typeof v.version=="number"&&{version:v.version}})}for(let v of this._handlers.get(h)??[])v(R)}),this._connection.onRequest("workspace/workspaceFolders",()=>o);let f=await A(lt(this._connection.sendRequest("initialize",{processId:this._ownerTransport?null:process.pid,rootUri:this._ownerTransport?.toServerUri(this.rootUri)??this.rootUri,workspaceFolders:o,capabilities:{workspace:{applyEdit:!1,configuration:!0,workspaceFolders:!0,didChangeWatchedFiles:{dynamicRegistration:this._fileWatchers!==void 0,relativePatternSupport:this._fileWatchers!==void 0},symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0},publishDiagnostics:{relatedInformation:!0},diagnostic:{dynamicRegistration:!1,relatedDocumentSupport:!1},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},foldingRange:{lineFoldingOnly:!0}}},initializationOptions:this._initOptions}),this._timeoutMs,`[lsp] ${this.serverId}: initialize timed out`),e).catch(h=>{let w=this._stderr.trim();throw w?new Error(`[lsp] ${this.serverId}: ${w}`,{cause:h}):h});if(await this._connection.sendNotification("initialized",{capabilities:f.capabilities}),this._settings!==void 0&&await this._connection.sendNotification("workspace/didChangeConfiguration",{settings:this._settings}),this._crashed)throw new Error(`[lsp] ${this.serverId}: transport failed during initialization`);e?.throwIfAborted(),this._initialized=!0,this._serverCapabilities=f.capabilities,this._diagnosticMode=f.capabilities.diagnosticProvider?"pull":"push"}touch(){}async restart(e){await this.shutdown(),this._closeFileWatchers(),this._connection?.dispose(),this._connection=null,this._process=null,this._initialized=!1,this._crashed=!1,this._disposed=!1,this._shutdownPromise=void 0,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._diagnosticMode="unknown",this._activeDiagnosticRequests.clear(),this._serverCapabilities=null,await this.start(e)}async sendRequest(e,t,r){this._assertReady(),r?.throwIfAborted();let o=this._ownerTransport,s=o?j(t,p=>o.toServerUri(p)):t,i=a(p=>o?j(p,d=>o.fromServerUri(d)):p,"mapResult");if(!r)return i(await _(this._connection).sendRequest(e,s));let l=new Qt,c;try{let p=_(this._connection).sendRequest(e,s,l.token);return i(await Promise.race([p,new Promise((d,g)=>{c=a(()=>{l.cancel(),g(r.reason)},"onAbort"),r.addEventListener("abort",c,{once:!0})})]))}finally{c&&r.removeEventListener("abort",c),l.dispose()}}sendNotification(e,t){this._assertReady(),this._sendNotification(e,t)}_sendNotification(e,t){let r=this._connection;if(!r)return;let o=this._ownerTransport,s=o?j(t,i=>o.toServerUri(i)):t;r.sendNotification(e,s).catch(i=>{this._connection!==r||this._disposed||(this._crashed=!0,this._initialized=!1,this._closeFileWatchers(),r.dispose(),console.error(`[lsp] ${this.serverId}: notification ${e} failed:`,i))})}onNotification(e,t){let r=this._handlers.get(e)??[];return r.push(t),this._handlers.set(e,r),()=>{let o=r.indexOf(t);o!==-1&&r.splice(o,1)}}toUri(e){return k(e,this.rootUri)}serverDocumentPath(e){let t=this.toUri(e),r=this._ownerTransport?.toServerUri(t)??t;return this._ownerTransport?decodeURIComponent(new URL(r).pathname):ct.parse(r).fsPath}openDocument(e,t,r,o=1){let s=this._documentVersions.get(e);if(s!==void 0){this.changeDocument(e,t,Math.max(o,s+1));return}this._diagnosticPublications.delete(e),this.sendNotification("textDocument/didOpen",{textDocument:{uri:e,languageId:r,version:o,text:t}}),this._documentVersions.set(e,o),this._documentContents.set(e,t)}syncDocument(e,t,r,o=!1){if(this._documentContents.get(e)===t)return;let s=this._documentVersions.get(e);s===void 0?this.openDocument(e,t,r):this.changeDocument(e,t,s+1);let i=this._serverCapabilities?.textDocumentSync,l=typeof i=="object"&&i!==null?i.save:void 0;o&&l&&this.sendNotification("textDocument/didSave",{textDocument:{uri:e},...typeof l=="object"&&l.includeText&&{text:t}})}changeDocument(e,t,r){let o=this._documentVersions.get(e),s=Math.max(r,(o??0)+1);this._diagnosticPublications.delete(e),this.sendNotification("textDocument/didChange",{textDocument:{uri:e,version:s},contentChanges:[{text:t}]}),this._documentVersions.set(e,s),this._documentContents.set(e,t)}closeDocument(e){this.sendNotification("textDocument/didClose",{textDocument:{uri:e}}),this._documentVersions.delete(e),this._documentContents.delete(e),this._diagnosticPublications.delete(e)}shutdown(){return this._shutdownPromise??=this._shutdown()}async _shutdown(){this._disposed=!0;let e=this._closeFileWatchers();if(this._connection&&this._initialized)try{await lt(this._connection.sendRequest("shutdown"),Math.min(this._timeoutMs,1e3),`[lsp] ${this.serverId}: shutdown timed out`),await this._connection.sendNotification("exit").catch(()=>{})}catch{}this._connection?.dispose(),this._connection=null;let t=this._ownedProcess??await this._ownedStartup?.catch(()=>{});this._ownedProcess=null,this._ownedStartup=void 0;let r=Promise.resolve().then(()=>t?.stop()),o=this._process;this._process=null,o&&!o.killed&&(o.kill("SIGTERM"),setTimeout(()=>{o.exitCode===null&&o.signalCode===null&&o.kill("SIGKILL")},2e3).unref()),this._initialized=!1,this._documentVersions.clear(),this._documentContents.clear(),this._diagnosticPublications.clear(),this._diagnosticMode="unknown",this._activeDiagnosticRequests.clear(),this._serverCapabilities=null;let s=await Promise.allSettled([r,e]),i=[];for(let l of s)l.status==="rejected"&&i.push(l.reason);if(i.length>0)throw new AggregateError(i,`[lsp] ${this.serverId}: owned cleanup failed`)}dispose(){return this.shutdown()}_closeFileWatchers(){let e=this._fileWatchers;return this._fileWatchers=void 0,e&&(this._fileWatcherCleanup=this._fileWatcherCleanup.catch(()=>{}).then(()=>e.dispose()),this._fileWatcherCleanup.catch(t=>{console.error(`[lsp] ${this.serverId}: file watcher cleanup failed:`,t)})),this._fileWatcherCleanup}_assertReady(){if(this._disposed)throw new Error(`[lsp] ${this.serverId}: disposed`);if(this._crashed)throw new Error(`[lsp] ${this.serverId}: crashed \u2014 call restart()`);if(!this._initialized)throw new Error(`[lsp] ${this.serverId}: not started \u2014 call start()`);if(!this._connection)throw new Error(`[lsp] ${this.serverId}: connection lost`)}};function Zt(n){return new Promise((e,t)=>{let r=a(()=>{n.off("spawn",o),n.off("error",s)},"cleanup"),o=a(()=>{r(),e()},"onSpawn"),s=a(i=>{r(),t(i)},"onError");n.once("spawn",o),n.once("error",s)})}a(Zt,"waitForSpawn");function lt(n,e,t){return new Promise((r,o)=>{let s=setTimeout(()=>{o(new Error(t))},e);n.then(i=>{clearTimeout(s),r(i)}).catch(i=>{clearTimeout(s),o(i instanceof Error?i:new Error(String(i)))})})}a(lt,"withTimeout");import{readFile as pt}from"node:fs/promises";import{URI as ut}from"vscode-uri";var K={Error:1,Warning:2,Information:3,Hint:4};var dt={command:"typescript.tsserverRequest",async request(n,e,t){return(await Promise.all(["syntacticDiagnosticsSync","semanticDiagnosticsSync","suggestionDiagnosticsSync"].map(async o=>{let s=await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:[o,{file:n.serverDocumentPath(e),includeLinePosition:!0},{isAsync:!1,expectsResult:!0}]},t);if(!de(s)||s.success!==!0||!Array.isArray(s.body))throw new Error(`Invalid completed TypeScript diagnostic report: ${o}`);return s.body.map(er)}))).flat()}};function se(n){return n.supportsCommand(dt.command)?dt:void 0}a(se,"completedDiagnosticAdapter");function er(n){if(!de(n)||typeof n.message!="string"||typeof n.code!="number"&&typeof n.code!="string"||!de(n.startLocation)||!Number.isInteger(n.startLocation.line)||!Number.isInteger(n.startLocation.offset)||Number(n.startLocation.line)<1||Number(n.startLocation.offset)<1||!["error","warning","suggestion","message"].includes(String(n.category)))throw new Error("Invalid TypeScript diagnostic entry");return{code:String(n.code),message:n.message,line:Number(n.startLocation.line),column:Number(n.startLocation.offset),severity:n.category==="error"?"error":n.category==="warning"?"warning":n.category==="suggestion"?"hint":"info"}}a(er,"convertTypeScriptDiagnostic");function de(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}a(de,"isRecord");async function X(n,e,t,r={}){let o=new AbortController,s=AbortSignal.any([o.signal,...r.signal?[r.signal]:[]]),i=setTimeout(()=>o.abort(new Error(`[lsp] ${n.serverId}: diagnostics timed out for ${e}`)),n.timeoutMs);try{return await tr(n,e,t,r.content,s)}finally{clearTimeout(i)}}a(X,"requestDiagnostics");async function tr(n,e,t,r,o){if(o.throwIfAborted(),n.diagnosticMode!=="push"){let c=n.documentVersion(e);try{let p=await n.sendRequest("textDocument/diagnostic",{textDocument:{uri:e}},o);if(p.kind!=="full"||!Array.isArray(p.items))throw new Error("Invalid full diagnostic report");if(n.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return n.setDiagnosticMode("pull"),gt(p.items,!1,!0)}catch(p){if(!rr(p))throw p;n.setDiagnosticMode("push")}}let s=se(n);if(s){n.documentVersion(e)===void 0&&n.syncDocument(e,r??await pt(ut.parse(e).fsPath,"utf8"),t??"plaintext");let c=n.documentVersion(e),p=await s.request(n,e,o);if(o.throwIfAborted(),n.documentVersion(e)!==c)throw new Error("Document changed during diagnostic request");return{diagnostics:p,syntaxErrors:[],otherDiagnostics:p,unversioned:!1,complete:!0}}o.throwIfAborted();let i=n.documentVersion(e)!==void 0,l=i?void 0:r??await pt(ut.parse(e).fsPath,"utf8");o.throwIfAborted(),n.beginDiagnosticRequest(e);try{return await new Promise((c,p)=>{let d=n.documentVersion(e)??1,g=a(f=>{let h=f;h.uri!==e||!Array.isArray(h.diagnostics)||h.version!==void 0&&h.version!==d||n.documentVersion(e)===d&&(y(),c(gt(h.diagnostics,h.version===void 0)))},"receive"),u=n.onNotification("textDocument/publishDiagnostics",g),m=a(()=>{y(),p(o.reason)},"onAbort");function y(){u(),o.removeEventListener("abort",m)}a(y,"cleanup"),o.addEventListener("abort",m,{once:!0});try{i||n.syncDocument(e,l??"",t??"plaintext");let f=n.diagnosticPublication(e);f&&g({uri:e,...f})}catch(f){y(),p(f)}})}finally{n.endDiagnosticRequest(e)}}a(tr,"requestCurrentDiagnostics");function pe(n){return{code:String(n.code??"LSP"),message:n.message,line:n.range.start.line+1,column:n.range.start.character+1,severity:n.severity===K.Warning?"warning":n.severity===K.Information?"info":n.severity===K.Hint?"hint":"error"}}a(pe,"toDiagnostic");function gt(n,e,t=!1){let r=n.map(pe);return{diagnostics:r,syntaxErrors:[],otherDiagnostics:r,unversioned:e,complete:t}}a(gt,"classify");function rr(n){return n!==null&&typeof n=="object"&&"code"in n&&n.code===-32601}a(rr,"isMethodNotFound");var nr={1:"File",2:"Module",3:"Namespace",4:"Package",5:"Class",6:"Method",7:"Property",8:"Field",9:"Constructor",10:"Enum",11:"Interface",12:"Function",13:"Variable",14:"Constant",15:"String",16:"Number",17:"Boolean",18:"Array",19:"Object",20:"Key",21:"Null",22:"EnumMember",23:"Struct",24:"Event",25:"Operator",26:"TypeParameter"};function T(n){return nr[n]??`SymbolKind(${n})`}a(T,"symbolKindName");async function Q(n,e,t){return await n.sendRequest("textDocument/documentSymbol",{textDocument:{uri:e}},t)??[]}a(Q,"requestDocumentSymbols");async function ue(n,e,t=100,r){return(await n.sendRequest("workspace/symbol",{query:e},r)??[]).slice(0,t)}a(ue,"requestWorkspaceSymbols");async function ie(n,e,t,r){return await n.sendRequest("textDocument/rename",{textDocument:{uri:e},position:t,newName:r})}a(ie,"requestRename");import Z from"node:path";import{URI as ar}from"vscode-uri";import{createHash as or}from"node:crypto";import{readdir as sr,stat as ae}from"node:fs/promises";import O from"node:path";import{URI as me}from"vscode-uri";async function ge(n,e){if(!n.supportsCommand("typescript.tsserverRequest"))return;if((await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:e,needFileNameList:!0},{isAsync:!1,expectsResult:!0}]}))?.success!==!0)throw new Error("TypeScript could not load the project for a workspace query.")}a(ge,"prepareProjectQuery");function mt(n,e){let t=a(r=>typeof r=="string"?r.replaceAll("{project}",()=>e):Array.isArray(r)?r.map(t):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([o,s])=>[o,t(s)])):r,"expand");return Object.fromEntries(Object.entries(n).map(([r,o])=>[r,t(o)]))}a(mt,"resolveInitializationOptions");var W=class n{constructor(e,t){this._registry=e;this._owner=t}static{a(this,"LspManager")}_clients=new Map;_clientStarts=new Map;_openDocs=new Set;_pushUnsubscribers=new Map;_pushHandlers=new Set;_pushFingerprints=new Map;_disposed=!1;static _instance=null;static getInstance(){if(!n._instance)throw new Error("[lsp] LspManager not initialized");return n._instance}static getInstanceOrNull(){return n._instance}static init(e,t){let r=n._instance;return r?._disposed?(r._registry=e,r._owner=t,r._disposed=!1,r):(n._instance=new n(e,t),n._instance)}static async resetForTest(){n._instance&&(await n._instance.shutdownAll(),n._instance=null)}requireOwner(){if(!this._owner)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});return this._owner}get workspaceRoot(){return this._registry.projectRoot}get clientCount(){return this._clients.size}onPushDiagnostics(e){return this._pushHandlers.add(e),()=>this._pushHandlers.delete(e)}async getOrStart(e,t,r,o){if(o?.throwIfAborted(),this._disposed)return null;let s=t.startsWith("ssh://"),i=s?this.requireOwner():void 0,l=i?await this._registry.resolveOwned(e,f=>i.exists(f,o)):this._registry.resolve(e);if(o?.throwIfAborted(),this._disposed)return null;let c=r==="symbols"?l[0]:l.find(f=>f.config.capabilities.includes(r));if(!c)return null;let p=s?t:me.file(t).toString(),d=`${c.serverId}:${p}`,g=this._clientStarts.get(d);if(g)return g.controller.signal.aborted?(await A(g.promise.catch(()=>{}),o),this.getOrStart(e,t,r,o)):g.wait(o);let u=this._clients.get(d);if(u?.ready)return u;let m=new H(f=>this._startClient(d,p,c,u,f));this._clientStarts.set(d,m);let y=a(()=>{this._clientStarts.get(d)===m&&this._clientStarts.delete(d)},"settled");return m.promise.then(y,y),m.wait(o)}async _startClient(e,t,r,o,s){let i=o??new $({serverId:r.serverId,rootUri:t,command:r.config.command,...t.startsWith("ssh://")&&this._owner&&{ownerTransport:this._owner.transport(t)},...r.config.env&&{env:r.config.env},...r.config.initializationOptions&&{initOptions:mt(r.config.initializationOptions,t.startsWith("ssh://")?decodeURIComponent(new URL(t).pathname):me.parse(t).fsPath)},...r.config.settings&&{settings:r.config.settings},...r.config.timeoutMs&&{timeoutMs:r.config.timeoutMs}});try{o?await o.restart(s):await i.start(s),s.throwIfAborted()}catch(l){try{await i.shutdown()}catch(c){if(c!==l)throw new AggregateError([l,c],"Language server startup and cleanup failed",{cause:c})}throw l}if(this._disposed)throw await i.shutdown(),new Error(`[lsp] ${r.serverId}: manager disposed during startup`);return this._clients.set(e,i),this._subscribeToPushDiagnostics(e,i),i}async isSourceFile(e,t,r){if(r?.throwIfAborted(),t.startsWith("ssh://")){if(this._owner===void 0)throw new Error("No language server workspace owner");return this._owner.isFile(k(e,t),r)}let o=await ae(O.resolve(t,e));return r?.throwIfAborted(),o.isFile()}async getWorkspaceClients(e,t="symbols",r=e,o=()=>!0,s){if(s?.throwIfAborted(),e.startsWith("ssh://")){let g=this._owner;if(!g)throw Object.assign(new Error("No language server workspace owner"),{code:"UNSUPPORTED_SOURCE"});let u=new Set,m=new Set(this._registry.knownExtensions),y=new Set([".git",".cache","node_modules","dist","build"]),f=a(async w=>{if(s?.throwIfAborted(),m.size!==0)for(let S of await g.entries(w,s)){s?.throwIfAborted();let R=k(S.name,`${w}/`);if(S.kind==="directory")y.has(S.name)||await f(R);else if(S.kind==="file"){let v=O.posix.extname(S.name).toLowerCase();if(!m.has(v)||!o(R))continue;let D=await this.openFile(R,e,t,s);D&&(u.add(D.client),m.delete(v))}}},"visit"),h=k(r,e);if(await g.isFile(h,s)){if(!o(h))return[];let w=await this.openFile(h,e,t,s);return w?[w.client]:[]}return await f(h),[...u]}let i=new Set,l=new Set(this._registry.knownExtensions),c=new Set([".git",".cache","node_modules","dist","build"]),p=a(async g=>{if(s?.throwIfAborted(),l.size===0)return;let u;try{u=await sr(g,{withFileTypes:!0})}catch{return}for(let m of u){if(s?.throwIfAborted(),l.size===0)return;if(m.isDirectory()){c.has(m.name)||await p(O.join(g,m.name));continue}if(!m.isFile())continue;let y=O.extname(m.name).toLowerCase();if(!l.has(y))continue;let f=O.join(g,m.name);if(!o(f))continue;let h=await this.openFile(f,e,t,s);h&&(l.delete(y),h.client.hasWorkspaceSymbolCapability&&(await ge(h.client,f),i.add(h.client)))}},"visit"),d=O.resolve(e,r);if((await ae(d)).isFile()){if(!o(d))return[];let g=await this.openFile(d,e,t,s);return g===null||!g.client.hasWorkspaceSymbolCapability?[]:(await ge(g.client,d),[g.client])}return await p(d),s?.throwIfAborted(),[...i]}async prepareWorkspaceSymbols(e,t=e,r,o){return this.getWorkspaceClients(e,"symbols",t,r,o)}hasServerFor(e){return this._registry.resolve(e).length>0}languageId(e){return this._registry.languageId(e)}isOpen(e){return this._openDocs.has(e)}syncEditedSource(e,t){for(let r of this._clients.values()){if(!r.ready)continue;let o=r.toUri(e);if(r.documentContent(o)===void 0)continue;let s=this.languageId(O.extname(decodeURIComponent(new URL(o).pathname)));r.syncDocument(o,t,s,!0)}}async readSourceSnapshot(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readSnapshot(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported rename source"),{code:"UNSUPPORTED_SOURCE"});let r=a(i=>`${i.dev}:${i.ino}:${i.mode}:${i.size}:${i.mtimeMs}:${i.ctimeMs}`,"identity"),o=r(await ae(e)),s=await this.readSourceText(e,t);if(o!==r(await ae(e)))throw new Error("A rename source changed while reading it. No edits applied.");return{content:s,version:or("sha256").update(o).update("\0").update(s).digest("hex")}}async readSourceBytes(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readBytes(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{signal:t})}async readSourceText(e,t){if(t?.throwIfAborted(),e.startsWith("ssh://"))return this.requireOwner().readText(e,t);if(e.includes("://"))throw Object.assign(new Error("Unsupported declaration source"),{code:"UNSUPPORTED_SOURCE"});let{readFile:r}=await import("node:fs/promises");return r(e,{encoding:"utf8",signal:t})}async openFile(e,t,r="diagnostics",o){if(o?.throwIfAborted(),e.startsWith("ssh://")&&!t.startsWith("ssh://")){if(!this._registry.projectRoot.startsWith("ssh://"))throw Object.assign(new Error("Remote document has no workspace owner"),{code:"UNSUPPORTED_SOURCE"});t=this._registry.projectRoot}let s=t.startsWith("ssh://"),i=s?k(e,t):O.resolve(t,e),l=await this.getOrStart(i,t,r,o);if(!l)return null;let c=l.toUri(i),p=s?this.requireOwner():void 0,g=(p?await this._registry.resolveOwned(i,u=>p.exists(u,o)):this._registry.resolve(i))[0]?.languageId??"plaintext";if(p){let u=await p.readText(c,o);return o?.throwIfAborted(),l.syncDocument(c,u,g),this._openDocs.add(c),{client:l,uri:c,languageId:g}}try{let{readFile:u}=await import("node:fs/promises"),m=await u(i,{encoding:"utf8",signal:o});o?.throwIfAborted(),l.syncDocument(c,m,g),this._openDocs.add(c)}catch(u){if(o?.throwIfAborted(),!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}return{client:l,uri:c,languageId:g}}_subscribeToPushDiagnostics(e,t){if(this._pushUnsubscribers.has(e))return;let r=t.onNotification("textDocument/publishDiagnostics",o=>{let s=ir(o);if(!s||t.hasActiveDiagnosticRequest(s.uri))return;let i=t.documentVersion(s.uri);if(s.version!==void 0&&i!==void 0&&s.version<i)return;let l=`${e}:${s.uri}`,c=s.diagnostics.map(pe),p=JSON.stringify([s.version,i,c]);if(this._pushFingerprints.get(l)===p)return;this._pushFingerprints.set(l,p);let d={cwd:t.rootUri.startsWith("ssh://")?t.rootUri:me.parse(t.rootUri).fsPath,serverId:t.serverId,uri:s.uri,diagnostics:c,...s.version!==void 0&&{version:s.version}};for(let g of this._pushHandlers)g(d)});this._pushUnsubscribers.set(e,r)}async shutdownAll(){this._disposed=!0;let e=[...this._clientStarts.values()];for(let i of e)i.controller.abort(new Error("Language server manager stopped"));let t=await Promise.allSettled(e.map(i=>i.promise)),r=[];for(let[i,l]of t.entries())l.status==="rejected"&&l.reason!==e[i]?.controller.signal.reason&&r.push(l.reason);let o=[...this._clients.values()],s=await Promise.allSettled(o.map(i=>i.shutdown()));for(let i of this._pushUnsubscribers.values())i();this._pushUnsubscribers.clear(),this._clientStarts.clear(),this._pushFingerprints.clear(),this._pushHandlers.clear(),this._clients.clear();for(let i of s)i.status==="rejected"&&r.push(i.reason);if(r.length>0)throw new AggregateError(r,"Language server cleanup failed")}dispose(){return this.shutdownAll()}};function ir(n){if(n===null||typeof n!="object")return;let e=n;if(!(typeof e.uri!="string"||!Array.isArray(e.diagnostics)))return{uri:e.uri,diagnostics:e.diagnostics,...typeof e.version=="number"&&{version:e.version}}}a(ir,"parsePushNotification");async function fe(n,e,t){if(t?.throwIfAborted(),!n.supportsCommand("typescript.tsserverRequest"))return;let r=await n.sendRequest("workspace/executeCommand",{command:"typescript.tsserverRequest",arguments:["projectInfo",{file:n.serverDocumentPath(e),needFileNameList:!0},{isAsync:!1,expectsResult:!0}]},t);if(t?.throwIfAborted(),r?.success!==!0)throw new Error("TypeScript could not load the project for the workspace query.")}a(fe,"loadQueryProject");async function Y(n,e,t,r){return await fe(n,e,r),await n.sendRequest("textDocument/references",{textDocument:{uri:e},position:t,context:{includeDeclaration:!0}},r)??[]}a(Y,"requestReferences");async function he(n,e,t,r){let o=await n.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:e},position:t},r),s=o?.[0];if(!s)return{items:[],incoming:[],outgoing:[]};let[i,l]=await Promise.all([n.sendRequest("callHierarchy/incomingCalls",{item:s},r),n.sendRequest("callHierarchy/outgoingCalls",{item:s},r)]);return{items:o,incoming:i??[],outgoing:l??[]}}a(he,"requestCallHierarchy");function G(n,e,t){let r=e.startsWith("ssh://"),o=r?Z.posix:Z,s=a(d=>r?decodeURIComponent(new URL(k(d,e)).pathname):d,"native"),i=r?s(t.path??e):Z.resolve(e,t.path??"."),l=o.relative(i,s(n));if(l===".."||l.startsWith(`..${o.sep}`)||o.isAbsolute(l))return!1;let c=o.relative(s(e),s(n)).split(o.sep).join("/"),p=a(d=>d.split(",").some(g=>{let u=g.trim();return u.length>0&&o.matchesGlob(u.includes("/")?c:o.basename(s(n)),u)}),"matches");return(t.include===void 0||p(t.include))&&(t.exclude===void 0||!p(t.exclude))}a(G,"withinScope");function ye(n,e){let t=k(n,e);if(t.startsWith("ssh://"))return t;let r=ar.parse(t);if(r.scheme!=="file")throw new Error("Unsupported LSP source location.");return Z.resolve(r.fsPath)}a(ye,"sourceOf");function cr(n,e){return n.start.line===e.start.line&&n.start.character===e.start.character&&n.end.line===e.end.line&&n.end.character===e.end.character}a(cr,"sameRange");function ft(n,e,t){return n.flatMap(r=>[...r.name===e&&r.range!==void 0&&cr(r.range,t)&&r.selectionRange!==void 0?[r.selectionRange]:[],...ft(r.children??[],e,t)])}a(ft,"declarationNames");async function we(n,e,t,r,o={},s=W.getInstance()){r?.throwIfAborted();let i=o.resultScope;if(i!==void 0&&(await F(i,r),i.targets.length===0))return{hits:[],complete:i.complete};if(i===void 0&&o.path!==void 0&&!G(e.startsWith("ssh://")?k(o.path,e):Z.resolve(e,o.path),e,o)&&await s.isSourceFile(o.path,e,r))return{hits:[],complete:!0};let l=i?.targets.map(y=>y.source)??[o.path??e],c=new Set((await Promise.all(l.map(y=>s.prepareWorkspaceSymbols(e,y,f=>G(f,e,o),r)))).flat());if(c.size===0)throw new Error("LSP symbol search is unavailable: no provider supports workspace/symbol in this scope.");let p=new Map,d=a(async y=>{r?.throwIfAborted();let f=ye(y.uri,e),h=p.get(f);if(h===void 0){let{content:L,version:N}=await s.readSourceSnapshot(f,r);h={document:Ee(f,L),version:N},p.set(f,h)}let{document:w}=h,{start:S,end:R}=y.range,v=[S,R];for(let L of v){let N=w.lines[L.line];if(!Number.isInteger(L.line)||!Number.isInteger(L.character)||N===void 0||L.character<0||L.character>N.content.length)throw new Error("LSP range does not match its source snapshot.")}let D=_(w.lines[S.line]),re=a(L=>w.lines.slice(0,L).reduce((N,xe)=>N+xe.content.length+xe.lineEnding.length,0),"offset"),U=re(S.line)+S.character,C=re(R.line)+R.character;if(C<U)throw new Error("LSP returned a reversed source range.");return{source:f,lineNumber:S.line+1,endLineNumber:R.line+1,startColumn:S.character,endColumn:R.character,matchedText:w.content.slice(U,C),lineText:D.content}},"toMatch"),g=a(y=>G(y.source,e,o)&&(i===void 0||st(i,y)),"included"),u=[],m=new Set;for(let y of c){r?.throwIfAborted();let f=await ue(y,n,Number.MAX_SAFE_INTEGER,r);for(let h of f){if(r?.throwIfAborted(),!G(ye(h.location.uri,e),e,{}))continue;let w=await d(h.location),S=await s.openFile(w.source,e,"symbols",r);if(S===null)throw new Error("LSP references are unavailable for a discovered declaration.");let R=h.location;if(w.matchedText!==h.name){let C=await Q(S.client,S.uri,r),L=ft(C,h.name,h.location.range);if(L.length!==1)throw new Error("LSP declaration has no unique provider selectionRange; cannot search its references.");R={uri:S.uri,range:_(L[0])}}let v=await d(R),D={id:JSON.stringify([y.serverId,v.source,h.location.range]),name:h.name,kind:String(h.kind),source:v.source,range:{startLine:v.lineNumber,startColumn:v.startColumn,endLine:v.endLineNumber??v.lineNumber,endColumn:v.endColumn}},re=await Y(S.client,S.uri,R.range.start,r);r?.throwIfAborted();let U=[{...v,role:"definition",symbol:D}];for(let C of re){if(!G(ye(C.uri,e),e,{}))continue;let L=await d(C);L.source===v.source&&L.lineNumber===v.lineNumber&&L.startColumn===v.startColumn&&L.endLineNumber===v.endLineNumber&&L.endColumn===v.endColumn||U.push({...L,role:"reference",symbol:D})}if(!(o.navigation==="references"&&!U.some(g)))for(let C of U){if(o.navigation!=="references"&&!g(C)||o.navigation==="references"&&!G(C.source,e,{}))continue;let L=JSON.stringify([D.id,C.source,C.lineNumber,C.startColumn,C.endLineNumber,C.endColumn]);m.has(L)||(m.add(L),u.push(C))}}}r?.throwIfAborted();for(let[y,f]of p){let h=await s.readSourceSnapshot(y,r);if(h.version!==f.version||h.content!==f.document.content)throw new Error("LSP source changed during search.")}return i!==void 0&&await F(i,r),u.sort((y,f)=>y.source.localeCompare(f.source)||y.lineNumber-f.lineNumber||y.startColumn-f.startColumn||y.endColumn-f.endColumn||y.symbol.id.localeCompare(f.symbol.id)),{hits:u.slice(0,t),complete:(i?.complete??!0)&&u.length<=t}}a(we,"searchSymbols");import{readFile as lr}from"node:fs/promises";import ve from"node:path";import{fileURLToPath as dr}from"node:url";var pr={failureLabel:"SYMBOL_READ_FAILED",emptyReason:"no symbol source was produced."},be=10,Se=5,B=10;async function yt(n,e,t,r,o){x(o);let s=await n.readSourceText(e,o),i=await te(n,e,r,o),l=ee(i.symbols,t,i.displayPath),c=await n.readSourceText(i.filePath,o);if(x(o),s!==c)throw new Error("The symbol source changed during resolution. Read it again before editing.");return{source:i.filePath,range:l.range,content:c}}a(yt,"resolveLspDeclaration");async function wt(n,e,t,r,o){x(o);let s=await n.readSourceText(e,o),i=await te(n,e,r,o),l=ee(i.symbols,t,i.displayPath);if(s!==await n.readSourceText(e,o))throw new Error("The rename source changed during resolution.");return x(o),{client:i.client,uri:i.uri,position:l.selectionRange.start,content:s}}a(wt,"resolveLspRenameTarget");async function Pe(n,e,t,r,o){x(o);let s=await te(n,e,r,o),i=ee(s.symbols,t,s.displayPath),l=await yr(s.filePath,n,o);x(o);let c=i.range.start.line+1,p=Math.min(i.range.end.line+1,l.lines.length),d=l.lines.slice(Math.max(0,c-1),Math.max(0,p)).map((u,m)=>{let y=c+m;return Ie({content:u,sourceLine:{source:s.filePath,lineNumber:y,content:u}})}),g={path:s.displayPath,heading:`symbol: ${M(i.selector)}`,details:[`defined in: ${s.displayPath}:${c}-${p} (${T(i.kind)})`],startLine:c,endLine:p,totalLines:l.lines.length,renderedLines:d};return De([g],pr)}a(Pe,"readLspSymbolBody");async function _e(n,e,t,r,o){x(o);let s=await te(n,e,r,o),i=ee(s.symbols,t,s.displayPath),l=await Lt(s,i,o),c=new ce(r);return await ur(s,i,l,c)}a(_e,"readLspSymbolGraph");async function Ce(n,e,t,r){x(r);let o=await te(n,e,t,r),s=new ce(t),i=[`## file graph: ${o.displayPath}`,`Top-level declarations: ${o.symbols.length}`];for(let l of o.symbols){x(r);let c=await Lt(o,l,r);i.push("",...await hr(o,l,c,s))}return i.join(`
|
|
2
|
+
`)}a(Ce,"readLspFileGraph");function ee(n,e,t){if(e.length===0)throw new TypeError("A symbol selector must contain at least one segment.");if(e.length===1){let s=St(n,_(e[0]));if(s.length===1)return _(s[0]);throw s.length>1?new Error(`Symbol selector "${M(e)}" is ambiguous in ${t}; use parent/child.`):ht(e,t)}let r=n,o;for(let s of e){let i=r.filter(l=>l.name===s);if(i.length===0)throw ht(e,t);if(i.length>1)throw new Error(`Symbol selector "${M(e)}" is ambiguous at "${s}" in ${t}.`);o=_(i[0]),r=o.children}return _(o)}a(ee,"resolveLspCodeSymbol");async function te(n,e,t,r){let o=E(e,t),s=await n.openFile(o,t,"symbols",r);if(!s)throw new Error(`No LSP server with symbol support is configured for ${Re(o,t)}.`);let i=await Q(s.client,s.uri,r),l=vt(i).sort(bt);return{client:s.client,uri:s.uri,filePath:o,displayPath:Re(o,t),symbols:l}}a(te,"openCodeDocument");function vt(n,e=[]){return n.flatMap(t=>{let r=t.selectionRange??t.range;if(!r)return[];let o=t.range??r,s=[...e,t.name];return[{name:t.name,kind:t.kind,range:o,selectionRange:r,selector:s,children:vt(t.children??[],s).sort(bt)}]})}a(vt,"normalizeDocumentSymbols");function bt(n,e){return n.range.start.line-e.range.start.line||n.range.start.character-e.range.start.character||n.name.localeCompare(e.name)}a(bt,"compareSymbols");function St(n,e){return n.flatMap(t=>[...t.name===e?[t]:[],...St(t.children,e)])}a(St,"collectNamedSymbols");function ht(n,e){return new Error(`Symbol "${M(n)}" was not found in ${e}.`)}a(ht,"symbolNotFound");async function Lt(n,e,t){let r=e.selectionRange.start,[o,s]=await Promise.all([Y(n.client,n.uri,r,t),he(n.client,n.uri,r,t)]);return x(t),{references:o,calls:s}}a(Lt,"queryRelations");async function ur(n,e,t,r){let o=M(e.selector),s=await r.line(n.uri,e.selectionRange.start.line+1);return[`## graph: ${o}`,`Definition: ${n.displayPath} ${s} (${T(e.kind)})`,`Source: ${J("graph",n.displayPath,e.selector)}`,"",...await gr(t.references,r),"",...await mr(t.calls.incoming,r),"",...await fr(t.calls.outgoing,r)].join(`
|
|
3
|
+
`)}a(ur,"formatSymbolGraph");async function gr(n,e){let t=Rt(n),r=[`References: ${n.length} in ${t.length} file(s)`];for(let[o,s]of t.slice(0,be)){r.push(`- ${e.display(o)} (${s.length})`);for(let i of s.slice(0,Se))r.push(` - ${await e.line(o,i.range.start.line+1)}`);s.length>Se&&r.push(` - ... ${s.length-Se} more`)}return t.length>be&&r.push(`- ... ${t.length-be} more file(s)`),r}a(gr,"formatReferences");async function mr(n,e){let t=[`Incoming calls: ${n.length}`];for(let r of n.slice(0,B)){let o=r.fromRanges[0]?.start.line??r.from.selectionRange.start.line,s=await e.line(r.from.uri,o+1);t.push(`- ${T(r.from.kind)} ${r.from.name} \u2014 ${e.display(r.from.uri)} ${s}`)}return n.length>B&&t.push(`- ... ${n.length-B} more`),t}a(mr,"formatIncomingCalls");async function fr(n,e){let t=[`Outgoing calls: ${n.length}`];for(let r of n.slice(0,B)){let o=await e.line(r.to.uri,r.to.selectionRange.start.line+1);t.push(`- ${T(r.to.kind)} ${r.to.name} \u2014 ${e.display(r.to.uri)} ${o}`)}return n.length>B&&t.push(`- ... ${n.length-B} more`),t}a(fr,"formatOutgoingCalls");async function hr(n,e,t,r){let o=T(e.kind),s=await r.line(n.uri,e.selectionRange.start.line+1),i=Rt(t.references).map(([d,g])=>`${r.display(d)} (${g.length})`),l=t.calls.incoming.map(d=>`${d.from.name} (${r.display(d.from.uri)})`),c=t.calls.outgoing.map(d=>`${d.to.name} (${r.display(d.to.uri)})`),p=[`### ${o} ${e.name}`,`Selector: ${M(e.selector)}`,`Definition: ${s}`,`Used by: ${Le(i)}`,`Incoming calls: ${Le(l)}`,`Outgoing calls: ${Le(c)}`];if(e.children.length>0){p.push("Members:");for(let d of e.children){let g=J("graph",n.displayPath,d.selector);p.push(`- ${T(d.kind)} ${d.name} \u2014 ${g}`)}}return p}a(hr,"formatFileGraphSymbol");function Le(n,e=5){if(n.length===0)return"none";let t=n.slice(0,e).join(", ");return n.length>e?`${t}, ... ${n.length-e} more`:t}a(Le,"summarize");function Rt(n){let e=new Map;for(let t of n){let r=e.get(t.uri)??[];r.push(t),e.set(t.uri,r)}return[...e].map(([t,r])=>[t,r.sort((o,s)=>o.range.start.line-s.range.start.line||o.range.start.character-s.range.start.character)]).sort(([t],[r])=>t.localeCompare(r))}a(Rt,"groupLocationsByUri");async function yr(n,e,t){let r=n.startsWith("ssh://")?Buffer.from(await e.readSourceBytes(n,t)):await lr(n,{signal:t});if(r.byteLength>256*1024)throw new Error(`File exceeds the 262144-byte code-view limit: ${n}`);if(r.includes(0))throw new Error(`File appears to be binary and cannot be read as text: ${n}`);let o=r.toString("utf8").replaceAll(`\r
|
|
4
|
+
`,`
|
|
5
|
+
`),s=o.endsWith(`
|
|
6
|
+
`)?o.slice(0,-1):o,i=s.length===0?[]:s.split(`
|
|
7
|
+
`);return{content:o,lines:i}}a(yr,"readTextFile");var ce=class{static{a(this,"LocationPresenter")}#e;constructor(e){this.#e=e}display(e){return Re(wr(e),this.#e)}line(e,t){return Promise.resolve(String(t))}};function wr(n){if(!n.startsWith("file://"))return n;try{return dr(n)}catch{return decodeURIComponent(n.slice(7))}}a(wr,"filePathFromUri");function Re(n,e){if(n.startsWith("ssh://"))return n;let t=ve.relative(e,n);return t.length===0||t.startsWith("..")||ve.isAbsolute(t)?n:t.replaceAll(ve.sep,"/")}a(Re,"displayFilePath");function x(n){if(n?.aborted===!0)throw vr(n)}a(x,"throwIfAborted");function vr(n,e){if(n.reason instanceof Error)return n.reason;if(e instanceof Error)return e;let t=new Error("The operation was aborted");return t.name="AbortError",t}a(vr,"abortReason");function ke(n){let e=null;return{kind:"compiler",name:"lsp",priority:100,extensions:["*"],detect:a(()=>Promise.resolve(!0),"detect"),async compile({filePath:t},r){r.signal?.throwIfAborted();let o=await n(r.cwd,t,r.signal);r.signal?.throwIfAborted();let s=await br(t,r,o);if(!s)throw new Error("No diagnostic language server for this source");let{client:i,diagnostics:l,syntaxErrors:c,otherDiagnostics:p}=s;return e=i,{ok:!l.some(d=>d.severity==="error"),diagnostics:l,syntaxErrors:c,otherDiagnostics:p}},async restart(){e&&(await e.restart(),e=null)}}}a(ke,"createLspCompiler");async function br(n,e,t){let r=await t.openFile(n,e.cwd,"diagnostics",e.signal);if(e.signal?.throwIfAborted(),!r)return null;let o=await X(r.client,r.uri,r.languageId,{signal:e.signal});if(e.signal?.throwIfAborted(),!o.complete)throw new Error("Language server diagnostics are a snapshot, not a completed report");return{client:r.client,...o}}a(br,"openAndDiagnose");import P from"node:path";import{existsSync as Sr}from"node:fs";function Pt(n){let e=new Map,t=new Map;for(let[r,o]of Object.entries(n))for(let[s,i]of Object.entries(o.languages))for(let l of i.extensions){let c=l.toLowerCase(),p=e.get(c);if(p!==void 0&&p!==s)throw new Error(`[lsp] extension conflict: "${c}" claimed by "${p}" and "${s}"`);e.set(c,s);let d=t.get(c)??[];d.push(r),t.set(c,d)}return{extToLanguageId:e,extToServerIds:t}}a(Pt,"buildLanguageLookup");var I=class n{constructor(e,t,r){this._projectRoot=r;this._entries=e;let o=e.filter(s=>s.layer!=="built-in"||t.has(s.id));this._servers=Object.fromEntries(o.map(s=>[s.id,s.config])),this._lookup=Pt(this._servers)}static{a(this,"LspServerRegistry")}_servers;_entries;_lookup;static async fromPackageDir(e,t={}){t.signal?.throwIfAborted();let r=await Ue(e,"lsp-servers",c=>Lr(c).servers,t);if(t.signal?.throwIfAborted(),e.startsWith("ssh://")&&(!t.executableAvailable&&!t.executableAvailability||t.requireBuiltInEvidence&&!t.recipeEvidence))throw Object.assign(new Error("Remote language server availability needs its workspace owner"),{code:"UNSUPPORTED_SOURCE"});let o=t.environment??process.env,s=r.entries.filter(c=>c.layer==="built-in"),i=[];if(t.executableAvailability){let c=await t.executableAvailability(s.map(p=>p.config));if(c.length!==s.length||c.some(p=>typeof p!="boolean"))throw new TypeError("Invalid owner executable availability report");for(let[p,d]of s.entries())i.push({id:d.id,available:c[p]===!0})}else if(t.executableAvailable)for(let c of s)i.push({id:c.id,available:await t.executableAvailable(c.config)});else i.push(...await Promise.all(s.map(async c=>({id:c.id,available:await Ne(c.config,e,o,t.signal)}))));t.signal?.throwIfAborted();let l=t.requireBuiltInEvidence?t.recipeEvidence?await t.recipeEvidence(t.recipes??[]):await Me(e,t.recipes??[],void 0,t.signal):void 0;return t.signal?.throwIfAborted(),new n(r.entries,new Set(i.filter(c=>c.available&&(l===void 0||(l.get(c.id)?.score??0)>0)).map(c=>c.id)),e.startsWith("ssh://")?e:P.resolve(e))}static fromConfig(e,t=process.cwd()){return new n(Object.entries(e.servers).map(([r,o])=>({id:r,config:o,layer:"project",sourcePath:"<memory>"})),new Set,t.startsWith("ssh://")?t:P.resolve(t))}resolve(e){return this.candidates(e).filter(t=>!t.config.requireRootMarker||this.hasRootMarker(e,t.config.rootMarkers))}candidates(e){let t=P.basename(e),r=P.extname(e)||(e.startsWith(".")?e:`.${e}`),o=a(i=>process.platform==="win32"?i.toLowerCase():i,"normalizeName"),s=[];for(let i of this._entries)if(this._servers[i.id]){for(let[l,c]of Object.entries(i.config.languages))if(c.extensions.some(p=>p.toLowerCase()===r.toLowerCase())||c.fileNames?.some(p=>o(p)===o(t))){s.push({serverId:i.id,config:i.config,languageId:l,layer:i.layer,sourcePath:i.sourcePath});break}}return s}async resolveOwned(e,t){if(!this._projectRoot.startsWith("ssh://"))return this.resolve(e);let r=new URL(this._projectRoot),o=decodeURIComponent(r.pathname),s=e.startsWith(".")&&!e.includes("/"),i=e.includes("://")?new URL(e):new URL(r.href),l=e.includes("://")?decodeURIComponent(i.pathname):P.posix.resolve(o,e),c=P.posix.relative(o,l);if(i.origin!==r.origin||i.host!==r.host||i.protocol!==r.protocol||i.username||i.password||i.port||i.search||i.hash||c===".."||c.startsWith("../"))throw Object.assign(new Error("Language server resource belongs to another owner"),{code:"UNSUPPORTED_SOURCE"});let p=[];for(let d of this.candidates(s?e:l)){if(!d.config.requireRootMarker){p.push(d);continue}let g=s||l===o?o:P.posix.dirname(l);for(;;){let u=!1;for(let m of d.config.rootMarkers){let y=P.posix.resolve(g,m),f=P.posix.relative(o,y);if(f===".."||f.startsWith("../"))continue;let h=new URL(r.href);if(h.pathname=y.split("/").map(encodeURIComponent).join("/"),await t(h.href)){u=!0;break}}if(u){p.push(d);break}if(g===o)break;g=P.posix.dirname(g)}}return p}hasRootMarker(e,t){let r=P.dirname(P.resolve(this._projectRoot,e));for(e.startsWith(".")&&!e.includes(P.sep)&&(r=this._projectRoot);;){let o=P.relative(this._projectRoot,r);if(o===".."||o.startsWith(`..${P.sep}`)||P.isAbsolute(o))return!1;if(t.some(s=>Sr(P.join(r,s))))return!0;if(r===this._projectRoot)return!1;r=P.dirname(r)}}get projectRoot(){return this._projectRoot}get servers(){return this._servers}get entries(){return this._entries}get knownExtensions(){return new Set(this._lookup.extToLanguageId.keys())}languageId(e){let t=e.startsWith("ssh://")?decodeURIComponent(new URL(e).pathname):e;return(this._projectRoot.startsWith("ssh://")?this.candidates(t):this.resolve(t))[0]?.languageId??e.slice(1)}};function Lr(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("LSP config must be an object");let e=n;if(e.version!==1)throw new Error("LSP config version must be 1");if(typeof e.servers!="object"||e.servers===null||Array.isArray(e.servers))throw new Error("LSP config servers must be an object");for(let[t,r]of Object.entries(e.servers)){if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LSP server ${t} must be an object`);let o=r;if(!Array.isArray(o.command)||o.command.length===0||o.command.some(s=>typeof s!="string"||s.length===0))throw new Error(`LSP server ${t}.command must be a non-empty string array`);if(o.transport!==void 0&&o.transport!=="stdio")throw new Error(`LSP server ${t} only supports stdio transport`);if(!Array.isArray(o.rootMarkers)||o.rootMarkers.some(s=>typeof s!="string"))throw new Error(`LSP server ${t}.rootMarkers must be a string array`);if(o.requireRootMarker!==void 0&&typeof o.requireRootMarker!="boolean")throw new TypeError(`LSP server ${t}.requireRootMarker must be a boolean`);if(o.requireRootMarker&&o.rootMarkers.length===0)throw new Error(`LSP server ${t}.requireRootMarker requires rootMarkers`);if(typeof o.languages!="object"||o.languages===null||Array.isArray(o.languages))throw new Error(`LSP server ${t}.languages must be an object`);for(let[s,i]of Object.entries(o.languages)){let l=typeof i=="object"&&i!==null&&!Array.isArray(i)?i.extensions:void 0;if(!Array.isArray(l)||l.length===0||l.some(p=>typeof p!="string"))throw new Error(`LSP server ${t} language ${s} requires extensions`);let c=i.fileNames;if(c!==void 0&&(!Array.isArray(c)||c.some(p=>typeof p!="string"||p.length===0||/[/\\]/u.test(p))))throw new Error(`LSP server ${t} language ${s}.fileNames must contain basenames`)}if(!Array.isArray(o.capabilities))throw new TypeError(`LSP server ${t}.capabilities must be an array`)}return n}a(Lr,"parseLspConfig");function _t(n){return kt("symbol","lsp-symbol",n,async e=>await Pe(e.manager,e.filePath,_(e.selector),e.cwd,e.signal))}a(_t,"createLspSymbolResolver");function Ct(n){return kt("graph","lsp-graph",n,async e=>e.selector===void 0?await Ce(e.manager,e.filePath,e.cwd,e.signal):await _e(e.manager,e.filePath,e.selector,e.cwd,e.signal))}a(Ct,"createLspGraphResolver");function kt(n,e,t,r){return{id:e,tryResolve(o,s){return Promise.resolve(Rr(o,s,n,t,r))}}}a(kt,"createCodeViewResolver");function Rr(n,e,t,r,o){let s;try{s=q(n,t)}catch(c){return{kind:"failed",error:c}}if(s===void 0)return{kind:"not-handled"};let i;try{i=E(s.path,e.cwd)}catch(c){return{kind:"failed",error:c}}return{kind:"resolved",resource:{source:J(t,i,s.selector),async read(c){let p=await r(e.cwd,i,c.signal),d=await o({manager:p,filePath:i,cwd:e.cwd,...Pr(s.selector),..._r(c.signal)});return[typeof d=="string"?{type:"text",text:d}:d]}}}}a(Rr,"resolveCodeViewSource");function Pr(n){return n===void 0?{}:{selector:n}}a(Pr,"optionalSelector");function _r(n){return n===void 0?{}:{signal:n}}a(_r,"optionalSignal");function Et(n,e=(t,r)=>Promise.resolve({cwd:r,external:!1})){return{id:"lsp",async diagnose(t,r){let o=await e(t,r.cwd,r.signal);if(o===void 0)return{status:"unavailable",diagnostics:[],reason:"No local language-server project found for this file"};let s=await n(o.cwd,o.external,r.signal);r.signal.throwIfAborted();let i=await s.getOrStart(t,o.cwd,"diagnostics",r.signal);if(r.signal.throwIfAborted(),!i)return{status:"unavailable",diagnostics:[],reason:"No language server configured for this file"};let l=i.toUri(t),c=s.languageId(t);i.syncDocument(l,r.content,c,!0);let p=i.documentVersion(l),d={active:!0,queued:!1},g=a(()=>!r.signal.aborted&&i.documentVersion(l)===p,"current"),u=a(()=>X(i,l,c,{signal:r.signal,content:r.content}),"request"),m=a(async()=>{if(d.queued=!0,!d.active){d.active=!0;try{for(;d.queued&&g();){d.queued=!1;let f=await u();g()&&r.publish(xt(f,i.commandName))}}catch(f){g()&&r.publish({status:"unavailable",diagnostics:[],reason:f instanceof Error?f.message:String(f),source:i.commandName})}finally{d.active=!1}}},"refresh"),y=s.onPushDiagnostics(f=>{!g()||f.uri!==l||f.serverId!==i.serverId||f.cwd!==o.cwd||f.version!==void 0&&f.version!==p||(i.diagnosticMode==="pull"||se(i)?m():r.publish({status:"snapshot",diagnostics:f.diagnostics,source:i.commandName,reason:It(f.version===void 0)}))});r.signal.addEventListener("abort",y,{once:!0});try{let f=await u();return p=i.documentVersion(l),xt(f,i.commandName)}catch(f){throw d.queued=!1,y(),r.signal.removeEventListener("abort",y),f}finally{d.active=!1,d.queued&&g()&&queueMicrotask(()=>{m()})}}}}a(Et,"createLspDiagnosticSource");function It(n){return`Latest push snapshot; completion is unknown${n?"; language server omitted the document version":""}`}a(It,"snapshotReason");function xt(n,e){return n.complete?{status:"ready",diagnostics:n.diagnostics,source:e}:{status:"snapshot",diagnostics:n.diagnostics,reason:It(n.unversioned),source:e}}a(xt,"toReport");import{URI as Cr}from"vscode-uri";var Dt={protocol:Fe,apiVersion:Ve,id:"lsp",setup(n){for(let e of V)n.addToolRecipe(e);n.addSetupCheck({id:"effective-config",inspect:kr}),n.addCheck({id:"config",title:"LSP",async run(e){try{let t=await I.fromPackageDir(e.cwd,At(e)),r=xr(t,e.files);return r.length===0?[{status:"skip",message:"No language server matches the inspected project files"}]:await Promise.all(r.map(async o=>{let s=`${o.serverId} [${o.layer}] command ${JSON.stringify(o.config.command)}`,i=e.workspace,l=new $({serverId:o.serverId,rootUri:i?e.cwd:Cr.file(e.cwd).toString(),...i&&{ownerTransport:{start:a(c=>i.start(c.command,c.env,c.signal),"start"),toServerUri:a(c=>i.toNativeUri(c),"toServerUri"),fromServerUri:a(c=>i.fromNativeUri(c),"fromServerUri")}},command:o.config.command,env:Er(e.env,o.config.env),...o.config.initializationOptions&&{initOptions:o.config.initializationOptions},...o.config.settings&&{settings:o.config.settings},...o.config.timeoutMs&&{timeoutMs:o.config.timeoutMs}});try{return await l.start(e.signal),{status:"pass",message:`${s}: initialized`,detail:o.sourcePath}}catch(c){return{status:"fail",message:`${s}: ${c instanceof Error?c.message:String(c)}`,detail:o.sourcePath}}finally{await l.shutdown()}}))}catch(t){return e.signal?.throwIfAborted(),[{status:"fail",message:t instanceof Error?t.message:String(t)}]}}})}};async function kr(n){try{let e=await I.fromPackageDir(n.cwd,At(n)),t=[],r=new Map;for(let[o,s]of n.detectedLanguages){let i=s.flatMap(l=>e.resolve(l)).find(l=>l.languageId===o);i!==void 0&&(t.push({kind:"lsp",languageId:o,toolId:i.serverId}),await He(n,i.config)||r.set(i.serverId,{id:`lsp-${i.serverId}-unavailable`,message:`Configured language server ${i.serverId} cannot run ${JSON.stringify(i.config.command)}`}))}return{selections:t,actions:[...r.values()]}}catch(e){return n.signal?.throwIfAborted(),{actions:[{id:"lsp-config-invalid",message:`Language server configuration cannot load: ${e instanceof Error?e.message:String(e)}`}]}}}a(kr,"inspectLspSetup");function At(n){let e=n.workspace;return{...ze(n),recipeEvidence:e?t=>e.evidence(t,n.signal):void 0}}a(At,"lspOptions");function xr(n,e){let t=new Map;for(let r of e){let o=n.resolve(r)[0];o!==void 0&&!t.has(o.serverId)&&t.set(o.serverId,o)}return[...t.values()]}a(xr,"applicableServers");function Er(n,e){return Object.fromEntries(Object.entries({...n,...e}).filter(t=>t[1]!==void 0))}a(Er,"definedEnvironment");import jt from"node:path";function Tt(n,e){return{id:"symbols",supportsResultScope:!0,readResources:a(t=>t.query.startsWith("symbols:")?void 0:[],"readResources"),toScriptData(t){return t.data},async tryResolve(t,r){if(!t.query.startsWith("symbols:"))return{kind:"not-handled"};let o=t.query.slice(8).trim();if(o.length===0)return{kind:"failed",error:new Error("symbols: query must not be empty")};let s=r.scope,i=new Map;if(s!==void 0){await F(s,r.signal);for(let u of s.targets){let m=await n(r.cwd,u.source,r.signal),y=i.get(m)??[];y.push(u),i.set(m,y)}}else i.set(await n(r.cwd,t.path,r.signal),[]);let l=t.limit??100,c=a(async u=>{let m=[],y=s?.complete??!0;for(let[f,h]of i){let w=await we(o,f.workspaceRoot,l,u,{...t,...s===void 0?{}:{resultScope:{targets:h,complete:s.complete}}},f);m.push(...w.hits),y=y&&w.complete}return s!==void 0&&await F(s,u),{hits:m.slice(0,l),complete:y&&m.length<=l}},"collect"),p=await c(r.signal),d=await e({request:t,matches:p.hits,complete:p.complete,refresh:a(async u=>{let m=await c(u);return{matches:m.hits,complete:m.complete}},"refresh")},r),g=it(p.hits,p.complete,d.id,d);return{kind:"resolved",payload:{query:o,sessionId:d.id,hits:p.hits,complete:p.complete,navigation:t.navigation,data:{...g,matches:g.matches.map((u,m)=>({...u,role:p.hits[m]?.role,symbol:p.hits[m]?.symbol}))}}}},renderResult(t,r,o){let s=t.details;return ot(s.hits,s.complete,o,r.expanded,s.cwd,s.navigation==="references"?["LSP reference navigation \xB7 may leave input scope"]:[],s.hits.map(i=>`${i.role} ${i.symbol.name}`))},format(t,r){let o=t,s=o.navigation==="references"?"LSP reference navigation (may leave input scope)":"LSP symbols inside scope",i=o.hits.length===0?["No symbols found."]:o.hits.slice(0,100).map((l,c)=>`SEARCH#${o.sessionId}:${c+1}:match ${l.source.startsWith("ssh://")?l.source:jt.relative(r.cwd,l.source)}:${l.lineNumber}:${l.startColumn+1} ${l.role} ${l.symbol.name} \xB7 declared at ${l.symbol.source.startsWith("ssh://")?l.symbol.source:jt.relative(r.cwd,l.symbol.source)}:${l.symbol.range.startLine}:${l.symbol.range.startColumn+1}`);return o.complete&&o.hits.length&&i.unshift(`SEARCH#${o.sessionId}:all:match selects all exact symbol matches.`),o.hits.length>100&&i.push("Preview shortened; full source targets retained."),{content:[{type:"text",text:[s,...i].join(`
|
|
8
|
+
`)}],details:{...o,cwd:r.cwd}}}}}a(Tt,"createLspSearchResolver");function Ot(n){return{id:"lsp-declaration-target",async tryResolve(e,t){let r=q(e,"symbol");if(r===void 0||e.endsWith("#name"))return{kind:"not-handled"};if(r.selector===void 0)return{kind:"rejected",rejection:{code:"invalid",reason:"Use symbol:<file>#<selector> to choose one declaration"}};try{let o=await yt(await n(t.cwd,E(r.path,t.cwd),t.signal),E(r.path,t.cwd),r.selector,t.cwd,t.signal);return{kind:"resolved",targets:[{source:o.source,expectedContent:o.content,ranges:[{start:{lineNumber:o.range.start.line+1,column:o.range.start.character},end:{lineNumber:o.range.end.line+1,column:o.range.end.character}}]}]}}catch(o){return{kind:"failed",error:new Error(`${o instanceof Error?o.message:String(o)} Read the physical file and use explicit text anchors if declaration resolution is unavailable.`,{cause:o})}}}}}a(Ot,"createDeclarationTargets");import{fileURLToPath as Ir}from"node:url";function Mt(n,e){if(n===null)throw new Error("The language server did not provide rename edits. No text fallback was applied.");let t=new Map(Object.entries(n.changes??{}));for(let r of n.documentChanges??[]){if(!("textDocument"in r)||!("edits"in r))throw new Error("Rename returned an unsupported file operation. No edits applied.");if(r.textDocument.version!=null&&r.textDocument.version!==e.documentVersion(r.textDocument.uri))throw new Error("Rename refers to an unavailable document revision. No edits applied.");if(t.has(r.textDocument.uri))throw new Error("Rename returned duplicate document edits.");t.set(r.textDocument.uri,r.edits)}return t}a(Mt,"renameEntries");function $t(n,e){let t=n.split(`
|
|
9
|
+
`),r=t[e.line];if(!Number.isInteger(e.line)||e.line<0||r===void 0||!Number.isInteger(e.character)||e.character<0||e.character>r.replace(/\r$/u,"").length)throw new Error("The language server returned an invalid text position.");return t.slice(0,e.line).reduce((o,s)=>o+s.length+1,0)+e.character}a($t,"offset");async function Wt(n,e){let t=n.input;if(typeof t.path!="string"||!t.path.startsWith("symbol:")||!t.path.endsWith("#name"))return;if(typeof t.text!="string"||t.text.trim()===""||t.start!==void 0||t.end!==void 0)throw new Error("Rename needs a symbol #name path and a non-empty new name in text, without start/end.");let r=q(t.path.slice(0,-5),"symbol");if(r?.selector===void 0)throw new Error("Rename needs an exact symbol selector before #name.");let o=E(r.path,n.cwd),s=await e(n.cwd,o,n.signal),i=await wt(s,o,r.selector,n.cwd,n.signal);await fe(i.client,i.uri,n.signal);let l=Mt(await ie(i.client,i.uri,i.position,t.text),i.client),c=new Map;for(let g of new Set([i.uri,...l.keys()])){n.signal?.throwIfAborted();let u=k(g,i.client.rootUri);if(u!==g)throw new Error("Rename returned a non-canonical participant. No edits applied.");let m=u.startsWith("ssh://")?u:Ir(u),y=await s.readSourceSnapshot(m,n.signal);if(m===o&&y.content!==i.content)throw new Error("The rename source changed. Read the symbol again before retrying.");let f=await s.openFile(m,n.cwd,"symbols",n.signal);if(f?.client!==i.client||f.uri!==g)throw new Error("A rename participant has a different language server owner. No edits applied.");if(i.client.documentContent(g)!==y.content)throw new Error("A rename participant changed during synchronization. No edits applied.");c.set(g,{file:m,...y})}let p=Mt(await ie(i.client,i.uri,i.position,t.text),i.client);n.signal?.throwIfAborted();for(let[g,u]of c){n.signal?.throwIfAborted();let m=await s.readSourceSnapshot(u.file,n.signal);if(u.version!==m.version||i.client.documentContent(g)!==u.content)throw new Error("A rename participant changed during the server request. No edits applied.")}let d=[];for(let[g,u]of p){let m=c.get(g);if(!m)throw new Error("Rename discovered a new participant after preflight. No edits applied.");d.push({source:m.file,expectedContent:m.content,changes:u.map(y=>({from:$t(m.content,y.range.start),to:$t(m.content,y.range.end),insert:y.newText}))})}return{...n,editPlan:{files:d},metadata:{...n.metadata,semanticEdit:{mode:"lsp-rename",server:i.client.serverId,referencesUpdated:!0},diffStatuses:[{text:"Renamed through LSP",tone:"success"}]}}}a(Wt,"prepareSymbolRename");var Ut=Xe({kind:"code-view",label:"LSP"});async function Ar(n){await jr(n)}a(Ar,"registerLsp");async function jr(n,e){let t=new Map,r=!1,o=a(async(d,g=!1,u)=>{if(u?.throwIfAborted(),r)throw new Error("LSP session has ended");let m=JSON.stringify([d,g]),y=t.get(m);if(y?.controller.signal.aborted)return await A(y.promise.catch(()=>{}),u),t.get(m)===y&&t.delete(m),o(d,g,u);if(!y){y=new H(async h=>{let w=e?await e.loadRegistry(d,g,h):await Tr(d,g,h);if(h.throwIfAborted(),r)throw new Error("LSP session has ended");return W.init(w,e?.workspace(d))});let f=y;t.set(m,f),f.promise.catch(()=>{t.get(m)===f&&t.delete(m)})}return y.wait(u)},"managerFor"),s=a(async(d,g,u)=>{if(u?.throwIfAborted(),e)return e.resolveProject(d,g,u);let m=await We(g,d,"lsp-servers",V,u);return u?.throwIfAborted(),m===void 0?void 0:{cwd:m,external:m!==Dr.resolve(g)}},"resolveLspProject"),i=a(async(d,g,u)=>{if(u?.throwIfAborted(),!g)return o(d,!1,u);let m=await s(g,d,u);if(u?.throwIfAborted(),!m)throw new Error("No language server project for this source");return o(m.cwd,m.external,u)},"managerForFile"),l={...ke(i),name:"pi-agent-ide-lsp",priority:200},c={protocol:je,apiVersion:5,id:"lsp",setup(d){d.addTool(l),d.addDiagnosticSource(Et(o,s))}};n.on("session_shutdown",async()=>{r=!0,await Promise.allSettled([...t.values()].map(async d=>{d.settled||d.controller.abort(new Error("LSP session has ended")),await(await d.promise).shutdownAll()})),t.clear()});let p={protocol:Be,apiVersion:Je,id:"lsp",setup(d){d.addResolver({resolver:_t(i),renderResult:Ut}),d.addResolver({resolver:Ct(i),renderResult:Ut}),d.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler:Ae()}),d.describe({path:"symbol:<file>#<selector> \u2014 declaration source, e.g. symbol:src/catalog.ts#Catalog/find. graph:<file> \u2014 top-level declarations, references and calls; members include selectors. graph:<file>#<selector> \u2014 references and incoming/outgoing calls for that declaration or member."})}};await Promise.all([Oe(n,c),et(n,{protocol:Qe,apiVersion:Ye,id:"lsp-declarations",setup(d){d.onDidEdit(async g=>{await Promise.all([...t.values()].filter(u=>u.settled).map(u=>u.promise.then(m=>m.syncEditedSource(g.source,g.after.content),()=>{})))}),d.addAnchorResolver({kind:Ze,type:"auxiliary",resolver:{id:"lsp-declaration",description:"symbol:<file>#<selector> selects an exact declaration for text fallback editing; imports and references are not rewritten.",renderFull:a(g=>g,"renderFull"),renderCompact:a(g=>g,"renderCompact"),tryResolve:a(()=>Promise.resolve({kind:"not-handled"}),"tryResolve")},resources:Ot(i),describeInPrompt:!1});for(let g of["copy","move","delete","replace"])d.tool(g).describe("Use symbol:<file>#<selector> as path to select one exact declaration without start/end. Use parent/child for ambiguous names. For declaration-text Copy/Move, supply an explicit target and destination anchor. This text fallback leaves imports and references unchanged; it is not semantic rename."+(g==="replace"?" Use symbol:<file>#<selector>#name with text containing the new name for native LSP rename across references. Omit start/end. A failed server rename never falls back to identifier text replacement.":"")),d.tool(g).addHandler({stage:"text-pre-edit",async handler(u){if(g==="replace"){let f=await Wt(u,i);if(f!==void 0)return f}let m=u.input;if(![m.path,m.start,m.end,m.target,m.targetStart,m.targetEnd].some(f=>typeof f=="string"&&f.startsWith("symbol:")))return u;if((g==="copy"||g==="move")&&typeof m.target!="string")throw new Error("Copying or moving a symbol requires an explicit target file and destination anchor.");return{...u,metadata:{...u.metadata,semanticEdit:{mode:"declaration-text",referencesUpdated:!1,importsUpdated:!1},diffStatuses:[{text:"Text fallback: imports and references unchanged",tone:"warning"}]}}}});d.tool("insert").describe("Symbol targets are unsupported for insert. Read the declaration and select an ordinary text line anchor instead."),d.tool("insert").addHandler({stage:"text-pre-edit",handler(g){let u=g.input;if([u.path,u.anchor].some(m=>typeof m=="string"&&m.startsWith("symbol:")))throw new Error("Semantic insert is not supported. Read the declaration and use an explicit text line anchor instead.");return g}})}}),Ke(n,p),Ge(n,Dt),nt(n,{protocol:tt,apiVersion:rt,id:"symbols",setup(d){d.addResolver({resolver:Tt(i,d.registerSelection)}),d.describe('Use `symbols:<query>` to locate named workspace declarations and references through configured language servers when the file is unknown. Results contain exact source targets, roles, and originating symbols. Default search stays within path. Use navigation: "references" explicitly to follow symbols represented inside path to references outside it, within the workspace.')}})])}a(jr,"registerLspWithOwner");async function Tr(n,e,t){let r=e?n:process.env.PI_AGENT_IDE_CONFIG_DIR??n;return I.fromPackageDir(r,{signal:t,includeGlobal:!e,requireBuiltInEvidence:e,recipes:V})}a(Tr,"loadRegistry");export{V as a,I as b,Ar as c,jr as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as p,c as y,d as w,e as g,f as b,g as l}from"./chunk-EY65TFHJ.js";import{a as c}from"./chunk-EI7MMDWY.js";import{spawn as v}from"node:child_process";import{PassThrough as S}from"node:stream";import{Type as r}from"typebox";import{Value as L}from"typebox/value";var I=r.Union([r.Object({kind:r.Literal("ready"),pid:r.Integer({minimum:1}),identity:r.Optional(r.String({pattern:"^[a-f0-9-]+:[0-9]+$"}))}),r.Object({kind:r.Literal("ack"),id:r.Integer({minimum:1})}),r.Object({kind:r.Union([r.Literal("stdout"),r.Literal("stderr")]),bytes:r.String({maxLength:32768})}),r.Object({kind:r.Literal("exit"),exitCode:r.Integer()}),r.Object({kind:r.Literal("error"),code:r.String({pattern:"^[A-Z][A-Z0-9_]*$"}),effect:r.Union([r.Literal("not-applied"),r.Literal("unknown")])})]);async function R(a,e,t,s,i={}){y(a),i.pty&&E(i.pty.cols,i.pty.rows);let d=p(a.id,s).source,n=i.timeoutMs??3e4;if(!Number.isFinite(n)||n<=0)throw new TypeError("SSH startup deadline must be positive");i.signal?.throwIfAborted();let o=await w(new URL("./ssh-channel-worker.py",new URL("../src/backend/ssh-channel.ts",import.meta.url).href));i.signal?.throwIfAborted();let u=JSON.stringify({command:e,args:t,cwd:s,...i.pty?{pty:i.pty}:{}});if(Buffer.byteLength(u)>48*1024*1024)throw new l("FRAME_LIMIT",d,"not-applied");let h=v("ssh",g(a,o),{stdio:"pipe"}),f=new m(h,d,i.pty!==void 0,i.signal),P=setTimeout(()=>f.cancel("TIMEOUT"),n);try{return await f.sendInitial(u),await f.ready,f}finally{clearTimeout(P)}}c(R,"startSshProcess");function E(a,e){if(![a,e].every(t=>Number.isSafeInteger(t)&&t>0&&t<=1e3))throw new TypeError("PTY dimensions must be integers between 1 and 1000")}c(E,"validateDimensions");var m=class{constructor(e,t,s,i){this.child=e;this.source=t;this.pty=s;this.ready=new Promise((n,o)=>{this.#c=n,this.#l=o}),this.completion=new Promise((n,o)=>{this.#u=n,this.#f=o}),this.ready.catch(()=>{}),this.completion.catch(()=>{}),e.stdout.on("data",n=>{this.#e=Buffer.concat([this.#e,n]),this.parse()}),e.stderr.on("data",n=>{this.#d.length<16384&&(this.#d+=n.toString())}),e.stdin.on("error",()=>{}),e.once("error",()=>{this.#i="DEPENDENCY_UNAVAILABLE"});let d=c(()=>this.cancel("CANCELLED"),"abort");i?.addEventListener("abort",d,{once:!0}),e.once("close",n=>{this.#r=!0,this.#S=n,clearTimeout(this.#E),i?.removeEventListener("abort",d);let o=this.#i??(n!==0?b(n,this.#d):this.#s===void 0?"TRANSPORT_FAILED":void 0);this.stdout.end(),this.stderr.end();let u=this.error(o??"INPUT_CLOSED");for(let h of this.#t.values())h.reject(u);if(this.#t.clear(),o){let h=this.error(o);this.#l(h),this.#f(h)}else this.#s!==void 0&&this.#u({exitCode:this.#s})});for(let n of[this.stdout,this.stderr]){let o=c(()=>{this.#n.delete(n),this.parse(),this.#n.size===0&&e.stdout.resume()},"resume");n.on("drain",o),n.on("close",o)}i?.aborted&&d()}static{c(this,"ProcessChannel")}stdout=new S({highWaterMark:65536});stderr=new S({highWaterMark:65536});completion;ready;#t=new Map;#n=new Set;#c;#l;#u;#f;#e=Buffer.alloc(0);#d="";#i;#m;#p=!1;#y=!1;#w=0;#g;#r=!1;#b=!1;#o=!1;#s;#S;#P=0;#a=0;#h=Promise.resolve();#E;get pid(){return this.#w}get identity(){return this.#g}async sendInitial(e){this.#p=!0,await this.sendLine(e)}async write(e){if(this.#r||this.#b||this.#o)throw this.error("INPUT_CLOSED");if(this.#a+e.length>1024*1024)throw this.error("INPUT_LIMIT");let t=Buffer.from(e);this.#a+=t.length;let s=this.#h.then(async()=>{for(let i=0;i<t.length;i+=16384){if(this.#o||this.#r)throw this.error("INPUT_CLOSED");await this.sendAcknowledged({kind:"input",bytes:t.subarray(i,i+16384).toString("base64")})}});this.#h=s.catch(()=>{});try{await s}finally{this.#a-=t.length}}async end(){if(this.pty)throw new l("PTY_INPUT_NOT_CLOSABLE",this.source,"not-applied");this.#b=!0,await this.#h,await this.send({kind:"end"})}async resize(e,t){if(!this.pty)throw new l("PTY_REQUIRED",this.source,"not-applied");E(e,t),await this.sendAcknowledged({kind:"resize",cols:e,rows:t})}stop(){return!this.#r&&!this.#o&&(this.#o=!0,this.send({kind:"stop"}).catch(()=>{}),this.#E=setTimeout(()=>{this.#i??="TRANSPORT_FAILED",this.child.kill("SIGKILL")},5e3),this.child.stdout.resume(),this.stdout.resume(),this.stderr.resume()),this.completion.catch(e=>{if(this.#i==="CANCELLED"&&this.#S===0&&this.#s!==void 0)return{exitCode:this.#s};throw e})}cancel(e){this.#r||(this.#i??=e,this.stop().catch(()=>{}))}error(e){let t=["HOST_KEY_FAILED","AUTH_FAILED","DEPENDENCY_UNAVAILABLE"].includes(e),s=this.#m??(!this.#p||t?"not-applied":"unknown");return new l(e,this.source,s)}async sendAcknowledged(e){let t=++this.#P,s=new Promise((i,d)=>{this.#t.set(t,{resolve:i,reject:d})});s.catch(()=>{});try{await this.send({...e,id:t}),await s}finally{this.#t.delete(t)}}async send(e){await this.sendLine(JSON.stringify(e))}sendLine(e){return this.#r?Promise.reject(this.error("INPUT_CLOSED")):new Promise((t,s)=>{this.child.stdin.write(`${e}
|
|
2
|
+
`,i=>{i?s(this.error("INPUT_CLOSED")):t()})})}parse(){for(;this.#n.size===0;){let e=this.#e.indexOf(10);if(e<0){this.#e.length>65536&&this.cancel("FRAME_LIMIT");return}if(e>65536){this.cancel("FRAME_LIMIT");return}let t=this.#e.subarray(0,e);this.#e=this.#e.subarray(e+1);let s;try{s=JSON.parse(t.toString("utf8"))}catch{this.cancel("INVALID_RESPONSE");return}if(!L.Check(I,s)){this.cancel("INVALID_RESPONSE");return}this.receive(s)}this.child.stdout.pause()}receive(e){if(e.kind==="ready"){if(this.#y){this.cancel("INVALID_RESPONSE");return}this.#y=!0,this.#w=e.pid,this.#g=e.identity,this.#c()}else if(e.kind==="ack"){let t=this.#t.get(e.id);if(!t){this.cancel("INVALID_RESPONSE");return}this.#t.delete(e.id),t.resolve()}else if(e.kind==="exit")this.#s=e.exitCode;else if(e.kind==="error")this.#i=e.code,this.#m=e.effect;else{let t=Buffer.from(e.bytes,"base64");if(t.toString("base64")!==e.bytes){this.cancel("INVALID_RESPONSE");return}let s=e.kind==="stdout"?this.stdout:this.stderr;!s.destroyed&&!s.write(t)&&this.#n.add(s)}}};export{R as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-XZDOVPRC.js";import"./chunk-7TJ6DWW3.js";import"./chunk-EY65TFHJ.js";import"./chunk-R5XJSEOE.js";import"./chunk-EI7MMDWY.js";export{a as runOwnedSshCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as k,e as f}from"./chunk-SSWUUBIR.js";import{a as v,b}from"./chunk-PS2B6THP.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{pathToFileURL as T}from"node:url";function $(e,n,t,o,i,a=[],l=[]){let c=a.map(r=>({kind:"note",text:r}));c.push(...b(e.flatMap(r=>{let p=h.isAbsolute(r.source),D=p&&i?h.relative(i,r.source)||h.basename(r.source):r.source,z=p?T(r.source).href:/^https?:/iu.test(r.source)?r.source:void 0,x=r.endLineNumber??r.lineNumber;return(x===r.lineNumber?[r.lineText]:[r.lineText,...r.matchedText.split(/\r\n|\n|\r/u).slice(1)]).slice(0,20).map((R,m)=>({source:r.source,label:D,...z===void 0?{}:{link:z},...p?{}:{badge:/^https?:/iu.test(r.source)?"WEB":"SH"},lineNumber:r.lineNumber+m,text:R,ranges:[{from:m?0:r.startColumn,to:r.lineNumber+m===x?r.endColumn:R.length}]}))}))),e.length||c.push({kind:"note",text:"No matches found"}),e.some(r=>(r.endLineNumber??r.lineNumber)-r.lineNumber>=20)&&c.push({kind:"note",text:"\u2026 source preview shortened"}),c.push(...l.map(r=>({kind:"note",text:r,expandedOnly:!0})));let u=`${e.length}${n?"":"+"}`,y=new Set(e.map(r=>r.source)),F=e.every(r=>h.isAbsolute(r.source));return new v({summary:`${u} ${e.length===1?"match":"matches"} in ${y.size} ${F?y.size===1?"file":"files":y.size===1?"source":"sources"}`,rows:c},t,o)}s($,"renderSearchMatches");function P(e,n){return e.targets.some(t=>t.source===n.source&&t.ranges.some(o=>(o.start.lineNumber<n.lineNumber||o.start.lineNumber===n.lineNumber&&o.start.column<=n.startColumn)&&(o.end.lineNumber>(n.endLineNumber??n.lineNumber)||o.end.lineNumber===(n.endLineNumber??n.lineNumber)&&o.end.column>=n.endColumn)))}s(P,"containsSearchMatch");import{Value as N}from"typebox/value";var d={candidates:5,previewMatches:3,identifiers:2e4,identifierLength:80,vocabularyBytes:8*1024*1024,matchesPerCandidate:200,verificationBytes:4*1024*1024,timeoutMs:2e3};function I(e){return N.Check(k,e)}s(I,"isFuzzyResultData");function g(e){return e.length>=5&&e.length<=d.identifierLength&&/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)&&/[A-Za-z]/u.test(e)}s(g,"isFuzzyQuery");var S=class{static{s(this,"FuzzyVocabulary")}names=new Set;bytes=0;limited=!1;account(n){return this.bytes+=n,this.bytes>d.vocabularyBytes&&(this.limited=!0),!this.limited}add(n){if(!(this.limited||!g(n)||this.names.has(n))){if(this.names.size===d.identifiers){this.limited=!0;return}this.names.add(n)}}addText(n){if(this.account(Buffer.byteLength(n))){for(let t of n.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/gu))if(this.add(t[0]),this.limited)break}}};function w(e){return e.replace(/([A-Z]+)([A-Z][a-z])/gu,"$1 $2").replace(/([a-z0-9])([A-Z])/gu,"$1 $2").split(/[^A-Za-z0-9]+/u).filter(Boolean).map(n=>n.toLowerCase())}s(w,"splitName");function C(e,n){return e.length===n.length&&e.every((t,o)=>t===n[o])}s(C,"same");function L(e,n){if(e.length<5||n.length<5||Math.abs(e.length-n.length)>1||/\d/u.test(e+n))return!1;let t=0;for(;t<Math.min(e.length,n.length)&&e[t]===n[t];)t++;if(e.length===n.length)return e.slice(t+1)===n.slice(t+1)||e[t]===n[t+1]&&e[t+1]===n[t]&&e.slice(t+2)===n.slice(t+2);let o=e.length<n.length?e:n,i=e.length<n.length?n:e;return o.slice(t)===i.slice(t+1)}s(L,"oneTypo");function M(e,n){if(e.join("")===n.join(""))return{kind:"normalized",reason:"same spelling with different case or separators"};let t=e.length<n.length?e:n,o=e.length<n.length?n:e;if(o.length===t.length+1&&t.length>=2&&t.every(l=>l.length>=3)){let l=C(t,o.slice(1)),c=C(t,o.slice(0,-1));if(l||c)return{kind:"component",reason:`${e.length>n.length?"remove":"add"} ${l?"leading":"trailing"} component '${l?o[0]:o.at(-1)}'`}}if(e.length!==n.length)return;let i=e.flatMap((l,c)=>{let u=n[c];return u!==void 0&&l!==u?[{word:l,other:u}]:[]}),a=i[0];if(!(i.length!==1||!a||!L(a.word,a.other)))return{kind:"typo",reason:`one character edit: '${a.word}' \u2192 '${a.other}'`}}s(M,"relation");var A={normalized:0,component:1,typo:2};function E(e,n){if(!g(e))return[];let t=w(e);if(t.length===0)return[];let o=[];for(let i of new Set(n)){if(i===e||!g(i))continue;let a=M(t,w(i));a&&o.push({identifier:i,...a})}return o.sort((i,a)=>A[i.kind]-A[a.kind]||(i.identifier<a.identifier?-1:i.identifier>a.identifier?1:0)).slice(0,d.candidates)}s(E,"rankFuzzyIdentifiers");function _(e,n,t){return{identifier:e.identifier,kind:e.kind,reason:e.reason,matchCount:e.matches.length,fileCount:new Set(e.matches.map(o=>o.source)).size,selection:{...f(e.matches.slice(0,d.previewMatches),e.complete,n,t),truncated:e.matches.length>d.previewMatches}}}s(_,"fuzzyCandidateData");function O(e){let n=e.selection.complete?"":"+",t=e.selection.all?.line??e.selection.matches[0]?.references?.line,o=e.selection.matches[0],i=t??o?.source;return[`Possible name: ${e.identifier} (${e.reason})`,`${e.matchCount}${n} ${e.matchCount===1&&e.selection.complete?"match":"matches"} in ${e.fileCount}${n} ${e.fileCount===1&&e.selection.complete?"file":"files"}`,`Exact alternative: ${JSON.stringify(e.identifier)} (case-sensitive, whole identifier)`,...e.selection.complete?[]:["Capture limit reached; no complete all reference. Inspect the returned location; do not treat this candidate as a complete match set."],...i?[`Read: ${i}${t||!o?"":` \xB7 line ${o.range.startLine}`}`]:[]].join(`
|
|
2
|
+
`)}s(O,"formatFuzzyCandidate");export{$ as a,P as b,d as c,I as d,g as e,S as f,E as g,_ as h,O as i};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as X}from"./chunk-PLKYHUNT.js";import{m as k}from"./chunk-ZPT5D4VP.js";import{a as w}from"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import{createHash as Ae}from"node:crypto";import{open as Ee,readFile as Ne}from"node:fs/promises";import x from"node:path";import{spawn as be}from"node:child_process";import{stat as xe}from"node:fs/promises";import E from"node:path";import{createInterface as we}from"node:readline";import{existsSync as pe}from"node:fs";import me from"node:os";import Y from"node:path";function Z(e=process.env.PI_CODING_AGENT_DIR??Y.join(me.homedir(),".pi","agent"),t=process.platform){let r=Y.join(e,"bin",t==="win32"?"rg.exe":"rg");return pe(r)?r:"rg"}l(Z,"resolveRipgrepExecutable");function D(e,t=!1){let r=$(e);return I(r)?W(P(new B(e,r).parse(),t)):t?e:Q(e)}l(D,"compileSearchQuery");function J(e,t=!1){let r=$(e);return I(r)?P(new B(e,r).parse(),t):void 0}l(J,"compileSearchCondition");function A(e,t){if(e.kind==="term")return t(e.value);let r=A(e.left,t);if(e.kind==="or")return r||A(e.right,t);let n=A(e.right,t);return r&&(e.kind==="not"?!n:n)}l(A,"satisfiesSearchCondition");function te(e){if(I($(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map(Q).join("|")})`:void 0}l(te,"compileSearchFallbackQuery");function I(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}l(I,"containsBooleanSyntax");var B=class{static{l(this,"BooleanQueryParser")}#t;#n;#i=0;constructor(t,r){this.#t=t,this.#n=r}parse(){let t=this.#a(),r=this.#e();if(r.type!=="end"){let n=r.type==="right"?"unexpected ')'.":`unexpected ${ye(r)}.`;throw R(r.offset,n)}return t}#a(){let t=this.#r();for(;this.#e().type==="or";){let r=this.#o(),n=this.#s(`after ${r.value}`);t={kind:"or",left:t,right:this.#c(n)}}return t}#r(){return this.#c(this.#s())}#c(t){let r=t;for(;;){let n=this.#e();if(n.type==="and"||n.type==="not"){this.#o();let o=this.#s(`after ${n.value}`);r={kind:n.type,left:r,right:o};continue}if(n.type==="term"||n.type==="left"){r={kind:"and",left:r,right:this.#s()};continue}return r}}#s(t){let r=this.#e();if(r.type==="term")return this.#o(),{kind:"term",value:r.value,quoted:r.quoted};if(r.type==="left"){if(this.#o(),this.#e().type==="right"||this.#e().type==="end")throw R(this.#e().offset,"expected a term after '('.");let o=this.#a();if(this.#e().type!=="right")throw R(this.#e().offset,"expected ')'.");return this.#o(),o}if(t===void 0&&(r.type==="and"||r.type==="or"||r.type==="not"))throw R(r.offset,`expected a term before ${r.value}.`);let n=t===void 0?"":` ${t}`;throw R(r.offset,`expected a term${n}.`)}#e(){return this.#n[this.#i]??{type:"end",value:"",offset:this.#t.length}}#o(){let t=this.#e();return this.#i+=1,t}};function $(e){let t=[],r=0;for(;r<e.length;){let n=e.charAt(r);if(/\s/u.test(n)){r+=1;continue}if(n==="("&&ge(e,r)){t.push({type:"left",value:n,offset:r}),r+=1;continue}if(n===")"){t.push({type:"right",value:n,offset:r}),r+=1;continue}if(ee(e,r)){let s=e.charAt(r+1)==="|"?2:1;t.push({type:"or",value:e.slice(r,r+s),offset:r}),r+=s;continue}if(n==="'"||n==='"'){let s=r,u=n,i="";for(r+=1;r<e.length&&e.charAt(r)!==u;)e.charAt(r)==="\\"&&(e.charAt(r+1)===u||e.charAt(r+1)==="\\")&&(r+=1),i+=e.charAt(r++);if(r>=e.length)throw R(s,`unterminated ${u==="'"?"single":"double"}-quoted term.`);if(r+=1,i.length===0)throw R(s,"quoted terms must not be empty.");t.push({type:"term",value:i,offset:s,quoted:!0});continue}let o=r;for(;r<e.length;){let s=e.charAt(r);if(/\s/u.test(s)||s===")"||ee(e,r))break;s==="\\"&&r+1<e.length?r+=2:s==="["||s==="("?r=z(e,r)??r+1:r+=1}let a=e.slice(o,r);t.push({type:Se(a),value:a,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}l($,"tokenize");function ee(e,t){return e.charAt(t)==="|"&&(e.charAt(t+1)==="|"||/\s/u.test(e.charAt(t-1))&&/\s/u.test(e.charAt(t+1)))}l(ee,"isBooleanPipe");function z(e,t){let r=e.charAt(t)==="["?"]":")",n=t+1;for(;n<e.length;){let o=e.charAt(n);if(o==="\\")n+=2;else{if(o===r)return n+1;if(r===")"&&(o==="("||o==="[")){let a=z(e,n);if(a===void 0)return;n=a}else n+=1}}}l(z,"regexBlockEnd");function ge(e,t){let r=z(e,t);if(r===void 0)return!0;let n=e.slice(t+1,r-1);return n.trim().length===0?!0:I($(n))}l(ge,"isBooleanGroup");function Se(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}l(Se,"operatorType");function ye(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}l(ye,"quoteToken");function R(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}l(R,"syntaxError");function P(e,t){return e.kind==="term"?{kind:"term",value:t&&!e.quoted?e.value:Q(e.value)}:{kind:e.kind,left:P(e.left,t),right:P(e.right,t)}}l(P,"compileTerms");function W(e){if(e.kind==="term")return e.value;let t=W(e.left);return e.kind==="not"?t:`(?:${t}|${W(e.right)})`}l(W,"matchPattern");function Q(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}l(Q,"escapeRegex");async function j(e,t,r,n,o){if(e.query.length===0)throw new Error("Search query must not be empty.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");return e.condition!==void 0?Re(e,t,r,o):oe(e,t,r,void 0,n,o)}l(j,"searchText");async function Te(e,t,r,n){if(r===void 0&&(e.path?.includes("://")||t.includes("://")))throw new Error("No search environment owns this scope.");let o=r?.resolve(t,ne(e.path??"."))??E.resolve(t,ne(e.path??".")),a=r===void 0?(await xe(o)).isDirectory():await r.isDirectory(o,n);return{cwd:a?o:r?.dirname(o)??E.dirname(o),target:a?".":`./${r?.basename(o)??E.basename(o)}`,arguments:["--no-config","--no-ignore-parent","--color=never",...re(e.include).flatMap(s=>["--glob",s]),...re(e.exclude).flatMap(s=>["--glob",`!${s}`])]}}l(Te,"ripgrepScope");async function Ye(e,t,r,n){if(e.condition!==void 0)throw new Error("Boolean scoped search is not available yet.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");let o=await L(["--json","--no-config","--color=never","--with-filename","--line-number",...e.regex===!0?["--engine","auto"]:["--fixed-strings"],e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],"--",e.query,"-"],r,n,void 0,void 0,t.length===0?`
|
|
2
|
+
`:t);return t.length===0?{...o,matches:o.matches.filter(a=>a.lineNumber===1&&a.startColumn===0&&a.endColumn===0)}:o}l(Ye,"searchTextContent");async function oe(e,t,r,n,o,a){let s=await Te(e,t,a,r),u=s.cwd,i=["--json","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],...s.arguments,"--",e.query,s.target];if(e.regex!==!0)return L(["--fixed-strings",...i],u,r,n,o,void 0,a);try{return await L(["--engine","auto",...i],u,r,n,o,void 0,a)}catch(c){if(!ve(c))throw c instanceof Error&&/PCRE2 is not available|does not support PCRE2/iu.test(c.message)?new Error("This regex requires PCRE2. Install ripgrep with PCRE2 support or simplify the regex.",{cause:c}):c;try{return await L(["--engine","default",...i],u,r,n,o,void 0,a)}catch(d){throw r?.aborted?d:new AggregateError([c,d],"Regex exceeded the PCRE2 match limit and cannot run with the default engine. Narrow the search or simplify the regex.",{cause:d})}}}l(oe,"searchPattern");async function Re(e,t,r,n){let o=e.condition;if(o===void 0)throw new Error("Boolean search requires a line condition.");let a=new Set;function s(f){if(f.kind==="term"){a.add(f.value);return}s(f.left),s(f.right)}l(s,"collect"),s(o);let{condition:u,...i}=e,c=new Map,d=l(f=>JSON.stringify([f.source,f.lineNumber]),"lineKey");for(let f of a){r?.throwIfAborted();let S=new Set;await oe({...i,query:f,regex:!0,wholeWord:!1},t,r,(b,T)=>S.add(JSON.stringify([b,T])),void 0,n),c.set(f,S)}let h=await j(i,t,r,void 0,n),p=new Set,g=h.matches.filter(f=>{let S=d(f);return p.has(S)||!A(o,b=>c.get(b)?.has(S)===!0)?!1:(p.add(S),!0)});return{...h,matches:g}}l(Re,"searchBoolean");function L(e,t,r,n,o,a,s){return s!==void 0?ke(e,t,s,r,n,o):new Promise((u,i)=>{let c=be(Z(),e,{stdio:["pipe","pipe","pipe"],cwd:t}),d=0,h=!1;o!==void 0&&c.stdout.on("data",m=>{d+=m.length,d>o.bytes&&(h=!0,c.kill())});let p=we({input:c.stdout});c.stdin.on("error",()=>{}),c.stdin.end(a);let g=[],f="",S,b=l(()=>{c.kill()},"abort"),T=l(()=>{r?.removeEventListener("abort",b),p.close()},"cleanup");c.stderr.setEncoding("utf8"),c.stderr.on("data",m=>{f+=m}),p.on("line",m=>{if(!(h||S!==void 0||m.length===0))try{let y=JSON.parse(m);if(y.type!=="match")return;if(n!==void 0){let{path:M,line_number:V}=y.data;M.text!==void 0&&Number.isSafeInteger(V)&&n(E.resolve(t,M.text),V);return}for(let M of ie(y,t)){if(o!==void 0&&g.length===o.matches){h=!0,c.kill();break}g.push(M)}}catch(y){S=y,c.kill()}}),c.once("error",m=>{T(),i(m)}),c.once("close",m=>{if(T(),r?.aborted===!0){let y=new Error("Search was aborted.");y.name="AbortError",i(y);return}if(S!==void 0){i(new Error("Unable to parse ripgrep search output.",{cause:S}));return}if(!h&&m!==0&&m!==1){i(new Error(f.trim()||`ripgrep exited with code ${String(m)}.`));return}g.sort(ae),u({matches:g,complete:!h})}),r?.addEventListener("abort",b,{once:!0}),r?.aborted===!0&&b()})}l(L,"runRipgrep");async function ke(e,t,r,n,o,a){let s=[],u=new AbortController,i=l(()=>u.abort(n?.reason),"abort");n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i();let c=0,d={limited:!1};try{let h=await r.runLines(e,t,p=>{if(d.limited||!p.length)return;if(c+=Buffer.byteLength(p)+1,a!==void 0&&c>a.bytes){d.limited=!0,u.abort();return}let g=JSON.parse(p);if(g.type==="match"){if(o!==void 0){let f=g.data.path.text;f!==void 0&&Number.isSafeInteger(g.data.line_number)&&o(r.resolve(t,f),g.data.line_number);return}for(let f of ie(g,t,r)){if(a!==void 0&&s.length>=a.matches){d.limited=!0,u.abort();break}s.push(f)}}},u.signal);if(h.code!==0&&h.code!==1)throw new Error(h.stderr.trim()||"Ripgrep failed.")}catch(h){if(n?.throwIfAborted(),!d.limited)throw h}finally{n?.removeEventListener("abort",i)}return n?.throwIfAborted(),s.sort(ae),{matches:s,complete:!d.limited}}l(ke,"runOwnedRipgrep");function ve(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}l(ve,"isPcre2MatchLimitError");function ie(e,t,r){let n=e.data.path.text,o=e.data.lines.text;if(n===void 0||o===void 0||!Number.isSafeInteger(e.data.line_number))return[];let a=o.replace(/(?:\r\n|\n)$/u,""),s=Buffer.from(o),u=[];for(let i of e.data.submatches){if(i.start<0||i.end<i.start||i.end>s.length)continue;let c=s.subarray(0,i.start).toString("utf8").length,d=s.subarray(0,i.end).toString("utf8").length;u.push({source:r?.resolve(t,n)??E.resolve(t,n),lineNumber:e.data.line_number,startColumn:c,endColumn:d,matchedText:a.slice(c,d),lineText:a})}return u}l(ie,"matchesFromEvent");function re(e){if(e===void 0)return[];let t=[],r=0,n="";for(let o of e){if(o==="{"?r+=1:o==="}"&&(r=Math.max(0,r-1)),r===0&&(o===","||/\s/u.test(o))){n.length>0&&(t.push(n),n="");continue}n+=o}return n.length>0&&t.push(n),t}l(re,"splitGlobList");function ne(e){return e.startsWith("@")?e.slice(1):e}l(ne,"stripFilePrefix");function ae(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}l(ae,"compareMatches");function nt(e){let t=D(e.query),r=D(e.query,!0),n=te(e.query),o=[],a=J(e.query),s=J(e.query,!0);return(r!==t||JSON.stringify(a)!==JSON.stringify(s))&&o.push({query:r,mode:"regex",condition:s}),n!==void 0&&n!==t&&n!==r&&o.push({query:n,mode:"words"}),{...e,query:t,regex:!0,condition:a,fallbacks:o}}l(nt,"createSearchRecipe");async function G(e,t,r,n){let o=e.query,a=await j(e,t,r,void 0,n),s=[];for(let u of e.fallbacks??[]){if(a.matches.length>0||!a.complete)break;r?.throwIfAborted();try{a=await j({...e,query:u.query,regex:!0,condition:u.condition},t,r,void 0,n),o=u.query,s.push(u.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words. Use these matches as location hints; refine the query before editing.")}catch(i){if(u.mode!=="regex"||!Ce(i)||r?.aborted)throw i;s.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...a,query:o,notices:s}}l(G,"runSearchRecipe");function Ce(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}l(Ce,"isRegexSyntaxError");var Me=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,ue=4;function ft(e,t,r,n){return de(e,t,r,n).slice(0,ue)}l(ft,"createSearchSessionId");function de(e,t,r,n){let o=r===void 0?Oe(t.map(i=>i.source)):C(r),a=t.map(i=>({match:i,source:i.source.includes("://")?C(i.source):x.relative(o,x.resolve(i.source))})).sort((i,c)=>i.source.localeCompare(c.source)||K(i.match,c.match)).map(({match:i,source:c})=>[c,i.lineNumber,i.startColumn,i.endLineNumber??i.lineNumber,i.endColumn,i.matchedText,i.lineText]),{limit:s,...u}=he(n??{query:e,regex:!0},o);return Ae("sha256").update(JSON.stringify([e,o,u,a])).digest("hex").toUpperCase()}l(de,"createSearchSessionIdentity");function Be(e,t){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let r=ue;r<=e.length;r+=1){let n=e.slice(0,r);if(!t.has(n))return n}throw new Error("Could not allocate a unique search session id.")}l(Be,"allocateSearchSessionId");function he(e,t){return{query:e.query,path:je(t,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,limit:e.limit??50,regex:e.regex===!0,condition:e.condition,fallbacks:e.fallbacks??[]}}l(he,"normalizeRecipe");var F=class extends Error{static{l(this,"SearchSnapshotChangedError")}constructor(t){super(`Search result in ${t} changed before its anchors were registered.`),this.name="SearchSnapshotChangedError"}},se=class{constructor(t=de,r,n){this.createIdentity=t;this.resultTargets=r;this.readSource=n}static{l(this,"SearchSessionStore")}#t=new Map;#n=new Map;async register(t,r,n,o,a,s={query:t,regex:!0},u,i,c){let d=r.map(m=>({...m,source:C(m.source)})).sort(K),h=this.readSource,p=h===void 0?void 0:(m,y)=>h(m,o,y),g=await ce(d,a,i,c,p),f=this.createIdentity(t,d,o,s),b=this.#n.get(f)??Be(f,new Set(this.#t.keys())),T={id:b,query:t,matches:d,complete:n,contentBySource:g,read:p,...Pe(this.resultTargets,d,g,o,n,(m,y)=>_(m,y,c,p)),...i===void 0?{}:{snapshotByteBudget:i},recipe:s,environment:c,...u!==void 0&&{refresh:u},cwd:C(o)};return this.#n.set(f,b),this.#t.set(b,T),T}async registerIfCurrent(t,r,n,o,a,s,u,i,c){try{return await this.register(t,r,n,o,a,s,u,i,c)}catch(d){if(d instanceof F)return;throw d}}async observeAfterEdit(t,r){let n=new Set(t.flatMap(a=>{let s=typeof a=="string"?O(a):void 0;return s===void 0?[]:[s.id]})),o=[];for(let a of n){let s=this.#t.get(a);if(s===void 0)continue;let u={sessionId:a,query:s.recipe.originalQuery??s.query,scope:he(s.recipe,s.cwd)};try{let i=s.refresh===void 0?await G(s.recipe,s.cwd,r,s.environment):await s.refresh(r);o.push({...u,matches:i.matches.length,complete:i.complete,notices:i.notices})}catch(i){o.push({...u,error:i instanceof Error?i.message:String(i)})}}return o}anchorResolver(){return{id:"search",description:["`SEARCH#HASH:N:line` selects one result's full line; `SEARCH#HASH:N:match` selects its exact match.","`SEARCH#HASH:all:line` selects each unique containing line; `SEARCH#HASH:all:match` selects every exact match.","Omit `path` when `all` spans files."].join(`
|
|
3
|
+
`),renderFull(t){return t},renderCompact(t){let r=O(t);return r===void 0?"selected result":r.selector==="all"?r.mode==="match"?"all matches":"all lines":r.mode==="match"?`match ${String(r.selector)}`:`line ${String(r.selector)}`},tryResolve:l((t,r)=>this.#i(t,r.source,r.signal),"tryResolve")}}resourceResolver(){return{id:"search-targets",tryResolve:l((t,r)=>this.#a(t,r.cwd),"tryResolve")}}async#i(t,r,n){let o=O(t);if(o===void 0)return{kind:"not-handled"};let a=this.#t.get(o.id);if(a===void 0)return N();if(o.selector==="all"&&!a.complete)return v();let s=C(r),u=a;if(o.selector==="all"){if(a.refreshedComplete?.complete===!0)u=a.refreshedComplete;else if(a.refreshedComplete!==void 0&&(u=await this.#r(a,n),!u.complete))return v()}let i=H(u,o.selector,o.mode),c=i.filter(p=>p.source===s);if(c.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await U(s,n,a.environment,a.read);if(d===void 0)return N(w(c[0]).lineNumber);if(o.selector==="all"&&d!==u.contentBySource.get(s)){if(u=await this.#r(a,n),!u.complete)return v();i=H(u,o.selector,o.mode),c=i.filter(p=>p.source===s)}if(c.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==a.contentBySource.get(s))return N(w(c[0]).lineNumber);let h=k(s,d);return{kind:"resolved",anchor:new X(t,s,c.map(p=>q(h,p,o.mode)))}}async#a(t,r){let n=O(t);if(n===void 0)return{kind:"not-handled"};let o=this.#t.get(n.id);if(o===void 0)return N();if(n.selector==="all"&&!o.complete)return v();let a=o;if(n.selector==="all"){if(o.refreshedComplete?.complete===!0)a=o.refreshedComplete;else if(o.refreshedComplete!==void 0&&(a=await this.#r(o),!a.complete))return v();let c=new Set(H(a,n.selector,n.mode).map(d=>d.source));for(let d of c)if(await U(d,void 0,o.environment,o.read)!==a.contentBySource.get(d)){if(a=await this.#r(o),!a.complete)return v();break}}let s=H(a,n.selector,n.mode);if(n.selector!=="all"){let c=s[0]?.source;if(c!==void 0&&await U(c,void 0,o.environment,o.read)!==a.contentBySource.get(c))return N(s[0]?.lineNumber)}let u=new Map;for(let c of s){let d=u.get(c.source)??[];d.push(q(k(c.source,a.contentBySource.get(c.source)??c.lineText),c,n.mode)),u.set(c.source,d)}let i=[...u].map(([c,d])=>({source:c,ranges:d,expectedContent:a.contentBySource.get(c)}));return i.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:i}}async#r(t,r){let n=t.refresh===void 0?await G(t.recipe,t.cwd,r,t.environment):await t.refresh(r),o=n.matches.map(s=>({...s,source:C(s.source)})).sort(K),a={matches:o,complete:n.complete,contentBySource:await ce(o,r,t.snapshotByteBudget,t.environment,t.read)};return this.#t.set(t.id,{...t,refreshedComplete:a}),a}};function Pe(e,t,r,n,o,a){if(e===void 0)return{};let s=new Map([...r].map(([i,c])=>[i,k(i,c)])),u=t.map(i=>({source:i.source,expectedContent:w(r.get(i.source)),ranges:[q(w(s.get(i.source)),i,"match")],readCurrent:l(c=>a(i.source,c),"readCurrent")}));return{target:e.register(u,n,o),matchTargets:u.slice(0,100).map(i=>e.register([i],n,o))}}l(Pe,"registerResultReferences");function O(e){let t=Me.exec(e);if(t!==null)return{id:w(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}l(O,"parseSearchAnchor");function H(e,t,r){let n=t==="all"?e.matches:[e.matches[t-1]].filter(Ie);if(r==="match"||t!=="all")return n;let o=new Set;return n.flatMap(a=>{let s=k(a.source,e.contentBySource.get(a.source)??a.lineText),u=fe(a);return s.lines.slice(a.lineNumber-1,u).flatMap(i=>{let c=`${a.source}\0${String(i.lineNumber)}`;return o.has(c)?[]:(o.add(c),[{...a,lineNumber:i.lineNumber,endLineNumber:i.lineNumber,startColumn:0,endColumn:i.content.length,lineText:i.content,matchedText:i.content}])})})}l(H,"selectMatches");function Ie(e){return e!==void 0}l(Ie,"isMatch");function fe(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}l(fe,"lastContainingLine");function q(e,t,r){if(r==="match")return{start:{lineNumber:t.lineNumber,column:t.startColumn},end:{lineNumber:t.endLineNumber??t.lineNumber,column:t.endColumn}};let n=fe(t),o=w(e.lines[n-1]);return{start:{lineNumber:t.lineNumber,column:0},end:{lineNumber:n+(o.lineEnding.length>0?1:0),column:o.lineEnding.length>0?0:o.content.length},linewise:!0}}l(q,"selectionRange");function $e(e,t){let r=t.endLineNumber??t.lineNumber;return e.lines.slice(t.lineNumber-1,r).map(n=>{let o=n.lineNumber===t.lineNumber?t.startColumn:0,a=n.lineNumber===r?t.endColumn:n.content.length;return n.content.slice(o,a)+(n.lineNumber===r?"":n.lineEnding)}).join("")}l($e,"matchedSourceText");async function ce(e,t,r,n,o){let a=[...new Set(e.map(i=>i.source))];if(r!==void 0){let i=new Map,c=r;for(let d of a){let h=await Le(d,c,t,n,o);c-=Buffer.byteLength(h),le(d,h,e),i.set(d,h)}return i}let s=await Promise.allSettled(a.map(async i=>{let c=await _(i,t,n,o);return le(i,c,e),[i,c]})),u=new Map;for(let i of s){if(i.status==="rejected")throw i.reason;u.set(...i.value)}return u}l(ce,"snapshotContents");function le(e,t,r){let n=k(e,t);for(let o of r.filter(a=>a.source===e))if(n.lines[o.lineNumber-1]?.content!==o.lineText||$e(n,o)!==o.matchedText)throw new F(e)}l(le,"validateSnapshot");async function Le(e,t,r,n,o){if(r?.throwIfAborted(),e.includes("://")){let s=await _(e,r,n,o);if(Buffer.byteLength(s)>t)throw new Error("Candidate snapshot byte budget reached.");return s}let a=await Ee(e,"r");try{let s=await a.stat();if(!s.isFile()||s.size>t)throw new Error("Candidate snapshot byte budget reached.");let u=Buffer.alloc(Math.min(s.size+1,t+1)),i=0;for(;i<u.length;){r?.throwIfAborted();let c=await a.read(u,i,u.length-i,i);if(c.bytesRead===0)break;i+=c.bytesRead}if(r?.throwIfAborted(),i>s.size||i>t)throw new Error("Candidate file grew during snapshot capture.");return u.subarray(0,i).toString("utf8")}finally{await a.close()}}l(Le,"readBoundedSnapshot");async function U(e,t,r,n){try{return await _(e,t,r,n)}catch{return}}l(U,"readCurrent");function C(e){return e.includes("://")?e:x.resolve(e)}l(C,"canonicalSource");function je(e,t){return t.includes("://")?t:e.includes("://")?new URL(t,e.endsWith("/")?e:e+"/").href:x.resolve(e,t)}l(je,"resolveScope");async function _(e,t,r,n){if(t?.throwIfAborted(),n!==void 0)return n(e,t);if(r!==void 0)return r.readText(e,t);if(e.includes("://"))throw new Error("No search snapshot owner for this source.");return Ne(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}l(_,"readOwnedText");function N(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}l(N,"staleAnchor");function v(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}l(v,"missingCompleteAnchor");function Oe(e){if(e.length===0)return".";let t=x.dirname(x.resolve(w(e[0])));for(let r of e.slice(1)){let n=x.resolve(r);for(;!He(t,n);){let o=x.dirname(t);if(o===t)return t;t=o}}return t}l(Oe,"commonSourceDirectory");function He(e,t){let r=x.relative(e,t);return r!==".."&&!r.startsWith(`..${x.sep}`)&&!x.isAbsolute(r)}l(He,"isWithin");function K(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||(e.endLineNumber??e.lineNumber)-(t.endLineNumber??t.lineNumber)||e.endColumn-t.endColumn}l(K,"compareMatches");export{Z as a,j as b,Te as c,Ye as d,nt as e,G as f,ft as g,de as h,Be as i,F as j,se as k};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as c}from"./chunk-EI7MMDWY.js";import{access as I,readFile as P,readdir as S}from"node:fs/promises";import w from"node:path";async function M(t,i,e,n){if(n?.throwIfAborted(),t.includes("://")&&!e)throw Object.assign(new Error("Project evidence requires its resource owner"),{code:"UNSUPPORTED_SOURCE"});let a=new Map,b=c(o=>{let r=a.get(o);return r===void 0&&(r=e?e.readText(o,n):P(w.join(t,o),{encoding:"utf8",signal:n}),r=r.catch(d=>{if(n?.throwIfAborted(),e)throw d}),a.set(o,r)),r},"content"),l=await b("package.json");n?.throwIfAborted();let k=g(l),m=new Set;for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let r=k?.[o];if(h(r))for(let d of Object.keys(r))m.add(d)}let R=await Promise.all(i.map(async o=>{let r;for(let s of o.configFiles??[]){n?.throwIfAborted();let u=await(e?e.hasMarker(s,n):E(t,s,n)).catch(f=>{throw n?.throwIfAborted(),f});if(n?.throwIfAborted(),u){r=s;break}}if(r===void 0)for(let[s,u]of Object.entries(o.configSections??{})){n?.throwIfAborted();let f=await b(s);if(n?.throwIfAborted(),f===void 0)continue;let y=s.endsWith(".json")?g(f):void 0;if(u.some(p=>y===void 0?f.split(/\r?\n/).some(j=>{let A=/^\s*\[([^\]]+)\]/.exec(j)?.[1]?.trim();return A===p||A?.startsWith(`${p}.`)===!0}):O(y,p)!==void 0)){r=s;break}}let d=o.dependencies?.find(s=>m.has(s));return[o.id,{score:(r===void 0?0:6)+(d===void 0?0:4),...r!==void 0&&{config:r},...d!==void 0&&{dependency:d}}]}));return n?.throwIfAborted(),new Map(R)}c(M,"inspectRecipeEvidence");async function E(t,i,e){if(e?.throwIfAborted(),t.includes("://"))throw Object.assign(new Error("Project marker requires its resource owner"),{code:"UNSUPPORTED_SOURCE"});if(!i.includes("*"))try{return await I(w.join(t,i)),e?.throwIfAborted(),!0}catch{return e?.throwIfAborted(),!1}try{let n=await S(t);return e?.throwIfAborted(),n.some(a=>w.matchesGlob(a,i))}catch{return e?.throwIfAborted(),!1}}c(E,"hasProjectMarker");function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}c(h,"isRecord");function g(t){try{let i=JSON.parse(t??"");return h(i)?i:void 0}catch{return}}c(g,"parseJson");function O(t,i){let e=t;for(let n of i.split("."))e=h(e)?e[n]:void 0;return e}c(O,"jsonSection");export{M as a,E as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as C}from"./chunk-E4HPRLRB.js";import{a as w}from"./chunk-IUSLSROY.js";import{a as E,b as g}from"./chunk-7HDK3NRQ.js";import{b as S}from"./chunk-OJX3RJ5A.js";import"./chunk-XZDOVPRC.js";import{a as u,b as v,c as U}from"./chunk-HCN5W76B.js";import"./chunk-7TJ6DWW3.js";import{g as l}from"./chunk-EY65TFHJ.js";import{a as p,b as O,c as f,e as j}from"./chunk-MKEC3U2M.js";import{c as R}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import"./chunk-YJ6T3PEP.js";import"./chunk-S72FVLUX.js";import"./chunk-K5G4FDXD.js";import"./chunk-R5XJSEOE.js";import"./chunk-ZAWRSA7N.js";import"./chunk-OFILFO6D.js";import{c as P}from"./chunk-IMGIDBCC.js";import"./chunk-BXGMMZT3.js";import"./chunk-756K3LJY.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{fileURLToPath as x}from"node:url";function A(i){let c=E(i),T=w(i);return{async resolveProject(e,o){if(e.startsWith("ssh://")||o.startsWith("ssh://")){let n=i.resolve(e,o);if(!n)throw new l("UNSUPPORTED_SOURCE",e,"not-applied");let a=i.resolve(o);if(a&&a.location.target!==n.location.target)throw new l("UNSUPPORTED_SOURCE",e,"not-applied");let r=await C(n.backend,n.location.path,a?.location.path,"linters",p);return r?{projectRoot:r.cwd,external:r.external}:void 0}if(e.includes("://")||o.includes("://"))throw new l("UNSUPPORTED_SOURCE",e,"not-applied");let t=await P(o,e,"linters",p);return t===void 0?void 0:{projectRoot:t,external:t!==h.resolve(o)}},async loadRegistry(e,o){let t=i.resolve(e);return O.fromDirectory(e,{includeGlobal:!o,requireBuiltInEvidence:!0,...t?{layerAccess:c,executableAvailability:s(n=>S(t.backend,t.location.path,n),"executableAvailability"),recipeEvidence:s(n=>g(t.backend,t.location.path,n),"recipeEvidence")}:{}})},async run(e,o){let t=i.resolve(o.filePath);if(!t)return f(e,o);let n=i.resolve(o.projectRoot);if(!n||n.location.target!==t.location.target)throw new l("UNSUPPORTED_SOURCE",o.filePath,"not-applied");let a=e.check.cwd==="file"?h.posix.dirname(t.location.path):n.location.path;return f(e,{...o,processAccess:T,acceptsFile(r){if(r.startsWith("ssh://")){let d=i.resolve(r);return d?.location.target===t.location.target&&d.location.path===t.location.path}let m=r.startsWith("file:")?x(r):r;return m.includes("://")?!1:h.posix.resolve(a,m)===t.location.path}})}}}s(A,"createOwnedLintRuntime");async function L(i){let c=new U(await v(u(R())));await j(i,A(c))}s(L,"registerOwnedLint");export{A as createOwnedLintRuntime,L as default};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as Ae}from"./chunk-IUSLSROY.js";import{a as Ee}from"./chunk-3G54ZL2L.js";import{a as Ie,b as Re}from"./chunk-7HDK3NRQ.js";import{a as xe}from"./chunk-NULNW6GK.js";import"./chunk-KL776TGR.js";import{b as Ce}from"./chunk-OJX3RJ5A.js";import"./chunk-CTJV77FR.js";import{a as X,d as ke}from"./chunk-SBLKPTL3.js";import"./chunk-XZDOVPRC.js";import{a as Pe,b as Se,c as Oe}from"./chunk-HCN5W76B.js";import{a as De}from"./chunk-7TJ6DWW3.js";import{a as K,g as D}from"./chunk-EY65TFHJ.js";import{c as ve}from"./chunk-W7CASEO3.js";import"./chunk-TOYN4W4F.js";import{a as H,b as he,c as me,d as ye,e as we,g as be}from"./chunk-S72FVLUX.js";import"./chunk-R5XJSEOE.js";import{d as le,e as L}from"./chunk-IMGIDBCC.js";import{a as de}from"./chunk-BXGMMZT3.js";import{d as pe}from"./chunk-756K3LJY.js";import{a as N}from"./chunk-ZC65Z3CK.js";import{a as ue,b as fe,c as ge}from"./chunk-JMVDFOTQ.js";import{a as s}from"./chunk-EI7MMDWY.js";import{mkdir as Ke,readFile as Xe,writeFile as Qe}from"node:fs/promises";async function Te(n,r,t,o){if(o?.throwIfAborted(),n.includes("://")&&!t||t&&t.source!==n)throw Object.assign(new Error("Doctor configuration needs its project owner"),{code:"UNSUPPORTED_SOURCE"});t||await Ke(le(n),{recursive:!0});let e=[],i=r.filter(f=>f.recipe.formatter!==void 0),a=r.filter(f=>f.recipe.linter!==void 0),u=r.filter(f=>f.recipe.lsp!==void 0);if(i.length>0){let f=t?(await t.configPaths("formatters",o)).project:L(n,"formatters"),{config:h,previous:p}=await Q(f,{version:1,formatters:{}},t,o),m=Z(h,"formatters");for(let w of i)m[w.recipe.id]??=w.recipe.formatter;await q(f,h,p,t,o)&&e.push(f)}if(a.length>0){let f=t?(await t.configPaths("linters",o)).project:L(n,"linters"),{config:h,previous:p}=await Q(f,{version:1,linters:{}},t,o),m=Z(h,"linters");for(let w of a)m[w.recipe.id]??=w.recipe.linter;await q(f,h,p,t,o)&&e.push(f)}if(u.length>0){let f=t?(await t.configPaths("lsp-servers",o)).project:L(n,"lsp-servers"),{config:h,previous:p}=await Q(f,{version:1,servers:{}},t,o),m=Z(h,"servers");for(let w of u){let g=N(w.recipe.lsp);m[w.recipe.id]??={command:g.command,transport:"stdio",rootMarkers:g.rootMarkers,...g.initializationOptions!==void 0&&{initializationOptions:g.initializationOptions},...g.settings!==void 0&&{settings:g.settings},...g.requireRootMarker!==void 0&&{requireRootMarker:g.requireRootMarker},languages:Object.fromEntries(Object.entries(g.languageIds).map(([y,C])=>[y,{extensions:C,...g.fileNames?.[y]&&{fileNames:g.fileNames[y]}}])),capabilities:["diagnostics"]}}await q(f,h,p,t,o)&&e.push(f)}return e}s(Te,"writeSuggestedConfigs");async function Q(n,r,t,o){let e;try{e=t?await t.readText(n,o):await Xe(n,{encoding:"utf8",signal:o})}catch(a){if(o?.throwIfAborted(),!(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT"))throw a}if(o?.throwIfAborted(),e===void 0)return{config:r,previous:e};let i=JSON.parse(e);if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${n} must contain an object`);return{config:i,previous:e}}s(Q,"readObject");function Z(n,r){let t=n[r];if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${r} must be an object`);return t}s(Z,"objectMember");async function q(n,r,t,o,e){e?.throwIfAborted();let i=`${JSON.stringify(r,null,2)}
|
|
2
|
+
`;return t===i?!1:(o?await o.writeText(n,i,t,e):await Qe(n,i,{encoding:"utf8",signal:e}),!0)}s(q,"writeJson");function je(n,r){let t=new Set,o;for(let e of n.trim().split(/\s+/u).filter(Boolean))if(["--apply","--no-apply","--agent"].includes(e))t.add(e);else if(e.startsWith("ssh://")&&o===void 0)o=e;else throw new TypeError("Use /pi-agent-ide-doctor [ssh://target/path] [--apply | --no-apply] [--agent]");if(t.has("--apply")&&t.has("--no-apply"))throw new TypeError("Choose --apply or --no-apply, not both");return{cwd:o??r,flags:t}}s(je,"parseDoctorArguments");var z=class{static{s(this,"DoctorCore")}plugins=new Map;languages=[];recipes=[];setupChecks=[];checks=[];queue=Promise.resolve();registerPlugin(r){let t=this.plugins.get(r.id);if(t!==void 0)return t;let o=this.queue.then(async()=>{let e=!0,i=[],a=[],u=[],f=[],h={addLanguage:s(p=>{V(p,i,r.id,"language",()=>e)},"addLanguage"),addToolRecipe:s(p=>{V(p,a,r.id,"tool recipe",()=>e)},"addToolRecipe"),addSetupCheck:s(p=>{V(p,u,r.id,"setup check",()=>e)},"addSetupCheck"),addCheck:s(p=>{V(p,f,r.id,"check",()=>e)},"addCheck")};try{await r.setup(h)}finally{e=!1}$e(this.languages,i,"language"),$e(this.recipes,a,"tool recipe"),this.languages.push(...i),this.recipes.push(...a),this.setupChecks.push(...u),this.checks.push(...f)});return this.plugins.set(r.id,o),this.queue=o.catch(()=>{}),o.catch(()=>{this.plugins.delete(r.id)}),o}async waitForPlugins(){await Promise.all(this.plugins.values())}snapshot(){return{languages:[...this.languages],recipes:[...this.recipes],setupChecks:[...this.setupChecks],checks:[...this.checks]}}};async function Ne(n,r){let t=[],o=[];for(let e of n.setupChecks)try{let i=await e.value.inspect(r);t.push(...(i.selections??[]).map(a=>({...a,pluginId:e.pluginId}))),o.push(...(i.actions??[]).map(a=>({...a,pluginId:e.pluginId})))}catch{}return{selections:t,actions:o}}s(Ne,"runContributedSetupChecks");async function Le(n,r){let t=[];for(let o of n.checks)try{t.push({pluginId:o.pluginId,title:o.value.title,findings:await o.value.run(r)})}catch(e){t.push({pluginId:o.pluginId,title:o.value.title,findings:[{status:"fail",message:e instanceof Error?e.message:String(e)}]})}return t}s(Le,"runContributedChecks");function $e(n,r,t){for(let o of r){let e=n.find(i=>i.value.id===o.value.id)?.pluginId;if(e!==void 0)throw new Error(`${t} ${o.value.id} is already owned by doctor plugin ${e}`)}}s($e,"assertAvailable");function V(n,r,t,o,e){if(!e())throw new Error(`Doctor plugin ${t} setup is complete`);if(!/^[a-z0-9][a-z0-9.-]*$/u.test(n.id))throw new Error(`Invalid ${o} ID: ${n.id}`);if(r.some(i=>i.value.id===n.id))throw new Error(`Doctor plugin ${t} registered ${o} ${n.id} twice`);r.push({pluginId:t,value:n})}s(V,"add");import st from"node:path";import{readFile as Ze}from"node:fs/promises";async function _e(n,r,t,o=process.env,e,i){e?.throwIfAborted();let a=t.filter(({value:g})=>g.languages.some(y=>r.has(y))),u=a.map(g=>g.value),f=i?await i.evidence(u,e):await de(n,u,void 0,e),h=await et(n,e,i),p=[...new Set(u.flatMap(g=>g.executables))],m=i?await i.executableAvailability(p.map(g=>({command:[g]})),e):void 0;if(e?.throwIfAborted(),m&&(m.length!==p.length||m.some(g=>typeof g!="boolean")))throw new TypeError("Invalid Doctor executable availability report");let w=[];for(let g of a){e?.throwIfAborted();let y=g.value,C=[],I=1,b=f.get(y.id),O=b?.config;O!==void 0&&(I+=6,C.push(`project config: ${O}`)),h.has(`${y.kind}:${y.id}`)&&(I+=6,C.push("Pi Agent IDE config"));let c=b?.dependency;c!==void 0&&(I+=4,C.push(`project dependency: ${c}`));let d=m?y.executables.find(l=>m[p.indexOf(l)]===!0):await qe(n,y.executables,o,e);d!==void 0&&(I+=3,C.push(`executable: ${d}`)),w.push({pluginId:g.pluginId,recipe:y,score:I,evidence:C,...d&&{executable:d}})}return w.sort((g,y)=>y.score-g.score||g.recipe.id.localeCompare(y.recipe.id))}s(_e,"discoverRecipeCandidates");function Ue(n,r,t=[]){let o=new Map,e=new Map(t.map(i=>[`${i.kind}:${i.languageId}`,i.toolId]));for(let i of r)for(let a of["formatter","linter","lsp"]){let u=e.get(`${a}:${i}`),f=u===void 0?4:7,h=n.filter(m=>m.recipe.kind===a&&m.recipe.languages.includes(i)&&m.executable!==void 0&&m.recipe.id!==u&&m.score>=f),p=h[0];p!==void 0&&(h.filter(m=>m.score===p.score).length>1||o.set(`${p.recipe.kind}:${p.recipe.id}`,p))}return[...o.values()]}s(Ue,"selectSuggestedRecipes");async function qe(n,r,t,o){for(let e of r)if(await pe(e,n,t,o))return e}s(qe,"firstExecutable");async function et(n,r,t){let o=new Set;for(let[e,i,a]of[["formatters","formatters","formatter"],["linters","linters","linter"],["lsp-servers","servers","lsp"]])try{r?.throwIfAborted();let u=t?(await t.configPaths(e,r)).project:L(n,e),f=t?await t.readText(u,r):await Ze(u,{encoding:"utf8",signal:r});if(r?.throwIfAborted(),f===void 0)continue;let h=JSON.parse(f);if(typeof h!="object"||h===null||Array.isArray(h))continue;let m=h[i];if(typeof m=="object"&&m!==null&&!Array.isArray(m))for(let w of Object.keys(m))o.add(`${a}:${w}`)}catch(u){if(r?.throwIfAborted(),!(u instanceof SyntaxError)&&!(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT"))throw u}return o}s(et,"managedRecipeIds");import{execFile as tt}from"node:child_process";import{readdir as ot}from"node:fs/promises";import _ from"node:path";import{promisify as nt}from"node:util";var rt=nt(tt),it=new Set([".git",".hg",".svn","node_modules","vendor","build","dist","coverage",".cache",".next","target"]);async function Be(n,r){r?.throwIfAborted();try{let o=(await rt("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:n,encoding:"utf8",maxBuffer:16777216,signal:r})).stdout.split("\0").filter(Boolean).map(e=>_.resolve(n,e)).filter(e=>!Me(e));return r?.throwIfAborted(),o.length>0?o:await ee(n,r)}catch{return r?.throwIfAborted(),ee(n,r)}}s(Be,"collectProjectFiles");function Fe(n,r,t=process.platform){let o=new Map,e=t==="win32"?_.win32:_;for(let i of r){let a=new Set(i.extensions.map(p=>p.toLowerCase())),u=s(p=>t==="win32"?p.toLowerCase():p,"normalizeName"),f=new Set(i.fileNames?.map(u)),h=n.filter(p=>!p.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")&&(a.has(e.extname(p).toLowerCase())||f.has(u(e.basename(p)))));h.length>0&&o.set(i.id,h)}return o}s(Fe,"detectProjectLanguages");async function ee(n,r){r?.throwIfAborted();let t=[];for(let o of await ot(n,{withFileTypes:!0})){if(o.isDirectory()&&it.has(o.name))continue;let e=_.join(n,o.name);Me(e)||(o.isDirectory()?t.push(...await ee(e,r)):o.isFile()&&t.push(e))}return t}s(ee,"walk");function Me(n){return n.split(_.sep).join("/").includes("/.pi/pi-agent-ide/")}s(Me,"isManagedIdeConfig");function at(n,r){if(n.includes("://")&&!r||r&&r.source!==n)throw Object.assign(new Error(`Doctor requires the owner of ${n}`),{code:"UNSUPPORTED_SOURCE"})}s(at,"assertWorkspace");async function te(n,r,t=process.env,o,e){o?.throwIfAborted(),at(r,e);let i=e?await e.files(o):await Be(r,o);o?.throwIfAborted();let a=Fe(i,n.languages.map(w=>w.value),e?.platform),u=new Set(a.keys()),f={cwd:r,files:i,detectedLanguageIds:u,detectedLanguages:a,env:e?{...e.toolPaths}:t,signal:o,workspace:e},[h,p]=await Promise.all([_e(r,u,n.recipes,e?{...e.toolPaths}:t,o,e),Ne(n,f)]);o?.throwIfAborted();let m=new Map;for(let w of u)for(let g of["formatter","linter","lsp"]){if(p.selections.some(b=>b.languageId===w&&b.kind===g))continue;let y=h.filter(b=>b.recipe.kind===g&&b.recipe.languages.includes(w)),C=s(b=>b.score-(b.executable===void 0?0:3),"nativeScore"),I=Math.max(1,...y.map(C));for(let b of y){if(b.executable!==void 0||C(b)!==I||I<=1)continue;let O=`${g}-${b.recipe.id}-unavailable`;m.set(O,{id:O,pluginId:b.pluginId,message:`Native project setup selects ${b.recipe.id}, but its executable is unavailable. Install ${b.recipe.executables.join(" or ")} and run Doctor again.`})}}return{cwd:r,files:i,detectedLanguages:a,candidates:h,selections:p.selections,actions:[...p.actions,...m.values()],suggestions:Ue(h,u,p.selections)}}s(te,"inspectDoctorSetup");async function Y(n,r,t=process.env,o,e){let i=await te(n,r,t,o,e),a=new Set(i.detectedLanguages.keys()),u={cwd:r,files:i.files,detectedLanguageIds:a,detectedLanguages:i.detectedLanguages,env:e?{...e.toolPaths}:t,signal:o,workspace:e},f=await Le(n,u);o?.throwIfAborted();let h=[{status:"pass",message:`Project: ${r}`},i.files.length>0?{status:"pass",message:`${i.files.length} project files inspected`}:{status:"warn",message:"No project files found"},a.size>0?{status:"pass",message:`Detected: ${[...a].join(", ")}`}:{status:"warn",message:"No registered project languages detected"}];return{...i,sections:[{title:"Project",pluginId:"doctor",findings:h},...f]}}s(Y,"runDoctor");function M(n){let r=["Pi Agent IDE doctor",""];for(let t of n.sections){r.push(`${t.title} (${t.pluginId})`);for(let o of t.findings)r.push(` ${o.status.toUpperCase().padEnd(4)} ${o.message}`),o.detail!==void 0&&r.push(` \`${o.detail}\``);r.push("")}if(n.actions.length>0){r.push("Setup needs attention");for(let t of n.actions)r.push(` ${t.message} [${t.pluginId}]`);r.push("")}if(n.suggestions.length>0){r.push("Suggested configuration");for(let t of n.suggestions){let o=t.evidence.length>0?` \u2014 ${t.evidence.join(", ")}`:"";r.push(` ${t.recipe.kind.padEnd(9)} ${t.recipe.id} [${t.pluginId}]${o}`)}r.push("")}return r.join(`
|
|
3
|
+
`).trimEnd()}s(M,"formatDoctorReport");function oe(n){return n.actions.length>0||n.suggestions.length>0||n.sections.some(r=>r.findings.some(t=>t.status==="fail"))}s(oe,"doctorNeedsWork");function We(n){let r=n.candidates.map(t=>({owner:t.pluginId,id:t.recipe.id,kind:t.recipe.kind,languages:t.recipe.languages,evidence:t.evidence,documentation:t.recipe.documentation}));return["Finish configuring Pi Agent IDE for this project.","Preserve existing formatter, linter, compiler, and style rules. Do not invent or replace native project settings.","Do not install packages, write credentials, or change source files without the user's normal confirmation.","Pi Agent IDE project configs live in .pi/pi-agent-ide/.","Use only the relevant plugin contributions listed below; each owner remains responsible for its own scope.","",M(n),"","Relevant registered recipes:",JSON.stringify(r,null,2),"",`Project root: ${n.cwd.includes("://")?n.cwd:st.resolve(n.cwd)}`].join(`
|
|
4
|
+
`)}s(We,"buildDoctorAgentPrompt");import{createHash as ct}from"node:crypto";var dt="doctor",ne=3;function Je(n,r){let t=ue(n,pt(r));t!==void 0&&t.catch(()=>{})}s(Je,"registerDoctorTipProvider");function pt(n){return{protocol:fe,apiVersion:ge,id:dt,async getTip(r){let t=await n(r),o=lt(t);if(o.length===0)return;let e=o.slice(0,ne).map(i=>`\u2022 ${i.message}`);return o.length>ne&&e.push(`\u2022 ${o.length-ne} more`),{id:`doctor-setup-${ut(o)}`,title:o.length===1?"Project setup needs attention":`${o.length} project setup items`,body:[...e,"Run /pi-agent-ide-doctor"].join(`
|
|
5
|
+
`)}}}}s(pt,"createDoctorTipProvider");function lt(n){let r=n.actions.map(o=>({id:`action:${o.pluginId}:${o.id}`,message:o.message})),t=n.suggestions.map(o=>{let e=o.recipe.languages.filter(a=>n.detectedLanguages.has(a)).join(", "),i={debugger:"debugging",formatter:"formatting",linter:"linting",lsp:"language support"}[o.recipe.kind];return{id:`suggestion:${o.pluginId}:${o.recipe.kind}:${o.recipe.id}`,message:`Use ${o.recipe.name} for ${e} ${i}`}});return[...r,...t].sort((o,e)=>o.id.localeCompare(e.id))}s(lt,"setupItems");function ut(n){return ct("sha256").update(n.map(r=>`${r.id}\0${r.message}`).join("\0")).digest("hex").slice(0,12)}s(ut,"fingerprint");async function Ve(n,r){let t=new z;Je(n,async i=>(await t.waitForPlugins(),te(t.snapshot(),i.cwd,process.env,i.signal)));let o,e=n.events.on(we,i=>{if(!be(i))throw new Error("Invalid doctor plugin registration request");i.accept(t.registerPlugin(i.plugin))});n.on("session_shutdown",e),n.registerCommand("pi-agent-ide-doctor",{description:"Check and configure this project or an explicit ssh://target/path",handler:s(async(i,a)=>{let{cwd:u,flags:f}=je(i,a.cwd),h=await r?.(u);await t.waitForPlugins();let p=await Y(t.snapshot(),u,process.env,void 0,h);if(re(n,M(p)),p.suggestions.length>0&&!f.has("--no-apply")&&(f.has("--apply")||a.hasUI&&await a.ui.confirm("Apply suggested configuration?","Add detected tools to .pi/pi-agent-ide/. Existing entries and native tool settings are kept."))){let g=await Te(u,p.suggestions,h),y=g.length===0?"Pi Agent IDE configs are already up to date":`Updated ${g.length} Pi Agent IDE config ${g.length===1?"file":"files"}`;a.ui.notify(y,"info"),p=await Y(t.snapshot(),u,process.env,void 0,h),re(n,M(p))}if(!oe(p)&&!f.has("--agent"))return;(f.has("--agent")||a.hasUI&&await a.ui.confirm("Ask the agent to finish setup?","The agent will receive this redacted report and relevant plugin recipes."))&&(o={cwd:u,workspace:h},n.sendUserMessage(We(p)))},"handler")}),n.on("agent_end",async(i,a)=>{let u=o;if(u===void 0)return;o=void 0;let f=await Y(t.snapshot(),u.cwd,process.env,void 0,u.workspace);re(n,`Doctor recheck after agent setup
|
|
6
|
+
|
|
7
|
+
${M(f)}`),oe(f)?a.ui.notify("Pi Agent IDE setup still needs attention","warning"):a.ui.notify("Pi Agent IDE setup is ready","info")}),n.events.emit(ye,{protocol:he,apiVersion:me}),await t.waitForPlugins()}s(Ve,"registerDoctorWithOwner");function re(n,r){n.sendMessage({customType:"pi-agent-ide-doctor",content:r,display:!0},{triggerTurn:!1})}s(re,"sendReport");import{readFile as ze}from"node:fs/promises";import U from"node:path";import{Type as E}from"typebox";import{Value as ie}from"typebox/value";var ft=E.Object({directory:E.String(),device:E.String({pattern:"^[0-9]+$"}),inode:E.String({pattern:"^[0-9]+$"}),containerCreated:E.Boolean(),containerDevice:E.String({pattern:"^[0-9]+$"}),containerInode:E.String({pattern:"^[0-9]+$"})});async function Ye(n,r,t){t?.throwIfAborted();let o=n.resolve(r);if(!o)throw new D("UNSUPPORTED_SOURCE",r,"not-applied");let e=o.location,i=o.backend;if((await i.stat(e.path,{signal:t})).kind!=="directory")throw new D("NOT_DIRECTORY",e.source,"not-applied");let a=s(c=>{let d=n.resolve(c);if(!d||d.location.target!==e.target)throw new D("UNSUPPORTED_SOURCE",c,"not-applied");return d.location.path},"resolve"),u=await X({...i.target,workspace:e.path},"python3",["-c","import json,os,sys; keys=json.loads(sys.argv[1]); print(json.dumps({k:os.environ[k] for k in keys if k in os.environ}))",JSON.stringify(H)],e.source,{signal:t,timeoutMs:5e3,maxBytes:128*1024});if(u.exitCode!==0)throw new D("DEPENDENCY_UNAVAILABLE",e.source,"not-applied");let f=JSON.parse(u.stdout.toString("utf8")),h=E.Object(Object.fromEntries(H.map(c=>[c,E.Optional(E.String({maxLength:4096}))])),{additionalProperties:!1});if(!ie.Check(h,f))throw new D("INVALID_RESPONSE",e.source,"not-applied");let p=Ie(n),m=Ae(n),w=Ee(n,e.source),g=new Map,y=s(async(c,d,l)=>{let P=await ze(new URL(`./${c}`,new URL("../src/backend/doctor-workspace.ts",import.meta.url).href),{encoding:"utf8",signal:l}),S=await X(i.target,"python3",["-c",P,...d],e.source,{signal:l,timeoutMs:3e4,maxBytes:32*1024*1024});if(S.exitCode!==0)throw new D("DOCTOR_FAILED",e.source,"not-applied");return JSON.parse(S.stdout.toString("utf8"))},"executeWorker"),C=s(async(c,d,l)=>{l?.throwIfAborted();let P=await ze(new URL("./doctor-probe-worker.py",new URL("../src/backend/doctor-workspace.ts",import.meta.url).href),{encoding:"utf8",signal:l}),S=new AbortController,j=l?AbortSignal.any([l,S.signal]):S.signal,$=setTimeout(()=>S.abort(new D("TIMEOUT",e.source,"not-applied")),3e4),R,x=!1,T,k;try{R=await De(i.target,"python3",["-c",P,JSON.stringify({operation:"create",source:c})],i.target.workspace,{signal:j});let v=0,B=s(A=>(v+=A.length,v<=128*1024?!0:(S.abort(new D("BYTE_LIMIT",e.source,"not-applied")),!1)),"consume");R.stderr.on("data",A=>{B(A)});let G=R,W=new Promise((A,Ge)=>{let F=Buffer.alloc(0),se=!1;G.stdout.on("data",ae=>{if(!B(ae)||se)return;F=Buffer.concat([F,ae]);let ce=F.indexOf(`
|
|
8
|
+
`);if(!(ce<0)){se=!0;try{A(JSON.parse(F.subarray(0,ce).toString("utf8")))}catch(He){Ge(He)}F=Buffer.alloc(0)}})}),J=await Promise.race([W,R.completion.then(()=>{throw new D("PROBE_FAILED",e.source,"not-applied")})]);if(l?.throwIfAborted(),!ie.Check(ft,J))throw new D("PROBE_FAILED",e.source,"not-applied");if(k=J,await R.write(Buffer.from(`retain
|
|
9
|
+
`)),await R.end(),(await R.completion).exitCode!==0)throw new D("PROBE_FAILED",e.source,"not-applied")}catch(v){x=!0,T=l?.aborted?l.reason:S.signal.aborted?S.signal.reason:v}finally{clearTimeout($)}try{let v=await R?.stop();if(v?.exitCode===0&&k&&d(k),v?.exitCode===2)throw new D("PROBE_CLEANUP_FAILED",e.source,"unknown")}catch(v){throw new AggregateError(x?[T,v]:[v],"Doctor allocation cleanup failed",{cause:v})}if(x)throw T},"allocateProbe"),I=new Map,b=s(async c=>{for(;;){let d=I.get(c);if(d?.cleanup){await d.cleanup;continue}let l=d??{users:0};return l.users++,I.set(c,l),l}},"acquireContainer"),O=s(async(c,d)=>{d.users--,d.users===0&&(d.cleanup=Promise.resolve().then(async()=>{if(d.created&&await y("doctor-probe-worker.py",[JSON.stringify({operation:"remove-container",...d.created})])!==null)throw new D("PROBE_CLEANUP_FAILED",e.source,"unknown")}).finally(()=>{I.get(c)===d&&I.delete(c)}),await d.cleanup)},"releaseContainer");return{source:e.source,platform:"linux",toolPaths:f,probeCapture:s(c=>xe({...i.target,workspace:e.path},e.source,c),"probeCapture"),async probeBrowser(c){return await ke({...i.target,workspace:e.path},e.source,c),{ok:!0,detail:"Target Playwright and Chromium started without navigation"}},async files(c){let d=await y("doctor-inventory-worker.py",[e.path],c);if(!ie.Check(E.Array(E.String()),d))throw new D(typeof d=="object"&&d!==null&&"error"in d&&d.error==="BYTE_LIMIT"?"BYTE_LIMIT":"INVENTORY_FAILED",e.source,"not-applied");return d.map(l=>{let P=U.posix.resolve(e.path,l);if(U.posix.isAbsolute(l)||!(P.startsWith(`${e.path}/`)||e.path==="/"))throw new D("INVALID_RESPONSE",e.source,"not-applied");return K(e.target,P).source})},async readText(c,d){try{let l=await i.read(a(c),{signal:d}),P=l.bytes.toString("utf8");return g.set(c,{content:P,version:l.version}),P}catch(l){if(l instanceof D&&l.code==="ENOENT")return;throw l}},async writeText(c,d,l,P){let S=g.get(c);if(l!==void 0&&(!S||S.content!==l))throw new D("CONFLICT",c,"not-applied");await i.write(a(c),Buffer.from(d),l===void 0?null:S?.version??null,{signal:P})},configPaths:s((c,d)=>p.paths(e.source,c,d),"configPaths"),async exists(c,d){try{return await i.stat(a(c),{signal:d}),!0}catch(l){if(l instanceof D&&l.code==="ENOENT")return!1;throw l}},evidence:s((c,d)=>Re(i,e.path,c,d),"evidence"),executableAvailability:s((c,d)=>Ce(i,e.path,c,d),"executableAvailability"),run:s((c,d,l)=>m.run(c,{projectRoot:e.source,filePath:d,signal:l}),"run"),async withProbeCopy(c,d,l){l?.throwIfAborted();let P=a(c),S=U.posix.join(U.posix.dirname(P),".tmp"),j=await b(S),$,R=U.posix.basename(P),x=[],T;try{let v=j.allocation,B={};j.allocation=new Promise(A=>{B.resolve=A});let G=N(B.resolve);try{await v,l?.throwIfAborted(),await C(P,A=>{$=A,A.containerCreated&&(j.created={container:S,device:A.containerDevice,inode:A.containerInode})},l)}finally{G()}let W=U.posix.join(N($).directory,R),J=await i.lstat(P,{signal:l});await i.copy(P,W,J.revision,null,{signal:l}),l?.throwIfAborted(),x.push({value:await d(K(e.target,W).source)})}catch(v){T=v}let k=[];if($)try{if(await y("doctor-probe-worker.py",[JSON.stringify({operation:"remove",...$,name:R})])!==null)throw new D("PROBE_CLEANUP_FAILED",c,"unknown")}catch(v){k.push(v)}try{await O(S,j)}catch(v){k.push(v)}if(k.length>0)throw new AggregateError(x.length===0?[T,...k]:k,"Doctor probe cleanup failed",{cause:k[0]});if(x.length===0)throw T;return N(x[0]).value},start:s((c,d,l)=>w.start({rootUri:e.source,command:c,env:d,signal:l}),"start"),toNativeUri:s(c=>w.toServerUri(c),"toNativeUri"),fromNativeUri:s(c=>w.fromServerUri(c),"fromNativeUri")}}s(Ye,"createSshDoctorWorkspace");async function gt(n){let r=new Oe(await Se(Pe(ve())));await Ve(n,t=>t.startsWith("ssh://")?Ye(r,t):Promise.resolve(void 0))}s(gt,"registerOwnedDoctor");export{gt as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g as a}from"./chunk-EY65TFHJ.js";import{a as c}from"./chunk-EI7MMDWY.js";import{readFile as l}from"node:fs/promises";import{Type as t}from"typebox";import{Value as p}from"typebox/value";var m=t.Object({pid:t.Integer({minimum:1}),parentPid:t.Integer({minimum:0}),command:t.String(),started:t.String(),identity:t.String({pattern:"^[a-f0-9-]+:[0-9]+$"}),executable:t.Union([t.String(),t.Null()])}),w=t.Object({processes:t.Array(m)}),f;async function P(i,n,r,o){return h(i,n,r,o,!1)}c(P,"readSshProcessMetadata");async function E(i,n,r,o){return(await h(i,n,r,o,!0))[0]}c(E,"findSshProcessMetadata");async function h(i,n,r,o,u){if(o?.throwIfAborted(),r!==void 0&&(!Number.isSafeInteger(r)||r<1))throw new Error("Invalid process PID");let d=i.resolve(n);if(!d)throw new a("UNSUPPORTED_SOURCE",n,"not-applied");f??=l(new URL("./process-metadata-worker.py",new URL("../src/backend/process-metadata.ts",import.meta.url).href),"utf8");let S=await d.backend.execute("python3",["-c",await f,...r===void 0?[]:[String(r)]],d.location.path,{signal:o});if(o?.throwIfAborted(),S.exitCode!==0)throw new a("CAPABILITY_UNAVAILABLE",n,"not-applied");let e;try{e=JSON.parse(S.stdout.toString("utf8"))}catch{throw new a("INVALID_RESPONSE",n,"not-applied")}if(typeof e=="object"&&e!==null&&"error"in e){if(u&&r!==void 0&&e.error==="ENOENT")return[];let s=new Set(["CAPABILITY_UNAVAILABLE","ENOENT","EACCES","BYTE_LIMIT"]);throw new a(typeof e.error=="string"&&s.has(e.error)?e.error:"INVALID_RESPONSE",n,"not-applied")}if(!p.Check(w,e)||r!==void 0&&(e.processes.length!==1||e.processes[0]?.pid!==r)||new Set(e.processes.map(s=>s.pid)).size!==e.processes.length)throw new a("INVALID_RESPONSE",n,"not-applied");return e.processes.map(s=>({...s,target:d.location.target,host:"ssh",owned:!1,resource:`process:ssh://${d.location.target}/${s.pid}`}))}c(h,"readSshProcessRows");export{P as a,E as b};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{b as x}from"./chunk-T4FTT3U4.js";import{j as $}from"./chunk-ZPT5D4VP.js";import{a as m}from"./chunk-KINKBPPX.js";import{a as p}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";function D(e,n,t){let i=`${n}:`;if(!e.startsWith(i))return;let o=e.slice(i.length);if(o.length===0)throw new Error(`${n}: requires a file path.`);return x(o,t)}a(D,"resolveDiagnosticViewPath");function R(e,n){return`${e}:${n}`}a(R,"formatDiagnosticViewSource");function k(e,n,t,i={}){let o={complete:t.length>0&&t.every(d=>d.status==="ready"),count:t.reduce((d,u)=>d+u.diagnostics.length,0),sources:t.map(d=>d.source)},r=n.split(/\r\n|\r|\n/u),s=b(t,r.length);if(s.size===0)return{type:"text",diagnosticCheck:o,text:L(t)||"No completed diagnostic checks are available.",sourceLines:{}};let c=i.contextLines??5;if(!Number.isInteger(c)||c<0)throw new TypeError("Diagnostic contextLines must be a non-negative integer.");let l=new Set;for(let d of s.keys()){let u=Math.max(1,d-c),f=Math.min(r.length,d+c);for(let g=u;g<=f;g+=1)l.add(g)}let w=L(t),y=w?[w]:[],h={};for(let d of[...l].sort((u,f)=>u-f)){let u=r[d-1]??"",f=(s.get(d)??[]).map(({diagnostic:g,source:V})=>`<!-- ${V}: ${m(g,V)} -->`).join(" ");y.push(f.length===0?u:`${u} ${f}`),h[String(y.length)]={source:e,lineNumber:d,content:u}}return{type:"text",diagnosticCheck:o,text:y.join(`
|
|
2
|
+
`),sourceLines:h}}a(k,"createDiagnosticViewContent");function T(e,n){let t=b(n,e.lines.length,/[\r\n]$/u.test(e.content)),i=e.lines.map(o=>{let r=t.get(o.lineNumber);if(r===void 0)return o;let s=r.map(({diagnostic:c,source:l})=>`<!-- ${l}: ${m(c,l)}${c.line===o.lineNumber?"":` @${c.line}:${c.column}`} -->`).join(" ");return{...o,presentation:{...o.presentation,suffix:`${o.presentation?.suffix??""} ${s}`}}});return{...e,lines:i}}a(T,"addDiagnosticAnnotations");function L(e){return e.length>0&&e.every(n=>n.status==="ready"&&n.diagnostics.length===0)?`Checks completed (${e.map(n=>n.source).join(", ")}); no diagnostics found at this point.`:e.filter(n=>n.status&&n.status!=="ready").map(n=>`${n.source}: ${n.status}${n.reason?` (${n.reason})`:""}.`).join(" ")}a(L,"diagnosticStatus");function b(e,n,t=!1){let i=new Map;for(let{diagnostics:o,source:r}of e)for(let s of o){let c=t&&s.line===n+1?n:s.line;if(!Number.isInteger(s.line)||c<1||c>n)continue;let l=i.get(c)??[];l.push({diagnostic:s,source:r}),i.set(c,l)}return i}a(b,"diagnosticsByValidLine");function C(e){return{text:`${e.content}${e.suffix??""}`,...e.sourceLine!==void 0&&{sourceLine:e.sourceLine}}}a(C,"renderSourceViewLine");function v(e,n){if(e.length===0)return S([{text:"<empty-result>"}]);if(e.length===1&&p(e[0]).status==="failed"&&p(e[0]).path===""){let i=p(e[0]),o=n.recovery===void 0?[]:["","Recovery:",...n.recovery],r=n.includeNoChange===!0?["","No file was changed."]:[];return S([i.code??n.failureLabel,"",`Reason: ${i.error??n.unknownFailure??"unknown failure"}`,...r,...o].map(s=>({text:s})))}let t=[];for(let[i,o]of e.entries())i>0&&t.push({text:""},{text:""}),t.push(...M(o,n));return S(t)}a(v,"formatSourceViewResults");function N(){return e=>{let n=e.state;if(n?.contentKind!=="text")return{kind:"continue",context:e};let t=j(n.content[0]);if(t===void 0)return{kind:"continue",context:e};let i=n.text.lines.map(o=>{let r=t[String(o.lineNumber)];return r===void 0?o:$(o,r)});return{kind:"continue",context:{...e,state:{...n,text:{...n.text,lines:i}}}}}}a(N,"createSourceMappedTextReadHandler");function M(e,n){if(e.status==="failed")return[...e.heading===void 0?[`## file: ${e.path||"<unknown>"}`]:[`## ${e.heading}`,...e.details??[]],`${n.failureLabel} | ${e.error??n.unknownFailure??"unknown failure"}`].map(s=>({text:s}));let t=e.heading===void 0?[`## file: ${e.path}`]:[`## ${e.heading}`,...e.details??[]],i=e.continuation??"",o=e.warning===void 0?[]:[{text:""},{text:e.warning}];return[...t.map(r=>({text:r})),{text:`Lines: ${e.startLine}-${e.endLine} of ${e.totalLines}${i}`},{text:""},...e.renderedLines,...o]}a(M,"formatSourceViewBlock");function S(e){let n={};for(let[t,i]of e.entries())i.sourceLine!==void 0&&(n[String(t+1)]=i.sourceLine);return{type:"text",text:e.map(t=>t.text).join(`
|
|
3
|
+
`),sourceLines:n}}a(S,"sourceMappedContent");function j(e){if(typeof e!="object"||e===null||!("sourceLines"in e))return;let n=e.sourceLines;if(!(typeof n!="object"||n===null)){for(let t of Object.values(n))if(!B(t))return;return n}}a(j,"sourceLineMap");function B(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.source=="string"&&n.source.length>0&&Number.isInteger(n.lineNumber)&&(n.lineNumber??0)>0&&typeof n.content=="string"}a(B,"isTextSourceLine");export{D as a,R as b,k as c,T as d,L as e,C as f,v as g,N as h};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as y}from"./chunk-7HDK3NRQ.js";import{a as c,g as m}from"./chunk-EY65TFHJ.js";import{q as w}from"./chunk-IMGIDBCC.js";import{a as p}from"./chunk-EI7MMDWY.js";import a from"node:path";async function C(e,f,t,v,h,n){n?.throwIfAborted();let i=c(e.target.id,f).path;if(t&&x(t,i))return{cwd:c(e.target.id,t).source,external:!1};let d=!1;try{d=(await e.stat(i,{signal:n})).kind==="directory"}catch(r){if(!(r instanceof m)||r.code!=="ENOENT")throw r}let g=d?h:h.filter(r=>w(r,i)),T=t===void 0&&x(e.target.workspace,i)?e.target.workspace:void 0,o=d?i:a.posix.dirname(i);for(;;){n?.throwIfAborted();let r=a.posix.join(o,".pi","pi-agent-ide",`${v}.json`),l=!1;try{await e.stat(r,{signal:n}),l=!0}catch(s){if(!(s instanceof m)||s.code!=="ENOENT")throw s}let E=!l&&g.length>0?[...(await y(e,o,g,n)).values()].some(s=>s.score>0):!1;if(l||E||o===T)return{cwd:c(e.target.id,o).source,external:t!==void 0};let u=a.posix.dirname(o);if(u===o)return;o=u}}p(C,"resolveSshToolProject");function x(e,f){let t=a.posix.relative(e,f);return t===""||t!==".."&&!t.startsWith("../")&&!a.posix.isAbsolute(t)}p(x,"inside");export{C as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as f}from"./chunk-R5XJSEOE.js";import{a}from"./chunk-EI7MMDWY.js";import k from"node:path";function p(i,t){if(!/^[a-z0-9][a-z0-9_-]*$/u.test(i))throw new TypeError("SSH target IDs must contain lowercase letters, digits, underscores or hyphens");if(!t.startsWith("/")||t.includes("\0"))throw new TypeError("Remote paths must be absolute and contain no NUL characters");let r=k.posix.normalize(t),e=r.split("/").map(encodeURIComponent).join("/");return{target:i,path:r,source:`ssh://${i}${e}`}}a(p,"remoteLocation");function O(i,t){if(i.startsWith("ssh:")){let e=new URL(i);if(!i.startsWith("ssh://")||!e.hostname||e.username||e.password||e.port||e.search||e.hash||i.includes("?")||i.includes("#"))throw new TypeError("SSH references require a configured target and an absolute path, without credentials or selectors");return p(e.hostname,decodeURIComponent(e.pathname))}if(!t?.startsWith("ssh:")||/^[A-Za-z][A-Za-z\d+.-]*:/u.test(i))return;let r=O(t);if(!r)throw new TypeError("Invalid remote workspace");return p(r.target,k.posix.resolve(r.path,i))}a(O,"resolveRemoteLocation");import{readFile as C}from"node:fs/promises";function S(i){if(p(i.id,i.workspace),!/^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9_][A-Za-z0-9_.-]*$/u.test(i.host))throw new TypeError("SSH host must be an OpenSSH host alias, not a command or URI")}a(S,"validateSshTarget");async function y(i){return`exec(__import__("base64").b64decode("${(await C(i)).toString("base64")}"))`}a(y,"sshWorkerProgram");async function F(i){return`python3 -c '${await y(i)}'`}a(F,"sshWorkerCommand");function D(i,t){let r=["-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ForwardAgent=no","-o","PermitLocalCommand=no","-o","ClearAllForwardings=yes"];return i.configFile!==void 0&&r.push("-F",i.configFile),r.push("--",i.host,t),r}a(D,"systemSshArguments");function H(i,t){return/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|No .* host key is known/u.test(t)?"HOST_KEY_FAILED":/Permission denied \([^)]*\)/u.test(t)?"AUTH_FAILED":i===127&&/\bpython3:\s*(?:command\s+)?not found\b/u.test(t)?"DEPENDENCY_UNAVAILABLE":"TRANSPORT_FAILED"}a(H,"sshFailureCode");import{createHash as I}from"node:crypto";import{Type as n}from"typebox";import{Value as x}from"typebox/value";var d=class extends f{static{a(this,"SshBackendError")}constructor(t,r,e,o){super(t,r,e,o),this.name=t==="CANCELLED"?"AbortError":"SshBackendError"}},L=n.Object({bytes:n.String(),version:n.String({pattern:"^[a-f0-9]{64}$"})}),v=n.Object({directory:n.String(),path:n.String(),revision:n.String({pattern:"^[a-f0-9]{64}$"}),sourceRevision:n.String({pattern:"^[a-f0-9]{64}$"}),sha256:n.String({pattern:"^[a-f0-9]{64}$"})}),E=n.Object({revision:n.String({pattern:"^[a-f0-9]{64}$"}),bytes:n.String(),offset:n.Integer({minimum:0}),totalBytes:n.Integer({minimum:0})}),T=n.Array(n.Object({name:n.String(),kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("symlink"),n.Literal("other")])})),B=n.Object({kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("other")]),size:n.Integer({minimum:0}),mode:n.Integer({minimum:0})}),m=n.Object({kind:n.Union([n.Literal("file"),n.Literal("directory"),n.Literal("symlink"),n.Literal("other")]),size:n.Integer({minimum:0}),mode:n.Integer({minimum:0}),links:n.Integer({minimum:0}),identity:n.Object({device:n.String({pattern:"^[0-9]+$"}),inode:n.String({pattern:"^[0-9]+$"})}),revision:n.String({pattern:"^[a-f0-9]{64}$"})}),N=n.Object({path:n.String({minLength:1}),entries:n.Array(n.Object({relativePath:n.String(),kind:m.properties.kind,revision:m.properties.revision,identity:m.properties.identity,mode:n.Integer({minimum:0}),link:n.Optional(n.String())}))}),A=n.Union([n.Object({ok:n.Literal(!0),data:n.Unknown()}),n.Object({ok:n.Literal(!1),code:n.String({pattern:"^[A-Z][A-Z0-9_]*$"}),effect:n.Union([n.Literal("not-applied"),n.Literal("applied"),n.Literal("unknown")])})]),w=class{static{a(this,"SshBackend")}target;constructor(t){S(t),this.target={...t}}async stat(t,r={}){let e=await this.request({operation:"stat",path:t},!1,r);return this.checked(B,e,t,!1),e}async lstat(t,r={}){let e=await this.request({operation:"lstat",path:t},!1,r);return this.checked(m,e,t,!1),e}async temporaryEnvironment(t={}){let r=await this.request({operation:"temporary-environment",path:this.target.workspace},!1,t);return this.checked(n.Object({home:n.String({minLength:1,pattern:"^/"}),temporary:n.String({minLength:1,pattern:"^/"}),agentDirectory:n.Optional(n.String({minLength:1,pattern:"^/"}))}),r,this.target.workspace,!1),r}async objectSnapshot(t,r={}){let e=await this.request({operation:"object-snapshot",path:t},!1,r);return this.checked(N,e,t,!1),e}async ensureObjectDirectory(t,r,e,o={}){let s=await this.request({operation:"mkdir-object",path:t,mode:r,revision:e},!0,o);this.checked(n.Null(),s,t,!0)}async createObjectLink(t,r,e={}){let o=await this.request({operation:"symlink-object",path:t,link:r,revision:null},!0,e);this.checked(n.Null(),o,t,!0)}async setObjectMode(t,r,e,o={}){let s=await this.request({operation:"chmod-object",path:t,mode:r,revision:e},!0,o);this.checked(n.Null(),s,t,!0)}async moveObject(t,r,e={}){let o=await this.request({operation:"move-object",path:t.path,destination:r.path,sourceSnapshot:t,targetSnapshot:r},!0,e);return this.checked(n.Boolean(),o,t.path,!0),o}async captureJournal(t,r={}){let e=await this.request({operation:"journal",path:t},!1,r);return this.checked(v,e,t,!1),e}async releaseJournal(t,r={}){let e=await this.request({operation:"journal-release",path:t},!1,r);this.checked(n.Null(),e,t,!1)}async read(t,r={}){let e=await this.request({operation:"read",path:t},!1,r);return this.checked(L,e,t,!1),{bytes:Buffer.from(e.bytes,"base64"),version:e.version}}async readRange(t,r,e,o={}){if(!Number.isSafeInteger(r)||!Number.isSafeInteger(e)||e<0)throw new TypeError("Byte offset and limit must be safe integers; limit must be nonnegative");let s=await this.request({operation:"range",path:t,offset:r,limit:e},!1,o);return this.checked(E,s,t,!1),{bytes:Buffer.from(s.bytes,"base64"),offset:s.offset,totalBytes:s.totalBytes,revision:s.revision}}async list(t,r={}){let e=await this.request({operation:"list",path:t},!1,r);return this.checked(T,e,t,!1),e}async write(t,r,e,o={}){let s=await this.request({operation:"write",path:t,bytes:Buffer.from(r).toString("base64"),expected:e},!0,o);return this.checked(n.String({pattern:"^[a-f0-9]{64}$"}),s,t,!0),s}async copy(t,r,e,o,s={}){return this.copyEntry("copy",t,r,e,o,s)}async restoreJournal(t,r,e,o,s={}){return this.copyEntry("restore",t,r,e,o,s)}async copyEntry(t,r,e,o,s,c){let u=await this.request({operation:t,path:r,destination:e,sourceRevision:o,targetRevision:s},!0,c);this.checked(n.Null(),u,r,!0)}async move(t,r,e,o,s={}){let c=await this.request({operation:"move",path:t,destination:r,sourceRevision:e,targetRevision:o},!0,s);this.checked(n.Null(),c,t,!0)}async realpath(t,r={}){let e=await this.request({operation:"realpath",path:t},!1,r);if(this.checked(n.String({minLength:1}),e,t,!1),!e.startsWith("/"))throw new d("INVALID_RESPONSE",t,"not-applied");return e}async queryGit(t,r,e={}){let o=await this.request({operation:"git-query",path:t,args:r},!1,{...e,timeoutMs:5e3});return this.checked(n.String(),o,t,!1),o}async removeObject(t,r,e={}){let o=await this.request({operation:"delete-object",path:t,revision:r},!0,e);this.checked(n.Null(),o,t,!0)}async removeEntry(t,r,e={}){let o=await this.request({operation:"unlink",path:t,revision:r},!0,e);this.checked(n.Null(),o,t,!0)}async remove(t,r,e={}){let o=await this.request({operation:"remove",path:t,expected:r},!0,e);this.checked(n.Null(),o,t,!0)}async writeGitIndex(t,r,e={}){let o=Buffer.from(r.text,"utf8");if(o.length>32*1024*1024)throw new d("CONTENT_LIMIT",p(this.target.id,t).source,"not-applied");let{text:s,expectedIndexText:c,expectedWorktreeText:u,...g}=r,l=a(b=>I("sha256").update(b,"utf8").digest("hex"),"digest"),h=await this.request({operation:"gitIndex",path:t,...g,bytes:o.toString("base64"),expectedIndexHash:l(c),...u!==void 0&&{expectedWorktreeHash:l(u)}},!0,e);this.checked(n.Null(),h,t,!0)}async execute(t,r,e,o={}){let{runOwnedSshCommand:s}=await import("./chunk-ABFCAOU5.js");return s({...this.target,workspace:e},t,r,p(this.target.id,e).source,{signal:o.signal,timeoutMs:o.timeoutMs??3e4,maxBytes:32*1024*1024,limitCode:"CONTENT_LIMIT",closeInput:!0,effect:"unknown"})}async startProcess(t,r,e,o={}){let{startSshProcess:s}=await import("./chunk-5KFVDYCI.js");return s(this.target,t,r,e,o)}checked(t,r,e,o){if(!x.Check(t,r))throw new d("INVALID_RESPONSE",p(this.target.id,e).source,o?"unknown":"not-applied")}async request(t,r,e){let o=typeof t.path=="string"?t.path:typeof t.cwd=="string"?t.cwd:this.target.workspace,s=p(this.target.id,o).source,c=e.timeoutMs??3e4;if(!Number.isFinite(c)||c<=0)throw new TypeError("SSH operation deadline must be positive");e.signal?.throwIfAborted();let{runOwnedSshCommand:u}=await import("./chunk-ABFCAOU5.js"),g=await y(new URL("./ssh-worker.py",new URL("../src/backend/ssh.ts",import.meta.url).href)),l=await u({...this.target,workspace:t.operation==="gitIndex"?o:"/"},"python3",["-c",g],s,{signal:e.signal,timeoutMs:c,maxBytes:48*1024*1024,limitCode:"CONTENT_LIMIT",effect:r?"unknown":"not-applied",input:Buffer.from(JSON.stringify(t))});if(l.exitCode!==0)throw new d("REMOTE_OPERATION_FAILED",s,r?"unknown":"not-applied");let h;try{h=JSON.parse(l.stdout.toString("utf8"))}catch{throw new d("INVALID_RESPONSE",s,r?"unknown":"not-applied")}if(!j(h))throw new d("INVALID_RESPONSE",s,r?"unknown":"not-applied");if(!h.ok)throw new d(h.code,s,h.effect);return h.data}};function j(i){return x.Check(A,i)}a(j,"isReply");export{p as a,O as b,S as c,F as d,D as e,H as f,d as g,w as h};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as T,i as m,j as M}from"./chunk-R5XJSEOE.js";import{a as p}from"./chunk-EI7MMDWY.js";import{Type as o}from"typebox";var E=o.Union([o.Literal("pending"),o.Literal("applied"),o.Literal("not-applied"),o.Literal("unknown")]),b=o.Object({source:o.String(),effect:E,state:o.Optional(o.Union([o.Literal("present"),o.Literal("absent"),o.Literal("unknown")]))},{additionalProperties:!1}),L={effect:E,files:o.Array(b)};function R(n){return o.Object({operation:o.Literal(n),...L,operationId:o.Optional(o.String()),...n==="delete"?{}:{target:o.Optional(o.String()),targetUnavailable:o.Optional(o.String())}},{additionalProperties:!1})}p(R,"mutationDataSchema");function v(n){return T(R(n))}p(v,"mutationResultSchema");function u(n){return typeof n=="object"&&n!==null}p(u,"record");function U(n,c,h=[]){let r=n.details,l=u(r)?r:{};if((u(r)&&u(r.nativeEditBatch)?r.nativeEditBatch:void 0)?.state==="accepted")return{status:"success",errors:[],data:{operation:c,effect:"pending",...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},files:typeof l.source=="string"?[{source:l.source,effect:"pending"}]:[]}};let g=new Set(h.map(t=>t.resourceSource)),s=[],f=[],y=r.results;for(let t of y??[]){let e=t.data,k=[...new Set([...(e.files??[]).map(i=>i.path),...e.path?[e.path]:[],...e.rollback?.failedSources??[],...e.rollback?.restoredSources??[]])];for(let i of k)f.push({source:i,...g.has(i)?{state:"present"}:{},effect:g.has(i)||e.ok===!0&&e.files?.some(A=>A.path===i)?"applied":e.rollback?.failedSources.includes(i)?"unknown":e.rollback?.restoredSources.includes(i)?"not-applied":r.effect??"unknown"});for(let i of e.errors??[])s.push({code:i.code??"MUTATION_FAILED",message:i.reason??"Mutation failed",source:i.path});e.ok===!1&&(e.errors?.length??0)===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed",...e.path?{source:e.path}:{}})}for(let t of g)f.some(e=>e.source===t)||f.push({source:t,effect:"applied",state:"present"});let a=u(r.metadata)&&u(r.metadata.semanticAction)?r.metadata.semanticAction:void 0;if(a){let t=a.effect==="not-applied"||a.effect==="unknown"?a.effect:a.ok===!1?"unknown":"applied",e=typeof a.source=="string"?a.source:void 0;e&&f.push({source:e,...a.kind==="file-operation"&&a.ok===!0?{state:c==="delete"||c==="move"?"absent":"present"}:{},effect:c==="copy"&&typeof a.target=="string"&&a.target!==e?"not-applied":t}),typeof a.target=="string"&&f.push({source:a.target,effect:t,...a.kind==="file-operation"&&a.ok===!0?{state:"present"}:{}}),u(a.error)&&s.push(m(a.error.message,typeof a.error.code=="string"?a.error.code:"MUTATION_FAILED",e)),typeof a.postProcessingError=="string"&&s.push(m(a.postProcessingError,"POST_EDIT_FAILED",e)),a.ok===!1&&s.length===0&&s.push(m("Resource operation failed","MUTATION_FAILED",e))}let d=[...new Map(f.map(t=>[t.source,t])).values()];if(Array.isArray(r.metadata?.resultFileStates))for(let t of r.metadata.resultFileStates){if(!u(t))continue;let e=d.find(k=>k.source===t.source);e&&(t.state==="present"||t.state==="absent")&&(e.state=t.state)}let S=d.some(t=>t.effect==="applied");n.isError&&s.length===0&&s.push({code:"MUTATION_FAILED",message:"Mutation failed"}),(y?.length??0)===0&&!a&&g.size===0&&s.length===0&&r.effect!=="not-applied"&&s.push({code:"UNKNOWN_RESULT",message:"Mutation effects were not reported"});let w=r.effect==="unknown"||d.some(t=>t.effect==="unknown")||s.some(t=>t.code==="UNKNOWN_RESULT")?"unknown":S?"applied":"not-applied";return{status:s.length===0?"success":!a&&S&&d.some(t=>t.effect!=="applied")?"partial":"error",data:{operation:c,effect:w,files:d,...c!=="delete"&&typeof r.metadata?.resultTarget=="string"?{target:r.metadata.resultTarget}:{},...c!=="delete"&&typeof r.metadata?.targetUnavailable=="string"?{targetUnavailable:r.metadata.targetUnavailable}:{}},errors:s}}p(U,"mutationOutcome");function F(n,c,h=[],r){let l=U(n,c,h);return l.data&&r!==void 0&&(l.data.operationId=r),M(n,R(c),l)}p(F,"structuredMutation");export{R as a,v as b,U as c,F as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as d,g,h as c}from"./chunk-EY65TFHJ.js";import{a as s}from"./chunk-EI7MMDWY.js";import{readFile as p}from"node:fs/promises";import a from"node:path";import{Type as i}from"typebox";import{Value as f}from"typebox/value";var S=i.Object({targets:i.Array(i.Object({id:i.String(),host:i.String(),workspace:i.String(),configFile:i.Optional(i.String({minLength:1}))},{additionalProperties:!1}))},{additionalProperties:!1});function T(o){return{globalPath:a.join(a.dirname(o.globalPath),"ssh.json"),projectPath:a.join(a.dirname(o.projectPath),"ssh.json")}}s(T,"resolveSshConfigPaths");async function j(o){let r=await h(o.globalPath),t=await h(o.projectPath),e=new Map(r.map(n=>[n.id,n]));for(let n of t)e.set(n.id,n);return[...e.values()]}s(j,"readSshTargets");async function h(o){let r;try{r=await p(o,"utf8")}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return[];throw new Error(`Cannot read SSH settings at ${o}`,{cause:t})}try{let t=JSON.parse(r);if(!f.Check(S,t))throw new Error("Invalid settings");return u(t,o)}catch{throw new Error(`Invalid SSH settings at ${o}`)}}s(h,"readScope");function u(o,r){let t=new Set;return o.targets.map(e=>{if(t.has(e.id))throw new Error("Duplicate target");t.add(e.id);let n={id:e.id,host:e.host,workspace:e.workspace,...e.configFile===void 0?{}:{configFile:a.resolve(a.dirname(r),e.configFile)}};return new c(n).target})}s(u,"validateScope");var l=class{static{s(this,"SshBackendRegistry")}#t=new Map;constructor(r){for(let t of r){if(this.#t.has(t.id))throw new TypeError(`Duplicate SSH target: ${t.id}`);this.#t.set(t.id,new c(t))}}resolve(r,t){let e=d(r,t);if(!e)return;let n=this.#t.get(e.target);if(!n)throw new g("UNKNOWN_TARGET",e.source,"not-applied");return{location:e,backend:n}}};export{T as a,j as b,l as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as E}from"./chunk-R5XJSEOE.js";import{e as f}from"./chunk-ZPT5D4VP.js";import{a as o}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as n}from"typebox/value";import{execFile as I}from"node:child_process";import{lstat as O,readdir as k,readFile as _,readlink as L,realpath as h}from"node:fs/promises";import i from"node:path";import v from"node:os";import{promisify as C}from"node:util";var F=C(I);function A(t){return t.isSymbolicLink()?"symlink":t.isDirectory()?"directory":t.isFile()?"file":"other"}o(A,"kind");function R(t){return JSON.stringify([t.dev,t.ino,t.birthtimeMs,t.ctimeMs,t.mtimeMs,t.size,t.mode])}o(R,"revision");async function x(t){return O(t).catch(r=>{if(r.code!=="ENOENT")throw r})}o(x,"optionalStat");async function b(t){try{return await h(t)}catch(r){if(r.code!=="ENOENT"||await x(t))throw r;return i.join(await b(i.dirname(t)),i.basename(t))}}o(b,"resolveParent");async function S(t,r){let c=i.join(await b(i.dirname(t)),i.basename(t)),l=[],p=o(async(s,d)=>{r?.throwIfAborted();let a=await x(s);if(a===void 0){if(d!=="")throw Object.assign(new Error("Transfer entry disappeared"),{code:"TRANSFER_TARGET_CHANGED"});return}let T={relativePath:d,kind:A(a),revision:R(a),identity:{device:String(a.dev),inode:String(a.ino)},mode:a.mode,...a.isSymbolicLink()?{link:(await L(s,{encoding:"buffer"})).toString("base64")}:{}};if(l.push(T),T.kind==="directory"){for(let m of(await k(s)).sort())await p(i.join(s,m),d===""?m:`${d}/${m}`);let y=await x(s);if(y===void 0||R(y)!==T.revision)throw Object.assign(new Error("Transfer directory changed while inspecting its children"),{code:"TRANSFER_TARGET_CHANGED"})}},"walk");return await p(c,""),{path:c,entries:l}}o(S,"snapshotLocalObjects");var N={owner:"local",async temporaryEnvironment(t){t?.throwIfAborted();let r=process.env.PI_CODING_AGENT_DIR?.trim();return{home:v.homedir(),temporary:v.tmpdir(),...r?{agentDirectory:i.resolve(r)}:{}}},pathStyle:"native",realpath:h,async inspect(t){let r=await O(t);return{kind:A(r),revision:R(r),identity:{device:String(r.dev),inode:String(r.ino)},mode:r.mode}},read:o(t=>_(t,"utf8"),"read"),async git(t,r,c){let l=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_"))),{stdout:p}=await F("git",["-C",t,...r],{env:{...l,GIT_OPTIONAL_LOCKS:"0"},signal:c,timeout:5e3,maxBuffer:16*1024*1024});return p},source:o(t=>t,"source"),snapshot:S};var u="pi-agent-text-editor",P=32,oe="pi-agent-text-editor/position",ie="pi-agent-text-editor/search",ne=`${u}/core/ready`,se=`${u}/plugin/register`,g=e.Function([],e.Unknown()),D=e.Object({tryResolve:g},{additionalProperties:!0}),j=e.Object({lineNumber:e.Integer({minimum:1}),column:e.Integer({minimum:0})}),M=e.Object({start:j,end:j,linewise:e.Optional(e.Boolean())}),G=e.Object({source:e.String({minLength:1}),ranges:e.Optional(e.Array(M))}),q=e.Union([e.Object({kind:e.Literal("not-handled")},{additionalProperties:!0}),e.Object({kind:e.Literal("resolved"),targets:e.Array(G,{minItems:1})},{additionalProperties:!0}),e.Object({kind:e.Literal("rejected"),rejection:e.Object({code:e.Union([e.Literal("invalid"),e.Literal("stale"),e.Literal("missing"),e.Literal("ambiguous")]),reason:e.String(),contextRange:e.Optional(e.Object({offset:e.Number(),limit:e.Number()}))})},{additionalProperties:!0}),e.Object({kind:e.Literal("failed"),error:e.Unknown()},{additionalProperties:!0})]),V=e.String({pattern:"\\S"}),X=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),U=e.Object({resolver:e.Unknown(),resources:e.Optional(e.Unknown()),kind:e.String({pattern:"\\S"}),type:e.Union([e.Literal("major"),e.Literal("auxiliary"),e.Literal("constant")]),priority:e.Optional(e.Number())}),H=e.Object({protocol:e.Literal(u),apiVersion:e.Literal(P)}),w=e.Object({protocol:e.Literal(u),apiVersion:e.Literal(P),id:e.String(),setup:g}),K=e.Object({plugin:w,accept:g});function ae(t){return n.Check(V,t)}o(ae,"isTextEditorToolId");function ce(t){if(!n.Check(X,t))return!1;let r=t;return E(r.resolver)&&(!("priority"in r)||typeof r.priority=="number")}o(ce,"isResourceResolverRegistration");function le(t){if(!n.Check(U,t))return!1;let r=t;return f(r.resolver)&&(!("resources"in r)||n.Check(D,r.resources))&&(!("priority"in r)||typeof r.priority=="number")}o(le,"isTextAnchorResolverRegistration");function pe(t){return n.Check(q,t)}o(pe,"isTextAnchorResourceResolutionAttempt");function de(t){return n.Check(H,t)}o(de,"isTextEditorCoreReady");function ue(t){return n.Check(w,t)}o(ue,"isTextEditorPlugin");function Te(t){return n.Check(K,t)}o(Te,"isTextEditorPluginRegistrationRequest");export{S as a,N as b,u as c,P as d,oe as e,ie as f,ne as g,se as h,ae as i,ce as j,le as k,pe as l,de as m,ue as n,Te as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as B,h as M}from"./chunk-XH5WN5XA.js";import{a as N}from"./chunk-
|
|
1
|
+
import{d as B,h as M}from"./chunk-XH5WN5XA.js";import{a as N}from"./chunk-GW6NZQTQ.js";import{i as w,j as P}from"./chunk-R5XJSEOE.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as $}from"partial-json";import{Guard as f}from"typebox-guard/guard";import{Allow as F,parse as H}from"partial-json";function _(o,e=F.ALL){if(!(!o||o.trim().length===0))try{let t=H(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(_,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),i=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),s=e.filterEntries?.(i,t)??i,d=new Set(s.map(c=>c.index));for(let c of i)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of s)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as W}from"@earendil-works/pi-ai";var O=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function K(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((i,s)=>{if(!i)return;let d=s.modelRegistry.getProvider(i.provider);if(!d)return;let u=r.get(i.provider);if(u){if(u.subscribers.add(a),u.api===i.api&&d.streamSimple===u.wrapper)return;u.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:u.wrapper});return}let m=d.streamSimple[O];if(m){if(m.subscribers.add(a),r.set(i.provider,m),m.api===i.api)return;m.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,v,C)=>U(c,p,v,C,g),"wrapper"),E={api:i.api,delegate:c,wrapper:b,subscribers:g};b[O]=E;let h=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...h,api:i.api,streamSimple:b}),r.set(i.provider,E)},"install");o.on("before_provider_request",(i,s)=>{a.context=s,l(s.model,s)}),o.on("turn_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("agent_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("session_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("model_select",(i,s)=>{a.context=s,l(i.model,s)}),o.on("session_shutdown",()=>{for(let[i,s]of r)s.subscribers.delete(a),s.subscribers.size===0&&o.unregisterProvider(i);r.clear(),a.context=void 0})}y(K,"registerStreamingInterceptorProvider");function U(o,e,t,n,r){let a=W(),l=new AbortController,i=n?.signal,s=!1,d=Y(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(h=>{for(let p of r)p.markStreamEventProcessed(h)},"markStreamEventProcessed"),E=y(()=>{l.abort()},"abortFromParent");return i&&(i.aborted?l.abort():i.addEventListener("abort",E,{once:!0})),(async()=>{try{let h=o(e,t,{...n,signal:l.signal});for await(let p of h){if(s)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),Q(p,u);let v;for(let C of r){let I=C.context;if(I){let T=await C.processStreamEvent(p,I);v??=T}}if(b(p),q(p,m,c,g),a.push(structuredClone(p)),v){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);s=!0,l.abort();let C=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,A)=>u.has(A)&&(C===void 0||A<=C||g.has(A))).map(x=>x.type==="toolCall"&&x.id===v.toolCallId?{...x,arguments:structuredClone(v.arguments)}:x)};V(a,b,I,u,m,c,g);let{errorMessage:T,...L}=I;a.push({type:"done",reason:"toolUse",message:{...L,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(h){if(s)return;let p=d,v=i?.aborted===!0?"aborted":"error",C={...p,stopReason:v,errorMessage:h instanceof Error?h.message:String(h)};a.push({type:"error",reason:v,error:C}),a.end()}finally{i?.removeEventListener("abort",E)}})(),a}y(U,"wrapStream");function Q(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(Q,"rememberStartEvent");function q(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(q,"rememberEndEvent");function V(o,e,t,n,r,a,l){for(let[i,s]of t.content.entries())if(n.has(i)){if(s.type==="text"&&!r.has(i)){let d={type:"text_end",contentIndex:i,content:s.text,partial:t};e(d),o.push(d)}else if(s.type==="thinking"&&!a.has(i)){let d={type:"thinking_end",contentIndex:i,content:s.thinking,partial:t};e(d),o.push(d)}else if(s.type==="toolCall"&&!l.has(i)){let d={type:"toolcall_end",contentIndex:i,toolCall:s,partial:t};e(d),o.push(d)}}}y(V,"emitMissingEndEvents");function Y(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Y,"emptyAssistantMessage");var Z="agentic-ide-partial-tool-recovery",G="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
|
|
2
2
|
`)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r){let a=r.details,l=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",i=r.content.flatMap(s=>s.type==="text"?[s.text]:[]).join(`
|
|
3
3
|
`);return P({content:r.content,details:a},N(t.toolName),{status:"error",errors:[w(i,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:l,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{y(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=_(a,$.OBJ|$.ARR)??{},i=ee(a),s=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:s,toolName:n,args:l,complete:i!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!i&&Object.keys(l).length===0)return;let u=i!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=i??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:s,batchEntries:this.getBatchEntries(s),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let i=!this.completeArgumentContentIndices.has(e.contentIndex),s;i&&(this.completeArgumentContentIndices.add(e.contentIndex),s=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),s}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=j(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=j(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit(G,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=X(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let i={content:[{type:"text",text:e.message.content}],details:B(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:i,...r&&{blockExecution:!0}}),i}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,s=(f.IsObjectNotArray(l)&&f.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(s))for(let d of s)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=f.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,i=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],s=[...new Set(r.map(g=>g.ctx.toolCall.id))],d=r.map(g=>g.blocked.message.details),u=r[0],m=u?this.recoveryRegistry.recoveryKeyFor(u.ctx.toolCall.name):void 0;if(!m)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:i,blockedToolCallIds:s,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?re(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=y(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function j(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}y(j,"toolStreamEventKey");function X(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}y(X,"abortReason");function ee(o){try{let e=JSON.parse(o);return f.IsObjectNotArray(e)?e:void 0}catch{return}}y(ee,"parseCompleteArguments");function te(o){let e=o.normalResult;if(!f.IsObjectNotArray(e)||!f.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=f.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(f.IsObjectNotArray).map(s=>f.IsObjectNotArray(s.data)?s.data:s),a=n===void 0?r:r.filter(s=>s.path===n),i=(a.length>0?a:r).flatMap(s=>{let d=s.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(i)]}y(te,"freshAnchorsAfterRecovery");function ne(o,e){let n=o.indexOf(`
|
|
4
4
|
|