pi-agent-ide 0.6.3 → 0.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -0
- package/README.md +8 -1
- package/dist/chunk-2P2OGO3G.js +2 -0
- package/dist/{chunk-5QQABP47.js → chunk-3BBJZSMS.js} +1 -1
- package/dist/chunk-5J43L2RL.js +11 -0
- package/dist/{chunk-ITSNK5YG.js → chunk-7AVXUV4A.js} +2 -2
- package/dist/chunk-BAYETTZZ.js +16 -0
- package/dist/{chunk-VCTK4JSN.js → chunk-BSICWXMH.js} +1 -1
- package/dist/chunk-BVK5A7ED.js +28 -0
- package/dist/{chunk-ZM4L5AGN.js → chunk-EDURPQAV.js} +3 -2
- package/dist/{chunk-L7JMDDSD.js → chunk-FBOW7XOV.js} +1 -1
- package/dist/{chunk-25CZ5ZIU.js → chunk-FUG2TEKI.js} +1 -1
- package/dist/chunk-FZBCKIJJ.js +1 -0
- package/dist/chunk-HPUAIWIH.js +25 -0
- package/dist/chunk-I5JLCFUX.js +1 -0
- package/dist/chunk-KUPHNMUK.js +2 -0
- package/dist/{chunk-NTYXZ3EL.js → chunk-KVHDMIZS.js} +1 -1
- package/dist/{chunk-QDST6VIU.js → chunk-KZC7TI5M.js} +1 -1
- package/dist/chunk-MIZAFRDR.js +1 -0
- package/dist/chunk-PJPA5EEE.js +2 -0
- package/dist/{chunk-GUTQ3PWL.js → chunk-PLKYHUNT.js} +1 -1
- package/dist/chunk-QEJGED4V.js +28 -0
- package/dist/chunk-SILJ3OL4.js +9 -0
- package/dist/{chunk-VXD6FZP5.js → chunk-TQZBVOTT.js} +3 -3
- package/dist/chunk-VBICI5YA.js +1 -0
- package/dist/chunk-VWW3RLUX.js +12 -0
- package/dist/{chunk-O6LE42GK.js → chunk-WJTHY6AG.js} +1 -1
- package/dist/chunk-YGGKGZO2.js +1 -0
- package/dist/chunk-ZODCBFBL.js +2 -0
- package/dist/chunk-ZPT5D4VP.js +2 -0
- package/dist/entry-0.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-16.js +1 -1
- package/dist/entry-17.js +1 -1
- package/dist/entry-25.js +2 -2
- package/dist/entry-26.js +1 -1
- package/dist/entry-27.js +1 -1
- package/dist/entry-28.js +1 -1
- package/dist/entry-29.js +1 -1
- package/dist/entry-30.js +1 -1
- package/dist/entry-31.js +11 -11
- package/dist/entry-33.js +1 -1
- package/dist/entry-37.js +2 -2
- package/dist/entry-42.js +1 -1
- package/dist/entry-44.js +1 -1
- package/dist/entry-45.js +13 -12
- package/dist/entry-46.js +1 -1
- package/dist/entry-49.js +1 -1
- package/dist/entry-50.js +4 -4
- package/dist/entry-51.js +9 -9
- package/dist/entry-52.js +1 -1
- package/dist/entry-53.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 -1
- package/dist/entry-63.js +1 -1
- package/dist/entry-66.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 -324
- package/dist/entry-78.js +324 -25
- package/dist/entry-79.js +18 -2
- package/dist/entry-80.js +2 -1
- package/dist/entry-81.js +1 -1
- package/dist/entry-82.js +1 -3
- package/dist/entry-83.js +5 -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 +15 -3
- package/docs/agent-guides/editing.md +12 -0
- package/docs/agent-guides/json-reading.md +19 -3
- package/docs/agent-guides/read-resources.md +6 -0
- package/docs/agent-guides/search-code.md +5 -1
- package/docs/agent-guides/terminal.md +1 -1
- package/docs/code-review.md +99 -0
- package/docs/configuration.md +34 -0
- package/docs/development.md +15 -19
- package/docs/nightly.md +7 -0
- package/docs/releases.md +42 -0
- package/docs/research/native-codemode-batch-decision.md +27 -0
- package/docs/research/native-codemode-batching.md +65 -0
- package/docs/structured-results.md +59 -0
- package/docs/tools.md +18 -2
- package/node_modules/pi-agent-doctor/package.json +1 -1
- package/node_modules/pi-agent-documentation/package.json +1 -1
- package/node_modules/pi-agent-documentation/src/index.ts +1 -1
- package/node_modules/pi-agent-filesystem/index.ts +6 -1
- package/node_modules/pi-agent-filesystem/package.json +7 -6
- package/node_modules/pi-agent-filesystem/src/path-recovery.ts +109 -0
- package/node_modules/pi-agent-filesystem-image/package.json +3 -3
- package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
- package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
- package/node_modules/pi-agent-filesystem-text/package.json +3 -3
- package/node_modules/pi-agent-ide-ast/package.json +10 -10
- package/node_modules/pi-agent-ide-ast/src/overflow-handler.ts +6 -1
- package/node_modules/pi-agent-ide-ast/src/scope-handler.ts +6 -2
- package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +17 -0
- package/node_modules/pi-agent-ide-changes/index.ts +3 -9
- package/node_modules/pi-agent-ide-changes/package.json +8 -7
- package/node_modules/pi-agent-ide-changes/src/current-change-presenter.ts +5 -0
- package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +125 -47
- package/node_modules/pi-agent-ide-formatter/package.json +3 -3
- package/node_modules/pi-agent-ide-languages/package.json +2 -2
- package/node_modules/pi-agent-ide-lint/package.json +7 -7
- package/node_modules/pi-agent-ide-lsp/package.json +9 -9
- package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +19 -0
- package/node_modules/pi-agent-image/package.json +2 -2
- package/node_modules/pi-agent-invariant/package.json +1 -1
- package/node_modules/pi-agent-pdf/package.json +2 -2
- package/node_modules/pi-agent-read/package.json +7 -7
- package/node_modules/pi-agent-read/src/api/tools/read.ts +31 -2
- package/node_modules/pi-agent-read/src/core/tools/read/raw-read.ts +9 -10
- package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +28 -15
- package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +216 -0
- package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +119 -72
- package/node_modules/pi-agent-resource/package.json +1 -1
- package/node_modules/pi-agent-resource/src/index.ts +12 -0
- package/node_modules/pi-agent-resource/src/resource-access.ts +55 -0
- package/node_modules/pi-agent-resource/src/resource-scheduler.ts +204 -0
- package/node_modules/pi-agent-resource/src/tool-result.ts +125 -0
- package/node_modules/pi-agent-search/package.json +5 -4
- package/node_modules/pi-agent-search/src/api/search-parameters.ts +6 -5
- package/node_modules/pi-agent-search/src/api/search.ts +11 -0
- package/node_modules/pi-agent-search/src/api/structured-result.ts +93 -0
- package/node_modules/pi-agent-search/src/core/extension.ts +40 -14
- package/node_modules/pi-agent-search/src/core/search-core.ts +136 -77
- package/node_modules/pi-agent-search-text/index.ts +3 -0
- package/node_modules/pi-agent-search-text/package.json +6 -6
- package/node_modules/pi-agent-search-text/src/resolvers.ts +17 -0
- package/node_modules/pi-agent-search-text/src/search-backend.ts +104 -8
- package/node_modules/pi-agent-search-text/src/search-query.ts +42 -34
- package/node_modules/pi-agent-search-text/src/search-recipe.ts +18 -4
- package/node_modules/pi-agent-search-text/src/search-renderer.ts +37 -3
- package/node_modules/pi-agent-search-text/src/search-session.ts +21 -13
- package/node_modules/pi-agent-text/package.json +2 -2
- package/node_modules/pi-agent-text/src/text-document.ts +15 -10
- package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
- package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
- package/node_modules/pi-agent-text-anchor-exact/src/anchor.ts +4 -3
- package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
- package/node_modules/pi-agent-text-editor/index.ts +4 -2
- package/node_modules/pi-agent-text-editor/package.json +21 -17
- package/node_modules/pi-agent-text-editor/runtime/entry-77.js +0 -1
- package/node_modules/pi-agent-text-editor/src/api/mutation-preview.ts +2 -0
- package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +6 -0
- package/node_modules/pi-agent-text-editor/src/api/native-edit-batch-event.ts +12 -0
- package/node_modules/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +4 -0
- package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +95 -34
- package/node_modules/pi-agent-text-editor/src/core/apply/results.ts +4 -0
- package/node_modules/pi-agent-text-editor/src/core/apply/structured-result.ts +251 -0
- package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +32 -12
- package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +154 -132
- package/node_modules/pi-agent-text-editor/src/core/builtin-edit.ts +16 -0
- package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +74 -18
- package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +8 -0
- package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +6 -0
- package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
- package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +640 -0
- package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +20 -6
- package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +314 -0
- package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +143 -138
- package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +2 -0
- package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +242 -116
- package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +109 -47
- package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +25 -5
- package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +8 -4
- package/node_modules/pi-agent-text-editor-renderer/index.ts +8 -1
- package/node_modules/pi-agent-text-editor-renderer/package.json +7 -6
- package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +262 -129
- package/node_modules/pi-agent-text-editor-renderer/src/diff-renderer.ts +36 -2
- package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +28 -2
- package/node_modules/pi-agent-text-editor-renderer/src/mutation-projection.ts +40 -10
- package/node_modules/pi-agent-text-editor-stale-anchor/index.ts +16 -1
- 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 +20 -0
- package/node_modules/pi-agent-web/package.json +8 -7
- package/node_modules/pi-agent-web/src/search.ts +112 -0
- 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 +42 -36
- package/skills/capture-code-review-rule/SKILL.md +60 -0
- package/src/code-review/config.ts +68 -0
- package/src/code-review/extension.ts +105 -0
- package/src/code-review/fragments.ts +26 -0
- package/src/code-review/reviewer.ts +198 -0
- package/src/composite/host-version.ts +13 -0
- package/src/composite/nested-tool-rendering.ts +298 -0
- package/src/composite/tool-availability.ts +90 -0
- package/src/core/extension.ts +2 -0
- package/src/documentation/extension.ts +81 -145
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +6 -1
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -6
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/src/path-recovery.ts +109 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +20 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -7
- 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/search.ts +112 -0
- package/src/extensions/pi-agent-read/package.json +7 -7
- package/src/extensions/pi-agent-read/src/api/tools/read.ts +31 -2
- package/src/extensions/pi-agent-read/src/core/tools/read/raw-read.ts +9 -10
- package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +28 -15
- package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +216 -0
- package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +119 -72
- package/src/extensions/pi-agent-search/package.json +5 -4
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +3 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +6 -6
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +17 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +104 -8
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-query.ts +42 -34
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-recipe.ts +18 -4
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +37 -3
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +21 -13
- package/src/extensions/pi-agent-search/src/api/search-parameters.ts +6 -5
- package/src/extensions/pi-agent-search/src/api/search.ts +11 -0
- package/src/extensions/pi-agent-search/src/api/structured-result.ts +93 -0
- package/src/extensions/pi-agent-search/src/core/extension.ts +40 -14
- package/src/extensions/pi-agent-search/src/core/search-core.ts +136 -77
- package/src/extensions/pi-agent-text-editor/index.ts +4 -2
- package/src/extensions/pi-agent-text-editor/package.json +21 -17
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/anchor.ts +4 -3
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +8 -1
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +7 -6
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +262 -129
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-renderer.ts +36 -2
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +28 -2
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-projection.ts +40 -10
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/index.ts +16 -1
- 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/mutation-preview.ts +2 -0
- package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +6 -0
- package/src/extensions/pi-agent-text-editor/src/api/native-edit-batch-event.ts +12 -0
- package/src/extensions/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +4 -0
- package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +95 -34
- package/src/extensions/pi-agent-text-editor/src/core/apply/results.ts +4 -0
- package/src/extensions/pi-agent-text-editor/src/core/apply/structured-result.ts +251 -0
- package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +32 -12
- package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +154 -132
- package/src/extensions/pi-agent-text-editor/src/core/builtin-edit.ts +16 -0
- package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +74 -18
- package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +8 -0
- package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +6 -0
- package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +2 -0
- package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +640 -0
- package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +20 -6
- package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +314 -0
- package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +143 -138
- package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +2 -0
- package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +242 -116
- package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +109 -47
- package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +25 -5
- package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +8 -4
- package/src/pi-agent-ide.ts +61 -2
- package/src/plugins/pi-agent-ide-ast/package.json +10 -10
- package/src/plugins/pi-agent-ide-ast/src/overflow-handler.ts +6 -1
- package/src/plugins/pi-agent-ide-ast/src/scope-handler.ts +6 -2
- package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +17 -0
- package/src/plugins/pi-agent-ide-changes/index.ts +3 -9
- package/src/plugins/pi-agent-ide-changes/package.json +8 -7
- package/src/plugins/pi-agent-ide-changes/src/current-change-presenter.ts +5 -0
- package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +125 -47
- package/src/plugins/pi-agent-ide-debugger/index.ts +63 -17
- package/src/plugins/pi-agent-ide-debugger/src/catalog.ts +18 -2
- package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +24 -4
- package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +68 -2
- package/src/plugins/pi-agent-ide-debugger/src/java-runtime.ts +357 -0
- package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +55 -3
- package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +13 -13
- package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
- package/src/plugins/pi-agent-ide-languages/package.json +2 -2
- package/src/plugins/pi-agent-ide-lint/package.json +7 -7
- package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
- package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +19 -0
- package/src/plugins/pi-agent-ide-terminal/index.ts +12 -2
- package/src/plugins/pi-agent-ide-terminal/src/output-limits.ts +1 -1
- package/src/plugins/pi-agent-ide-terminal/src/resources.ts +65 -30
- package/src/plugins/pi-agent-ide-terminal/src/search.ts +13 -8
- package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +1 -0
- package/src/plugins/pi-agent-ide-terminal/src/shell-result.ts +100 -0
- package/src/plugins/pi-agent-ide-terminal/src/steering.ts +62 -0
- package/src/plugins/pi-agent-ide-terminal/src/tools.ts +97 -45
- package/src/plugins/pi-agent-ide-terminal/src/types.ts +3 -1
- package/src/plugins/pi-agent-ide-terminal/src/ui.ts +15 -6
- package/src/plugins/pi-agent-ide-vision/index.ts +16 -1
- package/dist/chunk-3E2NTWCN.js +0 -2
- package/dist/chunk-4LUW26BX.js +0 -10
- package/dist/chunk-5VSE5X5R.js +0 -2
- package/dist/chunk-CEX3VOJ7.js +0 -2
- package/dist/chunk-FA6BKC5Y.js +0 -1
- package/dist/chunk-FEDVTZJG.js +0 -1
- package/dist/chunk-HMLH43ZS.js +0 -4
- package/dist/chunk-KII2JQC5.js +0 -1
- package/dist/chunk-LVWMWWWF.js +0 -28
- package/dist/chunk-P7XO5CIP.js +0 -2
- package/dist/chunk-PZFOOHY2.js +0 -15
- package/dist/chunk-S3ZPXWX7.js +0 -2
- package/dist/chunk-T7CZIACQ.js +0 -27
- package/dist/chunk-YT42LKFV.js +0 -16
- package/node_modules/pi-agent-text-editor/src/core/builtin-edit-filter.ts +0 -52
- 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-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-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +0 -2
- package/src/extensions/pi-agent-text-editor/src/core/builtin-edit-filter.ts +0 -52
- /package/dist/{chunk-4U2GUKNJ.js → chunk-F7NVAC4Q.js} +0 -0
- /package/dist/{chunk-ROXXK6TW.js → chunk-PXWDDBBC.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-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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,64 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.4 — 2026-10-03
|
|
4
|
+
|
|
5
|
+
### Native Pi integration
|
|
6
|
+
|
|
7
|
+
- Support Pi 0.99.1 and newer hosts with native tool namespaces, discovery, and Codemode execution.
|
|
8
|
+
- Keep the built-in edit placeholder hidden from declarations, discovery, and nested calls.
|
|
9
|
+
- Return structured IDE and shell results with explicit success, error, and partial outcomes.
|
|
10
|
+
- Batch sequential Codemode text edits against shared snapshots and expose committed results through `flush()`.
|
|
11
|
+
- Run disjoint Read, Search, and editing operations concurrently while preserving ordering and rollback protection for shared resources.
|
|
12
|
+
- Attach first-use guides without blocking or replaying tool calls, and preserve guidance across nested calls and session navigation.
|
|
13
|
+
- Keep IDE panels visible for nested calls, show final batch diffs without duplicate bookkeeping panels, and preserve bounded history and native usage accounting.
|
|
14
|
+
- Verify IDE tool coexistence with native MCP tools and resources.
|
|
15
|
+
|
|
16
|
+
### Packaging
|
|
17
|
+
|
|
18
|
+
- Fix Windows release entrypoint resolution, npm packing, and archive extraction.
|
|
19
|
+
|
|
20
|
+
### Editing and reading
|
|
21
|
+
|
|
22
|
+
- Suggest up to three nearby workspace paths when a local file is missing, without reading another file automatically.
|
|
23
|
+
- Preserve neighboring blank separators when exact-text anchors already include a newline.
|
|
24
|
+
- Bound large committed Apply results before serialization and keep full results addressable.
|
|
25
|
+
- Preserve structured source data when AST output exceeds the preview budget.
|
|
26
|
+
- Run independent post-read handlers concurrently while applying their transforms in order.
|
|
27
|
+
- Document and verify jq views for JSONL inspection.
|
|
28
|
+
|
|
29
|
+
### Search and presentation
|
|
30
|
+
|
|
31
|
+
- Search converted HTTP pages by URL, including regular-expression queries.
|
|
32
|
+
- Execute Boolean search without unsupported generated lookaround expressions.
|
|
33
|
+
- Keep Search footers within narrow terminals, including 40-column layouts.
|
|
34
|
+
- Refresh diff caches after native theme palette changes and preserve panel backgrounds and keyboard focus.
|
|
35
|
+
- Show precise character-level edit highlights and bound diff comparisons; report unavailable totals when comparison limits are reached.
|
|
36
|
+
- Keep known added and removed lines visible when detailed pairing reaches its limit, and avoid repeated short-string similarity work.
|
|
37
|
+
- Remove the redundant Git preview channel.
|
|
38
|
+
|
|
39
|
+
### Terminal
|
|
40
|
+
|
|
41
|
+
- Release foreground terminal waits as soon as Pi accepts user steering. Keep the same command running in the background with retained output and normal completion notifications; follow-up messages keep their existing wait behavior.
|
|
42
|
+
- Send one stale reminder per terminal session, including across reloads, while keeping completion notifications.
|
|
43
|
+
- Expose the actual shell, executable, and command syntax to agents, including PowerShell guidance on Windows.
|
|
44
|
+
|
|
45
|
+
### Optional code review
|
|
46
|
+
|
|
47
|
+
- Add opt-in background Jev review of saved diff fragments against user-defined YAML rules, without blocking edits or replacing diagnostics.
|
|
48
|
+
- Ship a separately enabled rule-capture skill that proposes reusable review rules and waits for confirmation before saving them. Both features are off by default.
|
|
49
|
+
|
|
50
|
+
### Debugging
|
|
51
|
+
|
|
52
|
+
- Fix the Java debugger lifecycle on Linux and native Windows with a dedicated java-debug/JDT LS backend. Start owned JVM targets suspended so the first breakpoint is not missed, and preserve source, locals, continue, and termination handling.
|
|
53
|
+
- Route deletion of terminated debugger sessions and breakpoints through the debugger resource handler.
|
|
54
|
+
- Bound replayable DAP events so noisy debug targets do not grow the queue without limit.
|
|
55
|
+
- Check each debugger's own executable or configured adapter path instead of applying Python or JavaScript probes to unrelated adapters.
|
|
56
|
+
|
|
57
|
+
### Verification
|
|
58
|
+
|
|
59
|
+
- Temporarily skip the flaky Windows Java public-Pi startup test. Keep Linux public-Pi and native Windows Java lifecycle checks enabled.
|
|
60
|
+
- Retain unit test reports immediately and stop before integration tests when the unit suite fails. Keep content checks independent of wall-clock load and allow independent formatters to finish in either order.
|
|
61
|
+
|
|
3
62
|
## 0.6.3 — 2026-09-27
|
|
4
63
|
|
|
5
64
|
### Editing
|
package/README.md
CHANGED
|
@@ -63,6 +63,10 @@ Views change how the same resource is presented. The agent can request source st
|
|
|
63
63
|
|
|
64
64
|
</div>
|
|
65
65
|
|
|
66
|
+
### Review edits against your own rules
|
|
67
|
+
|
|
68
|
+
Optional [Jev code review](docs/code-review.md) checks small saved diffs against natural-language YAML rules you supply. It delivers background hints without replacing normal diagnostics. A separately enabled skill helps turn your review feedback into proposed rules, saved only after confirmation. Both features are off by default.
|
|
69
|
+
|
|
66
70
|
### Express edits as intentions
|
|
67
71
|
|
|
68
72
|
Editing uses direct semantic operations:
|
|
@@ -128,6 +132,8 @@ Filesystem and HTTP reads, resource views, content converters, search backends,
|
|
|
128
132
|
|
|
129
133
|
A person can see the agent's edits, diffs, diagnostics, running processes, debugger state, and failures. Bounded presentation keeps live output readable without discarding the underlying result. Guarded snapshots and first-class undo make mistakes visible and recovery inexpensive.
|
|
130
134
|
|
|
135
|
+
IDE tools called from native Codemode keep their custom panels in a separate block below the script, even when the script prints no results. Successful edits in one batch show one final diff per file, without intermediate edit cards or an extra block title. The panels survive session restore and tree navigation. Oversized or missing display data is marked as incomplete; rendering never repeats an operation or adds its cost again.
|
|
136
|
+
|
|
131
137
|
<div align="center">
|
|
132
138
|
|
|
133
139
|
[](assets/summary/user_terminal.png)
|
|
@@ -150,7 +156,7 @@ Pi Agent IDE is experimental and under active development. Interfaces and behavi
|
|
|
150
156
|
|
|
151
157
|
## Installation
|
|
152
158
|
|
|
153
|
-
Install [Pi](https://pi.dev/) first, then install Pi Agent IDE from npm
|
|
159
|
+
Install [Pi](https://pi.dev/) **0.99.1 or newer** first, then install Pi Agent IDE from npm. Development and integration tests use Pi 1.0.0. Older hosts are rejected with an upgrade message.
|
|
154
160
|
|
|
155
161
|
```bash
|
|
156
162
|
pi install npm:pi-agent-ide
|
|
@@ -216,6 +222,7 @@ If something breaks, behaves badly, or does not fit your workflow, please [open
|
|
|
216
222
|
| [File hooks](./docs/user-hooks.md) | Inspect, change, or deny reads and edits |
|
|
217
223
|
| [Writing extensions](./docs/extensions.md) | Add resolvers, views, anchors, search backends, and IDE plugins |
|
|
218
224
|
| [Development](./docs/development.md) | Work from a checkout, test, and run modular mode |
|
|
225
|
+
| [Releases](./docs/releases.md) | Nightly builds, release branches, verification, and npm publication |
|
|
219
226
|
|
|
220
227
|
## License
|
|
221
228
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as ae}from"node:async_hooks";function X(){return{pending:new Set,active:new ae}}o(X,"createSchedulerState");function ue(e,t){return e===void 0||t===void 0?!0:e.some(n=>t.some(r=>(n.mode==="write"||r.mode==="write")&&(n.resource==="*"||r.resource==="*"||n.resource===r.resource||n.recursive===!0&&r.resource.startsWith(n.resource.endsWith("/")?n.resource:`${n.resource}/`)||r.recursive===!0&&n.resource.startsWith(r.resource.endsWith("/")?r.resource:`${r.resource}/`))))}o(ue,"conflicts");function de(e,t,n){if(t===void 0||!n&&t.some(s=>s.mode!=="read"))return!1;if(e===void 0)return!0;let r=new Map;for(let s of t){let i=s.group??s.resource;r.set(i,[...r.get(i)??[],s])}return[...r.values()].every(s=>s.some(i=>e.some(a=>(i.mode==="read"||a.mode==="write")&&(a.resource==="*"||i.resource===a.resource&&(i.recursive!==!0||a.recursive===!0)||a.recursive===!0&&i.resource.startsWith(a.resource.endsWith("/")?a.resource:`${a.resource}/`)))))}o(de,"coveredAccess");async function le(e,t){if(t===void 0)return await e;t.throwIfAborted();let n,r=new Promise((s,i)=>{n=o(()=>i(t.reason),"abort"),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,r])}finally{t.removeEventListener("abort",n)}}o(le,"waitForDependencies");var I=class e{constructor(t=X()){this.state=t}static{o(this,"ResourceScheduler")}run(t,n,r,s={}){let i=Promise.resolve(t),a=this.state.active.getStore();if(a?.open){let S=i.then(R=>{if(r?.throwIfAborted(),!de(a.accesses,R,a.allowNestedWrites))throw Object.assign(new Error("Nested resource access must be covered by its parent reservation and permitted by its owner."),{code:"UNDECLARED_RESOURCE_ACCESS"});return R});a.nested??=new e;let f=a.nested.run(S,n,r,{allowNestedWrites:a.allowNestedWrites});return a.children.add(f),f.then(()=>a.children.delete(f),()=>a.children.delete(f)),f}let m=[...this.state.pending],p=i.catch(()=>{}),w,d=new Promise(S=>{w=S}),E={accesses:p,done:d};return this.state.pending.add(E),(async()=>{try{r?.throwIfAborted();let S=await le(i.then(async R=>(await Promise.all(m.map($=>Promise.race([$.done,$.accesses.then(ce=>ue(R,ce)?$.done:void 0)]))),R)),r);r?.throwIfAborted();let f={accesses:S,children:new Set,open:!0,allowNestedWrites:s.allowNestedWrites===!0};try{return await this.state.active.run(f,n)}finally{for(;f.children.size>0;)await Promise.allSettled([...f.children]);f.open=!1}}finally{this.state.pending.delete(E),w()}})()}},pe=Symbol.for("pi-agent-resource.resource-scheduler-state"),fe=globalThis,Ce=fe[pe]??=X(),me=new I(Ce);import{realpath as ye,stat as ve}from"node:fs/promises";import N from"node:path";import{fileURLToPath as ge}from"node:url";async function Q(e,t,n){if(/^[a-z][a-z\d+.-]*:/iu.test(e)&&!/^[a-z]:[\\/]/iu.test(e)&&!e.startsWith("file:"))return[{resource:e,mode:n}];let r=N.resolve(t,e.startsWith("file:")?ge(e):e),[s,i]=await Promise.allSettled([ye(r),ve(r,{bigint:!0})]),a;if(s.status==="fulfilled")a=s.value;else{let d=s.reason;if(!(d instanceof Error)||!("code"in d)||d.code!=="ENOENT")throw d;let E=N.dirname(r);if(E===r)a=r;else{let f=(await Q(E,t,n)).find(R=>R.resource.startsWith("file:"));a=N.join(f?.resource.slice(5)??E,N.basename(r))}}let m=a.split(N.sep).join("/"),p=`file:${process.platform==="win32"?m.toLowerCase():m}`,w=[{resource:p,group:p,mode:n}];if(i.status==="fulfilled"){let d=i.value;d.isDirectory()&&(w[0]={resource:p,group:p,mode:n,recursive:!0}),d.ino!==0n&&w.push({resource:`inode:${d.dev}:${d.ino}`,group:p,mode:n,recursive:d.isDirectory()})}else{let d=i.reason;if(!(d instanceof Error)||!("code"in d)||d.code!=="ENOENT")throw d}return w}o(Q,"resourceAccesses");import{Type as l}from"typebox";import{Value as Re}from"typebox/value";var W=l.Object({code:l.String(),message:l.String(),source:l.Optional(l.String())},{additionalProperties:!1});function Z(e){return l.Union([l.Object({status:l.Literal("success"),data:e,errors:l.Array(W,{maxItems:0})},{additionalProperties:!1}),l.Object({status:l.Union([l.Literal("error"),l.Literal("partial")]),data:l.Optional(e),errors:l.Array(W,{minItems:1})},{additionalProperties:!1})])}o(Z,"structuredResultSchema");var ee=1024*1024;function H(e){let t=new Set,n=o(r=>{if(!(r===null||typeof r=="string"||typeof r=="boolean")&&!(typeof r=="number"&&Number.isFinite(r))){if(typeof r!="object"||t.has(r))throw new TypeError("Structured data must be finite, acyclic JSON");if(!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null)throw new TypeError("Structured data must not contain classes or raw byte buffers");t.add(r);for(let s of Array.isArray(r)?r:Object.values(r))n(s);t.delete(r)}},"visit");if(n(e),Buffer.byteLength(JSON.stringify(e))>ee)throw new RangeError("Structured data exceeds 1 MiB; return a smaller window or a full-result reference")}o(H,"assertJsonData");function te(e,t="EXECUTION_FAILED",n){return{code:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:t,message:e instanceof Error?e.message:String(e),...n===void 0?{}:{source:n}}}o(te,"resultError");function he(e,t,n){try{if(H(n),!Re.Check(Z(t),n))throw new TypeError("Result adapter returned data outside its public schema");return{...e,structuredContent:n,isError:n.status!=="success"}}catch(r){let s=te(r,"INVALID_STRUCTURED_RESULT"),i={status:"error",errors:[s]};return H(i),{...e,content:[...e.content,{type:"text",text:s.message}],structuredContent:i,isError:!0}}}o(he,"withStructuredResult");function Te(e,t){if(t.length===0)return;let n=e.trim();if(n.length===0||/[\r\n]/u.test(n))throw new TypeError("Content provider summary must be one non-empty line");return[n,...t.map(({description:r})=>r)].join(`
|
|
2
|
+
`)}o(Te,"renderContentDescription");import{Type as u}from"typebox";import{Value as Pe}from"typebox/value";import{Type as c}from"typebox";import{Value as we}from"typebox/value";var C={additionalProperties:!0},k=c.Function([],c.Unknown()),y=c.String({minLength:1}),Ee=c.Object({type:c.Literal("text"),text:c.String(),textSignature:c.Optional(c.String())},C),Se=c.Object({type:c.Literal("image"),data:c.String(),mimeType:c.String()},C),be=c.Object({type:c.Literal("custom"),kind:y,data:c.Unknown()},C),Oe=c.Array(c.Union([Ee,Se,be]),{minItems:1}),ne=c.Union([c.Object({source:y,link:c.Optional(y),read:k,write:c.Optional(c.Never())},C),c.Object({source:y,link:c.Optional(y),read:c.Optional(c.Never()),write:k},C),c.Object({source:y,link:c.Optional(y),read:k,write:k},C)]),Ae=c.Object({id:y,tryResolve:k},C),xe=c.Union([c.Object({kind:c.Literal("not-handled")},C),c.Object({kind:c.Literal("resolved"),resource:ne},C),c.Object({kind:c.Literal("failed"),error:c.Unknown()},C)]);function q(e){return _(Oe,e)?D(()=>e.every(t=>t.type!=="text"||!("textSignature"in t)||typeof t.textSignature=="string")):!1}o(q,"isAgentContent");function re(e){return _(ne,e)?D(()=>{let t=e,n=!("read"in t)||typeof t.read=="function",r=!("write"in t)||typeof t.write=="function";return n&&r}):!1}o(re,"isResource");function Ne(e){return _(Ae,e)}o(Ne,"isResourceResolver");function ke(e){return _(xe,e)?D(()=>{let t=e;return t.kind!=="resolved"||re(t.resource)}):!1}o(ke,"isResourceResolutionAttempt");function _(e,t){return D(()=>we.Check(e,t))}o(_,"safeCheck");function D(e){try{return e()}catch{return!1}}o(D,"safeEvaluate");var v={additionalProperties:!0},je=u.Function([],u.Unknown()),L=u.String({minLength:1}),Ie=u.Object({provider:L,capability:u.Union([u.Literal("read"),u.Literal("write")])},v),_e=u.Object({source:L,bytes:u.Unknown(),mediaType:u.Optional(u.String())},v),De=u.Object({signal:u.Optional(u.Unknown())},v),Le=u.Object({id:L,description:L,tryConvert:je},v),Ue=u.Union([u.Object({kind:u.Literal("not-handled")},v),u.Object({kind:u.Literal("converted"),content:u.Unknown()},v),u.Object({kind:u.Literal("failed"),error:u.Unknown()},v)]),Ve=u.Object({target:u.Unknown(),converter:u.Unknown(),priority:u.Optional(u.Number())},v);function b(e){return O(Ie,e)&&T(()=>e.provider.trim().length>0)}o(b,"isContentTarget");function K(e){return O(_e,e)?T(()=>{let t=e;return t.bytes instanceof Uint8Array&&(!("mediaType"in t)||typeof t.mediaType=="string")}):!1}o(K,"isContentInput");function z(e){return O(De,e)?T(()=>{let t=e;return!("signal"in t)||t.signal instanceof AbortSignal}):!1}o(z,"isContentConversionContext");function oe(e){return O(Le,e)?T(()=>{let t=e;return t.id.trim().length>0&&t.description.trim().length>0&&!/[\r\n]/u.test(t.description)}):!1}o(oe,"isContentConverter");function F(e){return O(Ue,e)?T(()=>{let t=e;return t.kind!=="converted"||q(t.content)}):!1}o(F,"isContentConversionAttempt");function h(e){return O(Ve,e)?T(()=>{let t=e;return b(t.target)&&oe(t.converter)&&(!("priority"in t)||typeof t.priority=="number"&&Number.isFinite(t.priority))}):!1}o(h,"isContentConverterRegistration");function O(e,t){return T(()=>Pe.Check(e,t))}o(O,"safeCheck");function T(e){try{return e()}catch{return!1}}o(T,"safeEvaluate");var U=class extends Error{static{o(this,"UnsupportedContentError")}source;target;constructor(t,n){super(`No content converter for ${t} in ${n.provider}/${n.capability}`),this.name="UnsupportedContentError",this.source=t,this.target=n}};function Y(e){if(!b(e))throw new TypeError("Invalid content target");let t={...e},n=[],r=o(()=>[...n].sort((s,i)=>s.priority-i.priority||s.order-i.order),"snapshotConverters");return{target:t,register(s){if(!h(s))throw new TypeError("Invalid content converter registration");if(!A(t,s.target))throw new Error(`Content converter ${s.converter.id} targets ${s.target.provider}/${s.target.capability}, not ${t.provider}/${t.capability}`);if(n.some(({converter:i})=>i.id===s.converter.id))throw new Error(`Content converter ${s.converter.id} is already registered for ${t.provider}/${t.capability}`);n.push({converter:s.converter,priority:s.priority??0,order:n.length})},listDescriptions(){return r().map(({converter:s})=>({id:s.id,description:s.description}))},async convert(s,i){if(!K(s))throw new TypeError("Invalid content input");if(!z(i))throw new TypeError("Invalid content conversion context");B(i.signal);let a=r();for(let{converter:m}of a){B(i.signal);let p=await m.tryConvert(s,i);if(B(i.signal),!F(p))throw new TypeError(`Content converter ${m.id} returned an invalid outcome`);if(p.kind!=="not-handled"){if(p.kind==="failed")throw p.error;return p.content}}throw new U(s.source,t)}}}o(Y,"createContentRunner");function A(e,t){return e.provider===t.provider&&e.capability===t.capability}o(A,"targetsEqual");function B(e){e?.throwIfAborted()}o(B,"throwIfAborted");import{Type as g}from"typebox";import{Value as $e}from"typebox/value";var x="pi-agent-resource/content-conversion",V=2,P=`${x}/host/ready`,j=`${x}/converter/register`,se={additionalProperties:!0},We=g.Function([],g.Unknown()),He=g.Object({protocol:g.Literal(x),apiVersion:g.Literal(V),target:g.Unknown()},se),qe=g.Object({registration:g.Unknown(),accept:We},se);function G(e){return ie(He,e)&&M(()=>b(e.target))}o(G,"isContentHostReady");function J(e){return ie(qe,e)&&M(()=>h(e.registration))}o(J,"isContentConverterRegistrationRequest");function ie(e,t){return M(()=>$e.Check(e,t))}o(ie,"safeCheck");function M(e){try{return e()}catch{return!1}}o(M,"safeEvaluate");function Ke(e,t){let n=Y(t),r=e.events.on(j,s=>{if(!J(s))throw new Error("Invalid content converter registration request");if(!A(n.target,s.registration.target))return;let i;try{n.register(s.registration),i=Promise.resolve()}catch(a){i=Promise.reject(a instanceof Error?a:new Error("Content converter registration failed",{cause:a}))}s.accept(i)});return e.on("session_shutdown",r),e.events.emit(P,{protocol:x,apiVersion:V,target:n.target}),{target:n.target,listDescriptions(){return n.listDescriptions()},convert(s,i){return n.convert(s,i)}}}o(Ke,"createContentHost");function ze(e,t){if(!h(t))throw new TypeError("Invalid content converter registration");let n=o(()=>{let i,a={registration:t,accept(m){if(i!==void 0)throw new Error(`Content converter ${t.converter.id} registration was accepted more than once`);i=m}};return e.events.emit(j,a),i},"announce"),r=o(()=>{},"unsubscribe");r=e.events.on(P,i=>{if(!G(i))throw new Error("Invalid content conversion host readiness event");if(!A(t.target,i.target))return;let a=n();if(a===void 0)throw new Error(`${i.target.provider}/${i.target.capability} announced readiness without accepting content converter ${t.converter.id}`);r(),a.catch(()=>{})}),e.on("session_shutdown",r);let s=n();if(s!==void 0)return r(),s}o(ze,"connectContentConverter");export{I as a,me as b,Q as c,W as d,Z as e,ee as f,H as g,te as h,he as i,Te as j,q as k,re as l,Ne as m,ke as n,b as o,K as p,z as q,oe as r,F as s,h as t,U as u,Y as v,A as w,x,V as y,P as z,j as A,G as B,J as C,Ke as D,ze as E};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as k,b as I,c as A}from"./chunk-
|
|
1
|
+
import{a as k,b as I,c as A}from"./chunk-FUG2TEKI.js";import{j as E,k as S}from"./chunk-KVHDMIZS.js";import"./chunk-ZPT5D4VP.js";import"./chunk-KINKBPPX.js";import{a as b}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{readdir as K}from"node:fs/promises";import W from"node:path";async function T(e){let n=[],t=await K(e,{withFileTypes:!0});for(let i of t){let o=W.join(e,i.name);i.isDirectory()?n.push(...await T(o)):(i.isFile()||i.isSymbolicLink())&&n.push(o)}return n}s(T,"collectFiles");import{readFile as X}from"node:fs/promises";var v=256*1024;async function w(e){let n=await X(e);if(n.byteLength>v)throw new Error(`File exceeds the ${v}-byte AST outline limit: ${e}`);if(n.includes(0))throw new Error(`File appears to be binary and cannot be read as text: ${e}`);let t=n.toString("utf8").replaceAll(`\r
|
|
2
2
|
`,`
|
|
3
3
|
`),i=t.endsWith(`
|
|
4
4
|
`)?t.slice(0,-1):t,o=i.length===0?[]:i.split(`
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{d as B,h as M}from"./chunk-GIRAEVUJ.js";import{a as N}from"./chunk-I5JLCFUX.js";import{h as w,i as P}from"./chunk-2P2OGO3G.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
|
+
`)||`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
|
+
`);return P({content:r.content,details:a},N,{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
|
+
|
|
5
|
+
Current nearby anchors:`);return`${n===-1?o:o.slice(0,n)}
|
|
6
|
+
|
|
7
|
+
Current nearby anchors:
|
|
8
|
+
${e.map(a=>` ${a}`).join(`
|
|
9
|
+
`)}`}y(ne,"replaceCurrentAnchors");function re(o,e){let t=e.appliedEntries.length,n=t>0?`${t} (indices: ${e.appliedEntries.join(", ")})`:"0",r=e.skippedEntries.length>0?e.skippedEntries.map(u=>`${u.index} (${u.reason})`).join(", "):"none",a=e.error?`Recovery execution failed: ${e.error}.`:"Recovery execution completed.",l=te(e),i=l.length>0&&f.IsObjectNotArray(o.message.details)?{...o.message.details,freshAnchors:l}:o.message.details,s=l.length>0?ne(o.message.content,l):o.message.content,d=l.length>0&&f.IsObjectNotArray(e.staleDetails)?{...e,staleDetails:{...e.staleDetails,freshAnchors:l}}:e;return{message:{customType:Z,content:`${s}
|
|
10
|
+
|
|
11
|
+
[RECOVERY] Status: ${e.status}. Applied entries: ${n}. Skipped entries: ${r}. ${a}`,display:!1,details:{blocked:i,recovery:d}}}}y(re,"makeRecoveryResult");var D=new WeakMap;function z(o){let e=D.get(o);if(e)return e;let t=new k(o);return D.set(o,t),K(o,(n,r)=>t.processStreamEvent(n,r),n=>{t.markStreamEventProcessed(n)},n=>{t.finalizeStreamInterception(n)}),t}y(z,"coordinatorFor");function oe(o,e){z(o).register(e)}y(oe,"registerToolCallInterceptor");function ae(o,e){if(S.get(o)?.(),S.delete(o),e===void 0)return;let t=o.events.on(G,n=>{!f.IsObjectNotArray(n)||typeof n.toolCallId!="string"||!M(n.annotation)||e(n.toolCallId,n.annotation)});S.set(o,t)}y(ae,"registerToolCallAnnotationSink");function Ee(o,e){z(o).registerBlockedCallSink(e)}y(Ee,"registerBlockedToolCallSink");export{oe as a,ae as b,Ee as c};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as d}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{createTwoFilesPatch as m,diffLines as
|
|
1
|
+
import{a as d}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import{createTwoFilesPatch as m,diffLines as l}from"diff";function y(i,e,n,r=i){return{diff:m(i,r,e,n,"","",{context:3}).replace(/^(?:Index: .*\n)?={3,}\n?/m,"").trimEnd(),stats:p(e,n)}}s(y,"createUnifiedDiff");function p(i,e){let n=0,r=0;for(let t of l(i,e)){let a=g(t.value);t.removed&&(n+=a),t.added&&(r+=a)}return{removed:n,added:r}}s(p,"computeStats");function g(i){if(i.length===0)return 0;let e=i.replaceAll(`\r
|
|
2
2
|
`,`
|
|
3
3
|
`);return e.endsWith(`
|
|
4
4
|
`)?e.slice(0,-1).split(`
|
|
5
5
|
`).length:e.split(`
|
|
6
|
-
`).length}s(
|
|
6
|
+
`).length}s(g,"countDiffLines");function x(i,e){let n=l(i,e),r=[],t=0;for(let a of n){let o=g(a.value);o!==0&&(a.removed||(a.added&&r.push({start:t+1,end:t+o}),t+=o))}return E(r)}s(x,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((r,t)=>r.start-t.start),n=[d(e[0])];for(let r=1;r<e.length;r++){let t=d(n.at(-1)),a=d(e[r]);a.start<=t.end+1?t.end=Math.max(t.end,a.end):n.push(a)}return n}s(E,"mergeAdjacentRanges");var f=class i{static{s(this,"FileRange")}start;end;constructor(e,n=e){n.lineNumber<e.lineNumber&&([e,n]=[n,e]),this.start=e,this.end=n}static fromLines(e,n){let r=n??e;return new i({lineNumber:e},{lineNumber:r})}},c=class i{static{s(this,"FileMutationResult")}data;constructor(e){this.data=e??{}}get ok(){return this.data.ok??!1}get isPartial(){return this.data.isPartial??!1}get diffs(){return this.data.diffs??[]}get files(){return this.data.files??[]}get warnings(){return this.data.warnings??[]}get errors(){return this.data.errors??[]}get lintViolations(){return this.data.lintViolations??[]}get hints(){return this.data.hints??[]}get syntaxErrorSummary(){return this.data.syntaxErrorSummary}get path(){return this.data.path}get editRange(){let e=this.data.activeEdits,n=e?.[0];if(n?.range){let r=n.range.start,a=d(e).at(-1)?.range?.end??r;return new f(r,a)}return this.data.editRange}get resolvedStartLine(){return this.editRange?.start.lineNumber}get resolvedEndLine(){return this.editRange?.end.lineNumber}get freshAnchors(){return this.data.freshAnchors}get failurePoint(){return this.data.failurePoint}get recovery(){return this.data.recovery}get expectedAnchor(){return this.data.expectedAnchor}get currentAnchor(){return this.data.currentAnchor}get internalErrorType(){return this.data.internalErrorType}get internalErrorMessage(){return this.data.internalErrorMessage}get editCount(){return this.data.editCount}get editRanges(){return this.data.editRanges}get addedLines(){return this.data.addedLines}get removedLines(){return this.data.removedLines}get appliedPaths(){return this.data.appliedPaths}get beforeContentMap(){return this.data.beforeContentMap}get afterContent(){return this.data.afterContent}get skipCount(){return this.data.skipCount??0}get staleEdits(){return this.data.staleEdits??[]}get proposedDiff(){return this.data.proposedDiff}get editIndex(){return this.data.editIndex}get editIndices(){return this.data.editIndices}get staleDiagnostic(){return this.data.staleDiagnostic}get fileChangedStatement(){return this.data.fileChangedStatement}get affectedPaths(){let e=new Set;for(let n of this.files)e.add(n.path);for(let n of this.errors)n.path&&e.add(n.path);for(let n of this.warnings)n.file&&e.add(n.file);return[...e]}get didChange(){return this.ok&&(this.files.length>0||this.diffs.length>0)}get createdFiles(){return this.files.filter(e=>e.action==="created")}get overwrittenFiles(){return this.files.filter(e=>e.action==="overwritten"||e.action==="edited")}get staleCount(){return this.staleEdits.length}get summary(){if(!this.ok){let t=this.errors[0];return t?`Failed: ${t.code??"ERROR"}${t.reason?` \u2014 ${t.reason}`:""}`:"Mutation failed"}if(this.files.length===0&&this.diffs.length===0){let t=this.appliedPaths;return t&&t.length>0?`${t.length} path${t.length===1?"":"s"} affected`:"No changes"}let e=this.createdFiles.length,n=this.overwrittenFiles.length,r=[];if(e>0&&r.push(`Created ${e} ${e===1?"file":"files"}`),n>0&&r.push(`Edited ${n} ${n===1?"file":"files"}`),this.diffs.length>0){let t=0,a=0;for(let o of this.diffs)for(let u of o.split(`
|
|
7
7
|
`))u.startsWith("+")&&!u.startsWith("+++")?t++:u.startsWith("-")&&!u.startsWith("---")&&a++;(t>0||a>0)&&r.push(`+${t}/-${a} lines`)}return r.join(", ")}getFileChange(e){return this.files.find(n=>n.path===e)}getDiffFor(e){let n=h(e);for(let r of this.diffs){let t=r.match(/^---\s+(.+)$/m);if(t&&(h(d(t[1]))===n||t[1]===e))return r}}getErrorsFor(e){return this.errors.filter(n=>n.path===e)}getWarningsFor(e){return this.warnings.filter(n=>n.file===e)}static fromFailureOptions(e){return new i({ok:!1,path:e.path,errors:[{path:e.path,code:e.code,reason:e.reason}],failurePoint:e.failurePoint,recovery:e.recovery,expectedAnchor:e.expectedAnchor,currentAnchor:e.currentAnchor,freshAnchors:e.freshLines?[...e.freshLines]:void 0,internalErrorType:e.internalError instanceof Error?e.internalError.name:void 0,internalErrorMessage:e.internalError instanceof Error?e.internalError.message:void 0})}static ensure(e){if(e instanceof i)return e;if(e&&typeof e=="object"){let n=e;return n.data&&typeof n.data=="object"?(Object.setPrototypeOf(n,i.prototype),n):new i(n)}return new i}};function h(i){return i.replace(/\\/g,"/").replace(/^a\//,"").replace(/^b\//,"")}s(h,"normalisePath");export{y as a,x as b,f as c,c as d};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{a as A,d as R}from"./chunk-7AVXUV4A.js";import{a as v}from"./chunk-FZBCKIJJ.js";import{b as N,d as L}from"./chunk-BSICWXMH.js";import{f as $}from"./chunk-YHUTTZC6.js";import{e as I,h as _,i as O}from"./chunk-2P2OGO3G.js";import{a as u}from"./chunk-EI7MMDWY.js";import B from"node:path";import{truncateHead as q,DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as ae}from"@earendil-works/pi-coding-agent";import{Text as k}from"@earendil-works/pi-tui";import{Type as h}from"typebox";import{Value as le}from"typebox/value";var U=h.Object({source:h.String(),sources:h.Array(h.String())},{additionalProperties:!1}),j=h.Object({kind:h.Literal("diff"),equal:h.Boolean(),before:U,after:U,stats:h.Object({added:h.Integer(),removed:h.Integer()}),diff:h.String(),truncated:h.Boolean(),fullResult:h.Optional(h.String())},{additionalProperties:!1}),ce=I(j),V=h.Union([h.String({minLength:1}),v]),H=h.Object({before:V,after:V},{additionalProperties:!1});async function fe(e,i,c){if(!le.Check(H,i))throw Object.assign(new Error("Use before and after source strings or read request objects"),{code:"INVALID_ARGUMENTS"});let n=i,r=u(async s=>{let t=typeof s=="string"?{path:s}:s,f=await e.read(t,c,"script");if(f.isError||f.details.failure)throw Object.assign(new Error(f.details.failure?.message??"Comparison read failed"),{code:f.details.failure?.code??"READ_FAILED",details:f.details.failure});if(f.script===void 0)throw Object.assign(new Error("Source has no comparable text data"),{code:"UNSUPPORTED_CONTENT"});return J(f.script,t.path??"source")},"resolve"),o=await r(n.before),a=await r(n.after),l=A(o.source,o.content,a.content,a.source);return{kind:"diff",ok:!0,equal:o.content===a.content,before:o,after:a,...l}}u(fe,"executeDiff");function J(e,i){if(e.kind==="text")return{source:e.source,sources:[e.source],content:e.content};if(e.kind==="resources"){let c=e.resources.map(n=>J(n,i));return{source:e.source??i,sources:c.flatMap(n=>n.sources),content:c.map(n=>n.content).join(`
|
|
2
|
+
`)}}if(e.kind==="bytes")throw Object.assign(new Error(`Byte sources are not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});if(e.blocks.length===0||e.blocks.some(c=>c.type!=="text"))throw Object.assign(new Error(`Source is not text: ${e.source}`),{code:"UNSUPPORTED_CONTENT"});return{source:e.source,sources:[e.source],content:e.blocks.flatMap(c=>c.type==="text"?[c.text]:[]).join(`
|
|
3
|
+
`)}}u(J,"comparisonText");function S(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="diff"&&"ok"in e&&e.ok===!0}u(S,"isDiffOutcome");function P(e,i=process.cwd()){let c=u(r=>B.isAbsolute(r)?B.relative(i,r)||".":r,"displaySource"),n=`Diff: ${c(e.before.source)} \u2192 ${c(e.after.source)}`;return{results:[new R({ok:!0,path:n,beforeContentMap:{[n]:e.before.content},afterContent:e.after.content,diffs:[e.diff]})]}}u(P,"diffPresentation");function T(e){return e.equal?`No differences: ${e.before.source} \u2192 ${e.after.source}`:e.diff}u(T,"diffText");function Ne(e){return{content:[{type:"text",text:T(e)}],details:{}}}u(Ne,"diffReadResult");function Le(e,i,c){e.registerTool({name:"diff",exposure:"direct",namespace:{name:"ide_read",description:"Read resources and compare sources."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:"Diff",parameters:H,outputSchema:ce,promptSnippet:"Compare two text-readable sources",description:"Use diff to compare two sources. before and after accept a source string or a read request {path, offset?, limit?, views?}. Use any source that read can resolve as text. Omit limit to compare complete resolved text; read presentation limits do not clip comparison inputs. Multiple resolved resources are joined with one newline separator in resolver order. Diff line numbers are relative to each selected text, not the original file when a window is selected. Native non-text content is rejected. Output uses the existing text diff and a shared output budget; oversized output has a full temporary reference. The same diff function is available inside Apply.",renderCall(n,r){return new k(r.fg("toolTitle",r.bold("Diff")),0,0)},renderResult(n,r,o,a){let l=n.details;if(l?.comparison?.equal)return new k(T(l.comparison),0,0);let s=i.getToolRenderer("diff")?.renderResult;return s?s(n,r,o,a):new k(n.content.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
4
|
+
`),0,0)},async execute(n,r,o,a,l){let s=c();if(s===void 0)throw new Error("Diff requires the read extension");try{let t=await fe(s,r,{cwd:l.cwd,signal:o}),f=T(t),m=q(f),y=m.truncated?await s.saveTemporary(f):void 0,p=y===void 0?"":`
|
|
5
|
+
Full diff: ${y}`;return O({content:[{type:"text",text:y===void 0?f:q(f,{maxLines:ae-2,maxBytes:se-Buffer.byteLength(p)}).content+p}],details:{...P(t,l.cwd),comparison:t,temporarySource:y}},j,{status:"success",data:{kind:"diff",equal:t.equal,before:{source:t.before.source,sources:t.before.sources},after:{source:t.after.source,sources:t.after.sources},stats:t.stats,diff:m.content,truncated:m.truncated,...y===void 0?{}:{fullResult:y}},errors:[]})}catch(t){if(o?.aborted)throw t;let f=_(t,"DIFF_FAILED");return O({content:[{type:"text",text:f.message}],details:{}},j,{status:"error",errors:[f]})}}})}u(Le,"registerDiff");import{parser as Y}from"@lezer/javascript";import{TreeFragment as W}from"@lezer/common";var pe=new Set(["read","search","diff","open","createFile","deleteFile","copyFile","moveFile","flush","result"]);function z(e,i=Y.parse(e)){let c=[];i.iterate({enter(r){if(r.name==="AssignmentExpression"){let t=r.node.firstChild;t?.name==="VariableName"&&c.push({name:e.slice(t.from,t.to),from:0,to:e.length})}if(r.name!=="VariableDefinition")return;let o=r.node.parent;for(;o?.parent&&!["VariableDeclaration","ParamList","Block","Script"].includes(o.name);)o=o.parent;let a=o?.name==="VariableDeclaration"&&o.firstChild?.name==="var",l=new Set(["Script","FunctionDeclaration","FunctionExpression","ArrowFunction",...a?[]:["Block"]]),s=r.node.parent;for(s?.name==="FunctionDeclaration"&&(s=s.parent);s?.parent&&!l.has(s.name);)s=s.parent;c.push({name:e.slice(r.from,r.to),from:s?.from??0,to:s?.to??e.length})}});let n=[];return i.iterate({enter(r){if(r.name!=="CallExpression")return;let o=r.node.firstChild;if(o?.name!=="VariableName")return;let a=e.slice(o.from,o.to);if(!pe.has(a)||c.some(t=>t.name===a&&t.from<=r.from&&t.to>=r.to))return;let l=r.node.getChild("ArgList")?.getChild("ObjectExpression"),s=Object.create(null);if(!l){let t=r.node.getChild("ArgList"),f=t?e.slice(t.from+1,t.to).replace(/\)$/,""):"";f&&(s.arguments={text:f.length>160?f.slice(0,120)+"\u2026":f,literal:!1})}for(let t of l?.getChildren("Property")??[]){let f=t.firstChild,y=(f?e.slice(f.from,f.to):"").replace(/^["']|["']$/g,"");if(!/^[a-zA-Z_$][\w$]*$/.test(y)){for(let ie of["path","query","target","before","after"])delete s[ie];let x=e.slice(t.from,t.to);s[`argument@${t.from}`]={text:x.length>160?x.slice(0,160)+"\u2026":x,literal:!1};continue}let p=t.lastChild;if(!p||p.type.isError||p.name===":")continue;let g=e.slice(p.from,p.to),d=g.replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t"),w=/^(?:["'])(?:\d+#[0-9A-F]+|CHANGE#[0-9A-F]+|begin|end|scope-(?:begin|end)-[^"']+)["']$/.test(g);s[y]={text:d.length>160&&!w?`${d.slice(0,100)}\u2026${d.slice(-40)} (${g.length} source chars)`:d,literal:["String","Number","BooleanLiteral","Null"].includes(p.name)&&p.lastChild?.type.isError!==!0}}return n.push({name:a,from:r.from,to:r.to,path:s.path,query:s.query,target:s.target,before:s.before,after:s.after,arguments:s}),!1}}),n}u(z,"parseApplyCalls");function ue(e,i=z(e),c,n=r=>r){let r=0,o=[],a=u(l=>n(l.split(`
|
|
6
|
+
`).map(s=>s.length>200?s.slice(0,200)+"\u2026":s).join(`
|
|
7
|
+
`)),"codePreview");for(let l of i)o.push(a(e.slice(r,l.from))),o.push(c?.(l)??`${l.name}(${l.path?l.path.literal?l.path.text:`\u2039${l.path.text}\u203A`:"\u2026"})`),r=l.to;return o.push(a(e.slice(r))),o.join("")}u(ue,"compactApplySource");function G(e,i){let c="",n="",r=[];return o=>{if(o===c)return n;let a=0;for(;a<c.length&&a<o.length&&c[a]===o[a];)a++;r=W.applyChanges(r,[{fromA:a,toA:c.length,fromB:a,toB:o.length}]);let l=Y.parse(o,r);return r=W.addTree(l),n=ue(o,z(o,l),e,i),c=o,n}}u(G,"createApplySourceProjection");import{lstat as Z,unlink as de}from"node:fs/promises";import K from"node:path";import X from"fs-extra";import{Type as b}from"typebox";import{Value as me}from"typebox/value";var D=b.String({minLength:1,description:"Local regular file path, relative to cwd or absolute."}),ge=b.Object({path:D},{additionalProperties:!1}),ye=b.Object({path:D,target:D,overwrite:b.Optional(b.Boolean({description:"Allow replacing an existing regular target file. Defaults to false."}))},{additionalProperties:!1});function E(e){return e!==null&&typeof e=="object"&&"kind"in e&&e.kind==="file-operation"}u(E,"isFileOperationResult");function C(e){return[`${e.operation}: ${e.effect}`,e.path,e.target===void 0?void 0:`Target: ${e.target}`,e.error===void 0?void 0:`${e.error.code}: ${e.error.message}`].filter(i=>i!==void 0).join(`
|
|
8
|
+
`)}u(C,"formatFileOperation");async function ze(e,i,c,n){let r=!1,o,a;try{let l=e==="delete"?ge:ye;if(!me.Check(l,i))throw Object.assign(new Error("Invalid file operation arguments"),{code:"INVALID_ARGUMENTS"});let s=i;o=K.resolve(c,s.path),a=s.target===void 0?void 0:K.resolve(c,s.target),n?.throwIfAborted();let t=await he(o);if(a!==void 0){let f=await we(a);if(f!==void 0){if(!f.isFile()||f.isSymbolicLink())throw Object.assign(new Error("Target must be a regular file"),{code:"INVALID_FILE_TYPE"});if(o===a||t.ino===f.ino&&t.dev===f.dev)throw Object.assign(new Error("Source and target are the same file"),{code:"SAME_FILE"});if(s.overwrite!==!0)throw Object.assign(new Error("Target exists; use overwrite: true to replace it"),{code:"EEXIST"})}}return n?.throwIfAborted(),r=!0,e==="delete"?await de(o):a!==void 0&&(e==="copy"?await X.copy(o,a,{overwrite:s.overwrite===!0,errorOnExist:!0}):await X.move(o,a,{overwrite:s.overwrite===!0})),{kind:"file-operation",operation:e,ok:!0,effect:"applied",path:o,...a===void 0?{}:{target:a}}}catch(l){return{kind:"file-operation",operation:e,ok:!1,effect:r?"unknown":"not-applied",...o===void 0?{}:{path:o},...a===void 0?{}:{target:a},error:{code:l!==null&&typeof l=="object"&&"code"in l?String(l.code):"FILE_OPERATION_FAILED",message:l instanceof Error?l.message:String(l)}}}}u(ze,"executeFileOperation");async function he(e){let i=await Z(e);if(!i.isFile()||i.isSymbolicLink())throw Object.assign(new Error("Source must be a regular file"),{code:"INVALID_FILE_TYPE"});return i}u(he,"regularFile");async function we(e){try{return await Z(e)}catch(i){if(i!==null&&typeof i=="object"&&"code"in i&&i.code==="ENOENT")return;throw i}}u(we,"optionalStat");import{Text as ne}from"@earendil-works/pi-tui";function Q(e){let i=e.select(),c=e.mutationValues().filter(xe);return i.files.map(n=>{let r=c.flatMap(l=>l.files.filter(s=>s.source===n.source).map(s=>({outcome:l,changed:s}))),o=e.mutationPresentation(n.source)?.data,a=o?.afterContent===n.after?o:void 0;return new R({ok:!0,path:n.source,files:[{path:n.source,action:n.before===null?"created":"edited"}],snapshot:{content:n.before??""},beforeContentMap:{[n.source]:n.before},afterContent:n.after??"",afterDocument:a?.afterDocument,resultPresentation:a?.resultPresentation,scopeMarkers:a?.scopeMarkers,hints:a?.hints,warnings:a?.warnings,diffStatuses:a?.diffStatuses,diffs:[A(n.source,n.before??"",n.after??"").diff],operations:r.map(({outcome:l,changed:s})=>({operation:l.operation==="remove"?"delete":l.operation,changes:s.changes.length})),formatting:a?.formatting??r.at(-1)?.changed.formatting})})}u(Q,"finalApplyMutations");function xe(e){return e!==null&&typeof e=="object"&&"operation"in e&&"files"in e&&Array.isArray(e.files)&&"effect"in e}u(xe,"isMutation");import{highlightCode as oe}from"@earendil-works/pi-coding-agent";import{wrapTextWithAnsi as ee,visibleWidth as te,truncateToWidth as be}from"@earendil-works/pi-tui";function ft(e,i,c,n=process.cwd()){let r=e.select(),o=[...r.automatic,...r.explicit.filter(t=>t.kind==="operation")].filter(t=>S(t.value)&&!t.value.equal),a=o.flatMap(t=>S(t.value)?[P(t.value,n)]:[]),l=new Set(o.flatMap(t=>t.presentation?.content??[]));if(r.files.length===0){let t=[...r.automatic.map(f=>f.presentation),...r.explicit.map(f=>f.kind==="operation"?f.presentation:void 0)].filter(f=>f!==void 0);return{comparisons:a,cwd:n,blocks:[...i.content.filter(f=>!l.has(f)).flatMap(f=>f.type==="text"?[{text:re(f.text),read:t.find(m=>m.content.includes(f))}]:[])]}}let s=i.mutations??Q(e);return{...s.length>0?{mutations:{results:s}}:{},comparisons:a,cwd:n,blocks:[...r.explicit.flatMap(t=>t.kind==="operation"&&S(t.value)&&!t.value.equal?[]:E(t.value)?[{text:C(t.value)}]:t.kind==="operation"?t.presentation?.content.flatMap(f=>f.type==="text"?[{text:f.text,read:t.presentation}]:[])??[]:[{text:re(typeof t.value=="string"?t.value:t.value===void 0?"undefined":JSON.stringify(t.value,null,2))}]),...r.automatic.flatMap(({value:t,presentation:f})=>{if(E(t))return[{text:C(t)}];if(t!==null&&typeof t=="object"&&"kind"in t&&t.kind==="index-operation")return f?.content.flatMap(m=>m.type==="text"?[{text:m.text}]:[])??[];if(t===null||typeof t!="object"||!("errors"in t)||!Array.isArray(t.errors))return[];if("operations"in t&&Array.isArray(t.operations)){let m=t.operations.filter(p=>p!==null&&typeof p=="object"&&"status"in p&&p.status==="applied").length;if(m===t.operations.length)return[];let y=t.operations.filter(p=>p!==null&&typeof p=="object"&&"status"in p&&p.status!=="applied").map(p=>({text:Oe(p)}));return[{text:`Apply partially applied: ${m} of ${t.operations.length} operations completed.`},...y]}return t.errors.flatMap(m=>m!==null&&typeof m=="object"&&"message"in m&&typeof m.message=="string"?[{text:m.message}]:[])}),...c===void 0?[]:[{text:c instanceof Error?c.message:JSON.stringify(c)}]]}}u(ft,"createApplyDisplay");function F(e,i,c,n,r,o,a=!1){let l=Math.max(1,c);if(l<5)return e.split(`
|
|
9
|
+
`).flatMap(d=>ee(d,l));let s=l-4,t=u(d=>i.fg("borderMuted",d),"border"),m=be(` ${n==="call"?"Apply \xB7 JavaScript":"Result"} `,l-4,""),y=[t(`${n==="call"?"\u256D":"\u251C"}\u2500`)+i.fg(a?"error":"accent",m)+t(`${"\u2500".repeat(Math.max(0,l-te(m)-3))}${n==="call"?"\u256E":"\u2524"}`)],p=`${t("\u2502")}${" ".repeat(l-2)}${t("\u2502")}`;for(let d of e.split(`
|
|
10
|
+
`)){let w=o==="diff"?i.fg(d.startsWith("+")?"toolDiffAdded":d.startsWith("-")?"toolDiffRemoved":"toolDiffContext",d):o?oe(d,o).join(`
|
|
11
|
+
`):i.fg("toolOutput",d);for(let x of ee(w,s))y.push(`${t("\u2502")} ${x}${" ".repeat(Math.max(0,s-te(x)))} ${t("\u2502")}`)}n==="call"&&y.push(p),r&&y.push(t(`\u2570${"\u2500".repeat(l-2)}\u256F`));let g=i.getBgAnsi("toolPendingBg");return y.map(d=>g+$(d,g)+"\x1B[0m")}u(F,"applyFrameRows");function Ae(e,i="compact"){return(c,n,r)=>{if(!r.expanded&&i==="disabled")return new ne(n.fg("toolTitle","apply"),0,0);let o=r.state,a=o.projectSource??=G(e?s=>e(s,n):void 0,e?s=>oe(s,"javascript").join(`
|
|
12
|
+
`):void 0),l=c!==null&&typeof c=="object"&&"source"in c&&typeof c.source=="string"?c.source:"";return{invalidate(){},render(s){return F(r.expanded||i==="full"?o.displaySource??l:i==="disabled"?"":Re(a(o.displaySource??l)),n,s,"call",!o.applyResultReady,r.expanded||i==="full"||!e?"javascript":void 0)}}}}u(Ae,"createApplyCallRenderer");function Re(e,i=N){let c=e.split(`
|
|
13
|
+
`);if(c.length<=i)return e;let n=Math.max(2,i-1),r=Math.ceil(n/2),o=Math.floor(n/2),a=c.length-r-o;return[...c.slice(0,r),`\u2026 ${a} lines omitted \u2026`,...c.slice(-o)].join(`
|
|
14
|
+
`)}u(Re,"compactApplyPreview");var pt=Ae();function Se(e){return(i,c,n,r)=>{r.state.applyResultReady=!0;let o=i.details;r.state.displaySource=o?.displaySource;let a=o?.display,l=a?.blocks??[{text:r.isError?"Apply failed":"Apply finished"}],s=L({kind:"source"}),t=l.map(p=>s(p.read??{content:[{type:"text",text:p.text}],details:ke(p.text)},c,n,{...r,isError:!1,lastComponent:void 0})),f=a?.mutations,m=(a?.comparisons??[]).flatMap(p=>[e?.(p,n,c.expanded,a?.cwd??process.cwd())??new ne((p.results??[]).flatMap(d=>d.data.diffs??[]).join(`
|
|
15
|
+
`),0,0)]),y=f===void 0?void 0:e?.(f,n,c.expanded,a?.cwd??process.cwd());return{invalidate(){y?.invalidate();for(let p of m)p.invalidate()},render(p){let g=[];for(let d of t){let w=d.render(Math.max(1,p-4));w.length!==0&&(g.length>0&&g.push(""),g.push(...w))}for(let d of m)g.length>0&&g.push(""),g.push(...d.render(Math.max(1,p-4)));if(y!==void 0){let d=y.render(Math.max(1,p-4));g.length>0&&d.length>0&&g.push(""),g.push(...d),d.length===0&&g.push(...(f?.results??[]).map(w=>w.path??"Changed file"))}else f!==void 0&&g.push(...(f.results??[]).map(d=>d.path??"Changed file"));return g.length===0&&l.length>0&&l.every(d=>d.read?.details.diagnosticCheck?.complete&&d.read.details.diagnosticCheck.count===0)?F("",n,p,"result",!0).slice(-1):F(g.length===0?"No output":g.join(`
|
|
16
|
+
`),n,p,"result",!0,void 0,r.isError)}}}}u(Se,"createApplyResultRenderer");function Oe(e){if(e===null||typeof e!="object")return String(e);let i="index"in e?Number(e.index)+1:"?",c="kind"in e?String(e.kind):"operation",n="status"in e?String(e.status):"unknown",r="error"in e&&e.error!==null&&typeof e.error=="object"?`: ${"code"in e.error?String(e.error.code):"ERROR"}: ${"message"in e.error?String(e.error.message):"Operation failed"}`:"";return`Operation ${i} (${c}): ${n}${r}`}u(Oe,"formatDisplayOutcome");function re(e){if(/^(?:Undo transaction:|Undo available)/u.test(e.trim()))return"";try{let i=JSON.parse(e);return JSON.stringify(M(i),null,2)}catch{return e.replace(/APPLY#[0-9A-F]{12}/gu,"Apply transaction")}}u(re,"redactApplyReceipts");function M(e){return Array.isArray(e)?e.map(M):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([i])=>i!=="transaction").map(([i,c])=>[i,M(c)]))}u(M,"redactTransactionKeys");function ke(e){try{let i=JSON.parse(e);return i!==null&&typeof i=="object"?{source:"result.json"}:{}}catch{return{}}}u(ke,"jsonDetails");var ut=Se();export{j as a,fe as b,S as c,Ne as d,Le as e,ze as f,Q as g,ft as h,Ae as i,pt as j,Se as k,ut as l};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as j}from"./chunk-YHUTTZC6.js";import{i as T,o as m,t as L,u as C}from"./chunk-
|
|
1
|
+
import{c as j}from"./chunk-YHUTTZC6.js";import{i as T,o as m,t as L,u as C}from"./chunk-ZPT5D4VP.js";import{a as y}from"./chunk-ZC65Z3CK.js";import{a as d}from"./chunk-EI7MMDWY.js";function Te(e,n){let{lines:t,truncation:r,...i}=e,o=t?.map(a=>{let l=[a.lineNumber,L(a.content,n),a.lineEnding];return(a.presentation!==void 0||a.metadata!==void 0)&&l.push(a.presentation),a.metadata!==void 0&&l.push(a.metadata),l}),{content:s,...u}=r??{};return{...i,...o===void 0?{}:{storedLines:o},...r===void 0?{}:{truncation:u,truncatedText:L(s??"",n)}}}d(Te,"compactReadDetails");function H(e,n){let t=e;if(t.storedLines===void 0&&t.truncatedText===void 0)return e;let{storedLines:r,truncatedText:i,truncation:o,...s}=t;return{...s,...r===void 0?{}:{lines:r.map(([u,a,l,c,p])=>({lineNumber:u,content:C(a,n),lineEnding:l,...c==null?{}:{presentation:c},...p==null?{}:{metadata:p}}))},...o===void 0?{}:{truncation:{...o,content:C(i??"",n)}}}}d(H,"restoreReadDetails");import f from"node:path";import{homedir as G}from"node:os";import{createReadToolDefinition as X,getReadmePath as J}from"@earendil-works/pi-coding-agent";import{Text as Z}from"@earendil-works/pi-tui";var v=X(process.cwd()),K=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function $(e,n=process.cwd()){if(typeof e!="object"||e===null)return;let t=e,r=t.path;if(typeof r!="string"||r.length===0||r.includes("#")||!f.isAbsolute(r)&&/^[a-z][a-z\d+.-]*:/iu.test(r)||t.views!==void 0&&(!Array.isArray(t.views)||t.views.length>0)||t.offset!==void 0&&(typeof t.offset!="number"||!Number.isInteger(t.offset)||t.offset<1)||t.limit!==void 0&&(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<1))return;let i=r.startsWith("~/")?f.join(G(),r.slice(2)):r,o=f.resolve(n,i),s=f.basename(o),u=f.relative(f.dirname(J()),o),a=!f.isAbsolute(u)&&(u==="README.md"||u.startsWith(`docs${f.sep}`)||u.startsWith(`examples${f.sep}`));if(!(s!=="SKILL.md"&&!K.has(s)&&!a))return{path:r,...t.offset===void 0?{}:{offset:t.offset},...t.limit===void 0?{}:{limit:t.limit}}}d($,"nativeReadArguments");function A(e,n){return{...e,args:n,lastComponent:e.lastComponent instanceof Z?e.lastComponent:void 0}}d(A,"nativeReadContext");import{getLanguageFromPath as k,getMarkdownTheme as Y,highlightCode as E,keyHint as Q}from"@earendil-works/pi-coding-agent";import{Container as w,Markdown as _,Text as ee,truncateToWidth as S,visibleWidth as R,wrapTextWithAnsi as q}from"@earendil-works/pi-tui";var g=12;function ne(e,n,t){let r=typeof n=="number"?n:void 0,i=typeof t=="number"?t:void 0;if(r===void 0&&i===void 0)return{pathSuffix:"",qualifiers:[],details:[]};if(e==="inherited source"||e.includes("#")){let a=r??1,l=i===void 0?String(a):`${a}-${a+i-1}`;return{pathSuffix:"",qualifiers:[{text:`relative lines ${l}`}],details:[{label:"relative lines",value:l}]}}if(r!==void 0&&r<0)return{pathSuffix:"",qualifiers:[{text:`tail ${Math.abs(r)}`},...i===void 0?[]:[{text:`limit ${i}`}]],details:[{label:"tail",value:String(Math.abs(r))},...i===void 0?[]:[{label:"limit",value:String(i)}]]};let s=Math.max(1,r??1),u=i===void 0?String(s):`${s}-${s+i-1}`;return{pathSuffix:`:${u}`,qualifiers:[],details:[{label:"lines",value:u}]}}d(ne,"readWindowPresentation");function We(e,n,t){let r=$(e,t.cwd);if(r!==void 0)return y(v.renderCall)(r,n,A(t,r));if(typeof e.path=="string"&&e.path.startsWith("shell:"))return new w;let i=typeof e.path=="string"?e.path:"inherited source",o=ne(i,e.offset,e.limit),s=Array.isArray(e.views)?e.views.filter(l=>typeof l=="string"):[],u=[...o.qualifiers,...s.length===0?[]:[{text:`views ${s.join(",")}`}]],a=[...typeof e.path=="string"?[{label:"path",value:e.path}]:[],...o.details,...s.length===0?[]:[{label:"views",value:s.join(",")}]];return j(t.lastComponent,{tool:"read",primary:{text:`${i}${o.pathSuffix}`,color:typeof e.path=="string"?"accent":"muted",underline:typeof e.path=="string",truncate:"start"},qualifiers:u,details:a,expanded:t.expanded},n)}d(We,"renderReadCall");function je(e){let n=new WeakMap;return(t,r,i,o)=>{let s=e.nativeResources?$(o.args,o.cwd):void 0;if(s!==void 0&&!r.isPartial)return y(v.renderResult)({...t,details:{truncation:D(t.details).truncation}},r,i,A(o,s));if(r.isPartial||o.isError){let p=P(t),B=o.isError?"error":"dim";return new ee(i.fg(B,p),0,0)}let u=D(t.details).diagnosticCheck;if(u?.complete&&u.count===0)return new w;if(!me(t))return o.lastComponent instanceof w?o.lastComponent:new w;let a=n.get(t);a===void 0&&(a=H(D(t.details),P(t)),n.set(t,a));let c=(o.lastComponent instanceof b?o.lastComponent:void 0)??new b({result:t,details:a,options:e,expanded:r.expanded,theme:i});return c.update({result:t,details:a,options:e,expanded:r.expanded,theme:i}),c}}d(je,"createReadResultRenderer");var b=class{constructor(n){this.state=n}static{d(this,"ReadResultPanel")}cached;update(n){this.state.result===n.result&&this.state.details===n.details&&this.state.options===n.options&&this.state.expanded===n.expanded&&this.state.theme===n.theme||(this.state=n,this.invalidate())}render(n){if(this.cached?.width===n)return this.cached.lines;if(n<8){let c=[S(V(this.state,n),Math.max(1,n))];return this.cached={width:n,lines:c},c}let t=n-2,r=Math.max(1,t-2),i=oe(this.state,r),o=se(i.state,r).flatMap(c=>q(c,r)),s=ue(o,this.state.expanded,this.state.theme,i.hasHiddenRows),u=[le(this.state,t,this.state.theme)];for(let c of s)for(let p of q(c,r))u.push(I(p,t,this.state.theme));let a=fe(this.state.details,this.state.theme);a!==void 0&&u.push(I(a,t,this.state.theme)),u.push(this.state.theme.fg("borderMuted",`\u2570${"\u2500".repeat(t)}\u256F`));let l=u.map(c=>S(c,n));return this.cached={width:n,lines:l},l}invalidate(){this.cached=void 0}},te=100,re=g,ie=4;function oe(e,n){if(e.expanded)return{state:e,hasHiddenRows:!1};let t=N(e.details);if(t!==void 0&&t.length>te)return{state:{...e,details:{...e.details,lines:t.slice(0,re)}},hasHiddenRows:!0};if(t!==void 0)return{state:e,hasHiddenRows:!1};let r=Math.max(g,n*g*ie),i=e.result.content.map(s=>s.type!=="text"||s.text.length<=r?s:{...s,text:s.text.slice(0,r)}),o=i.some((s,u)=>{let a=e.result.content[u];return s.type==="text"&&a?.type==="text"&&s.text.length<a.text.length});return o?{state:{...e,result:{...e.result,content:i}},hasHiddenRows:o}:{state:e,hasHiddenRows:!1}}d(oe,"compactRenderInput");function se(e,n){let t=N(e.details),r=pe(e.result,t,e.details,!e.expanded);if(e.options.kind==="markdown"||Re(e.details,t,e.options.kind)){let a=new _(r,0,0,Y());return M(a.render(n),e.theme)}if(e.options.kind==="code-view"){let a=t===void 0?h(r).map(l=>O(l,e.theme,!1)):z(t)?ae(t,!e.expanded,e.theme):de(t,e.theme);return M(a,e.theme)}let i=t!==void 0&&z(t),o=t===void 0||i?h(r).map(x):t.map(({content:a})=>x(a)),s=W(e.details,t),u=s===void 0?o.map(a=>e.theme.fg("toolOutput",a)):i?U(t,s,!e.expanded,e.theme):E(o.join(`
|
|
2
2
|
`),s);return M(u,e.theme)}d(se,"renderContentRows");function U(e,n,t,r){return e.flatMap(i=>{let o=x(i.content),s=E(o,n)[0]??r.fg("toolOutput",o),u=!1,a=m({source:"",content:i.content,lines:[i]},{compact:t});return h(a).map(l=>{if(!u&&o.length>0){let c=l.indexOf(o);if(c>=0)return u=!0,`${r.fg("toolOutput",l.slice(0,c))}${s}${r.fg("toolOutput",l.slice(c+o.length))}`}return r.fg("toolOutput",l)})})}d(U,"renderHighlightedPresentedLines");function ae(e,n,t){return e.flatMap(r=>{let i=T(r);if(i===void 0){let s=m({source:"",content:r.content,lines:[r]},{compact:n});return h(s).map(u=>O(u,t,!1))}let o=k(i.source);if(o===void 0){let s=m({source:"",content:r.content,lines:[r]},{compact:n});return h(s).map(u=>t.fg("toolOutput",u))}return U([r],o,n,t)})}d(ae,"renderPresentedCodeViewLines");function de(e,n){return e.map(t=>{let r=T(t);if(r===void 0)return O(t.content,n);let i=k(r.source),o=x(F(t.content));return i===void 0?n.fg("toolOutput",o):E(o,i)[0]??n.fg("toolOutput",o)})}d(de,"renderCodeViewLines");function F(e){return e.replace(/(?:[ \t]{2,}<!--[ \t]+scope-(?:begin|end)-[^\s>]+[ \t]+-->)+[ \t]*$/u,"")}d(F,"stripScopeMarkers");function O(e,n,t=!0){let r=x(t?F(e):e);return/^#{2,3}\s/u.test(r)?n.fg("mdHeading",n.bold(r.replace(/^#{2,3}\s+/u,""))):/^(?:Lines|Reason|Recovery):/u.test(r)?n.fg("dim",r):/^[\p{L}][^:]*:$/u.test(r)?n.fg("accent",n.bold(r)):/^\s*[-*]\s/u.test(r)?n.fg("mdListBullet",r):n.fg("toolOutput",r)}d(O,"renderCodeViewLabel");function ue(e,n,t,r=!1){if(n||e.length<=g&&!r)return e;let i=e.slice(0,g-1),o=e.length-i.length,s=r?"more rows":`${String(o)} more ${o===1?"row":"rows"}`;return[...i,`${t.fg("dim",`\u2026 ${s} \xB7 `)}${Q("app.tools.expand","to expand")}`]}d(ue,"compactRows");function le(e,n,t){let r=d(s=>t.fg("borderMuted",s),"frame"),i=S(` ${V(e,Math.max(1,n-1))} `,Math.max(0,n-1),""),o="\u2500".repeat(Math.max(0,n-R(i)-1));return`${r("\u256D\u2500")}${i}${r(`${o}\u256E`)}`}d(le,"renderTopBorder");function V(e,n){let t=e.options.label??he(W(e.details,N(e.details))),r=e.details.source??"read result",i=ce(e.details),o=e.theme.fg("accent",e.theme.bold(t)),s=i===void 0?"":e.theme.fg("dim",` \xB7 ${i}`),u=Math.max(1,n-R(o)-R(s)-2),a=xe(r,u);return`${o} ${e.theme.fg("muted",a)}${s}`}d(V,"readTitle");function ce(e){if(!(e.startLine===void 0||e.endLine===void 0||e.totalLines===void 0||e.totalLines<=0))return`${String(e.startLine)}\u2013${String(e.endLine)} / ${String(e.totalLines)}`}d(ce,"sourceRange");function fe(e,n){let t=e.truncation;if(t?.firstLineExceedsLimit===!0)return n.fg("warning","First source line is larger than the saved read limit");if(t?.truncated===!0)return n.fg("warning",`Saved result contains ${String(t.outputLines)} of ${String(t.totalLines)} rendered rows`)}d(fe,"readStatus");function I(e,n,t){let r=Math.max(0,n-2),i=S(e,r),o=` ${i}${" ".repeat(Math.max(0,r-R(i)))} `,s=t.fg("borderMuted","\u2502");return`${s}${o}${s}`}d(I,"framed");function pe(e,n,t,r){if(n!==void 0)return m({source:t.source??"",content:"",lines:n},{compact:r});let i=P(e);return t.truncation===void 0&&!(t.totalLines!==void 0&&t.endLine!==void 0&&t.endLine<t.totalLines)?i:i.replace(/\n\n\[(?:Showing lines|Output truncated|\d+ more lines in source)[\s\S]*\]$/u,"")}d(pe,"cleanText");function z(e){return e.some(n=>n.presentation!==void 0)}d(z,"hasPresentation");function h(e){let n=e.split(/\r\n|\r|\n/u);return n.at(-1)===""&&/(?:\r\n|\r|\n)$/u.test(e)&&n.pop(),n}d(h,"splitTextRows");function P(e){return e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
|
|
3
3
|
`)}d(P,"textBlocks");function N(e){return e.lines}d(N,"readLines");function D(e){return typeof e=="object"&&e!==null?e:{}}d(D,"readDetails");function me(e){return e.content.some(n=>n.type==="text")}d(me,"hasTextContent");function W(e,n){let r=n?.map(T).find(i=>i!==void 0)?.source??e.source;return r===void 0?void 0:k(ge(r))}d(W,"languageFor");function Re(e,n,t){return t==="source"&&W(e,n)==="markdown"}d(Re,"isMarkdownSource");function ge(e){try{let n=new URL(e);return n.protocol==="file:"?n.pathname:`${n.pathname}${n.search}`}catch{return e.replace(/#[^/\\]*$/u,"").replace(/^[A-Za-z][A-Za-z\d+.-]*:(?=[/\\])/u,"")}}d(ge,"normalizeSourcePath");function x(e){let n="";for(let t of e.replaceAll(" "," ".repeat(4))){let r=y(t.codePointAt(0));n+=r<32||r===127?"\uFFFD":t}return n}d(x,"normalizeText");function he(e){return e===void 0?"TEXT":{javascript:"JS",json:"JSON",markdown:"MD",python:"PY",rust:"RS",typescript:"TS"}[e]??e.slice(0,4).toUpperCase()}d(he,"languageLabel");function M(e,n){return e.length===0?[n.fg("dim","Empty content")]:[...e]}d(M,"nonEmptyRows");function xe(e,n){return R(e)<=n?e:n<=1?"\u2026":`\u2026${e.slice(-(n-1))}`}d(xe,"truncateFromStart");export{Te as a,g as b,We as c,je as d};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import{a as me,b as pe,c as fe}from"./chunk-ESPNEJHK.js";import{a as de}from"./chunk-M5IVSCR2.js";import"./chunk-PXWDDBBC.js";import{a as I}from"./chunk-I5JLCFUX.js";import"./chunk-7AVXUV4A.js";import{e as Q,f as ee}from"./chunk-T7I2VX3J.js";import{a as se}from"./chunk-FBOW7XOV.js";import{a as ie,b as oe}from"./chunk-WJTHY6AG.js";import{b as E}from"./chunk-BSICWXMH.js";import"./chunk-YHUTTZC6.js";import{a as re}from"./chunk-6CZO43OH.js";import{a as te,b as ne}from"./chunk-OBNING2A.js";import"./chunk-F7NVAC4Q.js";import{d as ce}from"./chunk-MIZAFRDR.js";import{a as ue}from"./chunk-ZTYWHL2F.js";import{a as ae,b as le}from"./chunk-7UGNGK7Y.js";import{h as H,i as L}from"./chunk-2P2OGO3G.js";import"./chunk-ZPT5D4VP.js";import"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";import tt from"node:path";import{stripVTControlCharacters as nt}from"node:util";import{truncateLine as rt}from"@earendil-works/pi-coding-agent";import{Text as R}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as ge,DEFAULT_MAX_LINES as he,formatSize as Qe,truncateTail as et}from"@earendil-works/pi-coding-agent";function $(t){return et(t,{maxBytes:ge-4096,maxLines:he-32})}s($,"terminalOutputTail");function M(t){let e=$(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0||t.status!=="running"?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(o=>o!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
|
|
2
|
+
`)}
|
|
3
|
+
output:${r.length===0?" (empty)":`
|
|
4
|
+
${r}`}`;let i=e.truncatedBy==="lines"?`${he} line output budget`:`${Qe(ge)} output budget`,a=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
|
|
5
|
+
`)}
|
|
6
|
+
output:
|
|
7
|
+
${a}${r.length===0?"":`
|
|
8
|
+
${r}`}`}s(M,"formatAgentTerminalSnapshot");var it=500;function ye(t,e,n,r,i){let a=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${D(n)} \xB7 ${a}`)}`;return new R(`${o}
|
|
9
|
+
${i.fg("accent",G(r.family))} ${t}`,0,0)}s(ye,"renderRunCall");function we(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new R(r.join(`
|
|
10
|
+
`),0,0)}s(we,"renderTerminalActionResult");function O(t,e,n,r,i){let a=[at(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&a.push(...r.map(o=>` ${i.fg("dim",o)}`)),new R(a.join(`
|
|
11
|
+
`),0,0)}s(O,"renderTerminalAction");function v(t,e,n,r){let i=be(t,E,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new R(i.join(`
|
|
12
|
+
`),0,0)}s(v,"renderTerminalResult");function Se(t,e,n){if(e===!0?e="full":e===!1&&(e="compact"),e==="disabled"){if(!(t.status!==void 0&&!["running","completed"].includes(t.status)||t.exitCode!==void 0&&t.exitCode!==0||t.error!==void 0))return new R(k(t,(l,u)=>n.fg(l,u)),0,0);let o=_(t.output??"",E),c=[...o.omission===void 0?[]:[` ${n.fg("muted",o.omission)}`],...o.lines.map(l=>` ${n.fg("dim",l)}`),...t.error===void 0?[]:[` ${n.fg("error",t.error)}`],k(t,(l,u)=>n.fg(l,u))];return new R(c.join(`
|
|
13
|
+
`),0,0)}if(e==="full"){let a=be(t,Number.POSITIVE_INFINITY,n).slice(2);return new R(a.join(`
|
|
14
|
+
`),0,0)}let r=_(t.output??"",E),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(a=>` ${n.fg("dim",a)}`)];return i.push(k(t,(a,o)=>n.fg(a,o))),new R(i.join(`
|
|
15
|
+
`),0,0)}s(Se,"renderRunResult");function Te(t,e){let n=s((o,c)=>e?.fg(o,c)??c,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${D(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",G(t.shellFamily))} ${B(t.command,84)}`],a=ot(t.output,2);return a.length>0&&i.push(...a.map(o=>` ${n("dim",B(o,90))}`)),i.push(k(t,n)),i.join(`
|
|
16
|
+
`)}s(Te,"renderActiveTerminal");function be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",a=t.cwd===void 0?"workspace":D(t.cwd),o=t.shellFamily??"posix",c=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${a} \xB7 ${i}`)}`,`${n.fg("accent",G(o))} ${t.command??""}`],l=_(t.output??"",e);return l.omission!==void 0&&c.push(` ${n.fg("muted",l.omission)}`),l.lines.length>0&&c.push(...l.lines.map(u=>` ${n.fg("dim",u)}`)),c.push(k(t,(u,d)=>n.fg(u,d))),c}s(be,"terminalCardLines");function ot(t,e){return _(t,e).lines}s(ot,"outputTail");function _(t,e){let n=$(nt(t).replaceAll("\r","")),r=n.content.split(`
|
|
17
|
+
`).map(l=>rt(l.trimEnd(),it).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,a=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),c=a+o;return{lines:r.slice(a),...n.truncated||c>0?{omission:c>0?`\u2026 ${c} earlier lines`:"\u2026 earlier output omitted"}:{}}}s(_,"outputWindow");function k(t,e){let n=t.status??"running",r=st(n),i=n==="completed"?"success":n==="running"?"accent":"error",a=[`${r} ${n}`,lt(t.elapsedMs??0)];return t.waitReason!==void 0&&a.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&a.push(`reason ${t.completionReason}`),t.exitCode!==void 0?a.push(`exit ${t.exitCode}`):t.signal!==void 0&&a.push(`signal ${t.signal}`),e(i,a.join(" \xB7 "))}s(k,"statusLine");function st(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}s(st,"statusIcon");function G(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}s(G,"promptMarker");function at(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":D(t.cwd),i=t.background===!0?"background":"wait",a=B(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${a}`)}`}s(at,"terminalIdentity");function D(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${tt.sep}`))?`~${t.slice(e.length)}`:t}s(D,"shortCwd");function B(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}s(B,"oneLine");function lt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(lt,"formatElapsed");function Re(t){return{id:"terminal",onDidChange:s(e=>t.onDidChange(e),"onDidChange"),list:s(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",...e.pid===void 0?{}:{pid:e.pid,owned:!0},renderSummary:s(n=>Te(e,n).split(`
|
|
18
|
+
`),"renderSummary"),renderDetail:s(n=>v(e,!0,n),"renderDetail"),sendInput:s(n=>t.write(e.source,n),"sendInput"),stop:s(()=>t.delete(e.source),"stop")})),"list")}}s(Re,"terminalProcessProvider");import{setTimeout as pt}from"node:timers/promises";var ut="#d8dee9",q="#111418",ct=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function V(t,e,n,r=1){let i=t.get(e);if(i===void 0)throw new Error(`Unknown terminal session ${e}`);await i.screenReady;let{createCanvas:a}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(i.rows-1,n?.start??0)),c=Math.max(1,Math.min(i.rows-o,n?.count??i.rows)),l=i.cols*9+24,u=c*18+24,d=a(Math.max(1,Math.round(l*r)),Math.max(1,Math.round(u*r))),m=d.getContext("2d");m.scale(r,r),m.fillStyle=q,m.fillRect(0,0,d.width,d.height),m.textBaseline="top";let p=i.screen.buffer.active,f=Math.max(0,p.baseY);for(let h=0;h<c;h+=1){let w=p.getLine(f+o+h);if(w!==void 0)for(let y=0;y<i.cols;y+=1){let P=w.getCell(y);P===void 0||P.getWidth()===0||dt(m,P,y,h)}}return i.status==="running"&&p.cursorY>=o&&p.cursorY<o+c&&(m.fillStyle="rgba(216, 222, 233, 0.75)",m.fillRect(12+p.cursorX*9,12+(p.cursorY-o)*18+18-2,9,2)),d.toBuffer("image/png").toString("base64")}s(V,"renderTerminalScreen");function dt(t,e,n,r){let i=ve(e,"foreground"),a=ve(e,"background");e.isInverse()&&([i,a]=[a,i]);let o=12+n*9,c=12+r*18;a!==q&&(t.fillStyle=a,t.fillRect(o,c,9*Math.max(1,e.getWidth()),18));let l=e.getChars();l.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(l,o,c),e.isUnderline()&&t.fillRect(o,c+18-2,9*Math.max(1,e.getWidth()),1))}s(dt,"drawCell");function ve(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?ut:q;let i=n?t.isFgRGB():t.isBgRGB(),a=n?t.getFgColor():t.getBgColor();return i?`#${a.toString(16).padStart(6,"0")}`:mt(a)}s(ve,"cellColor");function mt(t){let e=ct[t];if(e!==void 0)return e;if(t>=232){let c=8+(t-232)*10;return xe(c,c,c)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),a=n%6,o=s(c=>c===0?0:55+c*40,"channel");return xe(o(r),o(i),o(a))}s(mt,"ansiColor");function xe(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}s(xe,"rgb");var X="\0pi-terminal-write\0",K="\0pi-terminal-keys\0";function ft(t){let e=t?.find(l=>l==="image"||l==="sequence"||l.startsWith("image:")||l.startsWith("sequence:"));if(e===void 0)return;let n=e.indexOf(":"),r=n<0?e:e.slice(0,n),i=new Map;if(n>=0)for(let l of e.slice(n+1).split(",")){let[u,d,m]=l.split("=");if(u===void 0||d===void 0||m!==void 0||d.length===0)throw new Error(`Invalid terminal ${r} view parameter: ${l}`);if(u!=="duration"&&u!=="interval"&&u!=="scale")throw new Error(`Unsupported terminal ${r} view parameter: ${u}`);let p=Number(d);if(!Number.isFinite(p))throw new Error(`Terminal ${u} must be a number`);i.set(u,p)}let a=i.get("duration")??2,o=i.get("interval")??.5,c=i.get("scale")??1;if(!(c>0&&c<=1))throw new Error("Terminal image scale must be greater than 0 and at most 1");if(r==="sequence"){if(!(a>0&&a<=10))throw new Error("Terminal sequence duration must be greater than 0 and at most 10 seconds");if(!(o>0))throw new Error("Terminal sequence interval must be greater than 0 seconds");if(Math.floor(a/o)+1>20)throw new Error("Terminal sequence capture is limited to 20 frames")}return{mode:r,duration:a,interval:o,scale:c}}s(ft,"parseTerminalVisualView");async function $e(t,e){let n=new Map,r=new Map,i={protocol:te,apiVersion:ne,id:"terminal",setup(o){o.addResolver({resolver:gt(e),preserveTruncatedOutput:!0,renderResult(c,l,u){let d=c.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return v(m===void 0?p:{...p,output:e.screenTail(m).join(`
|
|
19
|
+
`)},l.expanded,u,"read terminal")}}),o.addHandler({stage:"pre-read",async handler(c){let l=c.request.path;if(l===void 0||!T(l))return{kind:"continue",context:c};let u;try{u=ft(c.request.views)}catch(m){return{kind:"return",result:Y(l,m instanceof Error?m.message:String(m))}}if(u===void 0)return{kind:"continue",context:c};let d=e.get(l);if(d===void 0)return{kind:"return",result:Y(l,`Unknown terminal session ${l}`)};try{e.markInspected(l);let m=u.mode==="image"?1:Math.floor(u.duration/u.interval)+1,p=[];for(let f=0;f<m;f+=1){c.resolverContext.signal?.throwIfAborted(),f>0&&await pt(u.interval*1e3,void 0,{signal:c.resolverContext.signal});let h=await V(e,l,void 0,u.scale);p.push({type:"image",data:h,mimeType:"image/png"})}return{kind:"return",result:{content:p,script:{kind:"native",source:d.source,blocks:p},details:{source:d.source,resolvedBy:"terminal",frames:m,mode:u.mode}}}}catch(m){return{kind:"return",result:Y(l,m instanceof Error?m.message:String(m))}}}}),o.describe("shell:<session> \u2014 terminal status and a bounded output tail with a full-log path when truncated. image and parameterized sequence views return the virtual terminal screen as ordered PNG frames.")}},a={protocol:ie,apiVersion:oe,id:"terminal",setup(o){o.addResolver({resolver:ht(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:s(async c=>(Ee(c.input,e,n),await Pe(c.input,e,r),yt(c,X)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:s(async c=>(await Pe(c.input,e,r),Ee(c.input,e,n),wt(c)),"handler")});for(let c of["write","insert","delete"])o.addToolRenderer({tool:c,matches:s((l,u)=>Rt(l,u),"matches"),renderCall(l,u,d){let m=l,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),O(f.snapshot??{},c,Ae(c,m),[],u)},renderResult(l,u,d){let m=bt(l.details);return we(m.action,m.changedLines,d)}});o.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([re(t,i),se(t,a)]),t.on("tool_result",async(o,c)=>{if(!b(o.input))return;let l=o.input.path;if(o.toolName==="replace"&&typeof l=="string"&&T(l)){let A=`replace is unsupported for ${l}; use write for text, insert for keys, or delete to terminate and remove the session.`;return L({content:[{type:"text",text:A}],details:o.details},I,{status:"error",errors:[H(A,"UNSUPPORTED_OPERATION",l)],data:{operation:"replace",effect:"not-applied",files:[{source:l,effect:"not-applied"}]}})}if(o.toolName==="delete"&&typeof l=="string"&&T(l)){let A=e.get(l);if(A===void 0)return;let Ze=e.snapshot(A);return e.delete(l).then(()=>L({content:[{type:"text",text:`Deleted terminal session ${l}.`}],details:{source:l,deleted:!0,snapshot:Ze,action:"delete",input:"session",changedLines:[]}},I,{status:"success",errors:[],data:{operation:"delete",effect:"applied",files:[{source:l,effect:"applied"}]}}),C=>L({content:[{type:"text",text:C instanceof Error?C.message:String(C)}],details:{source:l,deleted:!1}},I,{status:"error",errors:[H(C,"TERMINAL_DELETE_FAILED",l)],data:{operation:"delete",effect:"unknown",files:[{source:l,effect:"unknown"}]}}))}if(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let u=o.input.path;if(typeof u!="string"||!T(u))return;let d=e.get(u);if(d===void 0)return;let m=r.get(u)??e.screenRows(d);r.delete(u);let p=n.get(u)??d.outputStart+d.output.length;n.delete(u),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=o.toolName,w=Ae(h,o.input),y=e.screenChangeRegion(d,m,6),P=[{type:"text",text:`Sent ${w} to ${d.source}.`}];return c.model?.input.includes("image")===!0&&P.push({type:"image",data:await V(e,u,{start:y.startRow,count:y.lines.length}),mimeType:"image/png"}),{content:P,details:{source:d.source,action:h,status:d.status,snapshot:f,input:w,changedLines:y.lines},isError:o.isError,...o.structuredContent===void 0?{}:{structuredContent:o.structuredContent}}})}s($e,"registerTerminalResources");function gt(t){return{id:"terminal",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:St(r)}]}}}}}}s(gt,"createReadResolver");function ht(t){return{id:"terminal-input",async tryResolve(e){if(!T(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=Tt(r),a=i.indexOf(X),o=i.indexOf(K);if(a>=0){t.write(n.source,i.slice(a+X.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+K.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}s(ht,"createInputResolver");function yt(t,e){return!b(t.input)||!ke(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}s(yt,"transformWriteInput");function wt(t){if(!b(t.input)||!ke(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${K}${typeof t.input.text=="string"?t.input.text:""}`}}}s(wt,"transformInsertInput");function St(t){return M(t)}s(St,"formatSnapshot");function Tt(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}s(Tt,"singleText");function Y(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}s(Y,"failure");function T(t){return/^shell:[a-f\d]{12}$/u.test(t)}s(T,"isShellSource");function ke(t){return typeof t=="string"&&T(t)}s(ke,"isShellSourceValue");function bt(t){if(!b(t)||!b(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}s(bt,"terminalActionDetails");async function Pe(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}s(Pe,"rememberScreen");function Ee(t,e,n){if(!b(t)||typeof t.path!="string"||!T(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}s(Ee,"rememberOutputEnd");function Ae(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}s(Ae,"terminalInputLabel");function Rt(t,e){if(!b(t))return!1;if(e==="call")return typeof t.path=="string"&&T(t.path);let n=t.details;return b(n)&&typeof n.source=="string"&&T(n.source)}s(Rt,"isTerminalRenderValue");function b(t){return typeof t=="object"&&t!==null}s(b,"isRecord");import{truncateToWidth as vt,visibleWidth as xt}from"@earendil-works/pi-tui";async function Le(t,e){await ue(t,{protocol:ae,apiVersion:le,id:"terminal",setup(r){r.addResolver({resolver:Pt(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.")}})}s(Le,"registerTerminalSearch");function Pt(t){return{readResources:s(e=>e.path?.startsWith("shell:")?[e.path]:[],"readResources"),id:"terminal",toScriptData(e){let n=N(e);return ce(n.matches,!1)},async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=Et(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=N(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
|
|
20
|
+
`)}
|
|
21
|
+
|
|
22
|
+
${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,a=J(i)?N(i.payload):N(void 0),o=O(a.snapshot,"search",JSON.stringify(a.query),a.matches.slice(-6).map(c=>`${c.lineNumber}: ${c.lineText}`),r);return new z(o,n.expanded===!0,r)}}}s(Pt,"terminalSearchResolver");var Ce=12,z=class{constructor(e,n,r){this.content=e;this.expanded=n;this.theme=r}static{s(this,"TerminalSearchPanel")}render(e){let n=this.content.render(e);if(this.expanded||n.length<=Ce)return n;let r=Ce-1,i=String(n.length-r),a=`\u2026 ${i} visual rows omitted \xB7 ctrl+o to expand`,o=xt(a)<=e?a:`\u2026 ${i} visual rows omitted \xB7 ctrl+o`;return[...n.slice(0,r),this.theme.fg("muted",vt(o,e))]}invalidate(){this.content.invalidate()}};function Et(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[a,o]of t.output.replaceAll("\r","").split(`
|
|
23
|
+
`).entries()){let c=e.caseSensitive===!0?o:o.toLocaleLowerCase(),l=0;for(;r.length<i;){let u=c.indexOf(n,l);if(u<0)break;let d=u+n.length;(e.wholeWord!==!0||At(c,u,d))&&r.push({source:t.source,lineNumber:a+1,startColumn:u,endColumn:d,matchedText:o.slice(u,d),lineText:o}),l=Math.max(d,u+1)}if(r.length>=i)break}return r}s(Et,"findTerminalMatches");function At(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}s(At,"isWordBoundary");function N(t){if(!$t(t))throw new TypeError("Invalid terminal search result");return t}s(N,"parsePayload");function $t(t){return J(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&J(t.snapshot)&&typeof t.snapshot.source=="string"}s($t,"isTerminalSearchPayload");function J(t){return typeof t=="object"&&t!==null}s(J,"isRecord");import{spawn as kt}from"node:child_process";import{closeSync as Ct,mkdirSync as Lt,openSync as It,rmSync as Mt,writeSync as _t}from"node:fs";import Ot from"node:os";import Ie from"node:path";import{createRequire as Dt}from"node:module";import{randomUUID as Nt}from"node:crypto";import{stripVTControlCharacters as Wt}from"node:util";var Oe=Dt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Me=1e6,Ut=100,Ft=30,jt=2e3,W=class{static{s(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=Gt){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(qt(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,...e.process===void 0?{}:{pid:e.process.pid},background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#o)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Jt(n);this.#i.set(n,It(r,"a",384));let i=e.cols??Ut,a=e.rows??Ft,o=Bt(i,a),c=s(p=>{},"resolveCompletion"),l=new Promise(p=>{c=p}),u={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:a,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:l,resolveCompletion:c,completionDelivered:!1,staleReminderDelivered:!1},d;try{let p=Oe("node-pty"),f={name:"xterm-256color",cols:i,rows:a,cwd:e.cwd,env:Yt(Vt())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...u,status:"failed",endedAt:Date.now(),error:zt(p)};return this.#e.set(n,f),this.#s(n),c(f),queueMicrotask(()=>this.#l(f)),f}let m={...u,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{x(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#s(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return x(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,a)=>{let o=s(()=>{this.stop(r.source,"cancelled").then(i,a)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(c=>{n?.removeEventListener("abort",o),i(c)},a)})}async waitForForeground(e,n){let r=this.required(e);if(x(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(a=>{let o=!1,c,l=s(p=>{o||(p!==void 0&&x(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",u),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),a({session:r,...p===void 0?{}:{reason:p}}))},"finish"),u=s(()=>l("aborted"),"onAbort"),d=setTimeout(()=>l("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Ht(r)){c=void 0;return}c??=Date.now(),Date.now()-c>=i&&l("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",u,{once:!0}),n.signal?.aborted===!0&&u(),r.completion.then(()=>l())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,a;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,a=Date.now(),await e.screenReady;else if(a!==void 0&&Date.now()-a>=40)return;await Z(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),a=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(a/2)),c=-1;for(let d=0;d<=e.rows-a;d+=1){let m=0;for(let p=d;p<d+a;p+=1){let f=n[p]??"",h=i[p]??"",w=h.length>0&&!n.includes(h),y=f.length>0&&h.length===0;f!==h&&(w||y)&&(m+=1)}m>c&&(c=m,o=d)}let l=e.screen.buffer.active;return{lines:i.slice(o,o+a).map((d,m)=>{if(o+m!==l.cursorY)return d;let f=d.padEnd(l.cursorX," ");return`${f.slice(0,l.cursorX)}\u258C${f.slice(l.cursorX)}`}),startRow:o}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),a=[];for(let o=0;o<e.rows;o+=1){let c=r.getLine(i+o)?.translateToString(!0).trimEnd();c!==void 0&&c.length>0&&a.push(c)}return a.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(Xt(n))}async stop(e,n="stopped"){let r=this.required(e);return x(r.status)||(r.status="stopping",this.#n(r),await _e(r,!1),await Promise.race([r.completion.then(()=>!0),Z(jt).then(()=>!1)])||(await _e(r,!0),await Promise.race([r.completion,Z(1e3)])),x(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#s(n.id),Mt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],a=Math.max(0,r.baseY);for(let o=a;o<a+n.rows;o+=1)i.push(r.getLine(o)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#o){this.#o=!0,await Promise.all([...this.#e.values()].filter(e=>!x(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#s(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=Wt(n),i=this.#i.get(e.id);if(i!==void 0&&_t(i,r),e.output+=r,e.output.length>Me){let a=e.output.length-Me;e.output=e.output.slice(a),e.outputStart+=a}e.screenReady=e.screenReady.then(()=>new Promise(a=>{e.screen.write(n,a)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(Ct(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function Ht(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}s(Ht,"looksInteractive");function Bt(t,e){let{Terminal:n}=Oe("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}s(Bt,"createScreen");function Gt(){return Nt().replaceAll("-","").slice(0,12)}s(Gt,"defaultSessionId");function qt(t){return t.startsWith("shell:")?t.slice(6):t}s(qt,"normalizeSessionId");function x(t){return t!=="running"&&t!=="stopping"}s(x,"isTerminalStatus");function Vt(){return process.env}s(Vt,"processEnvironment");function Yt(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}s(Yt,"cleanEnvironment");function Xt(t){return t.split(/[\s,]+/u).filter(Boolean).map(Kt).join("")}s(Xt,"encodeTerminalKeys");function Kt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),a=r.has("alt")||r.has("meta"),o=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return a?`\x1B${m}`:m}let c={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!a&&!o&&c[n]!==void 0)return c[n];if(a&&!i&&!o&&c[n]!==void 0)return`\x1B${c[n]}`;let u={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(u!==void 0)return!i&&!a&&!o?`\x1B[${u}`:`\x1B[1;${1+(o?1:0)+(a?2:0)+(i?4:0)}${u}`;if(a&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}s(Kt,"encodeTerminalKey");async function _e(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=kt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}s(_e,"terminateProcessTree");function Z(t){return new Promise(e=>setTimeout(e,t))}s(Z,"delay");function zt(t){return t instanceof Error?t.message:String(t)}s(zt,"errorMessage");function Jt(t){let e=Ie.join(Ot.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return Lt(e,{recursive:!0,mode:448}),Ie.join(e,`${t}.log`)}s(Jt,"createOutputLog");import{AgentSession as Zt}from"@earendil-works/pi-coding-agent";var U=Symbol.for("pi-agent-ide.terminal-steering-observers");function De(t){let e=Zt.prototype,n=e[U]??Qt(e);return n.listeners.add(t),()=>{n.listeners.delete(t),n.listeners.size===0&&n.restore()}}s(De,"observeQueuedSteering");function Qt(t){let e=t.prompt,n=t.steer,r=new Set,i=s(l=>{for(let u of[...r])u(l)},"notify"),a=s(function(l,u){return u?.streamingBehavior!=="steer"?e.call(this,l,u):e.call(this,l,{...u,preflightResult:s(d=>{u.preflightResult?.(d),d==="queued"&&i(this)},"preflightResult")})},"prompt"),o=s(async function(...l){let u=await n.apply(this,l);return u==="queued"&&i(this),u},"steer");t.prompt=a,t.steer=o;let c={listeners:r,restore:s(()=>{t[U]===c&&(t.prompt===a&&(t.prompt=e),t.steer===o&&(t.steer=n),delete t[U])},"restore")};return t[U]=c,c}s(Qt,"installObservers");import en from"node:os";import Ne from"node:path";function We(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",a=Ne.win32.basename(i).toLowerCase();return a==="cmd"||a==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:s(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:a.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:s(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||en.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Ne.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:s(i=>["-c",i],"commandArgs")}}s(We,"resolveShellProfile");function Ue(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}s(Ue,"shellSyntaxGuidance");import Be from"node:path";import{stripVTControlCharacters as nn}from"node:util";import{defineTool as rn}from"@earendil-works/pi-coding-agent";import{Type as S}from"typebox";import{Text as on}from"@earendil-works/pi-tui";import{open as tn}from"node:fs/promises";import{Type as g}from"typebox";var Fe=1024*1024,je=g.Object({output:g.String({description:"ANSI-free PTY output, up to 1 MiB. Longer output joins the first and last 512 KiB without adding labels or an omission marker. See output_ranges for the gap."}),truncated:g.Boolean({description:"Whether output omits bytes from the retained log. This is independent of whether the process has finished."}),full_output_path:g.String({description:"UTF-8 log of all output received so far. Available until the shell session is deleted."}),output_ranges:g.Array(g.Object({start:g.Integer(),end:g.Integer()}),{description:"Zero-based, end-exclusive UTF-8 byte ranges in the log, concatenated into output."}),exit_code:g.Optional(g.Number({description:"Process exit code, only when known."})),wall_time_seconds:g.Number(),session:g.String({description:"Session ID."}),source:g.String({description:"Persistent shell: source for Read, input and termination."}),status:g.Union(["running","completed","failed","stopping","stopped","cancelled","lost"].map(t=>g.Literal(t))),background:g.Boolean(),wait_reason:g.Optional(g.Union([g.Literal("timeout"),g.Literal("interactive"),g.Literal("steering")])),completion_reason:g.Optional(g.Literal("timeout")),signal:g.Optional(g.Number()),error:g.Optional(g.String())});async function He(t){let e=await tn(t.fullOutputPath,"r");try{let n=(await e.stat()).size,r=s(async(c,l)=>{let u=Buffer.alloc(l),d=0;for(;d<l;){let m=await e.read(u,d,l-d,c+d);if(m.bytesRead===0)throw new Error("Shell output log ended before its snapshot size");d+=m.bytesRead}return u},"readRange"),i,a,o=n>Fe;if(!o)i=(await r(0,n)).toString("utf8"),a=[{start:0,end:n}];else{let c=Fe/2,l=await r(0,c),u=await r(n-c,c),d=new TextDecoder().decode(l,{stream:!0}),m=0;for(;m<u.length&&(u.readUInt8(m)&192)===128;)m++;let p=u.subarray(m).toString("utf8");i=d+p,a=[{start:0,end:Buffer.byteLength(d)},{start:n-c+m,end:n}]}return{output:i,truncated:o,full_output_path:t.fullOutputPath,output_ranges:a,...t.exitCode===void 0?{}:{exit_code:t.exitCode},wall_time_seconds:t.elapsedMs/1e3,session:t.id,source:t.source,status:t.status,background:t.background,...t.waitReason===void 0?{}:{wait_reason:t.waitReason},...t.completionReason===void 0?{}:{completion_reason:t.completionReason},...t.signal===void 0?{}:{signal:t.signal},...t.error===void 0?{}:{error:t.error}}}finally{await e.close()}}s(He,"structuredShellResult");var sn=s(t=>S.Object({command:S.String({minLength:1,description:`Command for ${t.displayName} (${t.executable}). ${Ue(t)}`}),background:S.Optional(S.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:S.Optional(S.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:S.Optional(S.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:S.Optional(S.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:S.Optional(S.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1}),"createRunParameters");function Ge(t,e,n,r,i="compact"){let a=new Set,o=process.platform==="win32"?"powershell":"bash",c=sn(n);return t.registerTool(rn({name:o,exposure:"direct",namespace:{name:"ide_terminal",description:"Run shell commands in persistent terminal sessions."},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Do not use ${o} commands or scripts to edit files. Use Apply or the standalone editing tools instead. Commands that inherently generate files, such as formatters and code generators, are allowed.`],description:`Use ${o} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent. Silent background sessions wake an idle agent once for inspection after two minutes, with no further stale reminders for that session. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated.`,parameters:c,outputSchema:je,async execute(l,u,d,m,p){r.bind(p);let f=u.cwd===void 0?p.cwd:Be.resolve(p.cwd,u.cwd),h=e.start({command:u.command,background:u.background??!1,cwd:f,shell:n,...u.cols===void 0?{}:{cols:u.cols},...u.rows===void 0?{}:{rows:u.rows}});if(u.background===!0&&h.status!=="failed")return await an(e,h,m),h.status!=="running"&&(h.completionDelivered=!0),F(e.snapshot(h));if(h.status==="failed")return F(e.snapshot(h));let w=new AbortController;a.add(w);let y;try{y=await e.waitForForeground(h.source,{signal:d===void 0?w.signal:AbortSignal.any([d,w.signal]),timeoutMs:(u.timeoutSeconds??60)*1e3})}finally{a.delete(w)}return y.reason==="aborted"&&w.signal.aborted&&d?.aborted!==!0?(y.session.waitReason="steering",F(e.snapshot(y.session))):(y.reason==="aborted"&&r.notifyWaitTransition(y.session),F(e.snapshot(y.session)))},renderCall(l,u,d){if((d.expanded?"full":i)==="disabled")return new on(u.fg("toolTitle",o),0,0);let p=typeof l.command=="string"?l.command:"",f=typeof l.cwd=="string"?Be.resolve(process.cwd(),l.cwd):process.cwd();return ye(p,l.background===!0,f,n,u)},renderResult(l,u,d){return Se(l.details,u.expanded?"full":i,d)}})),()=>{for(let l of a)l.abort()}}s(Ge,"registerTerminalTools");function qe(t){let e=$(t.output).content;return{content:[{type:"text",text:M(t)}],details:{...t,output:e,outputStart:t.outputEnd-e.length,truncated:t.truncated||e.length<t.output.length},isError:t.status==="failed"||t.status==="lost"}}s(qe,"terminalPreview");async function F(t){return{...qe(t),structuredContent:await He(t)}}s(F,"terminalResult");async function an(t,e,n){await new Promise(r=>{let i=!1,a,o=s(()=>{},"unsubscribe"),c=s(()=>{i||(i=!0,clearTimeout(a),o(),r())},"finish"),l=s(()=>{let u=t.snapshot(e);n?.(qe(u)),(nn(u.output).replaceAll("\r","").split(`
|
|
24
|
+
`).filter(m=>m.length>0).length>=E||u.status!=="running")&&c()},"publish");o=t.onDidChange(u=>{u.id===e.id&&l()}),a=setTimeout(c,2e3),l()})}s(an,"captureInitialBackgroundPreview");import{Box as Ve,Container as Ye}from"@earendil-works/pi-tui";var ln=120,un=12e4,j=class{constructor(e,n,r=un){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:a},o)=>{let c=Xe(i.details)?i.details:void 0,l=new Ye;c!==void 0&&l.addChild(v(c,a,o,"stale \xB7 inspect session"));let u=new Ve(1,1,d=>o.bg("toolPendingBg",d));return u.addChild(l),u}),e.registerMessageRenderer("terminal-completion",(i,{expanded:a},o)=>{let c=new Ye;for(let u of cn(i.details))c.addChild(v(u,a,o));let l=new Ve(1,1,u=>o.bg("toolSuccessBg",u));return l.addChild(c),l}),this.#u=[n.onDidChange(i=>this.#s(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{s(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#o=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#s(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait ended; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#o=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#s(e,n=!1){if(this.#l(e.id),this.#o||e.staleReminderDelivered||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#o||e.staleReminderDelivered||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}e.staleReminderDelivered=!0;let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:mn(n),details:n},{triggerTurn:!0,deliverAs:"followUp"})}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#o||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#o||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:dn(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},ln)))}};function cn(t){return!ze(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Xe)}s(cn,"completionSnapshots");function Xe(t){return ze(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}s(Xe,"isTerminalSessionSnapshot");function dn(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
|
|
25
|
+
${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,a=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${Ke(n.elapsedMs)}
|
|
26
|
+
${a||"(no output)"}`}).join(`
|
|
27
|
+
`)}`}s(dn,"formatCompletionMessage");function mn(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${Ke(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
|
|
28
|
+
${e||"(no output)"}`}s(mn,"formatStaleMessage");function Ke(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}s(Ke,"formatElapsed");function ze(t){return typeof t=="object"&&t!==null}s(ze,"isRecord");function Je(t){return t==="full"||t==="disabled"?t:"compact"}s(Je,"toolPresentation");async function pn(t,e){ee(t,[await Q({id:"terminal",description:"Foreground and background commands, shell resources, and processes",triggers:[{tool:"bash"},{tool:"powershell"},...["read","write","insert","delete"].map(l=>({tool:l,resourcePrefixes:["shell:","process:"]}))]})]);let n=pe("terminal")??new W,r=We(),i=new j(t,n),a=de(t).add(Re(n));await Promise.all([$e(t,n),Le(t,n)]);let o=Ge(t,n,r,i,Je(e?.preferences["ui.terminal"])),c=s(()=>{},"removeSteeringObserver");t.on("session_start",(l,u)=>{i.bind(u),c(),c=De(d=>{d.sessionManager===u.sessionManager&&o()})}),t.on("agent_settled",(l,u)=>i.onAgentSettled(u)),t.on("session_shutdown",async l=>{if(c(),i.dispose(),a(),l.reason!=="quit"){me("terminal",n);return}fe("terminal",n),await n.dispose()})}s(pn,"registerTerminal");export{pn as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as y}from"./chunk-
|
|
1
|
+
import{a as y}from"./chunk-PLKYHUNT.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Worker as v}from"node:worker_threads";var p=String.raw`
|
|
2
2
|
const { parentPort, workerData } = require("node:worker_threads");
|
|
3
3
|
let fuzzy;
|
|
4
4
|
let prepared;
|
|
@@ -96,7 +96,8 @@ parentPort.once("message", (message) => {
|
|
|
96
96
|
prepare().catch((error) => {
|
|
97
97
|
parentPort.postMessage({ kind: "failed", message: error instanceof Error ? error.message : String(error) });
|
|
98
98
|
});
|
|
99
|
-
`;async function x(n,e,r){if(e.rejection.code==="ambiguous"){let i=b(n,e,r.exactCandidateLimit);return{kind:"candidates",total:i.total,candidates:i.ranges.map((a,c)=>({rank:c+1,range:a}))}}if(e.rejection.code!=="missing"||!z(n,e.content,r))return{kind:"unavailable"};if(e.signal!==void 0&&e.signal.aborted)return{kind:"failed",error:e.signal.reason};let t=await R(n,e.lines,r,e.signal);if(t.kind!=="blocks")return t.outcome;let o=[];for(let[i,a]of t.blocks.entries()){let c=e.lines[a.endLine-1];if(c===void 0)return{kind:"failed",error:new Error("Fuzzy Worker returned an invalid source range")};o.push({rank:i+1,range:{start:{lineNumber:a.startLine,column:0},end:{lineNumber:a.endLine,column:c.length}}})}return{kind:"candidates",candidates:o,total:o.length}}s(x,"recoverExactText");function z(n,e,r){if(!r.fuzzyEnabled||n.replace(/\s/gu,"").length<4)return!1;let t=new TextEncoder;return t.encode(n).byteLength<=r.maxQuerySizeKiB*1024&&t.encode(e).byteLength<=r.maxFileSizeMiB*1024*1024}s(z,"canSearch");function R(n,e,r,t){return new Promise(o=>{let i=new v(p,{eval:!0,workerData:{moduleUrl:import.meta.resolve("fast-fuzzy"),value:n,sourceLines:e,config:r}}),a=!1,c,u=s(l=>{a||(a=!0,c!==void 0&&clearTimeout(c),t!==void 0&&t.removeEventListener("abort",d),i.terminate(),o(l))},"finish"),d=s(()=>{t!==void 0&&u({kind:"outcome",outcome:{kind:"failed",error:t.reason}})},"abort");t!==void 0&&t.addEventListener("abort",d,{once:!0}),i.on("error",l=>u({kind:"outcome",outcome:{kind:"failed",error:l}})),i.on("message",l=>{if(l.kind==="ready"){c=setTimeout(()=>u({kind:"outcome",outcome:{kind:"timed-out"}}),r.timeoutMs),i.postMessage("search",[]);return}if(l.kind==="failed"){u({kind:"outcome",outcome:{kind:"failed",error:new Error(l.message??"Fuzzy Worker failed")}});return}if(l.blocks===void 0){u({kind:"outcome",outcome:{kind:"failed",error:new Error("Fuzzy Worker omitted result blocks")}});return}u({kind:"blocks",blocks:l.blocks})})})}s(R,"runFuzzyWorker");function q(n){return{id:"exact-text",description:"Any non-empty value not handled as a structured anchor selects one unique exact text span.",renderFull(e){return e},renderCompact(){return"selected text"},tryResolve(e,r){return Promise.resolve(T(e,r))},recover(e,r){return x(e,r,n)}}}s(q,"createExactTextAnchorResolver");function T(n,e){if(n.length===0)return k("invalid","exact text anchor must be non-empty");let r=m(f(e.content)),t=m(f(n)).text,o=A(r.text,t,2);if(o.length===0)return k("missing","exact text anchor was not found");if(o.length>1)return k("ambiguous","exact text anchor matched more than once");let i=o[0];if(i===void 0)return{kind:"failed",error:new Error("Exact match index is missing")};let a=e.content.startsWith("\uFEFF")?1:0,c=a+h(r.boundaries,i),u=a+h(r.boundaries,i+t.length),d=w(e.content,c,u),l=d
|
|
99
|
+
`;async function x(n,e,r){if(e.rejection.code==="ambiguous"){let i=b(n,e,r.exactCandidateLimit);return{kind:"candidates",total:i.total,candidates:i.ranges.map((a,c)=>({rank:c+1,range:a}))}}if(e.rejection.code!=="missing"||!z(n,e.content,r))return{kind:"unavailable"};if(e.signal!==void 0&&e.signal.aborted)return{kind:"failed",error:e.signal.reason};let t=await R(n,e.lines,r,e.signal);if(t.kind!=="blocks")return t.outcome;let o=[];for(let[i,a]of t.blocks.entries()){let c=e.lines[a.endLine-1];if(c===void 0)return{kind:"failed",error:new Error("Fuzzy Worker returned an invalid source range")};o.push({rank:i+1,range:{start:{lineNumber:a.startLine,column:0},end:{lineNumber:a.endLine,column:c.length}}})}return{kind:"candidates",candidates:o,total:o.length}}s(x,"recoverExactText");function z(n,e,r){if(!r.fuzzyEnabled||n.replace(/\s/gu,"").length<4)return!1;let t=new TextEncoder;return t.encode(n).byteLength<=r.maxQuerySizeKiB*1024&&t.encode(e).byteLength<=r.maxFileSizeMiB*1024*1024}s(z,"canSearch");function R(n,e,r,t){return new Promise(o=>{let i=new v(p,{eval:!0,workerData:{moduleUrl:import.meta.resolve("fast-fuzzy"),value:n,sourceLines:e,config:r}}),a=!1,c,u=s(l=>{a||(a=!0,c!==void 0&&clearTimeout(c),t!==void 0&&t.removeEventListener("abort",d),i.terminate(),o(l))},"finish"),d=s(()=>{t!==void 0&&u({kind:"outcome",outcome:{kind:"failed",error:t.reason}})},"abort");t!==void 0&&t.addEventListener("abort",d,{once:!0}),i.on("error",l=>u({kind:"outcome",outcome:{kind:"failed",error:l}})),i.on("message",l=>{if(l.kind==="ready"){c=setTimeout(()=>u({kind:"outcome",outcome:{kind:"timed-out"}}),r.timeoutMs),i.postMessage("search",[]);return}if(l.kind==="failed"){u({kind:"outcome",outcome:{kind:"failed",error:new Error(l.message??"Fuzzy Worker failed")}});return}if(l.blocks===void 0){u({kind:"outcome",outcome:{kind:"failed",error:new Error("Fuzzy Worker omitted result blocks")}});return}u({kind:"blocks",blocks:l.blocks})})})}s(R,"runFuzzyWorker");function q(n){return{id:"exact-text",description:"Any non-empty value not handled as a structured anchor selects one unique exact text span.",renderFull(e){return e},renderCompact(){return"selected text"},tryResolve(e,r){return Promise.resolve(T(e,r))},recover(e,r){return x(e,r,n)}}}s(q,"createExactTextAnchorResolver");function T(n,e){if(n.length===0)return k("invalid","exact text anchor must be non-empty");let r=m(f(e.content)),t=m(f(n)).text,o=A(r.text,t,2);if(o.length===0)return k("missing","exact text anchor was not found");if(o.length>1)return k("ambiguous","exact text anchor matched more than once");let i=o[0];if(i===void 0)return{kind:"failed",error:new Error("Exact match index is missing")};let a=e.content.startsWith("\uFEFF")?1:0,c=a+h(r.boundaries,i),u=a+h(r.boundaries,i+t.length),d=w(e.content,c,u),l=d&&!t.endsWith(`
|
|
100
|
+
`)?E(e.content,u):u,L={start:g(e.content,c),end:g(e.content,l),...d&&{linewise:!0}};return{kind:"resolved",anchor:new y(n,e.source,[L])}}s(T,"resolveExactTextAnchor");function b(n,e,r){let t=m(f(e.content)),o=m(f(n)).text;if(o.length===0)return{ranges:[],total:0};let i=C(t.text,o,r),a=e.content.startsWith("\uFEFF")?1:0;return{total:i.total,ranges:i.starts.map(c=>({start:g(e.content,a+h(t.boundaries,c)),end:g(e.content,a+h(t.boundaries,c+o.length))}))}}s(b,"findExactTextMatches");function w(n,e,r){let t=e===0||n[e-1]===`
|
|
100
101
|
`||n[e-1]==="\r",o=r===n.length||n[r]===`
|
|
101
102
|
`||n[r]==="\r"||n[r-1]===`
|
|
102
103
|
`||n[r-1]==="\r";return t&&o}s(w,"isWholeLineMatch");function E(n,e){return n[e]==="\r"&&n[e+1]===`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as u,f as E,k as a}from"./chunk-
|
|
1
|
+
import{e as u,f as E,k as a}from"./chunk-WJTHY6AG.js";import{a as n}from"./chunk-EI7MMDWY.js";function T(o,r){let s=n(()=>{let e,i={plugin:r,accept(c){if(e!==void 0)throw new Error(`Plugin ${r.id} registration was accepted more than once`);e=c}};return o.events.emit(E,i),e},"announce"),t=n(()=>{},"unsubscribe");t=o.events.on(u,e=>{if(!a(e))throw new Error("Invalid pi-agent-text-editor core readiness event");let i=s();if(i===void 0)throw new Error("pi-agent-text-editor core announced readiness without accepting the plugin");t(),i.catch(()=>{})}),o.on("session_shutdown",t);let d=s();if(d!==void 0)return t(),d}n(T,"connectTextEditorPlugin");export{T as a};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as S}from"./chunk-
|
|
1
|
+
import{a as S}from"./chunk-ZPT5D4VP.js";import{a as d}from"./chunk-EI7MMDWY.js";import{createRequire as j}from"node:module";import{Lang as y,parse as T,registerDynamicLanguage as F}from"@ast-grep/napi";var R=j(new URL("../src/plugins/pi-agent-ide-ast/src/ast/native-parser.ts",import.meta.url).href),B={bash:"@ast-grep/lang-bash",csharp:"@ast-grep/lang-csharp",dart:"@ast-grep/lang-dart",elixir:"@ast-grep/lang-elixir",go:"@ast-grep/lang-go",html:"@ast-grep/lang-html",java:"@ast-grep/lang-java",kotlin:"@ast-grep/lang-kotlin",lua:"@ast-grep/lang-lua",markdown:"@ast-grep/lang-markdown",php:"@ast-grep/lang-php",ruby:"@ast-grep/lang-ruby",scala:"@ast-grep/lang-scala",sql:"@ast-grep/lang-sql",swift:"@ast-grep/lang-swift"},D={".bash":"bash",".cs":"csharp",".css":y.Css,".less":y.Css,".scss":y.Css,".dart":"dart",".ex":"elixir",".exs":"elixir",".go":"go",".htm":"html",".html":"html",".java":"java",".kt":"kotlin",".kts":"kotlin",".lua":"lua",".md":"markdown",".mdx":"markdown",".php":"php",".rb":"ruby",".rake":"ruby",".scala":"scala",".sc":"scala",".sql":"sql",".sh":"bash",".swift":"swift"},N=!1;function O(){if(N)return;let r={};for(let[e,t]of Object.entries(B))r[e]=R(t);F(r),N=!0}d(O,"ensureLanguagesRegistered");function C(r,e){let t=D[r];if(t)return O(),{rootNode:new b(T(t,e).root(),e)}}d(C,"parseNativeDocument");var b=class r{constructor(e,t){this.node=e;this.source=t}static{d(this,"NativeSyntaxNode")}get type(){return String(this.node.kind())}get text(){return this.node.text()}get isNamed(){return this.node.isNamed()}get hasError(){return this.type==="ERROR"||this.node.children().some(e=>new r(e,this.source).hasError)}get startIndex(){return k(this.source,this.node.range().start.index)}get endIndex(){return k(this.source,this.node.range().end.index)}get startPosition(){let{line:e,column:t}=this.node.range().start;return{row:e,column:t}}get endPosition(){let{line:e,column:t}=this.node.range().end;return{row:e,column:t}}get parent(){let e=this.node.parent();return e?new r(e,this.source):null}get namedChildCount(){return this.namedChildren.length}get namedChildren(){return this.node.children().filter(e=>e.isNamed()).map(e=>new r(e,this.source))}childForFieldName(e){let t=this.node.field(e);return t?new r(t,this.source):null}};function k(r,e){return Buffer.from(r).subarray(0,e).toString("utf8").length}d(k,"byteOffsetToStringIndex");import{createHash as q}from"node:crypto";import{createRequire as W}from"node:module";import L from"node:path";import*as p from"web-tree-sitter";var I=W(new URL("../src/plugins/pi-agent-ide-ast/src/ast/manager.ts",import.meta.url).href),M=new Set(["program","module"]),x=new Set(["body","consequence","alternative","handler","finalizer"]),A,P=new Map;function $(r){switch(r){case".ts":case".tsx":case".mts":case".cts":return"tree-sitter-typescript/tree-sitter-typescript.wasm";case".js":case".jsx":case".mjs":case".cjs":return"tree-sitter-javascript/tree-sitter-javascript.wasm";case".py":case".pyi":return"tree-sitter-python/tree-sitter-python.wasm";case".rs":return"tree-sitter-rust/tree-sitter-rust.wasm";case".c":case".cc":case".hh":case".hxx":case".cpp":case".cxx":case".h":case".hpp":return"tree-sitter-cpp/tree-sitter-cpp.wasm";case".json":case".jsonc":return"tree-sitter-json/tree-sitter-json.wasm";case".yaml":case".yml":return"@tree-sitter-grammars/tree-sitter-yaml/tree-sitter-yaml.wasm";case".toml":return"@tree-sitter-grammars/tree-sitter-toml/tree-sitter-toml.wasm";default:return}}d($,"grammarWasmPath");async function G(r){let e=$(r);if(!e)return;A??=p.Parser.init(),await A;let t=P.get(e);if(t===void 0){let i=I.resolve(e);t=p.Language.load(i),P.set(e,t)}let a=await t,o=new p.Parser;return o.setLanguage(a),o}d(G,"ensureParser");async function U(r,e,t){if(t.length===0)return;let a=L.isAbsolute(r)?r:L.resolve(e,r),o=L.extname(a).toLowerCase(),i=t.join(`
|
|
2
2
|
`),u=await G(o);return u?u.parse(i)??void 0:C(o,i)}d(U,"parseDocument");function E(r,e,t){let a=r.slice(Math.max(0,e-1),Math.max(0,t)).join(`
|
|
3
3
|
`);return q("sha1").update(a).digest("hex").slice(0,4).toUpperCase()}d(E,"hashScope");var w=class extends S{static{d(this,"AstScopeTextAnchor")}constructor(e,t,a,o){super(`scope-${e}-${t}${o===void 0?"":`-${o}`}`,a)}};function f(r,e,t,a){return new w(r,e,t,a)}d(f,"createScopeAnchor");var v=class{static{d(this,"AstScopeManager")}async getDocumentScopes(e,t,a){if(a.length===0)return[];let o=await U(e,t,a);if(!o)return[];let i=[];return this.collectCandidates(o.rootNode,i),this.buildEntries(i,a)}collectCandidates(e,t,a=0,o=!1){if(a>100||!e.isNamed)return;let i=e.type;if(!i||M.has(i)){for(let c of e.namedChildren)this.collectCandidates(c,t,a+1);return}for(let c of x){let n=e.childForFieldName(c);if(!n?.isNamed)continue;let s=n.startPosition.row+1,g=n.endPosition.row+1,h=g-s>=3,l=[...x].some(m=>n.childForFieldName(m)!==null);h&&!l&&t.push({startLine:s,endLine:g,kind:`${i}.${c}`,fromBodyField:!0}),this.collectCandidates(n,t,a+1,!0)}if(![...x].some(c=>e.childForFieldName(c)!==null)&&!o){let c=e.startPosition.row+1,n=e.endPosition.row+1;n-c>=3&&e.namedChildren.length>0&&t.push({startLine:c,endLine:n,kind:i,fromBodyField:!1})}for(let c of e.namedChildren)this.collectCandidates(c,t,a+1)}buildEntries(e,t){let a=new Map;for(let n of e){let s=a.get(n.startLine);(!s||n.endLine>s.endLine||n.endLine===s.endLine&&n.fromBodyField&&!s.fromBodyField)&&a.set(n.startLine,n)}let o=[...a.values()].sort((n,s)=>n.startLine-s.startLine||s.endLine-n.endLine),i=[];for(let n of o)i.some(g=>g.startLine<n.startLine&&g.endLine===n.endLine)||i.push(n);let u=new Map;for(let n of i){let s=E(t,n.startLine,n.endLine);u.set(s,(u.get(s)??0)+1)}let c=new Map;return i.map(n=>{let s=E(t,n.startLine,n.endLine),g=u.get(s)??1,h=(c.get(s)??0)+1;c.set(s,h);let l=g>1?h:void 0;return{name:n.kind,kind:n.kind,startLine:n.startLine,endLine:n.endLine,depth:i.filter(m=>m!==n&&m.startLine<=n.startLine&&m.endLine>=n.endLine&&(m.startLine<n.startLine||m.endLine>n.endLine)).length,hash:s,blockHash:s,...l!==void 0&&{occurrence:l},beginAnchor:f("begin",s,n.startLine,l),endScopeAnchor:f("end",s,n.endLine,l),scopeBeginAnchor:f("begin",s,n.startLine,l),scopeEndAnchor:f("end",s,n.endLine,l)}})}};export{D as a,U as b,v as c};
|