pi-agent-ide 0.6.4 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +2 -2
- package/dist/{chunk-AWXVJ5AC.js → chunk-2RTCSZB3.js} +1 -1
- package/dist/{chunk-QEJGED4V.js → chunk-3HYXQ4YA.js} +1 -1
- package/dist/chunk-3JO7QFIL.js +1 -0
- package/dist/{chunk-5J43L2RL.js → chunk-4NIFBFFR.js} +1 -1
- package/dist/{chunk-BSICWXMH.js → chunk-64M3SQPG.js} +1 -1
- package/dist/{chunk-3BBJZSMS.js → chunk-7LD2OQH3.js} +1 -1
- package/dist/chunk-7LZKOHH2.js +1 -0
- package/dist/chunk-AJRIASPQ.js +2 -0
- package/dist/chunk-EAZGN5ND.js +7 -0
- package/dist/{chunk-GIRAEVUJ.js → chunk-F5YZG77W.js} +1 -1
- package/dist/chunk-FK42RSF4.js +1 -0
- package/dist/{chunk-WJTHY6AG.js → chunk-FXNKMNSJ.js} +1 -1
- package/dist/chunk-GBLKIB6O.js +2 -0
- package/dist/{chunk-KUPHNMUK.js → chunk-KBP3QUDT.js} +1 -1
- package/dist/{chunk-VBICI5YA.js → chunk-KR36BT5E.js} +1 -1
- package/dist/chunk-OE7QVAI2.js +5 -0
- package/dist/chunk-PNU3E7IO.js +3 -0
- package/dist/chunk-PS2B6THP.js +3 -0
- package/dist/{chunk-HPUAIWIH.js → chunk-PYPPV2F5.js} +1 -1
- package/dist/{chunk-FUG2TEKI.js → chunk-QFTBY67N.js} +2 -2
- package/dist/chunk-S5LXX32D.js +28 -0
- package/dist/chunk-SQKAXYIR.js +2 -0
- package/dist/chunk-VCGNVTXQ.js +1 -0
- package/dist/chunk-XYS4FSCC.js +12 -0
- package/dist/{chunk-FBOW7XOV.js → chunk-YRF7OATP.js} +1 -1
- package/dist/entry-11.js +1 -1
- package/dist/entry-13.js +1 -1
- package/dist/entry-14.js +1 -1
- package/dist/entry-15.js +1 -1
- package/dist/entry-17.js +1 -1
- package/dist/entry-25.js +1 -1
- package/dist/entry-26.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 +13 -11
- package/dist/entry-33.js +1 -1
- package/dist/entry-37.js +6 -6
- package/dist/entry-42.js +1 -1
- package/dist/entry-44.js +1 -1
- package/dist/entry-45.js +13 -13
- package/dist/entry-46.js +1 -1
- package/dist/entry-49.js +1 -1
- package/dist/entry-50.js +3 -6
- package/dist/entry-51.js +11 -9
- package/dist/entry-52.js +1 -1
- package/dist/entry-53.js +1 -1
- package/dist/entry-54.js +1 -1
- package/dist/entry-56.js +1 -1
- package/dist/entry-58.js +1 -1
- package/dist/entry-60.js +1 -1
- package/dist/entry-61.js +0 -1
- package/dist/entry-62.js +1 -0
- package/dist/entry-63.js +0 -1
- package/dist/entry-64.js +1 -0
- package/dist/entry-65.js +1 -1
- package/dist/entry-66.js +1 -1
- package/dist/entry-67.js +1 -1
- package/dist/entry-68.js +1 -1
- package/dist/entry-69.js +1 -1
- package/dist/entry-70.js +1 -1
- package/dist/entry-71.js +0 -1
- package/dist/entry-72.js +1 -0
- package/dist/entry-73.js +0 -1
- package/dist/entry-74.js +1 -0
- package/dist/entry-75.js +1 -1
- package/dist/entry-76.js +1 -1
- package/dist/entry-77.js +67 -1
- package/dist/entry-78.js +14 -325
- package/dist/entry-79.js +2 -18
- package/dist/entry-80.js +1 -2
- package/dist/entry-81.js +1 -1
- package/dist/entry-82.js +5 -1
- package/dist/entry-83.js +3 -5
- package/dist/entry-84.js +1 -3
- package/dist/entry-85.js +1 -1
- package/dist/entry-86.js +1 -1
- package/dist/pi-agent-ide.js +5 -5
- package/docs/agent-guides/editing.md +20 -4
- package/docs/agent-guides/git-changes.md +1 -1
- package/docs/agent-guides/read-resources.md +9 -1
- package/docs/agent-guides/search-code.md +38 -1
- package/docs/agent-guides/select-code.md +194 -0
- package/docs/configuration.md +12 -17
- package/docs/development.md +2 -1
- package/docs/releases.md +1 -1
- package/docs/research/apply-native-capability-matrix.md +174 -0
- package/docs/research/apply-read-latency.md +2 -0
- package/docs/research/lpt-393-fuzzy-results/file.json +152 -0
- package/docs/research/lpt-393-fuzzy-results/repo.json +122 -0
- package/docs/research/lpt-393-search-fuzzy-fallback.md +97 -0
- package/docs/research/native-codemode-batch-decision.md +2 -0
- package/docs/research/native-codemode-batching.md +1 -1
- package/docs/structured-results.md +32 -5
- package/docs/tools.md +6 -2
- package/docs/user-hooks.md +1 -1
- 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-filesystem/package.json +7 -7
- 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 +15 -10
- package/node_modules/pi-agent-ide-ast/src/ast/constructs.ts +193 -0
- package/node_modules/pi-agent-ide-ast/src/ast/element-extent.ts +59 -0
- package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +5 -1
- package/node_modules/pi-agent-ide-ast/src/ast/selection.ts +204 -0
- package/node_modules/pi-agent-ide-ast/src/ast/syntax-tree.ts +2 -0
- package/node_modules/pi-agent-ide-ast/src/extension.ts +4 -2
- package/node_modules/pi-agent-ide-ast/src/geometry-selection.ts +184 -0
- package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +107 -21
- package/node_modules/pi-agent-ide-ast/src/select-presentation.ts +104 -0
- package/node_modules/pi-agent-ide-ast/src/select-schema.ts +384 -0
- package/node_modules/pi-agent-ide-ast/src/selection-region.ts +41 -0
- package/node_modules/pi-agent-ide-ast/src/source-text.ts +92 -0
- package/node_modules/pi-agent-ide-ast/src/text-selection.ts +214 -0
- package/node_modules/pi-agent-ide-ast/src/tool-select.ts +251 -0
- package/node_modules/pi-agent-ide-changes/index.ts +2 -18
- package/node_modules/pi-agent-ide-changes/package.json +8 -8
- package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +2 -2
- package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +11 -40
- 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/index.ts +2 -2
- package/node_modules/pi-agent-ide-lsp/package.json +9 -9
- package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +5 -0
- package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +8 -2
- package/node_modules/pi-agent-ide-lsp/src/lsp/project.ts +19 -0
- package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +204 -118
- package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +2 -17
- package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +88 -45
- 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/read-parameters.ts +2 -2
- package/node_modules/pi-agent-read/src/api/tools/read.ts +4 -0
- package/node_modules/pi-agent-read/src/core/extension.ts +11 -0
- package/node_modules/pi-agent-read/src/core/tools/read/result-target.ts +93 -0
- package/node_modules/pi-agent-read/src/core/tools/read/structured-result.ts +2 -0
- package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +8 -1
- package/node_modules/pi-agent-resource/package.json +1 -1
- package/node_modules/pi-agent-resource/src/index.ts +10 -0
- package/node_modules/pi-agent-resource/src/result-targets.ts +233 -0
- package/node_modules/pi-agent-search/package.json +5 -5
- package/node_modules/pi-agent-search/src/api/fuzzy.ts +208 -0
- package/node_modules/pi-agent-search/src/api/presentation.ts +68 -0
- package/node_modules/pi-agent-search/src/api/search-parameters.ts +9 -3
- package/node_modules/pi-agent-search/src/api/search-scope.ts +22 -0
- package/node_modules/pi-agent-search/src/api/search.ts +28 -0
- package/node_modules/pi-agent-search/src/api/structured-result.ts +69 -14
- package/node_modules/pi-agent-search/src/core/extension.ts +56 -16
- package/node_modules/pi-agent-search/src/core/search-core.ts +9 -1
- package/node_modules/pi-agent-search-text/index.ts +3 -1
- package/node_modules/pi-agent-search-text/package.json +7 -6
- package/node_modules/pi-agent-search-text/src/fuzzy-search.ts +164 -0
- package/node_modules/pi-agent-search-text/src/resolvers.ts +161 -30
- package/node_modules/pi-agent-search-text/src/scoped-search.ts +103 -0
- package/node_modules/pi-agent-search-text/src/search-backend.ts +104 -17
- package/node_modules/pi-agent-search-text/src/search-renderer.ts +89 -292
- package/node_modules/pi-agent-search-text/src/search-result.ts +77 -0
- package/node_modules/pi-agent-search-text/src/search-session.ts +96 -11
- package/node_modules/pi-agent-text/package.json +2 -2
- 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-line-hash/package.json +5 -5
- package/node_modules/pi-agent-text-editor/index.ts +0 -5
- package/node_modules/pi-agent-text-editor/package.json +26 -31
- package/node_modules/pi-agent-text-editor/runtime/entry-77.js +1 -0
- package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +3 -1
- package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -20
- package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +4 -23
- package/node_modules/pi-agent-text-editor/src/core/editing-guidelines.ts +2 -2
- package/node_modules/pi-agent-text-editor/src/core/extension.ts +12 -2
- package/node_modules/pi-agent-text-editor/src/core/file-operation-tools.ts +29 -4
- package/node_modules/pi-agent-text-editor/src/core/file-operations.ts +1 -1
- package/node_modules/pi-agent-text-editor/src/core/file-result-targets.ts +76 -0
- package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +1 -1
- package/node_modules/pi-agent-text-editor/src/core/mutation-result-targets.ts +168 -0
- package/node_modules/pi-agent-text-editor/src/core/native-text-edit-batch.ts +199 -19
- package/node_modules/pi-agent-text-editor/src/core/result-input.ts +22 -0
- package/node_modules/pi-agent-text-editor/src/core/result-target-anchors.ts +78 -0
- package/node_modules/pi-agent-text-editor/src/core/result-transfer.ts +175 -0
- package/node_modules/pi-agent-text-editor/src/core/structured-result.ts +109 -11
- package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +6 -1
- package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +0 -75
- package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +211 -223
- package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +9 -6
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +5 -5
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +5 -5
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -7
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +8 -8
- package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +8 -3
- package/node_modules/pi-agent-text-editor-renderer/index.ts +1 -72
- package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
- package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +19 -5
- package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +19 -45
- package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
- package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
- package/node_modules/pi-agent-tool-call-interception/runtime/entry-80.js +1 -0
- package/node_modules/pi-agent-tool-ui/package.json +2 -2
- package/node_modules/pi-agent-tool-ui/src/index.ts +7 -0
- package/node_modules/pi-agent-tool-ui/src/result-panel.ts +298 -0
- package/node_modules/pi-agent-web/index.ts +3 -0
- package/node_modules/pi-agent-web/package.json +8 -8
- package/node_modules/pi-agent-web/runtime/entry-82.js +2 -0
- package/node_modules/pi-agent-web/src/search.ts +111 -2
- 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/package.json +35 -36
- package/src/composite/module-labels.ts +1 -1
- package/src/composite/preferences.ts +0 -5
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
- 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-web/index.ts +3 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +8 -8
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-83.js +2 -0
- 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/runtime/entry-82.js +2 -0
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/search.ts +111 -2
- package/src/extensions/pi-agent-read/package.json +7 -7
- package/src/extensions/pi-agent-read/src/api/read-parameters.ts +2 -2
- package/src/extensions/pi-agent-read/src/api/tools/read.ts +4 -0
- package/src/extensions/pi-agent-read/src/core/extension.ts +11 -0
- package/src/extensions/pi-agent-read/src/core/tools/read/result-target.ts +93 -0
- package/src/extensions/pi-agent-read/src/core/tools/read/structured-result.ts +2 -0
- package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +8 -1
- package/src/extensions/pi-agent-search/package.json +5 -5
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +3 -1
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +7 -6
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/fuzzy-search.ts +164 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +161 -30
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/scoped-search.ts +103 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +104 -17
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +89 -292
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +77 -0
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +96 -11
- package/src/extensions/pi-agent-search/src/api/fuzzy.ts +208 -0
- package/src/extensions/pi-agent-search/src/api/presentation.ts +68 -0
- package/src/extensions/pi-agent-search/src/api/search-parameters.ts +9 -3
- package/src/extensions/pi-agent-search/src/api/search-scope.ts +22 -0
- package/src/extensions/pi-agent-search/src/api/search.ts +28 -0
- package/src/extensions/pi-agent-search/src/api/structured-result.ts +69 -14
- package/src/extensions/pi-agent-search/src/core/extension.ts +56 -16
- package/src/extensions/pi-agent-search/src/core/search-core.ts +9 -1
- package/src/extensions/pi-agent-text-editor/index.ts +0 -5
- package/src/extensions/pi-agent-text-editor/package.json +26 -31
- 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-line-hash/package.json +5 -5
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +1 -72
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-78.js +2 -0
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +19 -5
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +19 -45
- 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/runtime/entry-77.js +1 -0
- package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +3 -1
- package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -20
- package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +4 -23
- package/src/extensions/pi-agent-text-editor/src/core/editing-guidelines.ts +2 -2
- package/src/extensions/pi-agent-text-editor/src/core/extension.ts +12 -2
- package/src/extensions/pi-agent-text-editor/src/core/file-operation-tools.ts +29 -4
- package/src/extensions/pi-agent-text-editor/src/core/file-operations.ts +1 -1
- package/src/extensions/pi-agent-text-editor/src/core/file-result-targets.ts +76 -0
- package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +1 -1
- package/src/extensions/pi-agent-text-editor/src/core/mutation-result-targets.ts +168 -0
- package/src/extensions/pi-agent-text-editor/src/core/native-text-edit-batch.ts +199 -19
- package/src/extensions/pi-agent-text-editor/src/core/result-input.ts +22 -0
- package/src/extensions/pi-agent-text-editor/src/core/result-target-anchors.ts +78 -0
- package/src/extensions/pi-agent-text-editor/src/core/result-transfer.ts +175 -0
- package/src/extensions/pi-agent-text-editor/src/core/structured-result.ts +109 -11
- package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +6 -1
- package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +0 -75
- package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +211 -223
- package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +9 -6
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +5 -5
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +5 -5
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +9 -7
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +8 -8
- package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +8 -3
- package/src/pi-agent-ide.ts +0 -6
- package/src/plugins/pi-agent-ide-ast/package.json +15 -10
- package/src/plugins/pi-agent-ide-ast/src/ast/constructs.ts +193 -0
- package/src/plugins/pi-agent-ide-ast/src/ast/element-extent.ts +59 -0
- package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +5 -1
- package/src/plugins/pi-agent-ide-ast/src/ast/selection.ts +204 -0
- package/src/plugins/pi-agent-ide-ast/src/ast/syntax-tree.ts +2 -0
- package/src/plugins/pi-agent-ide-ast/src/extension.ts +4 -2
- package/src/plugins/pi-agent-ide-ast/src/geometry-selection.ts +184 -0
- package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +107 -21
- package/src/plugins/pi-agent-ide-ast/src/select-presentation.ts +104 -0
- package/src/plugins/pi-agent-ide-ast/src/select-schema.ts +384 -0
- package/src/plugins/pi-agent-ide-ast/src/selection-region.ts +41 -0
- package/src/plugins/pi-agent-ide-ast/src/source-text.ts +92 -0
- package/src/plugins/pi-agent-ide-ast/src/text-selection.ts +214 -0
- package/src/plugins/pi-agent-ide-ast/src/tool-select.ts +251 -0
- package/src/plugins/pi-agent-ide-changes/index.ts +2 -18
- package/src/plugins/pi-agent-ide-changes/package.json +8 -8
- package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +2 -2
- package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +11 -40
- 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/index.ts +2 -2
- package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
- package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +5 -0
- package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +8 -2
- package/src/plugins/pi-agent-ide-lsp/src/lsp/project.ts +19 -0
- package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +204 -118
- package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +2 -17
- package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +88 -45
- package/src/plugins/pi-agent-ide-terminal/src/search.ts +10 -36
- package/src/plugins/pi-agent-ide-terminal/src/tools.ts +1 -1
- package/src/plugins/pi-agent-ide-vision/index.ts +19 -0
- package/dist/chunk-2P2OGO3G.js +0 -2
- package/dist/chunk-6EYWFBNG.js +0 -0
- package/dist/chunk-7AVXUV4A.js +0 -7
- package/dist/chunk-7WCZOO5I.js +0 -1
- package/dist/chunk-BAYETTZZ.js +0 -16
- package/dist/chunk-BVK5A7ED.js +0 -28
- package/dist/chunk-F7NVAC4Q.js +0 -0
- package/dist/chunk-FZBCKIJJ.js +0 -1
- package/dist/chunk-I5JLCFUX.js +0 -1
- package/dist/chunk-MIZAFRDR.js +0 -1
- package/dist/chunk-PJPA5EEE.js +0 -2
- package/dist/chunk-PXWDDBBC.js +0 -0
- package/dist/chunk-TQZBVOTT.js +0 -5
- package/dist/chunk-VWW3RLUX.js +0 -12
- package/dist/chunk-YHUTTZC6.js +0 -2
- package/dist/chunk-ZODCBFBL.js +0 -2
- package/dist/entry-87.js +0 -1
- package/docs/agent-guides/apply.md +0 -333
- package/node_modules/pi-agent-text-editor/src/api/apply-renderer.ts +0 -3
- package/node_modules/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +0 -159
- package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +0 -405
- package/node_modules/pi-agent-text-editor/src/core/apply/final-mutations.ts +0 -50
- package/node_modules/pi-agent-text-editor/src/core/apply/format-source.ts +0 -11
- package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +0 -203
- package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +0 -55
- package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +0 -276
- package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +0 -13
- package/node_modules/pi-agent-text-editor/src/core/apply/queue.ts +0 -25
- package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +0 -405
- package/node_modules/pi-agent-text-editor/src/core/apply/results.ts +0 -137
- package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +0 -369
- package/node_modules/pi-agent-text-editor/src/core/apply/structured-result.ts +0 -251
- package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +0 -168
- package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +0 -942
- package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
- package/node_modules/pi-agent-tool-ui/runtime/entry-82.js +0 -1
- package/node_modules/pi-agent-web-text/runtime/entry-87.js +0 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-87.js +0 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-83.js +0 -2
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-80.js +0 -2
- package/src/extensions/pi-agent-text-editor/runtime/entry-78.js +0 -2
- package/src/extensions/pi-agent-text-editor/src/api/apply-renderer.ts +0 -3
- package/src/extensions/pi-agent-text-editor/src/core/apply/apply-undo-store.ts +0 -159
- package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +0 -405
- package/src/extensions/pi-agent-text-editor/src/core/apply/final-mutations.ts +0 -50
- package/src/extensions/pi-agent-text-editor/src/core/apply/format-source.ts +0 -11
- package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +0 -203
- package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +0 -55
- package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +0 -276
- package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +0 -13
- package/src/extensions/pi-agent-text-editor/src/core/apply/queue.ts +0 -25
- package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +0 -405
- package/src/extensions/pi-agent-text-editor/src/core/apply/results.ts +0 -137
- package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +0 -369
- package/src/extensions/pi-agent-text-editor/src/core/apply/structured-result.ts +0 -251
- package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +0 -168
- package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +0 -942
- /package/node_modules/{pi-agent-text-editor → pi-agent-text-editor-renderer}/runtime/entry-78.js +0 -0
- /package/node_modules/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-79.js +0 -0
- /package/node_modules/{pi-agent-tool-call-interception → pi-agent-tool-ui}/runtime/entry-81.js +0 -0
- /package/node_modules/{pi-agent-web → pi-agent-web-html}/runtime/entry-83.js +0 -0
- /package/node_modules/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-84.js +0 -0
- /package/node_modules/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-85.js +0 -0
- /package/node_modules/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-86.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-html → pi-agent-web-image}/runtime/entry-84.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-image → pi-agent-web-pdf}/runtime/entry-85.js +0 -0
- /package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/{pi-agent-web-pdf → pi-agent-web-text}/runtime/entry-86.js +0 -0
- /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-editor-renderer → pi-agent-text-editor-stale-anchor}/runtime/entry-79.js +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,43 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0 — 2026-10-05
|
|
4
|
+
|
|
5
|
+
### Native tool composition
|
|
6
|
+
|
|
7
|
+
- Compose Read, Search, Select and editing tools through source-backed results and exact snapshot targets, including sparse and multi-file selections. Reject stale or incomplete inputs without widening their scope.
|
|
8
|
+
- Search within returned Read and mutation targets. Keep mutation change records and destination targets available for follow-up work, with explicit reasons when a text target cannot be returned.
|
|
9
|
+
- Expose AST captures as source targets and LSP symbol identity and definition/reference roles. Follow references outside a seed scope only when explicitly requested.
|
|
10
|
+
- Remove Apply, its grouped undo receipts and preview settings. Use ordinary tools through native Codemode; per-file text undo and Git change undo remain. Native copy/move pairs selections rather than concatenating and broadcasting them.
|
|
11
|
+
- Fix empty-file creation so successful native writes report truthful applied effects and return usable targets.
|
|
12
|
+
|
|
13
|
+
### Select
|
|
14
|
+
|
|
15
|
+
- Add guarded text boundaries, marker pairs, slices, trimming, splitting, line expansion and exact insertion positions, preserving UTF-16 and CRLF boundaries.
|
|
16
|
+
- Add source-local range operations: containment, intersection, subtraction and explicit merging, without filling gaps between selections.
|
|
17
|
+
- Add JavaScript and TypeScript AST enclosing constructs, navigation and named parts. Select call arguments and function parameters with owned separators; refuse ambiguous neighboring comments instead of guessing or repairing syntax.
|
|
18
|
+
|
|
19
|
+
### Search and presentation
|
|
20
|
+
|
|
21
|
+
- Suggest bounded possible identifier names after eligible zero-result searches, with separate exact candidate scopes. Keep quoted, Boolean and explicit-protocol queries exact.
|
|
22
|
+
- Unify structural and text search panels and keep agent guidance out of fuzzy user cards.
|
|
23
|
+
- Skip LSP providers that do not support workspace symbols instead of sending unsupported requests.
|
|
24
|
+
|
|
25
|
+
### Mutation diffs
|
|
26
|
+
|
|
27
|
+
- Keep whole replacements visible when old and new blocks share no trimmed line. Avoid unnecessary character refinement while preserving the existing time, pairing and size limits, precise small-edit highlights and truthful unavailable state for unfinished comparisons.
|
|
28
|
+
|
|
29
|
+
### Packaging
|
|
30
|
+
|
|
31
|
+
- Fix a documentation link to excluded tests so public package validation succeeds.
|
|
32
|
+
|
|
33
|
+
### Verification
|
|
34
|
+
|
|
35
|
+
- Run the full integration suite in four standalone CI shards with separate reports and retained logs, without raising timeouts or skipping tests. Close each scenario's Pi process instead of accumulating shared fixture hosts.
|
|
36
|
+
- Check that each final file is formatted once without requiring independent files to finish in a fixed order.
|
|
37
|
+
- Make the shell-result scenario independent of background completion timing while keeping separate completion-delivery coverage.
|
|
38
|
+
- Run Windows source and installed-package checks without a retained shared harness workspace, avoiding locks on the shared cleanup directory.
|
|
39
|
+
- Retry transient Windows test-workspace removal locks a bounded number of times after the Pi process tree exits; persistent locks still fail. Retain Windows host traces on failure without changing test timeouts or assertions.
|
|
40
|
+
|
|
3
41
|
## 0.6.4 — 2026-10-03
|
|
4
42
|
|
|
5
43
|
### Native Pi integration
|
package/README.md
CHANGED
|
@@ -76,9 +76,9 @@ Editing uses direct semantic operations:
|
|
|
76
76
|
- `insert` adds text around a selection;
|
|
77
77
|
- `delete` removes selected text or a resource;
|
|
78
78
|
- `copy` and `move` duplicate or relocate text and files;
|
|
79
|
-
- `undo` restores
|
|
79
|
+
- `undo` restores the last text edit or a selected Git change.
|
|
80
80
|
|
|
81
|
-
Independent edits can be submitted together as a tool-call batch.
|
|
81
|
+
Independent edits can be submitted together as a tool-call batch. For conditional or dependent work, native Codemode composes the same guarded tools with Read, Search and Select results. Check each operation's status and final effects; a script error does not roll back accepted edits. Diffing and staging are first-class tools too.
|
|
82
82
|
|
|
83
83
|
<div align="center">
|
|
84
84
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r}from"./chunk-EI7MMDWY.js";function l(t,n){return typeof n=="string"&&n.length>0&&t.nonAnchorValues?.includes(n)!==!0}r(l,"isMutationAnchorValue");function u(t){if(typeof t.name!="string"||t.name.trim().length===0)throw new TypeError("Mutation tool name must be a non-empty string");if(typeof t.description!="string"||typeof t.mutate!="function")throw new TypeError(`Mutation tool ${t.name} has an invalid description or operation`);if(t.direct!==void 0&&(typeof t.direct.matches!="function"||typeof t.direct.execute!="function"))throw new TypeError(`Mutation tool ${t.name} has an invalid direct operation`);let n=t.intent;if(n!==void 0&&n!=="edit"&&n!=="restore")throw new TypeError(`Mutation tool ${t.name} has an invalid intent`);let o=d(t.parameters,t.name);c(o,t.source.field,`${t.name} primary source`);let a=new Set([t.source.field]);for(let e of t.source.targets??[]){if(c(o,e.field,`${t.name} target source`),!a.has(e.fallbackTo))throw new TypeError(`Mutation tool ${t.name} target ${e.field} has an unknown fallback ${e.fallbackTo}`);a.add(e.field)}let s=new Set;for(let e of t.anchors??[]){if(c(o,e.field,`${t.name} anchor`),!a.has(e.sourceField))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} has an unknown source ${e.sourceField}`);if(!Array.isArray(e.kinds)||e.kinds.length===0||e.kinds.some(i=>typeof i!="string"||i.trim().length===0))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must accept non-empty kinds`);if(new Set(e.kinds).size!==e.kinds.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate kinds`);if(e.nonAnchorValues!==void 0&&(e.nonAnchorValues.length===0||e.nonAnchorValues.some(i=>typeof i!="string"||i.length===0)))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must declare non-empty non-anchor values`);if(e.nonAnchorValues!==void 0&&new Set(e.nonAnchorValues).size!==e.nonAnchorValues.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate non-anchor values`);if(s.has(e.field))throw new TypeError(`Mutation tool ${t.name} declares anchor ${e.field} more than once`);s.add(e.field)}for(let e of t.pair??[])if(!s.has(e))throw new TypeError(`Mutation tool ${t.name} pair field ${e} is not an anchor`)}r(u,"assertTextMutationToolRegistration");function
|
|
1
|
+
import{a as r}from"./chunk-EI7MMDWY.js";function l(t,n){return typeof n=="string"&&n.length>0&&t.nonAnchorValues?.includes(n)!==!0}r(l,"isMutationAnchorValue");function u(t){if(typeof t.name!="string"||t.name.trim().length===0)throw new TypeError("Mutation tool name must be a non-empty string");if(typeof t.description!="string"||typeof t.mutate!="function")throw new TypeError(`Mutation tool ${t.name} has an invalid description or operation`);if(t.direct!==void 0&&(typeof t.direct.matches!="function"||typeof t.direct.execute!="function"))throw new TypeError(`Mutation tool ${t.name} has an invalid direct operation`);let n=t.intent;if(n!==void 0&&n!=="edit"&&n!=="restore")throw new TypeError(`Mutation tool ${t.name} has an invalid intent`);let o=d(t.parameters,t.name);c(o,t.source.field,`${t.name} primary source`);let a=new Set([t.source.field]);for(let e of t.source.targets??[]){if(c(o,e.field,`${t.name} target source`),!a.has(e.fallbackTo))throw new TypeError(`Mutation tool ${t.name} target ${e.field} has an unknown fallback ${e.fallbackTo}`);a.add(e.field)}let s=new Set;for(let e of t.anchors??[]){if(c(o,e.field,`${t.name} anchor`),!a.has(e.sourceField))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} has an unknown source ${e.sourceField}`);if(!Array.isArray(e.kinds)||e.kinds.length===0||e.kinds.some(i=>typeof i!="string"||i.trim().length===0))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must accept non-empty kinds`);if(new Set(e.kinds).size!==e.kinds.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate kinds`);if(e.nonAnchorValues!==void 0&&(e.nonAnchorValues.length===0||e.nonAnchorValues.some(i=>typeof i!="string"||i.length===0)))throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} must declare non-empty non-anchor values`);if(e.nonAnchorValues!==void 0&&new Set(e.nonAnchorValues).size!==e.nonAnchorValues.length)throw new TypeError(`Mutation tool ${t.name} anchor ${e.field} declares duplicate non-anchor values`);if(s.has(e.field))throw new TypeError(`Mutation tool ${t.name} declares anchor ${e.field} more than once`);s.add(e.field)}for(let e of t.pair??[])if(!s.has(e))throw new TypeError(`Mutation tool ${t.name} pair field ${e} is not an anchor`)}r(u,"assertTextMutationToolRegistration");function y(t,n){let o=n[t.source.field];return typeof o=="string"?o:""}r(y,"mutationSource");function d(t,n){let o=t.properties;if(typeof o!="object"||o===null)throw new TypeError(`Mutation tool ${n} parameters must be an object schema`);return o}r(d,"schemaProperties");function c(t,n,o){if(typeof n!="string"||n.length===0||!(n in t))throw new TypeError(`${o} field ${n} is not declared by its schema`)}r(c,"assertProperty");export{l as a,u as b,y as c};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as De,b as Pe,c as Se}from"./chunk-ESPNEJHK.js";import{a as ye}from"./chunk-M5IVSCR2.js";import{e as de,f as ue}from"./chunk-T7I2VX3J.js";import{a as le}from"./chunk-MGCHOGQD.js";import{a as ie,b as se}from"./chunk-T6LX2RX5.js";import{a as we}from"./chunk-
|
|
1
|
+
import{a as De,b as Pe,c as Se}from"./chunk-ESPNEJHK.js";import{a as ye}from"./chunk-M5IVSCR2.js";import{e as de,f as ue}from"./chunk-T7I2VX3J.js";import{a as le}from"./chunk-MGCHOGQD.js";import{a as ie,b as se}from"./chunk-T6LX2RX5.js";import{a as we}from"./chunk-YRF7OATP.js";import{a as he,b as ve}from"./chunk-FXNKMNSJ.js";import{a as C}from"./chunk-K5G4FDXD.js";import{a as ge}from"./chunk-6CZO43OH.js";import{a as ce,b as pe}from"./chunk-OBNING2A.js";import{e as be}from"./chunk-PS2B6THP.js";import{e as fe,h as me,i as Y}from"./chunk-SQKAXYIR.js";import"./chunk-ZPT5D4VP.js";import{d as S,e as w}from"./chunk-N34ATN52.js";import{a as s}from"./chunk-EI7MMDWY.js";import A from"node:path";import{access as Lt}from"node:fs/promises";import{StringEnum as Bt}from"@earendil-works/pi-ai";import{defineTool as Ht}from"@earendil-works/pi-coding-agent";import{Type as h}from"typebox";import{access as B}from"node:fs/promises";async function j(r,e=process.env,t=process.platform){if(e.PI_PYTHON_PATH!==void 0)return{command:e.PI_PYTHON_PATH,args:[]};let n=t==="win32"?[{command:"python",args:[]},{command:"python3",args:[]},{command:"py",args:["-3"]}]:[{command:"python3",args:[]},{command:"python",args:[]}];for(let o of n)if(await S(o.command,r,e))return o;return n[0]}s(j,"resolvePythonDebuggerCommand");import Qe from"cross-spawn";import{cp as et,mkdtemp as tt,readdir as rt,rm as nt,stat as O}from"node:fs/promises";import{tmpdir as at}from"node:os";import ot from"node:net";import P from"node:path";import{pathToFileURL as it}from"node:url";import{createMessageConnection as st,StreamMessageReader as dt,StreamMessageWriter as ut}from"vscode-jsonrpc/node";import Ke from"cross-spawn";import Xe from"node:net";var Ye=new Set(["initialized","stopped","continued","terminated","exited","loadedSource","breakpoint","custom"]),Ze=128,k=class r{static{s(this,"DapClient")}#t;#o;#u;#r=new Map;#n=[];#i=new Set;#c=new Set;#a=Buffer.alloc(0);#g=1;#l;#f;#p;constructor(e,t,n){this.#t=e,this.#o=t,this.#u=n,e.on("data",o=>this.#b(o)),e.once("error",o=>this.#e(o)),e.once("close",()=>this.#e(new Error("Debug adapter connection closed"))),n!==void 0&&(n.stderr.on("data",o=>{process.env.PI_DEBUG_DAP_TRACE==="1"&&process.stderr.write(o)}),n.once("error",o=>this.#e(o)),n.once("exit",(o,a)=>{this.#e(new Error(`Debug adapter exited${o===null?"":` with code ${o}`}${a===null?"":` (${a})`}`))}))}static start(e,t,n){let a=Ke(e,[...t],{cwd:n,env:process.env,stdio:["pipe","pipe","pipe"]});return new r(a.stdout,a.stdin,a)}static fromSocket(e,t=1){let n=new r(e,e);return n.#g=t,n}static connect(e,t="127.0.0.1"){return new Promise((n,o)=>{let a=Xe.createConnection({port:e,host:t}),i=s(d=>o(d),"fail");a.once("error",i),a.once("connect",()=>{a.off("error",i),n(new r(a,a))})})}onReverseRequest(e){this.#f=e}onEvent(e){return this.#c.add(e),()=>this.#c.delete(e)}request(e,t,n={}){if(this.#l!==void 0)return Promise.reject(this.#l);if(n.signal?.aborted===!0)return Promise.reject(n.signal.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"));["continue","next","stepIn","stepOut"].includes(e)&&(this.#p=void 0);let o=this.#g++,a={seq:o,type:"request",command:e,...t===void 0?{}:{arguments:t}},i=new Promise((d,u)=>{let b,l=s(()=>{b!==void 0&&clearTimeout(b),n.signal?.removeEventListener("abort",p)},"cleanup"),p=s(()=>{this.#r.delete(o),l(),u(n.signal?.reason instanceof Error?n.signal.reason:new Error("Debug operation aborted"))},"abort");n.timeoutMs!==void 0&&(b=setTimeout(()=>{this.#r.delete(o),l(),u(new Error(`Timed out waiting for debug response ${e}`))},n.timeoutMs)),this.#r.set(o,{resolve:s(m=>d(m),"resolve"),reject:u,cleanup:l}),n.signal?.addEventListener("abort",p,{once:!0})});return this.#d(a),i}waitForEvent(e,t=3e4){return this.waitForAnyEvent([e],t)}waitForAnyEvent(e,t=3e4,n){let o=new Set(e),a=this.#n.findIndex(i=>o.has(i.event));return a>=0?Promise.resolve(this.#n.splice(a,1)[0]):this.#l!==void 0?Promise.reject(this.#l):new Promise((i,d)=>{let u={events:o,resolve:s(l=>{clearTimeout(u.timer),this.#i.delete(u),i(l)},"resolve"),reject:s(l=>{clearTimeout(u.timer),this.#i.delete(u),d(l)},"reject"),timer:setTimeout(()=>{this.#i.delete(u),d(new Error(`Timed out waiting for debug event ${e.join(" or ")}`))},t)};this.#i.add(u);let b=s(()=>u.reject(n?.reason instanceof Error?n.reason:new Error("Debug operation aborted")),"abort");n?.aborted===!0?b():n?.addEventListener("abort",b,{once:!0})})}close(){this.#t.destroy(),this.#o.destroy(),this.#u!==void 0&&!this.#u.killed&&this.#u.kill(),this.#e(new Error("Debug adapter closed"))}#d(e){let t=Buffer.from(JSON.stringify(e),"utf8");this.#o.write(Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r
|
|
2
2
|
\r
|
|
3
3
|
`),t]))}#b(e){for(this.#a=Buffer.concat([this.#a,e]);;){let t=this.#a.indexOf(`\r
|
|
4
4
|
\r
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as g,d as p}from"./chunk-AJRIASPQ.js";import{a as c}from"./chunk-EI7MMDWY.js";import b from"node:path";import{pathToFileURL as C}from"node:url";function S(e,r){let o=new Map;for(let n of e){let t=o.get(n.source)??[];t.push(n),o.set(n.source,t)}let i=new Set,a=e.length,s=[...o].sort(([n,t],[h,l])=>l.length-t.length||n.localeCompare(h));for(let[n,t]of s){if(a<=r)break;i.add(n),a-=t.length}return{files:[...o].sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>{if(!i.has(n))return{kind:"detailed",source:n,matches:t};let h=new Map;for(let l of t)h.set(l.lineText,(h.get(l.lineText)??0)+1);return{kind:"compacted",source:n,matchCount:t.length,uniqueLineCount:h.size,groups:o.size===1?[...h].sort(([l,d],[m,R])=>R-d||l.localeCompare(m)).slice(0,r).map(([l,d])=>({text:l,matchCount:d})):[]}})}}c(S,"planSearchPresentation");function F(e,r,o,i,a,s=50){let n=S(r,s).files.map(t=>t.kind==="detailed"?k(t.source,t.matches,i):{path:z(t.source,i),link:C(t.source).href,matchCount:t.matchCount,uniqueLineCount:t.uniqueLineCount,groups:t.groups,lines:[]});return{...a!==void 0&&{sessionId:a},query:e,matchCount:r.length,fileCount:n.length,complete:o,files:n}}c(F,"createSearchToolDetails");function D(e,r){return{fileCount:new Set(e.flatMap(o=>o.matches.map(i=>i.source))).size,groups:e.map(o=>{let a=F(o.identifier,o.matches.slice(0,g.previewMatches),o.complete,r).files.map(s=>{let u=s.lines.map(n=>{let t=Math.max(0,(n.ranges[0]?.from??0)-64),h=Math.min(n.text.length,(n.ranges[0]?.to??0)+64),l=t>0?"\u2026":"",d=n.ranges.filter(m=>m.from>=t&&m.to<=h).map(m=>({from:m.from-t+l.length,to:m.to-t+l.length}));return{...n,text:l+n.text.slice(t,h)+(h<n.text.length?"\u2026":""),ranges:d,matchCount:d.length}});return{...s,lines:u,matchCount:u.reduce((n,t)=>n+t.matchCount,0)}});return{identifier:o.identifier,files:a}})}}c(D,"createFuzzyPresentation");function M(e){return f(e)&&y(e.fileCount)&&Array.isArray(e.groups)&&e.groups.every(r=>f(r)&&typeof r.identifier=="string"&&Array.isArray(r.files)&&r.files.every(x))}c(M,"isFuzzyPresentation");function G(e){if(!f(e)||typeof e.query!="string"||!y(e.matchCount)||!y(e.fileCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||e.fuzzy!==void 0&&!p(e.fuzzy)||e.fuzzyPresentation!==void 0&&!M(e.fuzzyPresentation)||!Array.isArray(e.files)||!e.files.every(x))return!1;let r=e.files;return e.fileCount===r.length&&e.matchCount===r.reduce((o,i)=>o+i.matchCount,0)}c(G,"isSearchToolDetails");function k(e,r,o){let i=new Map;for(let s of r){let u=i.get(s.lineNumber);if(u!==void 0&&u.text!==s.lineText)throw new Error(`Search results disagree about line ${String(s.lineNumber)} in ${e}.`);let n=u??{lineNumber:s.lineNumber,text:s.lineText,ranges:[]};n.ranges.push({from:s.startColumn,to:s.endColumn}),i.set(s.lineNumber,n)}let a=[...i.values()].sort((s,u)=>s.lineNumber-u.lineNumber).map(s=>{let u=[...s.ranges].sort((n,t)=>n.from-t.from||n.to-t.to);return{lineNumber:s.lineNumber,text:s.text,matchCount:u.length,ranges:u}});return{path:z(e,o),link:C(e).href,matchCount:r.length,lines:a}}c(k,"createSearchResultFile");function x(e){if(!f(e)||typeof e.path!="string"||typeof e.link!="string"||!y(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(w))return!1;let r=e.lines,o=e.groups,i=new Set(r.flatMap(a=>a.logicalMatchIds??[]));return(o===void 0||Array.isArray(o)&&o.every(a=>f(a)&&typeof a.text=="string"&&y(a.matchCount)))&&(e.uniqueLineCount===void 0||y(e.uniqueLineCount))&&(r.length===0||(i.size>0?i.size===e.matchCount:e.matchCount===r.reduce((a,s)=>a+s.matchCount,0)))}c(x,"isSearchResultFile");function w(e){return f(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&y(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&(e.logicalMatchIds===void 0||Array.isArray(e.logicalMatchIds)&&e.logicalMatchIds.every(r=>typeof r=="string"))&&e.ranges.every(r=>L(r,e.text))}c(w,"isSearchResultLine");function L(e,r){return f(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=r.length}c(L,"isSearchResultRange");function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(f,"isRecord");function y(e){return Number.isSafeInteger(e)&&e>=0}c(y,"isCount");function z(e,r){let o=b.relative(r,e);return o.length>0&&!o.startsWith("..")&&!b.isAbsolute(o)?o:e}c(z,"displaySource");export{S as a,F as b,D as c,G as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as B,h as M}from"./chunk-
|
|
1
|
+
import{d as B,h as M}from"./chunk-F5YZG77W.js";import{a as N}from"./chunk-VCGNVTXQ.js";import{h as w,i as P}from"./chunk-SQKAXYIR.js";import{a as y}from"./chunk-EI7MMDWY.js";import{Allow as $}from"partial-json";import{Guard as f}from"typebox-guard/guard";import{Allow as F,parse as H}from"partial-json";function _(o,e=F.ALL){if(!(!o||o.trim().length===0))try{let t=H(o,e);return t==null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}y(_,"resolvePartial");var R=class{static{y(this,"PartialToolRecoveryRegistry")}registrations=new Map;states=new Map;register(e){this.registrations.set(e.recoveryKey??e.toolName,e)}unregister(e){for(let[t,n]of this.registrations)(n.toolName===e||t===e)&&this.registrations.delete(t)}recoveryKeyFor(e){for(let[t,n]of this.registrations)if(n.toolName===e||n.toolNames?.includes(e)||t===e)return t}async recover(e){let t=this.states.get(e.contentIndex);if(t?.status==="done")return t.result;if(t?.status==="running")return t.promise;let n=this.registrations.get(e.recoveryKey??e.toolName);if(!n)return;let r=this.run(n,e);this.states.set(e.contentIndex,{status:"running",promise:r});let a=await r;return this.states.set(e.contentIndex,{status:"done",result:a}),a}cancel(e){this.states.delete(e)}cleanup(e){this.states.delete(e)}cleanupAll(){this.states.clear()}async run(e,t){let n=[],r=new Set(t.completedEntryIndexes),a=new Set(t.blockedEntryIndexes),i=e.extractEntries(t).filter(c=>{if(r.has(c.index))return n.push({index:c.index,reason:"entry already completed before recovery"}),!1;if(a.has(c.index))return n.push({index:c.index,reason:"entry was blocked by a guard"}),!1;let g=e.isCompleteEntry?.(c,t)??c.complete;return g||n.push({index:c.index,reason:t.recoverCompleteBatch?"entry was incomplete in the recovered batch":"entry was incomplete before the stale entry"}),!t.recoverCompleteBatch&&t.staleEntryIndex!==void 0&&c.index>=t.staleEntryIndex?!1:g}),s=e.filterEntries?.(i,t)??i,d=new Set(s.map(c=>c.index));for(let c of i)d.has(c.index)||n.push({index:c.index,reason:"entry was excluded by recovery filtering"});let u=[];for(let c of s)try{e.validateEntry?.(c,t),u.push(c)}catch(g){n.push({index:c.index,reason:g instanceof Error?g.message:String(g)})}let m={toolName:t.toolName,contentIndex:t.contentIndex,...t.staleEntryIndex!==void 0&&{staleEntryIndex:t.staleEntryIndex},staleDetails:t.staleDetails};if(u.length===0)return{...m,status:"skipped",appliedEntries:[],skippedEntries:n};try{let c=e.buildParams(u,t),g=await e.execute(c,{contentIndex:t.contentIndex,toolCallId:t.toolCallId,toolName:t.toolName,cwd:t.cwd,ctx:t.ctx,signal:new AbortController().signal});return{...m,status:"recovered",appliedEntries:e.getAppliedEntries?.(g,u,t)??u.map(b=>b.index),skippedEntries:n,normalResult:g}}catch(c){return{...m,status:"failed",appliedEntries:[],skippedEntries:n,error:c instanceof Error?c.message:String(c)}}}};import{createAssistantMessageEventStream as W}from"@earendil-works/pi-ai";var O=Symbol.for("pi-agent-text-editor.tool-call-interceptor.streaming-provider.state");function K(o,e,t,n){let r=new Map,a={context:void 0,processStreamEvent:e,markStreamEventProcessed:t,finalizeStreamInterception:n},l=y((i,s)=>{if(!i)return;let d=s.modelRegistry.getProvider(i.provider);if(!d)return;let u=r.get(i.provider);if(u){if(u.subscribers.add(a),u.api===i.api&&d.streamSimple===u.wrapper)return;u.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:u.wrapper});return}let m=d.streamSimple[O];if(m){if(m.subscribers.add(a),r.set(i.provider,m),m.api===i.api)return;m.api=i.api;let p=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...p,api:i.api,streamSimple:m.wrapper});return}let c=d.streamSimple.bind(d),g=new Set([a]),b=y((p,v,C)=>U(c,p,v,C,g),"wrapper"),E={api:i.api,delegate:c,wrapper:b,subscribers:g};b[O]=E;let h=s.modelRegistry.getRegisteredProviderConfig(i.provider);o.registerProvider(i.provider,{...h,api:i.api,streamSimple:b}),r.set(i.provider,E)},"install");o.on("before_provider_request",(i,s)=>{a.context=s,l(s.model,s)}),o.on("turn_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("agent_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("session_start",(i,s)=>{a.context=s,l(s.model,s)}),o.on("model_select",(i,s)=>{a.context=s,l(i.model,s)}),o.on("session_shutdown",()=>{for(let[i,s]of r)s.subscribers.delete(a),s.subscribers.size===0&&o.unregisterProvider(i);r.clear(),a.context=void 0})}y(K,"registerStreamingInterceptorProvider");function U(o,e,t,n,r){let a=W(),l=new AbortController,i=n?.signal,s=!1,d=Y(e),u=new Set,m=new Set,c=new Set,g=new Set,b=y(h=>{for(let p of r)p.markStreamEventProcessed(h)},"markStreamEventProcessed"),E=y(()=>{l.abort()},"abortFromParent");return i&&(i.aborted?l.abort():i.addEventListener("abort",E,{once:!0})),(async()=>{try{let h=o(e,t,{...n,signal:l.signal});for await(let p of h){if(s)continue;p.type==="done"?d=structuredClone(p.message):p.type==="error"?d=structuredClone(p.error):d=structuredClone(p.partial),Q(p,u);let v;for(let C of r){let I=C.context;if(I){let T=await C.processStreamEvent(p,I);v??=T}}if(b(p),q(p,m,c,g),a.push(structuredClone(p)),v){if(p.type==="toolcall_delta"||p.type==="toolcall_end")for(let x of r)x.finalizeStreamInterception(p.contentIndex);s=!0,l.abort();let C=p.type==="toolcall_delta"||p.type==="toolcall_end"?p.contentIndex:void 0,I={...d,content:d.content.filter((x,A)=>u.has(A)&&(C===void 0||A<=C||g.has(A))).map(x=>x.type==="toolCall"&&x.id===v.toolCallId?{...x,arguments:structuredClone(v.arguments)}:x)};V(a,b,I,u,m,c,g);let{errorMessage:T,...L}=I;a.push({type:"done",reason:"toolUse",message:{...L,stopReason:"toolUse"}}),a.end();continue}if(p.type==="done"||p.type==="error"){a.end();return}}}catch(h){if(s)return;let p=d,v=i?.aborted===!0?"aborted":"error",C={...p,stopReason:v,errorMessage:h instanceof Error?h.message:String(h)};a.push({type:"error",reason:v,error:C}),a.end()}finally{i?.removeEventListener("abort",E)}})(),a}y(U,"wrapStream");function Q(o,e){(o.type==="text_start"||o.type==="thinking_start"||o.type==="toolcall_start")&&e.add(o.contentIndex)}y(Q,"rememberStartEvent");function q(o,e,t,n){switch(o.type){case"text_end":{e.add(o.contentIndex);break}case"thinking_end":{t.add(o.contentIndex);break}case"toolcall_end":{n.add(o.contentIndex);break}}}y(q,"rememberEndEvent");function V(o,e,t,n,r,a,l){for(let[i,s]of t.content.entries())if(n.has(i)){if(s.type==="text"&&!r.has(i)){let d={type:"text_end",contentIndex:i,content:s.text,partial:t};e(d),o.push(d)}else if(s.type==="thinking"&&!a.has(i)){let d={type:"thinking_end",contentIndex:i,content:s.thinking,partial:t};e(d),o.push(d)}else if(s.type==="toolCall"&&!l.has(i)){let d={type:"toolcall_end",contentIndex:i,toolCall:s,partial:t};e(d),o.push(d)}}}y(V,"emitMissingEndEvents");function Y(o){return{role:"assistant",content:[],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}y(Y,"emptyAssistantMessage");var Z="agentic-ide-partial-tool-recovery",G="pi-agent-text-editor/tool-call-annotation",S=new WeakMap,k=class{constructor(e){this.pi=e;e.on("tool_call",t=>{let n=this.toolCallRecords.get(t.toolCallId),r=n?.blockExecution?n.guardResult:void 0;return r?{block:!0,reason:r.content.filter(l=>l.type==="text").map(l=>l.text).join(`
|
|
2
2
|
`)||`Tool call ${t.toolName} was blocked by a streaming interceptor.`}:void 0}),e.on("tool_result",t=>{let n=this.toolCallBatchEntryIndexes.get(t.toolCallId);n!==void 0&&this.completedBatchEntryIndexes.add(n);let r=this.toolCallRecords.get(t.toolCallId)?.guardResult;if(this.toolCallRecords.delete(t.toolCallId),r){let a=r.details,l=typeof a=="object"&&a!==null&&"effect"in a&&(a.effect==="not-applied"||a.effect==="applied")?a.effect:"unknown",i=r.content.flatMap(s=>s.type==="text"?[s.text]:[]).join(`
|
|
3
3
|
`);return P({content:r.content,details:a},N,{status:"error",errors:[w(i,"INTERCEPTED")],data:{operation:t.toolName,operationId:t.toolCallId,effect:l,files:[]}})}}),e.on("message_update",async(t,n)=>{let r=t.assistantMessageEvent;this.consumeProcessedStreamEvent(r)||await this.processStreamEvent(r,n)}),e.on("message_end",async t=>{if(await this.finalizeRecovery(),this.annotateIncompleteCalls(),t.message.role!=="assistant")return;let n=this.pendingAbortReason;if(this.pendingAbortReason=void 0,!(n===void 0||t.message.stopReason!=="aborted"))return{message:{...t.message,errorMessage:n}}}),e.on("agent_end",async()=>{await this.finalizeRecovery(),this.annotateIncompleteCalls(),this.cleanupAll()})}static{y(this,"InterceptorImpl")}handlers=new Map;recoveryRegistry=new R;pendingRecoveryBlocks=[];pendingAbortReason;recoveryAppliedBatchIndexes=new Set;partialBuffers=new Map;completeArgumentContentIndices=new Set;streamedBatchEntries=new Map;batchEntryIndexes=new Map;toolCallBatchEntryIndexes=new Map;completedBatchEntryIndexes=new Set;nextBatchEntryIndex=0;contentNames=new Map;contentToolCallIds=new Map;pendingToolCallAnnotations=new Map;emittedToolCallAnnotationKinds=new Map;abortedContentIndices=new Set;dispatchQueues=new Map;abortCleanups=new Map;processedStreamEvents=new WeakSet;processedStreamEventKeys=new Map;toolCallRecords=new Map;blockedCallSink;processStreamEvent(e,t){if(e.type==="toolcall_start"){let n=e.partial.content[e.contentIndex];if(n?.type==="toolCall"){let r=this.getOrCreateBatchEntryIndex(e.contentIndex);this.contentNames.set(e.contentIndex,n.name),typeof n.id=="string"&&this.bindToolCallId(e.contentIndex,n.id),this.partialBuffers.set(e.contentIndex,""),this.streamedBatchEntries.set(e.contentIndex,{index:r,toolName:n.name,args:{},complete:!1}),this.installAbortCleanup(e.contentIndex,t.signal)}return Promise.resolve(void 0)}return e.type==="toolcall_delta"?this.enqueue(e.contentIndex,async()=>{let n=this.contentNames.get(e.contentIndex),r=this.contentToolCallIds.get(e.contentIndex);if(!n)return;let a=(this.partialBuffers.get(e.contentIndex)??"")+e.delta;this.partialBuffers.set(e.contentIndex,a),this.installAbortCleanup(e.contentIndex,t.signal);let l=_(a,$.OBJ|$.ARR)??{},i=ee(a),s=this.getOrCreateBatchEntryIndex(e.contentIndex);this.streamedBatchEntries.set(e.contentIndex,{index:s,toolName:n,args:l,complete:i!==void 0});let d=this.handlers.get(n);if(!r||!d||d.length===0||!i&&Object.keys(l).length===0)return;let u=i!==void 0;if(u&&this.completeArgumentContentIndices.has(e.contentIndex))return;u&&this.completeArgumentContentIndices.add(e.contentIndex);let m=i??l,c=await this.dispatchHandlers(d,{toolCall:{id:r,name:n,arguments:m},args:m,...!u&&{partialArgs:l},batchEntryIndex:s,batchEntries:this.getBatchEntries(s),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t});return c&&this.rememberOriginalArguments(c.toolCallId,c.arguments),c}):e.type==="toolcall_end"?this.enqueue(e.contentIndex,async()=>{let n=e.toolCall.name,r=this.handlers.get(n),a=this.getOrCreateBatchEntryIndex(e.contentIndex);this.bindToolCallId(e.contentIndex,e.toolCall.id);let l=this.toolCallRecords.get(e.toolCall.id);this.toolCallRecords.set(e.toolCall.id,{originalArguments:structuredClone(e.toolCall.arguments),...l?.guardResult&&{guardResult:l.guardResult},...l?.blockExecution&&{blockExecution:!0}}),this.streamedBatchEntries.set(e.contentIndex,{index:a,toolName:n,args:e.toolCall.arguments,complete:!1});let i=!this.completeArgumentContentIndices.has(e.contentIndex),s;i&&(this.completeArgumentContentIndices.add(e.contentIndex),s=r&&r.length>0?await this.dispatchHandlers(r,{toolCall:e.toolCall,args:e.toolCall.arguments,batchEntryIndex:a,batchEntries:this.getBatchEntries(a),contentIndex:e.contentIndex,cwd:t.cwd,signal:t.signal,ctx:t}):void 0);let d=this.streamedBatchEntries.get(e.contentIndex);return d&&this.streamedBatchEntries.set(e.contentIndex,{...d,complete:!0}),this.cleanupContent(e.contentIndex,n),s}):Promise.resolve(void 0)}markStreamEventProcessed(e){this.processedStreamEvents.add(e);let t=j(e);t!==void 0&&this.processedStreamEventKeys.set(t,(this.processedStreamEventKeys.get(t)??0)+1)}consumeProcessedStreamEvent(e){let t=this.processedStreamEvents.delete(e),n=j(e);if(n===void 0)return t;let r=this.processedStreamEventKeys.get(n)??0;return r===0?t:(r===1?this.processedStreamEventKeys.delete(n):this.processedStreamEventKeys.set(n,r-1),!0)}finalizeStreamInterception(e){this.cleanupTransientContent(e,void 0,!0)}getToolCallRecord(e){return this.toolCallRecords.get(e)}rememberOriginalArguments(e,t){let n=this.toolCallRecords.get(e);n&&this.toolCallRecords.set(e,{originalArguments:structuredClone(t),...n.guardResult&&{guardResult:n.guardResult},...n.blockExecution&&{blockExecution:!0}})}async dispatchHandlers(e,t){for(let n of e){let r=await n.intercept(t);if(r!==void 0){this.pendingRecoveryBlocks.push({blocked:r,ctx:t});let a={content:[{type:"text",text:r.message.content}],details:r.message.details??null};return this.blockedCallSink?.({callId:t.toolCall.id,toolName:t.toolCall.name,arguments:structuredClone(t.args),...t.contentIndex!==void 0&&{contentIndex:t.contentIndex},...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},...r.message.details!==void 0&&{details:r.message.details},result:a,nativeExecutionBlocked:n.blockExecution===!0}),{toolCallId:t.toolCall.id,arguments:structuredClone(t.args),result:this.abortToolCall(r,t,n.name,n.blockExecution===!0)}}}}annotateIncompleteCalls(){for(let[e,t]of this.streamedBatchEntries)!t.complete&&this.contentNames.has(e)&&!this.recoveryAppliedBatchIndexes.has(t.index)&&!this.emittedToolCallAnnotationKinds.get(e)?.has("stale-anchor")&&this.annotateContent(e,{kind:"aborted"})}bindToolCallId(e,t){this.contentToolCallIds.set(e,t);let n=this.batchEntryIndexes.get(e);n!==void 0&&this.toolCallBatchEntryIndexes.set(t,n);let r=this.pendingToolCallAnnotations.get(e);if(r){for(let a of r)this.emitToolCallAnnotation(t,a);this.pendingToolCallAnnotations.delete(e)}}annotateContent(e,t){let n=this.emittedToolCallAnnotationKinds.get(e)??new Set;if(n.has(t.kind))return;n.add(t.kind),this.emittedToolCallAnnotationKinds.set(e,n);let r=this.contentToolCallIds.get(e);if(r){this.emitToolCallAnnotation(r,t);return}let a=this.pendingToolCallAnnotations.get(e)??[];a.push(t),this.pendingToolCallAnnotations.set(e,a)}emitToolCallAnnotation(e,t){let n={toolCallId:e,annotation:t};this.pi.events.emit(G,n)}getOrCreateBatchEntryIndex(e){let t=this.batchEntryIndexes.get(e);if(t!==void 0)return t;let n=this.nextBatchEntryIndex;return this.nextBatchEntryIndex+=1,this.batchEntryIndexes.set(e,n),n}getBatchEntries(e){return[...this.streamedBatchEntries.values()].filter(t=>t.index<=e).sort((t,n)=>t.index-n.index)}getAllBatchEntries(){return[...this.streamedBatchEntries.values()].sort((e,t)=>e.index-t.index)}abortToolCall(e,t,n,r){let a=X(e,n),l=e.annotation?e.annotation.kind==="aborted"&&e.annotation.label===void 0?{...e.annotation,label:a}:e.annotation:e.message.customType==="text-editor-stale-anchor-block"?{kind:"stale-anchor",label:a}:{kind:"aborted",label:a,color:"error"};t.contentIndex!==void 0&&(this.abortedContentIndices.add(t.contentIndex),this.annotateContent(t.contentIndex,l));let i={content:[{type:"text",text:e.message.content}],details:B(e.message.details,l,a)};return this.toolCallRecords.set(t.toolCall.id,{originalArguments:structuredClone(t.args),guardResult:i,...r&&{blockExecution:!0}}),i}async finalizeRecovery(){let e=this.pendingRecoveryBlocks.splice(0);if(e.length===0)return;let t=new Map;for(let n of e){let r=this.recoveryRegistry.recoveryKeyFor(n.ctx.toolCall.name);if(r===void 0)continue;let a=t.get(r)??[];a.push(n),t.set(r,a)}for(let n of t.values()){let r=n[0];if(!r)continue;let a=await this.recoverIfNeeded(r.blocked,r.ctx,this.getAllBatchEntries(),n);if(a===r.blocked)continue;let l=a.message.details,s=(f.IsObjectNotArray(l)&&f.IsObjectNotArray(l.recovery)?l.recovery:void 0)?.appliedEntries;if(Array.isArray(s))for(let d of s)typeof d=="number"&&this.recoveryAppliedBatchIndexes.add(d)}}async recoverIfNeeded(e,t,n,r){if(t.contentIndex===void 0)return e;let a=e.message.details,l=f.IsObjectNotArray(a)&&typeof a.entryIndex=="number"?a.entryIndex:void 0,i=[...new Set(r.map(g=>g.ctx.batchEntryIndex).filter(g=>g!==void 0))],s=[...new Set(r.map(g=>g.ctx.toolCall.id))],d=r.map(g=>g.blocked.message.details),u=r[0],m=u?this.recoveryRegistry.recoveryKeyFor(u.ctx.toolCall.name):void 0;if(!m)return e;let c=await this.recoveryRegistry.recover({contentIndex:t.contentIndex,toolCallId:t.toolCall.id,toolName:t.toolCall.name,...l!==void 0&&{staleEntryIndex:l},staleDetails:a,...t.partialArgs&&{partialArgs:t.partialArgs},args:t.args,batchEntries:n,...t.batchEntryIndex!==void 0&&{batchEntryIndex:t.batchEntryIndex},recoverCompleteBatch:!0,completedEntryIndexes:[...this.completedBatchEntryIndexes],blockedEntryIndexes:i,blockedToolCallIds:s,blockedDetails:d,recoveryKey:m,cwd:t.cwd,ctx:t.ctx});return c&&(c.appliedEntries.length>0||c.skippedEntries.length>0)?re(e,c):e}async enqueue(e,t){let r=(this.dispatchQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t);this.dispatchQueues.set(e,r);try{return await r}finally{this.dispatchQueues.get(e)===r&&this.dispatchQueues.delete(e)}}installAbortCleanup(e,t){if(!t||this.abortCleanups.has(e))return;let n=y(()=>{let r=this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])l.onAbort?.(e)},"listener");t.addEventListener("abort",n,{once:!0}),this.abortCleanups.set(e,()=>{t.removeEventListener("abort",n)})}cleanupContent(e,t){this.cleanupTransientContent(e,t),this.recoveryRegistry.cleanup(e)}cleanupTransientContent(e,t,n=!1){let r=t??this.contentNames.get(e),a=r?this.handlers.get(r):void 0;for(let l of a??[])n&&l.onAbort?.(e),l.onContentEnd?.(e);this.abortCleanups.get(e)?.(),this.abortCleanups.delete(e),this.contentNames.delete(e),this.contentToolCallIds.delete(e),this.pendingToolCallAnnotations.delete(e),this.emittedToolCallAnnotationKinds.delete(e),this.completeArgumentContentIndices.delete(e),this.partialBuffers.delete(e),this.abortedContentIndices.delete(e)}cleanupAll(){for(let e of this.handlers.values())for(let t of e)t.onAgentEnd?.();for(let e of this.abortCleanups.values())e();this.abortCleanups.clear(),this.contentNames.clear(),this.contentToolCallIds.clear(),this.pendingToolCallAnnotations.clear(),this.completeArgumentContentIndices.clear(),this.emittedToolCallAnnotationKinds.clear(),this.partialBuffers.clear(),this.streamedBatchEntries.clear(),this.batchEntryIndexes.clear(),this.toolCallBatchEntryIndexes.clear(),this.toolCallRecords.clear(),this.completedBatchEntryIndexes.clear(),this.nextBatchEntryIndex=0,this.abortedContentIndices.clear(),this.pendingAbortReason=void 0,this.dispatchQueues.clear(),this.processedStreamEventKeys.clear(),this.recoveryRegistry.cleanupAll(),this.pendingRecoveryBlocks.length=0,this.recoveryAppliedBatchIndexes.clear()}registerRecovery(e){this.recoveryRegistry.register(e)}unregisterRecovery(e){this.recoveryRegistry.unregister(e)}registerBlockedCallSink(e){this.blockedCallSink=e}register(e){let t=new Set(e.toolNames);for(let[n,r]of this.handlers){let a=r.findIndex(l=>l.name===e.name);a!==-1&&(t.has(n)?(r[a]=e,t.delete(n)):r.splice(a,1))}for(let n of t){let r=this.handlers.get(n)??[];r.push(e),this.handlers.set(n,r)}}unregister(e){for(let[t,n]of this.handlers)this.handlers.set(t,n.filter(r=>r.name!==e))}};function j(o){if(o.type==="toolcall_end")return`${o.type}\0${o.contentIndex}\0${o.toolCall.id}`;if(o.type!=="toolcall_start"&&o.type!=="toolcall_delta")return;let e=o.partial.content[o.contentIndex],t=e?.type==="toolCall"?e.id:"",n=o.type==="toolcall_delta"?o.delta:"";return`${o.type}\0${o.contentIndex}\0${t}\0${n}`}y(j,"toolStreamEventKey");function X(o,e){return o.annotation?.reason?o.annotation.reason:o.annotation?.label?o.annotation.label:o.message.customType==="text-editor-stale-anchor-block"?"Stale Anchor":e.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())||"Blocked"}y(X,"abortReason");function ee(o){try{let e=JSON.parse(o);return f.IsObjectNotArray(e)?e:void 0}catch{return}}y(ee,"parseCompleteArguments");function te(o){let e=o.normalResult;if(!f.IsObjectNotArray(e)||!f.IsObjectNotArray(e.details))return[];let t=e.details.results;if(!Array.isArray(t))return[];let n=f.IsObjectNotArray(o.staleDetails)&&typeof o.staleDetails.path=="string"?o.staleDetails.path:void 0,r=t.filter(f.IsObjectNotArray).map(s=>f.IsObjectNotArray(s.data)?s.data:s),a=n===void 0?r:r.filter(s=>s.path===n),i=(a.length>0?a:r).flatMap(s=>{let d=s.freshAnchors;return Array.isArray(d)?d.filter(u=>typeof u=="string"):[]});return[...new Set(i)]}y(te,"freshAnchorsAfterRecovery");function ne(o,e){let n=o.indexOf(`
|
|
4
4
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{e as j}from"./chunk-PS2B6THP.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};
|
|
@@ -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-QFTBY67N.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 @@
|
|
|
1
|
+
import{e as f,i as p,m}from"./chunk-SQKAXYIR.js";import{a as i}from"./chunk-EI7MMDWY.js";import{Type as r}from"typebox";import{Value as u}from"typebox/value";import{Type as d}from"typebox";var T=d.Object({path:d.Optional(d.String({description:"What to read: a supported resource such as a file or directory path, URL, returned temp: reference, SEARCH# or RESULT# reference, or registered protocol source. Supply a path; an empty call cannot select a source."})),offset:d.Optional(d.Number({description:"For raw: sources, use a zero-based byte offset; negative offsets count from the file end. For other sources: first line to return, numbered from 1. Omit or use 0 to start at line 1; -1 starts at the last line, -10 at the tenth line from the end. For path#anchor, SEARCH or RESULT# selections, count from its containing line instead: 0 or 1 starts there, 2 starts one line later, -1 one line earlier. For image and sequence views, offset is a zero-based row-major grid cell index and requires limit."})),limit:d.Optional(d.Number({description:"For raw: sources, use a non-negative byte count (0 reads no bytes). Otherwise, maximum lines from the selected starting position. Output is bounded; omit for the default read. For image and sequence views, limit is the square grid cell size in pixels; omit offset to select cell 0, or omit both for the bounded full image."})),views:d.Optional(d.Array(d.String(),{description:`Optional source-specific presentations. Combine views when both presentations are needed, for example ["anchors", "ast"]. Omit for the source's default presentation.`}))});import{Type as t}from"typebox";var O=t.Object({value:t.String(),kind:t.String(),state:t.Optional(t.String())},{additionalProperties:!1}),L=t.Object({lineNumber:t.Integer(),content:t.String(),lineEnding:t.String(),anchors:t.Optional(t.Array(t.String()))},{additionalProperties:!1}),k=t.Object({path:t.String(),offset:t.Integer()},{additionalProperties:!1}),y={source:t.String(),truncated:t.Boolean(),continuation:t.Optional(k),fullResult:t.Optional(t.String())},x=t.Object({...y,kind:t.Literal("text"),target:t.Optional(t.String()),lines:t.Array(L),startLine:t.Integer(),endLine:t.Integer(),totalLines:t.Integer(),references:t.Optional(t.Array(O))},{additionalProperties:!1}),b=t.Object({...y,kind:t.Literal("bytes"),bytes:t.Array(t.Integer({minimum:0,maximum:255})),byteOffset:t.Integer(),byteLength:t.Integer(),totalBytes:t.Integer()},{additionalProperties:!1}),C=t.Union([t.Object({type:t.Literal("text"),text:t.String()},{additionalProperties:!1}),t.Object({type:t.Literal("image"),data:t.String(),mimeType:t.String()},{additionalProperties:!1})]),h=t.Object({...y,kind:t.Literal("native"),blocks:t.Array(C)},{additionalProperties:!1}),c=t.Union([t.Object({kind:t.Literal("recovery"),source:t.String(),candidates:t.Array(t.Object({path:t.String()},{additionalProperties:!1}))},{additionalProperties:!1}),x,b,h,t.Object({kind:t.Literal("resources"),source:t.Optional(t.String()),resources:t.Array(t.Union([x,b,h])),truncated:t.Boolean(),fullResult:t.Optional(t.String())},{additionalProperties:!1})]),P=f(c);function w(e){return{lineNumber:e.lineNumber,content:e.content,lineEnding:e.lineEnding,...e.anchors===void 0?{}:{anchors:[...e.anchors]}}}i(w,"publicLine");function S(e){if(e.kind==="resources"){let o=e.resources.map(s=>S(s));return{kind:e.kind,...e.source===void 0?{}:{source:e.source},resources:o,truncated:o.some(s=>typeof s=="object"&&s!==null&&"truncated"in s&&s.truncated===!0)}}if(e.kind==="bytes"){let o=e.bytes.slice(0,32768),s=e.truncated===!0||o.length<e.bytes.length;return{kind:e.kind,source:e.source,bytes:o,byteOffset:e.byteOffset,byteLength:o.length,totalBytes:e.totalBytes,truncated:s,...e.byteOffset+o.length<e.totalBytes?{continuation:{path:e.source,offset:e.byteOffset+o.length}}:{}}}if(e.kind==="native")return{kind:e.kind,source:e.source,truncated:!1,blocks:e.blocks.map(o=>{if(o.type==="text")return{type:o.type,text:o.text};if(o.type==="image")return{type:o.type,data:o.data,mimeType:o.mimeType};throw new TypeError("Custom content requires a structured adapter")})};let n=[],a=0;for(let o of e.lines){let s=w(o);if(a+=Buffer.byteLength(JSON.stringify(s)),n.length>=2e3||a>512*1024)break;n.push(s)}if(n.length===0&&e.lines.length>0)throw new RangeError("Selected line exceeds the structured window; use a raw byte range or a source-specific view");let R=n.length<e.lines.length,g=n.at(-1)?.lineNumber??e.startLine-1;return{kind:e.kind,source:e.source,lines:n,startLine:n[0]?.lineNumber??0,endLine:n.at(-1)?.lineNumber??0,totalLines:e.totalLines,truncated:R,...e.target===void 0?{}:{target:e.target},...e.references===void 0?{}:{references:e.references},...R||g<e.totalLines?{continuation:{path:e.source,offset:g+1}}:{}}}i(S,"publicData");function E(e){let n=e.details.failure;if(e.isError||n!==void 0)return p(e,c,{status:"error",...n?.candidates?.length&&n.source!==void 0?{data:{kind:"recovery",source:n.source,candidates:n.candidates}}:{},errors:[{code:n?.code??"READ_FAILED",message:n?.message??"Read failed",...n?.source===void 0?{}:{source:n.source}}]});try{if(e.script===void 0)throw new TypeError("Read handler must return structured script data");let a=S(e.script);return p(e,c,{status:"success",data:e.details.temporarySource!==void 0&&typeof a=="object"&&a!==null?{...a,fullResult:e.details.temporarySource}:a,errors:[]})}catch(a){return p(e,c,{status:"error",errors:[{code:a instanceof RangeError?"STRUCTURED_RESULT_TOO_LARGE":"STRUCTURED_ADAPTER_REQUIRED",message:a instanceof Error?a.message:String(a)}]})}}i(E,"structuredRead");var l=r.Function([],r.Unknown()),v=r.Object({resolver:r.Unknown(),matchesCall:r.Optional(l),renderCall:r.Optional(l),priority:r.Optional(r.Number()),renderResult:r.Optional(l),preserveTruncatedOutput:r.Optional(r.Boolean())}),D=r.Object({resolver:r.Unknown(),priority:r.Optional(r.Number())}),A=r.Object({id:r.String({pattern:"\\S"}),priority:r.Optional(r.Number()),resolve:l}),N=r.Object({view:r.String({pattern:"\\S"}),includes:r.Optional(r.Array(r.String({pattern:"\\S"}))),presenter:r.Object({id:r.String(),present:l}),priority:r.Optional(r.Number())}),F=r.Object({resolvedBy:r.String({pattern:"\\S"}),contentKind:r.Union([r.Literal("text"),r.Literal("any")])}),U=r.Union([r.Object({stage:r.Literal("pre-read"),handler:l}),r.Object({stage:r.Literal("read"),when:F,handler:l}),r.Object({stage:r.Literal("post-read"),handler:l})]);function W(e){if(!u.Check(D,e))return!1;let n=e,a=n.resolver;return typeof a.id=="string"&&a.id.length>0&&typeof a.tryResolve=="function"&&(!("priority"in n)||typeof n.priority=="number")}i(W,"isTextTargetResolverRegistration");function M(e){if(!u.Check(v,e))return!1;let n=e;return m(n.resolver)?n.resolver.id!=="any"&&(!("priority"in n)||typeof n.priority=="number")&&(!("matchesCall"in n)||typeof n.matchesCall=="function")&&(!("renderCall"in n)||typeof n.renderCall=="function")&&"matchesCall"in n=="renderCall"in n&&(!("renderResult"in n)||typeof n.renderResult=="function"):!1}i(M,"isResourceResolverRegistration");function Q(e){return u.Check(U,e)}i(Q,"isReadHandlerRegistration");function J(e){return u.Check(N,e)}i(J,"isReadViewRegistration");function Y(e){return u.Check(A,e)}i(Y,"isFragmentResolverRegistration");function X(e){return I(e)?e.kind==="not-handled"?!0:e.kind==="failed"?typeof e.message=="string"&&e.message.length>0:e.kind==="resolved"&&typeof e.originLine=="number":!1}i(X,"isReadFragmentResolution");function I(e){return typeof e=="object"&&e!==null}i(I,"isRecord");export{T as a,c as b,P as c,E as d,W as e,M as f,Q as g,J as h,Y as i,X as j};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as k,e as m}from"./chunk-FK42RSF4.js";import{a as b,b as v}from"./chunk-PS2B6THP.js";import{a as s}from"./chunk-EI7MMDWY.js";import h from"node:path";import{pathToFileURL as $}from"node:url";function T(e,n,t,o,i,a=[],l=[]){let c=a.map(r=>({kind:"note",text:r}));c.push(...v(e.flatMap(r=>{let p=h.isAbsolute(r.source),D=p&&i?h.relative(i,r.source)||h.basename(r.source):r.source,z=p?$(r.source).href:/^https?:/iu.test(r.source)?r.source:void 0,R=r.endLineNumber??r.lineNumber;return(R===r.lineNumber?[r.lineText]:[r.lineText,...r.matchedText.split(/\r\n|\n|\r/u).slice(1)]).slice(0,20).map((x,g)=>({source:r.source,label:D,...z===void 0?{}:{link:z},...p?{}:{badge:/^https?:/iu.test(r.source)?"WEB":"SH"},lineNumber:r.lineNumber+g,text:x,ranges:[{from:g?0:r.startColumn,to:r.lineNumber+g===R?r.endColumn:x.length}]}))}))),e.length||c.push({kind:"note",text:"No matches found"}),e.some(r=>(r.endLineNumber??r.lineNumber)-r.lineNumber>=20)&&c.push({kind:"note",text:"\u2026 source preview shortened"}),c.push(...l.map(r=>({kind:"note",text:r,expandedOnly:!0})));let u=`${e.length}${n?"":"+"}`,f=new Set(e.map(r=>r.source)),A=e.every(r=>h.isAbsolute(r.source));return new b({summary:`${u} ${e.length===1?"match":"matches"} in ${f.size} ${A?f.size===1?"file":"files":f.size===1?"source":"sources"}`,rows:c},t,o)}s(T,"renderSearchMatches");function N(e,n){return e.targets.some(t=>t.source===n.source&&t.ranges.some(o=>(o.start.lineNumber<n.lineNumber||o.start.lineNumber===n.lineNumber&&o.start.column<=n.startColumn)&&(o.end.lineNumber>(n.endLineNumber??n.lineNumber)||o.end.lineNumber===(n.endLineNumber??n.lineNumber)&&o.end.column>=n.endColumn)))}s(N,"containsSearchMatch");import{Value as I}from"typebox/value";var d={candidates:5,previewMatches:3,identifiers:2e4,identifierLength:80,vocabularyBytes:8*1024*1024,matchesPerCandidate:200,verificationBytes:4*1024*1024,timeoutMs:2e3};function L(e){return I.Check(k,e)}s(L,"isFuzzyResultData");function y(e){return e.length>=5&&e.length<=d.identifierLength&&/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)&&/[A-Za-z]/u.test(e)}s(y,"isFuzzyQuery");var S=class{static{s(this,"FuzzyVocabulary")}names=new Set;bytes=0;limited=!1;account(n){return this.bytes+=n,this.bytes>d.vocabularyBytes&&(this.limited=!0),!this.limited}add(n){if(!(this.limited||!y(n)||this.names.has(n))){if(this.names.size===d.identifiers){this.limited=!0;return}this.names.add(n)}}addText(n){if(this.account(Buffer.byteLength(n))){for(let t of n.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/gu))if(this.add(t[0]),this.limited)break}}};function C(e){return e.replace(/([A-Z]+)([A-Z][a-z])/gu,"$1 $2").replace(/([a-z0-9])([A-Z])/gu,"$1 $2").split(/[^A-Za-z0-9]+/u).filter(Boolean).map(n=>n.toLowerCase())}s(C,"splitName");function w(e,n){return e.length===n.length&&e.every((t,o)=>t===n[o])}s(w,"same");function M(e,n){if(e.length<5||n.length<5||Math.abs(e.length-n.length)>1||/\d/u.test(e+n))return!1;let t=0;for(;t<Math.min(e.length,n.length)&&e[t]===n[t];)t++;if(e.length===n.length)return e.slice(t+1)===n.slice(t+1)||e[t]===n[t+1]&&e[t+1]===n[t]&&e.slice(t+2)===n.slice(t+2);let o=e.length<n.length?e:n,i=e.length<n.length?n:e;return o.slice(t)===i.slice(t+1)}s(M,"oneTypo");function P(e,n){if(e.join("")===n.join(""))return{kind:"normalized",reason:"same spelling with different case or separators"};let t=e.length<n.length?e:n,o=e.length<n.length?n:e;if(o.length===t.length+1&&t.length>=2&&t.every(l=>l.length>=3)){let l=w(t,o.slice(1)),c=w(t,o.slice(0,-1));if(l||c)return{kind:"component",reason:`${e.length>n.length?"remove":"add"} ${l?"leading":"trailing"} component '${l?o[0]:o.at(-1)}'`}}if(e.length!==n.length)return;let i=e.flatMap((l,c)=>{let u=n[c];return u!==void 0&&l!==u?[{word:l,other:u}]:[]}),a=i[0];if(!(i.length!==1||!a||!M(a.word,a.other)))return{kind:"typo",reason:`one character edit: '${a.word}' \u2192 '${a.other}'`}}s(P,"relation");var F={normalized:0,component:1,typo:2};function E(e,n){if(!y(e))return[];let t=C(e);if(t.length===0)return[];let o=[];for(let i of new Set(n)){if(i===e||!y(i))continue;let a=P(t,C(i));a&&o.push({identifier:i,...a})}return o.sort((i,a)=>F[i.kind]-F[a.kind]||(i.identifier<a.identifier?-1:i.identifier>a.identifier?1:0)).slice(0,d.candidates)}s(E,"rankFuzzyIdentifiers");function _(e,n,t){return{identifier:e.identifier,kind:e.kind,reason:e.reason,matchCount:e.matches.length,fileCount:new Set(e.matches.map(o=>o.source)).size,selection:{...m(e.matches.slice(0,d.previewMatches),e.complete,n,t),truncated:e.matches.length>d.previewMatches}}}s(_,"fuzzyCandidateData");function O(e){let n=e.selection.complete?"":"+",t=e.selection.all?.line??e.selection.matches[0]?.references?.line,o=e.selection.matches[0],i=t??o?.source;return[`Possible name: ${e.identifier} (${e.reason})`,`${e.matchCount}${n} ${e.matchCount===1&&e.selection.complete?"match":"matches"} in ${e.fileCount}${n} ${e.fileCount===1&&e.selection.complete?"file":"files"}`,`Exact alternative: ${JSON.stringify(e.identifier)} (case-sensitive, whole identifier)`,...e.selection.complete?[]:["Capture limit reached; no complete all reference."],...i?[`Read: ${i}${t||!o?"":` \xB7 line ${o.range.startLine}`}`]:[]].join(`
|
|
2
|
+
`)}s(O,"formatFuzzyCandidate");export{T as a,N as b,d as c,L as d,y as e,S as f,E as g,_ as h,O as i};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{a as d}from"./chunk-ZC65Z3CK.js";import{a as s}from"./chunk-EI7MMDWY.js";var f=class i{static{s(this,"FileRange")}start;end;constructor(e,t=e){t.lineNumber<e.lineNumber&&([e,t]=[t,e]),this.start=e,this.end=t}static fromLines(e,t){let r=t??e;return new i({lineNumber:e},{lineNumber:r})}},l=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,t=e?.[0];if(t?.range){let r=t.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 t of this.files)e.add(t.path);for(let t of this.errors)t.path&&e.add(t.path);for(let t of this.warnings)t.file&&e.add(t.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 n=this.errors[0];return n?`Failed: ${n.code??"ERROR"}${n.reason?` \u2014 ${n.reason}`:""}`:"Mutation failed"}if(this.files.length===0&&this.diffs.length===0){let n=this.appliedPaths;return n&&n.length>0?`${n.length} path${n.length===1?"":"s"} affected`:"No changes"}let e=this.createdFiles.length,t=this.overwrittenFiles.length,r=[];if(e>0&&r.push(`Created ${e} ${e===1?"file":"files"}`),t>0&&r.push(`Edited ${t} ${t===1?"file":"files"}`),this.diffs.length>0){let n=0,a=0;for(let o of this.diffs)for(let u of o.split(`
|
|
2
|
+
`))u.startsWith("+")&&!u.startsWith("+++")?n++:u.startsWith("-")&&!u.startsWith("---")&&a++;(n>0||a>0)&&r.push(`+${n}/-${a} lines`)}return r.join(", ")}getFileChange(e){return this.files.find(t=>t.path===e)}getDiffFor(e){let t=g(e);for(let r of this.diffs){let n=r.match(/^---\s+(.+)$/m);if(n&&(g(d(n[1]))===t||n[1]===e))return r}}getErrorsFor(e){return this.errors.filter(t=>t.path===e)}getWarningsFor(e){return this.warnings.filter(t=>t.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 t=e;return t.data&&typeof t.data=="object"?(Object.setPrototypeOf(t,i.prototype),t):new i(t)}return new i}};function g(i){return i.replace(/\\/g,"/").replace(/^a\//,"").replace(/^b\//,"")}s(g,"normalisePath");import{createTwoFilesPatch as p,diffLines as c}from"diff";function D(i,e,t,r=i){return{diff:p(i,r,e,t,"","",{context:3}).replace(/^(?:Index: .*\n)?={3,}\n?/m,"").trimEnd(),stats:m(e,t)}}s(D,"createUnifiedDiff");function m(i,e){let t=0,r=0;for(let n of c(i,e)){let a=h(n.value);n.removed&&(t+=a),n.added&&(r+=a)}return{removed:t,added:r}}s(m,"computeStats");function h(i){if(i.length===0)return 0;let e=i.replaceAll(`\r
|
|
3
|
+
`,`
|
|
4
|
+
`);return e.endsWith(`
|
|
5
|
+
`)?e.slice(0,-1).split(`
|
|
6
|
+
`).length:e.split(`
|
|
7
|
+
`).length}s(h,"countDiffLines");function y(i,e){let t=c(i,e),r=[],n=0;for(let a of t){let o=h(a.value);o!==0&&(a.removed||(a.added&&r.push({start:n+1,end:n+o}),n+=o))}return E(r)}s(y,"computeChangedRanges");function E(i){if(i.length===0)return[];let e=[...i].sort((r,n)=>r.start-n.start),t=[d(e[0])];for(let r=1;r<e.length;r++){let n=d(t.at(-1)),a=d(e[r]);a.start<=n.end+1?n.end=Math.max(n.end,a.end):t.push(a)}return t}s(E,"mergeAdjacentRanges");export{f as a,l as b,D as c,y as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{c as w,h as _}from"./chunk-PS2B6THP.js";import{a as l}from"./chunk-EI7MMDWY.js";import{Container as D,Text as H,truncateToWidth as E,visibleWidth as W}from"@earendil-works/pi-tui";var v="pi-agent-text-editor/tool-call-interception",h=Symbol("pi-agent-tool-call-interception/annotation"),k=Symbol("pi-agent-tool-call-interception/render-argument-patch"),y=Symbol("pi-agent-tool-call-interception/anchor-render-patch");function x(n){if(!C(n))return;let e=n[v];return Y(e)?e:void 0}l(x,"getToolCallInterception");function M(n,e,o){let t={annotation:e,...o!==void 0&&{blocked:{reason:o}}};return C(n)?{...n,[v]:t}:{[v]:t,agentDetails:n??null}}l(M,"withToolCallInterceptionDetails");function Q(n,e){return{...n,details:M(n.details,{kind:"blocked",reason:e},e)}}l(Q,"withBlockedToolResult");function j(n,e){if(n===void 0)return!1;let o=n,t=e,r=Reflect.ownKeys(e);return r.length===Reflect.ownKeys(n).length&&r.every(d=>o[d]===t[d])}l(j,"sameArgumentPatch");function U(n,e){let o={...n,...e},t=b(n),r=b(e);return(t!==void 0||r!==void 0)&&(o[y]={...t,...r}),o}l(U,"mergeArgumentPatches");function O(n){if(n===void 0||!(y in n))return n;let e={...n};return delete e[y],e}l(O,"argumentPatchWithoutAnchorRendering");function b(n){if(n!==void 0)return n[y]}l(b,"anchorRenderPatchFromArguments");var L=class{static{l(this,"ToolCallInterceptionRenderStore")}entries=new Map;annotate=l((e,o)=>{let t=this.entries.get(e);this.entries.set(e,{annotation:o,renderArgumentPatch:t?.renderArgumentPatch,invalidate:t?.invalidate}),t?.invalidate?.()},"annotate");bind(e,o){let t=this.entries.get(e);return this.entries.set(e,{annotation:t?.annotation,renderArgumentPatch:t?.renderArgumentPatch,invalidate:o}),t?.annotation}get(e){return this.entries.get(e)?.annotation}resolveArguments=l((e,o)=>{let t=this.entries.get(e),r=U(t?.renderArgumentPatch,o);j(t?.renderArgumentPatch,r)||(this.entries.set(e,{annotation:t?.annotation,renderArgumentPatch:r,invalidate:t?.invalidate}),t?.invalidate?.())},"resolveArguments");getRenderArgumentPatch(e){return this.entries.get(e)?.renderArgumentPatch}complete(e){this.entries.delete(e)}clear(){this.entries.clear()}},P=class{constructor(e,o,t,r,d,s){this.component=e;this.theme=o;this.state=t;this.annotations=r;this.toolCallId=d;this.backgroundAnsi=s}static{l(this,"AnnotatedToolCall")}get inner(){return this.component}update(e,o,t,r){this.component=e,this.theme=o,this.state=t,this.backgroundAnsi=r}render(e){let o=this.component.render(e),t=this.annotations.get(this.toolCallId)??this.state[h],r;if(t===void 0)r=o;else{let d=F(t,this.theme);if(o.length===0)r=[E(d,e)];else{let s=` \u2190 ${d}`,a=W(s);r=a>=e?[E(s.trimStart(),e,""),...o.slice(1)]:[`${E(o[0]??"",e-a,"")}${s}`,...o.slice(1)]}}return B(r,this.backgroundAnsi)}invalidate(){this.component.invalidate()}},I=class{constructor(e,o){this.component=e;this.backgroundAnsi=o}static{l(this,"EnclosingBackgroundComponent")}get inner(){return this.component}update(e,o){this.component=e,this.backgroundAnsi=o}render(e){return B(this.component.render(e),this.backgroundAnsi)}invalidate(){this.component.invalidate()}};function B(n,e){return e===void 0?[...n]:n.map(o=>_(o,e))}l(B,"preserveBackgroundLines");function V(n,e){let o=n.renderCall,t=n.renderResult,r=n.renderShell!=="self";return{...n,get description(){return n.description},get promptGuidelines(){return n.promptGuidelines},renderCall(d,s,a){let i=a.state,c=e.bind(a.toolCallId,a.invalidate),u=e.getRenderArgumentPatch(a.toolCallId)??i[k],T=b(u),R=O(u);u!==void 0&&(i[k]=u),T!==void 0&&(i[y]=T);let p=R===void 0?d:{...R,...d};c!==void 0&&(i[h]=c);let g=a.lastComponent instanceof P?a.lastComponent:void 0,f;try{f=o?.(p,s,{...a,args:p,lastComponent:g?.inner})??K(n.name,s)}catch{f=K(n.name,s)}let A=r?w(s,a):void 0;return g!==void 0?(g.update(f,s,i,A),g):new P(f,s,i,e,a.toolCallId,A)},renderResult(d,s,a,i){let c=i.state,u=e.getRenderArgumentPatch(i.toolCallId)??c[k],T=b(u),R=O(u);u!==void 0&&(c[k]=u),T!==void 0&&(c[y]=T);let p=i.lastComponent instanceof I?i.lastComponent:void 0,g={...i,...R!==void 0&&{args:{...R,...i.args}},lastComponent:p?.inner??i.lastComponent},f=x(d.details)?.annotation,A=e.get(i.toolCallId)??c[h],N=f??(s.isPartial||i.isError?A:void 0);if(N!==void 0){if(c[h]=N,e.complete(i.toolCallId),t!==void 0){let G={...d,content:[],details:void 0};try{t(G,s,a,g)}catch{return new D}}return new D}e.complete(i.toolCallId),Reflect.deleteProperty(c,h);let m;if(t!==void 0)try{m=t(d,s,a,g)}catch{m=$(d,a,i.isError)}else m=$(d,a,i.isError);if(!r)return m;let S=w(a,i);return p!==void 0?(p.update(m,S),p):new I(m,S)}}}l(V,"withToolCallInterceptionRendering");function K(n,e){return new H(e.fg("toolTitle",e.bold(n)),0,0)}l(K,"fallbackCall");function $(n,e,o){let t=n.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
2
2
|
`);return t.length===0?new D:new H(e.fg(o?"error":"toolOutput",t),0,0)}l($,"fallbackResult");function F(n,e){let o=n.kind==="stale-anchor",t=o?"\u26A0":"\u2298",r=n.label??(o?"Stale Anchor":"Blocked"),d=n.color??(o?"warning":"error"),s=n.reason===void 0?"":`: ${n.reason}`;return e.fg(d,`${t} ${r}${s}`)}l(F,"renderAnnotation");function Y(n){return!C(n)||!q(n.annotation)?!1:n.blocked===void 0||C(n.blocked)&&typeof n.blocked.reason=="string"}l(Y,"isToolCallInterceptionDetails");function q(n){return!C(n)||typeof n.kind!="string"||n.label!==void 0&&typeof n.label!="string"||n.reason!==void 0&&typeof n.reason!="string"||n.color!==void 0&&typeof n.color!="string"?!1:n.kind==="blocked"?typeof n.reason=="string":n.kind==="custom"?typeof n.label=="string"&&typeof n.color=="string":n.kind==="stale-anchor"||n.kind==="aborted"}l(q,"isToolCallAnnotation");function C(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}l(C,"isRecord");export{v as a,y as b,x as c,M as d,Q as e,L as f,V as g,q as h};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as d,e as c}from"./chunk-SQKAXYIR.js";import{a as s}from"./chunk-EI7MMDWY.js";import{Type as t}from"typebox";var y=t.Object({query:t.String({minLength:1,description:"Text to find, a Boolean expression, or a prefixed query described below, such as files:*.ts. Quote text to keep it literal, or use regex:<pattern> for regular-expression matching."}),path:t.Optional({...d,description:"File, directory, URL, or a source-aware Read/Search/Select/mutation result with a live target, RESULT# reference, or array of returned targets. Result scopes search only their exact ranges unless symbols: navigation explicitly follows external references; plain preview text is not a source."}),navigation:t.Optional(t.Literal("references",{description:"Only for symbols: queries. Explicitly follow symbols represented inside path to their references outside that scope. Without navigation, all returned ranges stay inside path."})),include:t.Optional(t.String({description:"Optional include glob for local search"})),exclude:t.Optional(t.String({description:"Optional exclude glob for local search"})),caseSensitive:t.Optional(t.Boolean({description:"Match letter case"})),wholeWord:t.Optional(t.Boolean({description:"Match complete words"})),limit:t.Optional(t.Integer({minimum:1,maximum:1e3,description:"Maximum detailed results returned to the agent (default 50)"}))},{additionalProperties:!1});import{Type as e}from"typebox";var u=e.Object({startLine:e.Integer(),startColumn:e.Integer(),endLine:e.Integer(),endColumn:e.Integer()},{additionalProperties:!1}),m=e.Object({line:e.Optional(e.String()),match:e.Optional(e.String())},{additionalProperties:!1}),p={source:e.String(),target:e.Optional(e.String()),range:u,matchedText:e.Optional(e.String()),textTruncated:e.Optional(e.Boolean()),references:e.Optional(m)},f=e.Object({...p,captures:e.Optional(e.Record(e.String(),e.Array(e.Object(p,{additionalProperties:!1})))),role:e.Optional(e.Union([e.Literal("definition"),e.Literal("reference")])),symbol:e.Optional(e.Object({id:e.String(),name:e.String(),kind:e.String(),source:e.String(),range:u},{additionalProperties:!1}))},{additionalProperties:!1}),g={target:e.Optional(e.String()),kind:e.Literal("matches"),truncated:e.Optional(e.Boolean()),fullResult:e.Optional(e.String()),complete:e.Boolean(),matches:e.Array(f),all:e.Optional(m),notices:e.Optional(e.Array(e.String()))},h=e.Object({status:e.Union([e.Literal("ready"),e.Literal("skipped")]),message:e.Optional(e.String()),candidates:e.Array(e.Object({identifier:e.String(),kind:e.Union([e.Literal("normalized"),e.Literal("component"),e.Literal("typo")]),reason:e.String(),matchCount:e.Integer(),fileCount:e.Integer(),selection:e.Object(g,{additionalProperties:!1})},{additionalProperties:!1}))},{additionalProperties:!1}),O=e.Union([e.Object({...g,fuzzy:e.Optional(h)},{additionalProperties:!1}),e.Object({kind:e.Literal("files"),complete:e.Boolean(),files:e.Array(e.String())},{additionalProperties:!1}),e.Object({kind:e.Literal("custom"),resolverId:e.String(),value:e.Unknown()},{additionalProperties:!1})]),T=c(O);function P(o,l,n,i){return{kind:"matches",...i?.target===void 0?{}:{target:i.target},truncated:o.length>100,complete:l,matches:o.slice(0,100).map((r,a)=>({source:r.source,...i?.matchTargets?.[a]===void 0?{}:{target:i.matchTargets[a]},range:{startLine:r.lineNumber,startColumn:r.startColumn,endLine:r.endLineNumber??r.lineNumber,endColumn:r.endColumn},...Buffer.byteLength(r.matchedText)<=4096?{matchedText:r.matchedText}:{textTruncated:!0},...n===void 0?{}:{references:{line:`SEARCH#${n}:${a+1}:line`,match:`SEARCH#${n}:${a+1}:match`}}})),...l&&n!==void 0?{all:{line:`SEARCH#${n}:all:line`,match:`SEARCH#${n}:all:match`}}:{}}}s(P,"selectionData");export{y as a,h as b,O as c,T as d,P as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as c}from"./chunk-
|
|
1
|
+
import{m as c}from"./chunk-SQKAXYIR.js";import{e as a}from"./chunk-ZPT5D4VP.js";import{a as r}from"./chunk-EI7MMDWY.js";import{Type as e}from"typebox";import{Value as i}from"typebox/value";var n="pi-agent-text-editor",p=23,P="pi-agent-text-editor/position",I="pi-agent-text-editor/search",b=`${n}/core/ready`,S=`${n}/plugin/register`,s=e.Function([],e.Unknown()),d=e.Object({tryResolve:s},{additionalProperties:!0}),l=e.Object({lineNumber:e.Integer({minimum:1}),column:e.Integer({minimum:0})}),T=e.Object({start:l,end:l,linewise:e.Optional(e.Boolean())}),R=e.Object({source:e.String({minLength:1}),ranges:e.Optional(e.Array(T))}),x=e.Union([e.Object({kind:e.Literal("not-handled")},{additionalProperties:!0}),e.Object({kind:e.Literal("resolved"),targets:e.Array(R,{minItems:1})},{additionalProperties:!0}),e.Object({kind:e.Literal("rejected"),rejection:e.Object({code:e.Union([e.Literal("invalid"),e.Literal("stale"),e.Literal("missing"),e.Literal("ambiguous")]),reason:e.String(),contextRange:e.Optional(e.Object({offset:e.Number(),limit:e.Number()}))})},{additionalProperties:!0}),e.Object({kind:e.Literal("failed"),error:e.Unknown()},{additionalProperties:!0})]),g=e.String({pattern:"\\S"}),m=e.Object({resolver:e.Unknown(),priority:e.Optional(e.Number())}),y=e.Object({resolver:e.Unknown(),resources:e.Optional(e.Unknown()),kind:e.String({pattern:"\\S"}),type:e.Union([e.Literal("major"),e.Literal("auxiliary"),e.Literal("constant")]),priority:e.Optional(e.Number())}),v=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p)}),u=e.Object({protocol:e.Literal(n),apiVersion:e.Literal(p),id:e.String(),setup:s}),E=e.Object({plugin:u,accept:s});function k(t){return i.Check(g,t)}r(k,"isTextEditorToolId");function _(t){if(!i.Check(m,t))return!1;let o=t;return c(o.resolver)&&(!("priority"in o)||typeof o.priority=="number")}r(_,"isResourceResolverRegistration");function j(t){if(!i.Check(y,t))return!1;let o=t;return a(o.resolver)&&(!("resources"in o)||i.Check(d,o.resources))&&(!("priority"in o)||typeof o.priority=="number")}r(j,"isTextAnchorResolverRegistration");function C(t){return i.Check(x,t)}r(C,"isTextAnchorResourceResolutionAttempt");function L(t){return i.Check(v,t)}r(L,"isTextEditorCoreReady");function w(t){return i.Check(u,t)}r(w,"isTextEditorPlugin");function N(t){return i.Check(E,t)}r(N,"isTextEditorPluginRegistrationRequest");export{n as a,p as b,P as c,I as d,b as e,S as f,k as g,_ as h,j as i,C as j,L as k,w as l,N as m};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{d as R}from"./chunk-3JO7QFIL.js";import{a as S}from"./chunk-PS2B6THP.js";import{t as p,u as y}from"./chunk-ZPT5D4VP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{keyText as C}from"@earendil-works/pi-coding-agent";import{Text as D}from"@earendil-works/pi-tui";function x(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(x,"sourceText");function w(e,r){let{files:o,...t}=e,s=x(r);return{...t,storedFiles:o.map(({lines:l,...a})=>({...a,lines:l.map(n=>{let i=[n.lineNumber,p(n.text,s),n.ranges];return n.logicalMatchIds===void 0?i:[...i,n.logicalMatchIds]})}))}}c(w,"compactSearchDetails");function g(e,r){if("files"in e)return e;let{storedFiles:o,...t}=e,s=x(r);return{...t,files:o.map(({lines:l,...a})=>({...a,lines:l.map(([n,i,h,u])=>({lineNumber:n,text:y(i,s),ranges:h,matchCount:h.length,...u===void 0?{}:{logicalMatchIds:u}}))}))}}c(g,"restoreSearchDetails");var k=new WeakMap,z=12;function v(e,r,o,t){if(typeof e.details=="object"){let a=k.get(e.details);a===void 0&&(a=g(e.details,e.content.flatMap(n=>n.type==="text"?[n.text]:[]).join(`
|
|
2
|
+
`)),k.set(e.details,a)),e={...e,details:a}}if(r.isPartial||t.isError||!R(e.details)){let a=e.content[0],n=a?.type==="text"?a.text:"",i=t.isError?"error":r.isPartial?"dim":"toolOutput";return new D(o.fg(i,n),0,0)}let l=(t.lastComponent instanceof f?t.lastComponent:void 0)??new f(e.details,o,r.expanded);return l.updateSearch(e.details,o,r.expanded),l}c(v,"renderSearchResult");var f=class extends S{static{c(this,"SearchResultPanel")}constructor(r,o,t){super(T(r,t),o,t)}updateSearch(r,o,t){super.update(T(r,t),o,t)}};function T(e,r){let o=$(e,r).map(t=>t.kind==="file"?{kind:"source",label:t.file.path,link:t.file.link,count:t.file.matchCount}:t.kind==="line"?{kind:"line",...t.line}:t.kind==="candidate"?{kind:"note",text:t.identifier}:t.kind==="summary"?{kind:"note",text:t.text}:t.kind==="omitted"?{kind:"note",text:`\u2026 ${t.matches} more ${d(t.matches,"match","matches")} \xB7 ${C("app.tools.expand")} to expand`}:{kind:"note",text:"No matches found"});return{summary:P(e),rows:o}}c(T,"searchModel");function $(e,r){let o=e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0,t=e.files.length===0?o?[]:[{kind:"empty"}]:e.files.flatMap(n=>[{kind:"file",file:n},...n.uniqueLineCount===void 0?n.lines.map(i=>({kind:"line",file:n,line:i})):[{kind:"summary",text:`${String(n.uniqueLineCount)} unique line texts \xB7 search this path with a narrower query`},...(n.groups??[]).map(i=>({kind:"summary",text:`\xD7${String(i.matchCount)} ${i.text}`}))]]);if(e.fuzzy!==void 0&&(e.fuzzy.status==="skipped"?t.push({kind:"summary",text:"Fuzzy search unavailable"}):e.fuzzy.candidates.length>0&&t.push(...e.fuzzy.candidates.flatMap(n=>{let i=e.fuzzyPresentation?.groups.find(u=>u.identifier===n.identifier)?.files??[],h=i.reduce((u,m)=>u+m.matchCount,0);return[{kind:"candidate",identifier:n.identifier},...i.length===0?[]:[{kind:"summary",text:`Shown ${String(h)} of ${String(n.matchCount)}${n.selection.complete?"":"+"}`},...i.flatMap(u=>[{kind:"file",file:u},...u.lines.map(m=>({kind:"line",file:u,line:m}))])]]}))),e.fuzzy!==void 0||r||t.length<=z)return t;let s=t.slice(0,z-1);for(;s.at(-1)?.kind==="file";)s.pop();let l=new Set(s.flatMap(n=>n.kind==="line"?n.line.logicalMatchIds??[]:[])),a=l.size>0?l.size:s.reduce((n,i)=>n+(i.kind==="line"?i.line.matchCount:0),0);return[...s,{kind:"omitted",matches:Math.max(0,e.matchCount-a)}]}c($,"searchViewport");function P(e){if(e.matchCount===0&&e.fuzzy?.status==="ready"&&e.fuzzy.candidates.length>0&&e.fuzzyPresentation!==void 0){let o=e.fuzzy.candidates.reduce((l,a)=>l+a.matchCount,0),t=e.fuzzy.candidates.every(l=>l.selection.complete)?"":"+",s=e.fuzzyPresentation.fileCount;return`0 exact \xB7 ${String(o)}${t} fuzzy ${d(o,"match","matches")} \xB7 ${String(s)}${t} ${d(s,"file","files")}`}return e.matchCount===0?e.complete?"No matches":"No matches \xB7 incomplete":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${d(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${d(e.fileCount,"file","files")}`}c(P,"searchSummary");function d(e,r,o){return e===1?r:o}c(d,"plural");export{w as a,v as b,f as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{e as E,f as b}from"./chunk-T7I2VX3J.js";import{d as M}from"./chunk-
|
|
1
|
+
import{e as E,f as b}from"./chunk-T7I2VX3J.js";import{d as M}from"./chunk-KR36BT5E.js";import"./chunk-FXNKMNSJ.js";import"./chunk-NNCZYO4Q.js";import{d as q}from"./chunk-64M3SQPG.js";import{a as T}from"./chunk-6CZO43OH.js";import{a as N,b as O}from"./chunk-OBNING2A.js";import"./chunk-PS2B6THP.js";import"./chunk-SQKAXYIR.js";import{e as h,f as w,g as P,h as k,i as y,l as I}from"./chunk-KVHDMIZS.js";import"./chunk-ZPT5D4VP.js";import{a as A}from"./chunk-QDLTO5PH.js";import{a as v,b as C}from"./chunk-QIK2E64R.js";import"./chunk-KINKBPPX.js";import"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import H from"node:path";var S="diagnostics",L=q({kind:"code-view",label:"Diagnostics"});async function V(r){b(r,[await E({id:"diagnostics",description:"Diagnostic resources, readiness, and verification",triggers:[{tool:"read",resourcePrefixes:["diagnostics:"]}]})]);let n,t=l((c,f,e)=>{if(n===void 0)throw new Error("IDE diagnostics are not connected");return n(c,{cwd:f,...e})},"collect"),i={protocol:v,apiVersion:4,id:"diagnostics",setup(c){n=c.readDiagnostics}},o=new WeakMap,s=new WeakMap,a=new WeakMap,u=new WeakMap,W={protocol:N,apiVersion:O,id:"diagnostics",setup(c){c.addResolver({resolver:j(t,s),renderResult:L});let f=I();c.addView({view:"diagnostics",priority:100,presenter:B(t,u)}),c.addHandler({stage:"read",when:{resolvedBy:"any",contentKind:"text"},handler(e){if(e.state?.resolvedBy==="diagnostics"){let p=e.state.content[0],g=s.get(p);return g&&o.set(e.request,g),f(e)}return e.state?.contentKind==="text"&&e.request.views?.includes("diagnostics")&&a.set(e.request,e.state.text),{kind:"continue",context:e}}}),c.addHandler({stage:"post-read",handler(e){let p=o.get(e.request);if(p&&e.result)return{kind:"continue",context:e,transform:l(d=>({...d,details:{...d.details,diagnosticCheck:p}}),"transform")};let g=a.get(e.request),m=g&&u.get(g),D=e.result,_=D?.content[0];return!m||!D||_?.type!=="text"?{kind:"continue",context:e}:{kind:"continue",context:e,transform(d){let R=d.content[0];return R?.type!=="text"?d:{...d,content:[{...R,text:`${m}
|
|
2
2
|
${R.text}`},...d.content.slice(1)]}}}}}),c.describe('diagnostics:<path> \u2014 lint and language-server diagnostics. views: ["diagnostics"] \u2014 diagnostics alongside source text. Results identify their reporting tool and readiness; pending results and snapshots are not completed checks.')}};await Promise.all([A(r,i),T(r,W)])}l(V,"registerDiagnostics");function j(r,n){return{id:"diagnostics",tryResolve(t,i){return Promise.resolve(x(t,i.cwd,r,n,{signal:i.signal,...i.audience==="script"&&{mode:"complete"}}))}}}l(j,"createDiagnosticResolver");function x(r,n,t,i,o){let s;try{s=h(r,S,n)}catch(a){return{kind:"failed",error:a}}return s===void 0?{kind:"not-handled"}:{kind:"resolved",resource:{source:w(S,s),async read(){let a=await t(s,n,o),u=P(s,a.content,a.results);return i.set(u,u.diagnosticCheck),[u]}}}}l(x,"resolveDiagnosticSource");function B(r,n){return{id:"diagnostics",async present(t,i){if(i.purpose!=="read"||!H.isAbsolute(t.source))return t;let o=i.audience==="script"&&!i.requestedViews?.includes("diagnostics");if(o&&M(t.source))return t;let s=await r(t.source,i.cwd,{signal:i.signal,...i.audience==="script"&&{mode:o?"snapshot":"complete"}}).catch(a=>{if(i.signal?.throwIfAborted(),!o)throw a});if(s===void 0||o&&s.content!==t.content)return t;if(s.content!==t.content)throw new Error("File changed during diagnostic read; read it again for current source lines.");return n.set(t,y(s.results)),k(t,s.results)}}}l(B,"createDiagnosticPresenter");export{V as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as x,e as y,k as E}from"./chunk-
|
|
1
|
+
import{a as x,e as y,k as E}from"./chunk-FXNKMNSJ.js";import{a as g,c as m}from"./chunk-SQKAXYIR.js";import{a as o}from"./chunk-EI7MMDWY.js";import{AsyncLocalStorage as T}from"node:async_hooks";var u=new T,f=new T;function S(t){let e=f.getStore();e?e.push(t):t()}o(S,"afterPostEditScope");async function R(t){if(f.getStore())return t();let e=[];try{return await f.run(e,t)}finally{for(let r of e)r()}}o(R,"collectPostEditNotifications");function A(t,e){let r=u.getStore();return r?(r.set(t,e),!0):!1}o(A,"deferPostEdit");function v(t){return u.getStore()?.has(t)??!1}o(v,"hasDeferredPostEdit");function H(t){u.getStore()?.delete(t)}o(H,"forgetDeferredPostEdit");function j(t=process.cwd()){let e=new Map;return{run(r){return u.run(e,r)},forget(r){e.delete(r)},sources(){return[...e.keys()]},async finish(r){let c=[...e];e.clear();let a=[],i=[];if(await R(async()=>{let s=new g,P=await Promise.allSettled(c.map(([d,p])=>s.run(m(d,t,"write"),p)));for(let d of P){if(d.status==="rejected"){i.push(d.reason);continue}a.push(d.value);try{r?.(d.value)}catch(p){i.push(p)}}}),i.length>0)throw new AggregateError(i,`Some final post-processing failed; completed edits remain applied. ${i.map(s=>s instanceof Error?s.message:String(s)).join("; ")}`);return a}}}o(j,"createPostEditScope");import{Type as n}from"typebox";import{Value as l}from"typebox/value";var b=`${x}/post-edit/register`;function L(t){return l.Check(n.Object({formatting:n.Object({status:n.Union(["disabled","unavailable","skipped-syntax","unchanged","changed","failed","not-reported","deferred"].map(e=>n.Literal(e))),formatter:n.Optional(n.String())})}),t)}o(L,"isFormattingContribution");function z(t){return l.Check(n.Object({diffStatuses:n.Array(n.Object({text:n.String({minLength:1}),formatter:n.Optional(n.String()),tone:n.Optional(n.Union(["muted","success","warning","error"].map(e=>n.Literal(e))))}))}),t)}o(z,"isDiffStatusContribution");var h=n.Function([],n.Unknown()),w=n.Object({id:n.String({minLength:1}),handler:h}),k=n.Object({registration:w,accept:h});function C(t){return l.Check(w,t)}o(C,"isTextPostEditHandlerRegistration");function N(t){return l.Check(k,t)}o(N,"isTextPostEditHandlerRegistrationRequest");function U(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.hints)&&typeof e.scopeMarkers=="object"&&e.scopeMarkers!==null&&Array.isArray(e.warnings)}o(U,"isTextMutationResultContributionData");function V(t,e){if(!C(e))throw new TypeError("Invalid text editor post-edit handler registration");let r,c=o(()=>{let i={registration:e,accept(s){if(r!==void 0)throw new Error(`Post-edit handler ${e.id} was accepted more than once`);r=s}};return t.events.emit(b,i),r!==void 0},"announce"),a=o(()=>{},"unsubscribeReady");a=t.events.on(y,i=>{if(!E(i))throw new Error("Invalid pi-agent-text-editor core readiness event");if(!c())throw new Error("pi-agent-text-editor core announced readiness without accepting the post-edit handler");a()}),t.on("session_shutdown",()=>{a(),r?.()}),c()&&a()}o(V,"connectTextEditorPostEditHandler");export{S as a,R as b,A as c,v as d,H as e,j as f,b as g,L as h,z as i,C as j,N as k,U as l,V as m};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as z}from"./chunk-M5IVSCR2.js";import{e as V,f as q}from"./chunk-T7I2VX3J.js";import{a as O}from"./chunk-6CZO43OH.js";import{a as k,b as T}from"./chunk-OBNING2A.js";import{a as _}from"./chunk-ZTYWHL2F.js";import{a as L,b as W}from"./chunk-7UGNGK7Y.js";import{a as U}from"./chunk-PS2B6THP.js";import{a as c}from"./chunk-EI7MMDWY.js";import{execFile as te}from"node:child_process";import re from"node:os";import{promisify as oe}from"node:util";import{createCanvas as B,loadImage as se}from"@napi-rs/canvas";var w=oe(te),I=20*1024*1024,H={durationSeconds:2,intervalSeconds:.5,scale:.5},j=new Set;function G(e){let n=R({mode:"sequence",durationSeconds:Number(e.durationSeconds??2),intervalSeconds:Number(e.intervalSeconds??.5),scale:Number(e.scale??.5)});H={durationSeconds:n.durationSeconds,intervalSeconds:n.intervalSeconds,scale:n.scale},j=new Set((e.allowedExecutables??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))}c(G,"configureVision");function y(){return H}c(y,"getVisionDefaults");function J(e){let n=e.includes("\\")?e.slice(e.lastIndexOf("\\")+1):e,r=n.trim().split(/\s+/u)[0]??"",t=r.slice(r.lastIndexOf("/")+1);return j.has((e.includes("\\")?n:t).toLowerCase())}c(J,"isExecutableAllowed");function X(e,n){let r=e?.filter(s=>/^(?:image|sequence)(?::|$)/u.test(s))??[];if(r.length===0)return;if(r.length>1)throw new Error("Use only one image or sequence view");let t=r[0],i=t.indexOf(":"),a=t.slice(0,i<0?void 0:i),o={};if(i>=0&&ie(t.slice(i+1),o),a==="image"&&(o.duration!==void 0||o.interval!==void 0))throw new Error("duration and interval are supported only by the sequence view");return R({mode:a,durationSeconds:o.duration??n.durationSeconds,intervalSeconds:o.interval??n.intervalSeconds,scale:o.scale??n.scale,...o.region===void 0?{}:{region:o.region}})}c(X,"parseVisionView");function ie(e,n){if(e.length===0)throw new Error("View parameters cannot be empty");let r=e.split(",");for(let t=0;t<r.length;t+=1){let i=r[t],a=i.indexOf("=");if(a<=0)throw new Error(`Invalid view parameter ${i}`);let o=i.slice(0,a),s=i.slice(a+1);if(o==="region"){let u=[s,r[t+1],r[t+2],r[t+3]].map(Number);if(u.some(m=>!Number.isFinite(m)))throw new Error("region requires x,y,width,height values");n.region={x:u[0],y:u[1],width:u[2],height:u[3]},t+=3;continue}if(o!=="duration"&&o!=="interval"&&o!=="scale")throw new Error(`Unknown view parameter ${o}`);let d=Number(s);if(!Number.isFinite(d))throw new Error(`View parameter ${o} must be a number`);if(n[o]!==void 0)throw new Error(`Duplicate view parameter ${o}`);n[o]=d}}c(ie,"parseViewParameters");function Y(e){if(!e.startsWith("display:"))return;if(e==="display:")return 0;let n=/^display:#(\d+)$/u.exec(e);if(n===null)throw new Error("Display sources use display: or display:#N with a zero-based index");let r=Number(n[1]);if(!Number.isSafeInteger(r))throw new Error("Display sources use display: or display:#N with a zero-based index");return r}c(Y,"parseDisplaySource");async function E(e){let n=new Map(e.list().flatMap(i=>i.pid===void 0?[]:[[i.pid,i]]));if(process.platform!=="linux"&&process.platform!=="darwin")return[...n].map(([i,a])=>({pid:i,command:a.description,owned:!0,source:a.source,host:"local"}));let{stdout:r}=await w("ps",["-eo","pid=,ppid=,lstart=,args="],{maxBuffer:4*1024*1024}),t=r.split(`
|
|
2
|
+
`).flatMap(i=>{let a=/^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.*)$/u.exec(i);if(a===null)return[];let o=Number(a[1]),s=n.get(o);return[{pid:o,parentPid:Number(a[2]),started:a[3],command:a[4]??"",owned:s!==void 0,host:"local",...s===void 0?{}:{source:s.source}}]});return S()?[...t,...await ae()]:t}c(E,"listProcesses");async function ae(){try{let{stdout:e}=await w("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command","Get-Process | Select-Object Id,ProcessName,Path,StartTime | ConvertTo-Json -Compress"],{maxBuffer:4194304}),n=JSON.parse(e);return(Array.isArray(n)?n:[n]).flatMap(t=>{if(typeof t!="object"||t===null||!("Id"in t)||typeof t.Id!="number")return[];let i="ProcessName"in t&&typeof t.ProcessName=="string"?t.ProcessName:"Windows process",a="Path"in t&&typeof t.Path=="string"?t.Path:void 0,o="StartTime"in t&&typeof t.StartTime=="string"?t.StartTime:void 0;return[{pid:t.Id,command:a??i,owned:!1,host:"windows",...o===void 0?{}:{started:o}}]})}catch{return[]}}c(ae,"listWindowsProcesses");async function A(e,n){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Process PID must be a positive integer");let r=(await E(n)).find(t=>t.pid===e);if(r===void 0)throw new Error(`Process ${e} is not running`);return r}c(A,"readProcess");function R(e){let n=e.scale??1;if(!(n>0&&n<=1))throw new Error("Image scale must be greater than 0 and at most 1");let r=e.durationSeconds??0,t=e.intervalSeconds??1;if(e.mode==="sequence"){if(!(r>0&&r<=10))throw new Error("Sequence duration must be greater than 0 and at most 10 seconds");if(!(t>0))throw new Error("Sequence interval must be greater than 0 seconds");if(Math.floor(r/t)+1>20)throw new Error("Sequence capture is limited to 20 frames")}if(e.region!==void 0){let{x:i,y:a,width:o,height:s}=e.region;if(i<0||a<0||o<=0||s<=0||i+o>1||a+s>1)throw new Error("Image region x,y,width,height must fit within normalized bounds 0..1")}if(e.cellIndex!==void 0&&e.cellSize===void 0)throw new Error("Image offset requires limit to set the square grid cell size");if(e.cellSize!==void 0&&(!Number.isSafeInteger(e.cellSize)||e.cellSize<=0))throw new Error("Image limit must be a positive integer pixel size");if(e.cellIndex!==void 0&&(!Number.isSafeInteger(e.cellIndex)||e.cellIndex<0))throw new Error("Image offset must be a zero-based cell index");return e}c(R,"validateVisionOptions");async function b(e,n,r){let t=R(n),i=t.mode==="image"?1:Math.floor(t.durationSeconds/t.intervalSeconds)+1,a=[],o=0;for(let s=0;s<i;s+=1){r?.throwIfAborted(),s>0&&await pe(t.intervalSeconds*1e3,r);let d=await e();if(o+=d.byteLength,o>I)throw new Error("Captured images exceed the 20MB aggregate limit");for(let u of await ce(d,t))a.push({type:"image",data:Buffer.from(u).toString("base64"),mimeType:"image/png"})}return a}c(b,"captureImages");async function ce(e,n){let r=await se(e),t=n.region??{x:0,y:0,width:1,height:1},i=Math.round(t.x*r.width),a=Math.round(t.y*r.height),o=Math.max(1,Math.round(t.width*r.width)),s=Math.max(1,Math.round(t.height*r.height)),d=n.scale??1,u=Math.max(1,Math.round(o*d)),m=Math.max(1,Math.round(s*d)),f=B(u,m);if(f.getContext("2d").drawImage(r,i,a,o,s,0,0,u,m),n.cellSize===void 0)return[await f.encode("png")];let l=Math.ceil(u/n.cellSize),p=Math.ceil(m/n.cellSize),h=n.cellIndex??0;if(h>=l*p)throw new Error(`Image cell offset ${h} exceeds the ${l}x${p} grid`);let ee=h%l,ne=Math.floor(h/l),C=ee*n.cellSize,M=ne*n.cellSize,P=Math.min(n.cellSize,u-C),x=Math.min(n.cellSize,m-M),$=B(P,x);return $.getContext("2d").drawImage(f,C,M,P,x,0,0,P,x),[await $.encode("png")]}c(ce,"selectImage");function de(e,n){return e&&n==="windows"}c(de,"usesWindowsHostWindowCapture");function K(){return{async captureWindow(e,n,r){if(r?.throwIfAborted(),de(S(),n))return ue(e,r);if(process.platform!=="linux"&&process.platform!=="darwin")throw new Error(`Window capture is unsupported on ${process.platform}`);let{Window:t}=await import("node-screenshots"),i;try{i=t.all()}catch(s){throw new Error(`Desktop window enumeration is unavailable: ${F(s)}`,{cause:s})}let a=i.find(s=>{try{return s.pid()===e}catch{return!1}});if(a===void 0)throw new Error(`No capturable desktop window belongs to PID ${e}`);let o=await a.captureImage();return r?.throwIfAborted(),new Uint8Array(await o.toPng())},async captureDisplay(e,n){if(n?.throwIfAborted(),S())return le(e,n);if(process.platform!=="linux"&&process.platform!=="darwin"&&process.platform!=="win32")throw new Error(`Display capture is unsupported on ${process.platform}`);let{Monitor:r}=await import("node-screenshots"),t;try{t=r.all()}catch(o){throw new Error(`Desktop display enumeration is unavailable: ${F(o)}`,{cause:o})}let i=t[e];if(i===void 0)throw new Error(`Display index ${e} is unavailable; found ${t.length} display(s)`);let a=await i.captureImage();return n?.throwIfAborted(),new Uint8Array(await a.toPng())},async captureUrl(e,n){if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error("Web screenshots require an HTTP(S) URL");let{chromium:r}=await import("playwright-core"),t=await me(),i=await r.launch({executablePath:t,headless:!0,chromiumSandbox:!1,timeout:3e4}),a=c(()=>{i.close()},"abort");n?.addEventListener("abort",a,{once:!0});try{let o=await i.newPage({viewport:{width:1280,height:720}});return await o.goto(e.href,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle",{timeout:1500}).catch(()=>{}),n?.throwIfAborted(),new Uint8Array(await o.screenshot({type:"png",fullPage:!0}))}finally{n?.removeEventListener("abort",a),await i.close().catch(()=>{})}}}}c(K,"createCaptureBackend");async function ue(e,n){let r=new URL("windows-window-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await w("wslpath",["-w",r.pathname],{signal:n}),{stdout:i}=await w("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-ProcessId",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(i)}c(ue,"captureWslWindow");async function le(e,n){let r=new URL("windows-display-capture.ps1",new URL("../src/plugins/pi-agent-ide-vision/src/vision.ts",import.meta.url).href);n?.throwIfAborted();let{stdout:t}=await w("wslpath",["-w",r.pathname],{signal:n}),{stdout:i}=await w("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",t.trim(),"-DisplayIndex",String(e)],{encoding:"buffer",maxBuffer:I,signal:n});return new Uint8Array(i)}c(le,"captureWslDisplay");function S(){return process.platform==="linux"&&(process.env.WSL_DISTRO_NAME!==void 0||re.release().toLowerCase().includes("microsoft"))}c(S,"isWsl");async function me(){let e=process.env.PI_AGENT_IDE_BROWSER_PATH;if(e!==void 0)return e;let{stdout:n}=await w("bash",["-lc","command -v google-chrome-stable || command -v google-chrome || command -v chromium || command -v chromium-browser"]),r=n.trim();if(r.length===0)throw new Error("No Chrome or Chromium executable was found; set PI_AGENT_IDE_BROWSER_PATH");return r}c(me,"resolveBrowser");function pe(e,n){return new Promise((r,t)=>{let i=setTimeout(r,e),a=c(()=>{clearTimeout(i),t(n?.reason??new Error("Capture aborted"))},"abort");n?.addEventListener("abort",a,{once:!0}),i.unref()})}c(pe,"delay");function F(e){return e instanceof Error?e.message:String(e)}c(F,"errorMessage");async function fe(e,n){q(e,[await V({id:"vision",description:"Window, display, image, and sequence capture",triggers:[{tool:"read",resourcePrefixes:["window:","display:"]}]})]);let r=n?.preferences??{};G({durationSeconds:r["vision.sequenceDurationSeconds"],intervalSeconds:r["vision.sequenceIntervalSeconds"],scale:r["vision.imageScale"],allowedExecutables:r["vision.allowedExecutables"]});let t=z(e),i=K();await Promise.all([O(e,{protocol:k,apiVersion:T,id:"vision",setup(a){for(let s of["image","sequence"])a.addView({view:s,presenter:{id:`vision-${s}`,present:c(d=>d,"present")}});a.addHandler({stage:"pre-read",async handler(s){let d=s.request.path;if(d===void 0)return{kind:"continue",context:s};let u=Y(d);if(u!==void 0){if(e.getFlag("pi-agent-ide-vision-displays")!==!0)return g(d,"Display capture is disabled. Enable --pi-agent-ide-vision-displays to allow it.");try{let l=await b(()=>i.captureDisplay(u,s.resolverContext.signal),D(s.request),s.resolverContext.signal);return v(d,l)}catch(l){return g(d,N(l))}}let m=Q(d,"process:");if(m!==void 0){let l=await A(m,t);return v(d,[{type:"text",text:Z(l)}])}let f=Q(d,"window:");if(f!==void 0){let l=await A(f,t);if(!l.owned&&!J(l.command)&&e.getFlag("pi-agent-ide-vision-arbitrary-windows")!==!0)return g(d,`Window capture for PID ${f} is denied because the process is neither Agent IDE-owned nor allowlisted by executable name. Enable --pi-agent-ide-vision-arbitrary-windows to allow it.`);try{let p=await b(()=>i.captureWindow(f,l.host,s.resolverContext.signal),D(s.request),s.resolverContext.signal);return v(d,p)}catch(p){return g(d,N(p))}}if(/^https?:\/\//iu.test(d)&&we(s.request)){let l=new URL(d);try{let p=await b(()=>i.captureUrl(l,s.resolverContext.signal),D(s.request),s.resolverContext.signal);return v(l.href,p)}catch(p){return g(l.href,N(p))}}return{kind:"continue",context:s}}});let o=y();a.describe(`Process metadata: process:PID. Visual capture: window:PID and display: or display:#N. HTTP(S) sources accept image and sequence screenshots. Use named view parameters such as sequence:duration=2,interval=0.5,scale=0.5 and image:scale=0.5,region=0.25,0.25,0.5,0.5. Duration is limited to 10 seconds and sequences to 20 frames. Defaults: duration=${o.durationSeconds}, interval=${o.intervalSeconds}, scale=${o.scale}. Region uses normalized x,y,width,height and runs before scaling. For captures, limit is a square grid cell size in output pixels and offset is one zero-based row-major cell index; limit without offset selects cell 0, while offset without limit is invalid. Omit both for the bounded transformed image.`)}}),_(e,{protocol:L,apiVersion:W,id:"vision-processes",setup(a){a.addResolver({priority:-100,resolver:{id:"processes",readResources:c(o=>/^process:/iu.test(o.query)?void 0:[],"readResources"),toScriptData(o){return{kind:"custom",resolverId:"processes",value:{processes:o.map(d=>({pid:d.pid,command:d.command}))}}},async tryResolve(o){let s=/^process:(.*)$/isu.exec(o.query);if(s===null)return{kind:"not-handled"};let d=(s[1]??"").trim().toLowerCase();return{kind:"resolved",payload:(await E(t)).filter(m=>d.length===0||String(m.pid)===d||m.command.toLowerCase().includes(d)).slice(0,Math.min(o.limit??50,100))}},renderResult(o,s,d){let u=o.details;return new U({summary:`${u.processes.length} processes shown`,rows:u.processes.length?u.processes.map(m=>({kind:"note",text:`${m.pid} ${m.command}`})):[{kind:"note",text:"No matching processes"}]},d,s.expanded)},format(o){let s=o;return{content:[{type:"text",text:s.length===0?"No matching processes.":s.map(Z).join(`
|
|
3
|
+
|
|
4
|
+
`)}],details:{count:s.length,processes:s}}}}}),a.describe("process:<query> finds running processes by PID or command for process:PID metadata reads and guarded window:PID capture.")}})])}c(fe,"registerVision");function Q(e,n){if(!e.startsWith(n))return;let r=e.slice(n.length);if(!/^\d+$/u.test(r))throw new Error(`${n} sources require a numeric PID`);return Number(r)}c(Q,"prefixedPid");function D(e){return{...X(e.views,y())??{mode:"image",...y()},...e.limit===void 0?{}:{cellSize:e.limit},...e.offset===void 0?{}:{cellIndex:e.offset}}}c(D,"options");function we(e){return e.views?.some(n=>/^(?:image|sequence)(?::|$)/u.test(n))===!0}c(we,"requestsScreenshot");function v(e,n){return{kind:"return",result:{content:n,script:{kind:"native",source:e,blocks:n},details:{source:e,resolvedBy:"vision"}}}}c(v,"returned");function g(e,n){return{kind:"return",result:{content:[{type:"text",text:n}],details:{source:e,resolvedBy:"vision",failure:{code:"READ_FAILED",source:e,resolverId:"vision",message:n}},isError:!0}}}c(g,"failed");function N(e){return e instanceof Error?e.message:String(e)}c(N,"errorMessage");function Z(e){return[`PID: ${e.pid}`,`Command: ${e.command}`,`Owned by Agent IDE: ${e.owned?"yes":"no"}`,...e.parentPid===void 0?[]:[`Parent PID: ${e.parentPid}`],...e.started===void 0?[]:[`Started: ${e.started}`],...e.source===void 0?[]:[`Agent IDE source: ${e.source}`]].join(`
|
|
5
|
+
`)}c(Z,"formatProcess");export{fe as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as U}from"./chunk-PLKYHUNT.js";import{m as T}from"./chunk-ZPT5D4VP.js";import{a as x}from"./chunk-ZC65Z3CK.js";import{a as l}from"./chunk-EI7MMDWY.js";import{createHash as ke}from"node:crypto";import{open as Ce,readFile as oe}from"node:fs/promises";import f from"node:path";import{spawn as me}from"node:child_process";import{stat as pe}from"node:fs/promises";import C from"node:path";import{createInterface as ge}from"node:readline";import{existsSync as le}from"node:fs";import ue from"node:os";import K from"node:path";function V(e=process.env.PI_CODING_AGENT_DIR??K.join(ue.homedir(),".pi","agent"),t=process.platform){let r=K.join(e,"bin",t==="win32"?"rg.exe":"rg");return le(r)?r:"rg"}l(V,"resolveRipgrepExecutable");function O(e,t=!1){let r=P(e);return B(r)?F(E(new M(e,r).parse(),t)):t?e:D(e)}l(O,"compileSearchQuery");function _(e,t=!1){let r=P(e);return B(r)?E(new M(e,r).parse(),t):void 0}l(_,"compileSearchCondition");function k(e,t){if(e.kind==="term")return t(e.value);let r=k(e.left,t);if(e.kind==="or")return r||k(e.right,t);let n=k(e.right,t);return r&&(e.kind==="not"?!n:n)}l(k,"satisfiesSearchCondition");function Y(e){if(B(P(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map(D).join("|")})`:void 0}l(Y,"compileSearchFallbackQuery");function B(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}l(B,"containsBooleanSyntax");var M=class{static{l(this,"BooleanQueryParser")}#t;#n;#i=0;constructor(t,r){this.#t=t,this.#n=r}parse(){let t=this.#s(),r=this.#e();if(r.type!=="end"){let n=r.type==="right"?"unexpected ')'.":`unexpected ${fe(r)}.`;throw w(r.offset,n)}return t}#s(){let t=this.#r();for(;this.#e().type==="or";){let r=this.#o(),n=this.#a(`after ${r.value}`);t={kind:"or",left:t,right:this.#c(n)}}return t}#r(){return this.#c(this.#a())}#c(t){let r=t;for(;;){let n=this.#e();if(n.type==="and"||n.type==="not"){this.#o();let o=this.#a(`after ${n.value}`);r={kind:n.type,left:r,right:o};continue}if(n.type==="term"||n.type==="left"){r={kind:"and",left:r,right:this.#a()};continue}return r}}#a(t){let r=this.#e();if(r.type==="term")return this.#o(),{kind:"term",value:r.value,quoted:r.quoted};if(r.type==="left"){if(this.#o(),this.#e().type==="right"||this.#e().type==="end")throw w(this.#e().offset,"expected a term after '('.");let o=this.#s();if(this.#e().type!=="right")throw w(this.#e().offset,"expected ')'.");return this.#o(),o}if(t===void 0&&(r.type==="and"||r.type==="or"||r.type==="not"))throw w(r.offset,`expected a term before ${r.value}.`);let n=t===void 0?"":` ${t}`;throw w(r.offset,`expected a term${n}.`)}#e(){return this.#n[this.#i]??{type:"end",value:"",offset:this.#t.length}}#o(){let t=this.#e();return this.#i+=1,t}};function P(e){let t=[],r=0;for(;r<e.length;){let n=e.charAt(r);if(/\s/u.test(n)){r+=1;continue}if(n==="("&&de(e,r)){t.push({type:"left",value:n,offset:r}),r+=1;continue}if(n===")"){t.push({type:"right",value:n,offset:r}),r+=1;continue}if(X(e,r)){let i=e.charAt(r+1)==="|"?2:1;t.push({type:"or",value:e.slice(r,r+i),offset:r}),r+=i;continue}if(n==="'"||n==='"'){let i=r,c=n,a="";for(r+=1;r<e.length&&e.charAt(r)!==c;)e.charAt(r)==="\\"&&(e.charAt(r+1)===c||e.charAt(r+1)==="\\")&&(r+=1),a+=e.charAt(r++);if(r>=e.length)throw w(i,`unterminated ${c==="'"?"single":"double"}-quoted term.`);if(r+=1,a.length===0)throw w(i,"quoted terms must not be empty.");t.push({type:"term",value:a,offset:i,quoted:!0});continue}let o=r;for(;r<e.length;){let i=e.charAt(r);if(/\s/u.test(i)||i===")"||X(e,r))break;i==="\\"&&r+1<e.length?r+=2:i==="["||i==="("?r=W(e,r)??r+1:r+=1}let s=e.slice(o,r);t.push({type:he(s),value:s,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}l(P,"tokenize");function X(e,t){return e.charAt(t)==="|"&&(e.charAt(t+1)==="|"||/\s/u.test(e.charAt(t-1))&&/\s/u.test(e.charAt(t+1)))}l(X,"isBooleanPipe");function W(e,t){let r=e.charAt(t)==="["?"]":")",n=t+1;for(;n<e.length;){let o=e.charAt(n);if(o==="\\")n+=2;else{if(o===r)return n+1;if(r===")"&&(o==="("||o==="[")){let s=W(e,n);if(s===void 0)return;n=s}else n+=1}}}l(W,"regexBlockEnd");function de(e,t){let r=W(e,t);if(r===void 0)return!0;let n=e.slice(t+1,r-1);return n.trim().length===0?!0:B(P(n))}l(de,"isBooleanGroup");function he(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}l(he,"operatorType");function fe(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}l(fe,"quoteToken");function w(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}l(w,"syntaxError");function E(e,t){return e.kind==="term"?{kind:"term",value:t&&!e.quoted?e.value:D(e.value)}:{kind:e.kind,left:E(e.left,t),right:E(e.right,t)}}l(E,"compileTerms");function F(e){if(e.kind==="term")return e.value;let t=F(e.left);return e.kind==="not"?t:`(?:${t}|${F(e.right)})`}l(F,"matchPattern");function D(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}l(D,"escapeRegex");async function $(e,t,r,n){if(e.query.length===0)throw new Error("Search query must not be empty.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");return e.condition!==void 0?ye(e,t,r):ee(e,t,r,void 0,n)}l($,"searchText");async function Se(e,t){let r=C.resolve(t,we(e.path??".")),n=(await pe(r)).isDirectory();return{cwd:n?r:C.dirname(r),target:n?".":C.basename(r),arguments:["--no-config","--no-ignore-parent","--color=never",...Z(e.include).flatMap(o=>["--glob",o]),...Z(e.exclude).flatMap(o=>["--glob",`!${o}`])]}}l(Se,"ripgrepScope");async function Ge(e,t,r,n){if(e.condition!==void 0)throw new Error("Boolean scoped search is not available yet.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");let o=await I(["--json","--no-config","--color=never","--with-filename","--line-number",...e.regex===!0?["--engine","auto"]:["--fixed-strings"],e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],"--",e.query,"-"],r,n,void 0,void 0,t.length===0?`
|
|
2
|
+
`:t);return t.length===0?{...o,matches:o.matches.filter(s=>s.lineNumber===1&&s.startColumn===0&&s.endColumn===0)}:o}l(Ge,"searchTextContent");async function ee(e,t,r,n,o){let s=await Se(e,t),i=s.cwd,c=["--json","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],...s.arguments,"--",e.query,s.target];if(e.regex!==!0)return I(["--fixed-strings",...c],i,r,n,o);try{return await I(["--engine","auto",...c],i,r,n,o)}catch(a){if(!be(a))throw a instanceof Error&&/PCRE2 is not available|does not support PCRE2/iu.test(a.message)?new Error("This regex requires PCRE2. Install ripgrep with PCRE2 support or simplify the regex.",{cause:a}):a;try{return await I(["--engine","default",...c],i,r,n,o)}catch(u){throw r?.aborted?u:new AggregateError([a,u],"Regex exceeded the PCRE2 match limit and cannot run with the default engine. Narrow the search or simplify the regex.",{cause:u})}}}l(ee,"searchPattern");async function ye(e,t,r){let n=e.condition;if(n===void 0)throw new Error("Boolean search requires a line condition.");let o=new Set;function s(h){if(h.kind==="term"){o.add(h.value);return}s(h.left),s(h.right)}l(s,"collect"),s(n);let{condition:i,...c}=e,a=new Map,u=l(h=>JSON.stringify([h.source,h.lineNumber]),"lineKey");for(let h of o){r?.throwIfAborted();let m=new Set;await ee({...c,query:h,regex:!0,wholeWord:!1},t,r,(y,A)=>m.add(JSON.stringify([y,A]))),a.set(h,m)}let d=await $(c,t,r),g=new Set,p=d.matches.filter(h=>{let m=u(h);return g.has(m)||!k(n,y=>a.get(y)?.has(m)===!0)?!1:(g.add(m),!0)});return{...d,matches:p}}l(ye,"searchBoolean");function I(e,t,r,n,o,s){return new Promise((i,c)=>{let a=me(V(),e,{stdio:["pipe","pipe","pipe"],cwd:t}),u=0,d=!1;o!==void 0&&a.stdout.on("data",S=>{u+=S.length,u>o.bytes&&(d=!0,a.kill())});let g=ge({input:a.stdout});a.stdin.on("error",()=>{}),a.stdin.end(s);let p=[],h="",m,y=l(()=>{a.kill()},"abort"),A=l(()=>{r?.removeEventListener("abort",y),g.close()},"cleanup");a.stderr.setEncoding("utf8"),a.stderr.on("data",S=>{h+=S}),g.on("line",S=>{if(!(d||m!==void 0||S.length===0))try{let b=JSON.parse(S);if(b.type!=="match")return;if(n!==void 0){let{path:N,line_number:G}=b.data;N.text!==void 0&&Number.isSafeInteger(G)&&n(C.resolve(t,N.text),G);return}for(let N of xe(b,t)){if(o!==void 0&&p.length===o.matches){d=!0,a.kill();break}p.push(N)}}catch(b){m=b,a.kill()}}),a.once("error",S=>{A(),c(S)}),a.once("close",S=>{if(A(),r?.aborted===!0){let b=new Error("Search was aborted.");b.name="AbortError",c(b);return}if(m!==void 0){c(new Error("Unable to parse ripgrep search output.",{cause:m}));return}if(!d&&S!==0&&S!==1){c(new Error(h.trim()||`ripgrep exited with code ${String(S)}.`));return}p.sort(Te),i({matches:p,complete:!d})}),r?.addEventListener("abort",y,{once:!0}),r?.aborted===!0&&y()})}l(I,"runRipgrep");function be(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}l(be,"isPcre2MatchLimitError");function xe(e,t){let r=e.data.path.text,n=e.data.lines.text;if(r===void 0||n===void 0||!Number.isSafeInteger(e.data.line_number))return[];let o=n.replace(/(?:\r\n|\n)$/u,""),s=Buffer.from(n),i=[];for(let c of e.data.submatches){if(c.start<0||c.end<c.start||c.end>s.length)continue;let a=s.subarray(0,c.start).toString("utf8").length,u=s.subarray(0,c.end).toString("utf8").length;i.push({source:C.resolve(t,r),lineNumber:e.data.line_number,startColumn:a,endColumn:u,matchedText:o.slice(a,u),lineText:o})}return i}l(xe,"matchesFromEvent");function Z(e){if(e===void 0)return[];let t=[],r=0,n="";for(let o of e){if(o==="{"?r+=1:o==="}"&&(r=Math.max(0,r-1)),r===0&&(o===","||/\s/u.test(o))){n.length>0&&(t.push(n),n="");continue}n+=o}return n.length>0&&t.push(n),t}l(Z,"splitGlobList");function we(e){return e.startsWith("@")?e.slice(1):e}l(we,"stripFilePrefix");function Te(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}l(Te,"compareMatches");function Ye(e){let t=O(e.query),r=O(e.query,!0),n=Y(e.query),o=[],s=_(e.query),i=_(e.query,!0);return(r!==t||JSON.stringify(s)!==JSON.stringify(i))&&o.push({query:r,mode:"regex",condition:i}),n!==void 0&&n!==t&&n!==r&&o.push({query:n,mode:"words"}),{...e,query:t,regex:!0,condition:s,fallbacks:o}}l(Ye,"createSearchRecipe");async function J(e,t,r){let n=e.query,o=await $(e,t,r),s=[];for(let i of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;r?.throwIfAborted();try{o=await $({...e,query:i.query,regex:!0,condition:i.condition},t,r),n=i.query,s.push(i.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words.")}catch(c){if(i.mode!=="regex"||!Re(c)||r?.aborted)throw c;s.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:n,notices:s}}l(J,"runSearchRecipe");function Re(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}l(Re,"isRegexSyntaxError");var ve=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,ie=4;function ct(e,t,r,n){return se(e,t,r,n).slice(0,ie)}l(ct,"createSearchSessionId");function se(e,t,r,n){let o=r===void 0?Pe(t.map(a=>a.source)):f.resolve(r),s=t.map(a=>({match:a,source:f.relative(o,f.resolve(a.source))})).sort((a,u)=>a.source.localeCompare(u.source)||q(a.match,u.match)).map(({match:a,source:u})=>[u,a.lineNumber,a.startColumn,a.endLineNumber??a.lineNumber,a.endColumn,a.matchedText,a.lineText]),{limit:i,...c}=ae(n??{query:e,regex:!0},o);return ke("sha256").update(JSON.stringify([e,o,c,s])).digest("hex").toUpperCase()}l(se,"createSearchSessionIdentity");function Ae(e,t){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let r=ie;r<=e.length;r+=1){let n=e.slice(0,r);if(!t.has(n))return n}throw new Error("Could not allocate a unique search session id.")}l(Ae,"allocateSearchSessionId");function ae(e,t){return{query:e.query,path:f.resolve(t,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,limit:e.limit??50,regex:e.regex===!0,condition:e.condition,fallbacks:e.fallbacks??[]}}l(ae,"normalizeRecipe");var H=class extends Error{static{l(this,"SearchSnapshotChangedError")}constructor(t){super(`Search result in ${t} changed before its anchors were registered.`),this.name="SearchSnapshotChangedError"}},te=class{constructor(t=se,r){this.createIdentity=t;this.resultTargets=r}static{l(this,"SearchSessionStore")}#t=new Map;#n=new Map;async register(t,r,n,o,s,i={query:t,regex:!0},c,a){let u=r.map(y=>({...y,source:f.resolve(y.source)})).sort(q),d=await re(u,s,a),g=this.createIdentity(t,u,o,i),h=this.#n.get(g)??Ae(g,new Set(this.#t.keys())),m={id:h,query:t,matches:u,complete:n,contentBySource:d,...Ne(this.resultTargets,u,d,o,n),...a===void 0?{}:{snapshotByteBudget:a},recipe:i,...c!==void 0&&{refresh:c},cwd:f.resolve(o)};return this.#n.set(g,h),this.#t.set(h,m),m}async registerIfCurrent(t,r,n,o,s,i,c,a){try{return await this.register(t,r,n,o,s,i,c,a)}catch(u){if(u instanceof H)return;throw u}}async observeAfterEdit(t,r){let n=new Set(t.flatMap(s=>{let i=typeof s=="string"?j(s):void 0;return i===void 0?[]:[i.id]})),o=[];for(let s of n){let i=this.#t.get(s);if(i===void 0)continue;let c={sessionId:s,query:i.recipe.originalQuery??i.query,scope:ae(i.recipe,i.cwd)};try{let a=i.refresh===void 0?await J(i.recipe,i.cwd,r):await i.refresh(r);o.push({...c,matches:a.matches.length,complete:a.complete,notices:a.notices})}catch(a){o.push({...c,error:a instanceof Error?a.message:String(a)})}}return o}anchorResolver(){return{id:"search",description:["`SEARCH#HASH:N:line` selects one result's full line; `SEARCH#HASH:N:match` selects its exact match.","`SEARCH#HASH:all:line` selects each unique containing line; `SEARCH#HASH:all:match` selects every exact match.","Omit `path` when `all` spans files."].join(`
|
|
3
|
+
`),renderFull(t){return t},renderCompact(t){let r=j(t);return r===void 0?"selected result":r.selector==="all"?r.mode==="match"?"all matches":"all lines":r.mode==="match"?`match ${String(r.selector)}`:`line ${String(r.selector)}`},tryResolve:l((t,r)=>this.#i(t,r.source,r.signal),"tryResolve")}}resourceResolver(){return{id:"search-targets",tryResolve:l((t,r)=>this.#s(t,r.cwd),"tryResolve")}}async#i(t,r,n){let o=j(t);if(o===void 0)return{kind:"not-handled"};let s=this.#t.get(o.id);if(s===void 0)return v();if(o.selector==="all"&&!s.complete)return R();let i=f.resolve(r),c=s;if(o.selector==="all"){if(s.refreshedComplete?.complete===!0)c=s.refreshedComplete;else if(s.refreshedComplete!==void 0&&(c=await this.#r(s,n),!c.complete))return R()}let a=L(c,o.selector,o.mode),u=a.filter(p=>p.source===i);if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await z(i,n);if(d===void 0)return v(x(u[0]).lineNumber);if(o.selector==="all"&&d!==c.contentBySource.get(i)){if(c=await this.#r(s,n),!c.complete)return R();a=L(c,o.selector,o.mode),u=a.filter(p=>p.source===i)}if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==s.contentBySource.get(i))return v(x(u[0]).lineNumber);let g=T(i,d);return{kind:"resolved",anchor:new U(t,i,u.map(p=>Q(g,p,o.mode)))}}async#s(t,r){let n=j(t);if(n===void 0)return{kind:"not-handled"};let o=this.#t.get(n.id);if(o===void 0)return v();if(n.selector==="all"&&!o.complete)return R();let s=o;if(n.selector==="all"){if(o.refreshedComplete?.complete===!0)s=o.refreshedComplete;else if(o.refreshedComplete!==void 0&&(s=await this.#r(o),!s.complete))return R();let u=new Set(L(s,n.selector,n.mode).map(d=>d.source));for(let d of u)if(await z(d)!==s.contentBySource.get(d)){if(s=await this.#r(o),!s.complete)return R();break}}let i=L(s,n.selector,n.mode);if(n.selector!=="all"){let u=i[0]?.source;if(u!==void 0&&await z(u)!==s.contentBySource.get(u))return v(i[0]?.lineNumber)}let c=new Map;for(let u of i){let d=c.get(u.source)??[];d.push(Q(T(u.source,s.contentBySource.get(u.source)??u.lineText),u,n.mode)),c.set(u.source,d)}let a=[...c].map(([u,d])=>({source:u,ranges:d,expectedContent:s.contentBySource.get(u)}));return a.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:a}}async#r(t,r){let n=t.refresh===void 0?await J(t.recipe,t.cwd,r):await t.refresh(r),o=n.matches.map(i=>({...i,source:f.resolve(i.source)})).sort(q),s={matches:o,complete:n.complete,contentBySource:await re(o,r,t.snapshotByteBudget)};return this.#t.set(t.id,{...t,refreshedComplete:s}),s}};function Ne(e,t,r,n,o){if(e===void 0)return{};let s=new Map([...r].map(([c,a])=>[c,T(c,a)])),i=t.map(c=>({source:c.source,expectedContent:x(r.get(c.source)),ranges:[Q(x(s.get(c.source)),c,"match")]}));return{target:e.register(i,n,o),matchTargets:i.slice(0,100).map(c=>e.register([c],n,o))}}l(Ne,"registerResultReferences");function j(e){let t=ve.exec(e);if(t!==null)return{id:x(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}l(j,"parseSearchAnchor");function L(e,t,r){let n=t==="all"?e.matches:[e.matches[t-1]].filter(Me);if(r==="match"||t!=="all")return n;let o=new Set;return n.flatMap(s=>{let i=T(s.source,e.contentBySource.get(s.source)??s.lineText),c=ce(s);return i.lines.slice(s.lineNumber-1,c).flatMap(a=>{let u=`${s.source}\0${String(a.lineNumber)}`;return o.has(u)?[]:(o.add(u),[{...s,lineNumber:a.lineNumber,endLineNumber:a.lineNumber,startColumn:0,endColumn:a.content.length,lineText:a.content,matchedText:a.content}])})})}l(L,"selectMatches");function Me(e){return e!==void 0}l(Me,"isMatch");function ce(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}l(ce,"lastContainingLine");function Q(e,t,r){if(r==="match")return{start:{lineNumber:t.lineNumber,column:t.startColumn},end:{lineNumber:t.endLineNumber??t.lineNumber,column:t.endColumn}};let n=ce(t),o=x(e.lines[n-1]);return{start:{lineNumber:t.lineNumber,column:0},end:{lineNumber:n+(o.lineEnding.length>0?1:0),column:o.lineEnding.length>0?0:o.content.length},linewise:!0}}l(Q,"selectionRange");function Ee(e,t){let r=t.endLineNumber??t.lineNumber;return e.lines.slice(t.lineNumber-1,r).map(n=>{let o=n.lineNumber===t.lineNumber?t.startColumn:0,s=n.lineNumber===r?t.endColumn:n.content.length;return n.content.slice(o,s)+(n.lineNumber===r?"":n.lineEnding)}).join("")}l(Ee,"matchedSourceText");async function re(e,t,r){let n=[...new Set(e.map(i=>i.source))];if(r!==void 0){let i=new Map,c=r;for(let a of n){let u=await Be(a,c,t);c-=Buffer.byteLength(u),ne(a,u,e),i.set(a,u)}return i}let o=await Promise.allSettled(n.map(async i=>{let c=await oe(i,{encoding:"utf8",...t!==void 0&&{signal:t}});return ne(i,c,e),[i,c]})),s=new Map;for(let i of o){if(i.status==="rejected")throw i.reason;s.set(...i.value)}return s}l(re,"snapshotContents");function ne(e,t,r){let n=T(e,t);for(let o of r.filter(s=>s.source===e))if(n.lines[o.lineNumber-1]?.content!==o.lineText||Ee(n,o)!==o.matchedText)throw new H(e)}l(ne,"validateSnapshot");async function Be(e,t,r){r?.throwIfAborted();let n=await Ce(e,"r");try{let o=await n.stat();if(!o.isFile()||o.size>t)throw new Error("Candidate snapshot byte budget reached.");let s=Buffer.alloc(Math.min(o.size+1,t+1)),i=0;for(;i<s.length;){r?.throwIfAborted();let c=await n.read(s,i,s.length-i,i);if(c.bytesRead===0)break;i+=c.bytesRead}if(r?.throwIfAborted(),i>o.size||i>t)throw new Error("Candidate file grew during snapshot capture.");return s.subarray(0,i).toString("utf8")}finally{await n.close()}}l(Be,"readBoundedSnapshot");async function z(e,t){try{return await oe(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}catch{return}}l(z,"readCurrent");function v(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}l(v,"staleAnchor");function R(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}l(R,"missingCompleteAnchor");function Pe(e){if(e.length===0)return".";let t=f.dirname(f.resolve(x(e[0])));for(let r of e.slice(1)){let n=f.resolve(r);for(;!Ie(t,n);){let o=f.dirname(t);if(o===t)return t;t=o}}return t}l(Pe,"commonSourceDirectory");function Ie(e,t){let r=f.relative(e,t);return r!==".."&&!r.startsWith(`..${f.sep}`)&&!f.isAbsolute(r)}l(Ie,"isWithin");function q(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||(e.endLineNumber??e.lineNumber)-(t.endLineNumber??t.lineNumber)||e.endColumn-t.endColumn}l(q,"compareMatches");export{V as a,$ as b,Se as c,Ge as d,Ye as e,J as f,ct as g,se as h,Ae as i,H as j,te as k};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as l}from"./chunk-EI7MMDWY.js";import{sliceByColumn as Q,truncateToWidth as R,visibleWidth as h,wrapTextWithAnsi as X}from"@earendil-works/pi-tui";import O from"node:path";import{getLanguageFromPath as A,highlightCode as D,keyText as L}from"@earendil-works/pi-coding-agent";import{truncateToWidth as T,visibleWidth as m,wrapTextWithAnsi as I,sliceByColumn as H}from"@earendil-works/pi-tui";var P=class{constructor(e,t,r){this.model=e;this.theme=t;this.expanded=r}static{l(this,"ResultPanel")}cache;update(e,t,r){this.model=e,this.theme=t,this.expanded=r,this.invalidate()}invalidate(){this.cache=void 0}render(e){if(this.cache?.width===e)return[...this.cache.lines];if(e<4)return[T(f(this.model.summary),Math.max(1,e))];let t=e-2,r=this.model.rows.filter(c=>c.kind!=="note"||!c.expandedOnly||this.expanded),o=Math.max(3,...r.map(c=>c.kind==="line"?String(c.lineNumber).length:0)),i=this.expanded?r:r.slice(0,13),a=F(i,this.theme),s=i.flatMap(c=>this.renderRow(c,t,o,a.get(c)));!this.expanded&&(s.length>12||i.length<r.length)&&(s=[...s.slice(0,11),this.frame(this.theme.fg("dim",` \u2026 output truncated \xB7 ${L("app.tools.expand")} to expand`),t)]);let u=T(` ${f(this.model.summary)} `,t-1,""),d=l(c=>this.theme.fg("borderMuted",c),"border"),g=[`${d("\u256D\u2500")}${this.theme.fg("accent",u)}${d(`${"\u2500".repeat(Math.max(0,t-m(u)-1))}\u256E`)}`,...s,d(`\u2570${"\u2500".repeat(t)}\u256F`)].map(c=>T(c,e));return this.cache={width:e,lines:g},[...g]}frame(e,t,r=!1){let o=T(e,t),i=o+" ".repeat(Math.max(0,t-m(o)));if(r){let s=this.theme.bg("selectedBg","").replace(/\u001B\[(?:0|49)m/gu,"");i=this.theme.bg("selectedBg",S(i,s))}let a=this.theme.fg("borderMuted","\u2502");return`${a}${i}${a}`}renderRow(e,t,r,o){if(e.kind==="source"){let c=this.theme.fg(J(e.label),this.theme.bold(e.badge??_(e.label))),p=e.count===void 0?"":this.theme.fg("accent",this.theme.bold(String(e.count))),b=Math.max(1,t-m(c)-m(p)-4),x=f(e.label),y=m(x)<=b?x:`\u2026${H(x,Math.max(0,m(x)-b+1),b-1,!0)}`,v=Math.max(y.lastIndexOf("/"),y.lastIndexOf("\\")),N=y.slice(0,v+1),j=y.slice(v+1),C=this.theme.fg("muted",N)+this.theme.underline(this.theme.fg("accent",j));e.link&&!/[\u0000-\u001F\u007F]/u.test(e.link)&&(C=`\x1B]8;;${e.link}\x07${C}\x1B]8;;\x07`);let B=` ${c} ${C}`;return[this.frame(`${B}${" ".repeat(Math.max(1,t-m(B)-m(p)-1))}${p} `,t,!0)]}if(e.kind==="note")return[this.frame(this.theme.fg("dim",` ${f(e.text).slice(0,2048)}`),t)];let a=` ${this.theme.fg("dim",String(e.lineNumber).padStart(r))} ${this.theme.fg("borderMuted","\u2502")} `,s=Math.max(1,t-m(a)-1),u=W(e),g=I(G(u,this.theme,o),s).map((c,p)=>this.frame(`${p?" ".repeat(m(a)):a}${c}`,t));return u!==e&&g.push(this.frame(this.theme.fg("dim"," \u2026 line shortened \xB7 read source for full text"),t)),g}};function q(n){let e=new Map;for(let t of n){let r=e.get(t.source);r||(r={first:t,lines:new Map},e.set(t.source,r));let o=r.lines.get(t.lineNumber);o?o.ranges.push(...t.ranges):r.lines.set(t.lineNumber,{text:t.text,ranges:[...t.ranges]})}return[...e.values()].flatMap(({first:t,lines:r})=>[{kind:"source",label:t.label,...t.link===void 0?{}:{link:t.link},...t.badge===void 0?{}:{badge:t.badge}},...[...r.entries()].sort(([o],[i])=>o-i).map(([o,i])=>({kind:"line",lineNumber:o,text:i.text,ranges:i.ranges}))])}l(q,"sourceRows");function W(n){if(n.text.length<=2048)return n;let e=Math.max(0,(n.ranges[0]?.from??0)-64),t=Math.min(n.text.length,e+256),r=e?"\u2026":"";return{...n,text:`${r}${n.text.slice(e,t)}${t<n.text.length?"\u2026":""}`,ranges:n.ranges.filter(o=>o.from<t&&o.to>e).map(o=>({from:Math.max(o.from,e)-e+r.length,to:Math.min(o.to,t)-e+r.length}))}}l(W,"previewLine");function F(n,e){let t=new Map,r,o=[],i=l(()=>{if(!o.length)return;let a=o.map(u=>$(W(u).text)),s=r?D(a.join(`
|
|
2
|
+
`),r):a.map(u=>e.fg("toolOutput",u));o.forEach((u,d)=>t.set(u,s[d]??a[d]??"")),o=[]},"flush");for(let a of n)a.kind==="source"?(i(),r=a.badge==="WEB"||a.badge==="SH"?void 0:A(a.label)):a.kind==="line"?(o.at(-1)?.lineNumber!==a.lineNumber-1&&i(),o.push(a)):i();return i(),t}l(F,"highlightSourceRows");function G(n,e,t){let r=t??e.fg("toolOutput",$(n.text));if(!n.ranges.length)return r;let o=l((u,d)=>H(r,m($(n.text.slice(0,u))),m($(n.text.slice(u,d))),!0),"fragment"),i=e.bg("selectedBg","").replace(/\u001B\[(?:0|49)m/gu,""),a="",s=0;for(let u of[...n.ranges].sort((d,g)=>d.from-g.from)){let d=Math.max(s,Math.min(n.text.length,u.from)),g=Math.max(d,Math.min(n.text.length,u.to));a+=o(s,d),g>d&&(a+=e.bg("selectedBg",S(e.bold(o(d,g)),i))),s=g}return a+o(s,n.text.length)}l(G,"highlight");function $(n){return f(n.replaceAll(" "," "))}l($,"safeCode");function _(n){return{".ts":"TS",".tsx":"TX",".js":"JS",".jsx":"JX",".json":"{}",".md":"MD",".py":"PY",".rs":"RS",".go":"GO",".css":"CS",".html":"<>"}[O.extname(n).toLowerCase()]??"\u25C7"}l(_,"fileBadge");function J(n){return/\.(?:js|jsx|json)$/iu.test(n)?"warning":"accent"}l(J,"badgeColor");function se(n,e){return n.getBgAnsi(e.isPartial?"toolPendingBg":e.isError?"toolErrorBg":"toolSuccessBg")}l(se,"toolBackgroundAnsi");var k=class{constructor(e,t){this.model=e;this.theme=t}static{l(this,"ToolCallHeader")}cache;update(e,t){this.model===e&&this.theme===t||(this.model=e,this.theme=t,this.invalidate())}render(e){if(this.cache?.width===e)return[...this.cache.lines];let t=U(this.model,this.theme,e);return this.cache={width:e,lines:t},[...t]}invalidate(){this.cache=void 0}};function ue(n,e,t){let r=n instanceof k?n:new k(e,t);return r.update(e,t),r}l(ue,"toolCallHeader");function U(n,e,t){let r=Math.max(1,t),o=Z(n,e,r),i=n.details;return!n.expanded||i===void 0||i.length===0?[o]:[o,...Y(i,e,r)]}l(U,"renderToolCallHeader");function Y(n,e,t){if(n.length===0)return[];let r=[e.fg("dim","args ")].concat(n.map(({label:i,value:a},s)=>`${s===0?"":e.fg("dim"," \xB7 ")}${e.fg("muted",`${f(i)}=`)}${e.fg("toolOutput",f(a))}`)).join(""),o=Math.max(1,t);return X(r,o).map(i=>R(i,o))}l(Y,"renderToolCallDetails");var z=/\u001B\[([\d:;]*)m/gu,K=/^\u001B\[([\d:;]*)m/u;function S(n,e){return e.length===0?n:n.replace(z,(t,r,o,i)=>E(r)==="reset"&&!V(i,o+t.length)?`${t}${e}`:t)}l(S,"preserveEnclosingBackground");function V(n,e){let t=K.exec(n.slice(e));return t!==null&&E(t[1]??"")==="set"}l(V,"backgroundIsImmediatelySet");function E(n){let e=n.length===0?["0"]:n.split(";"),t="unchanged";for(let r=0;r<e.length;r++){let o=e[r]??"",i=Number(o.split(":",1)[0]||"0");if(i===0||i===49){t="reset";continue}if(i>=40&&i<=47||i>=100&&i<=107){t="set";continue}if(i!==38&&i!==48&&i!==58||(i===48&&(t="set"),o.includes(":")))continue;let a=Number(e[r+1]);r+=a===2?4:a===5?2:0}return t}l(E,"sgrBackgroundState");function f(n){let e="",t=typeof n=="string"?n:"";for(let r of t){if(r===`
|
|
3
|
+
`){e+="\\n";continue}if(r==="\r"){e+="\\r";continue}if(r===" "){e+="\\t";continue}let o=r.codePointAt(0)??0;e+=o<32||o===127?"\uFFFD":r}return e}l(f,"singleLine");function Z(n,e,t){let r=e.fg("toolTitle",e.bold(f(n.tool))),o=h(r);if(o>=t||n.primary===void 0)return R(r,t);let i=e.fg("dim"," \xB7 "),a=[...n.qualifiers??[]],s=0;for(;a.length>0&&w(r,n.primary,a,s,e)>t;)a.pop(),s++;let u=a.reduce((b,x)=>b+h(i)+h(M(x,e)),0),d=s===0?"":e.fg("dim",` \xB7 \u2026 +${String(s)}`),g=Math.max(1,t-o-1-u-h(d)),c=M({...n.primary,text:ee(f(n.primary.text),g,n.primary.truncate)},e),p=a.map(b=>`${i}${M(b,e)}`).join("");return R(`${r} ${c}${p}${d}`,t)}l(Z,"renderSummary");function w(n,e,t,r,o){let i=t.reduce((s,u)=>s+3+h(M(u,o)),0),a=r===0?0:h(` \xB7 \u2026 +${String(r)}`);return h(n)+1+h(f(e.text))+i+a}l(w,"summaryWidth");function M(n,e){let t=f(n.text);return n.bold===!0&&(t=e.bold(t)),n.underline===!0&&(t=e.underline(t)),e.fg(n.color??"muted",t)}l(M,"renderPart");function ee(n,e,t){if(h(n)<=e)return n;if(e<=1)return"\u2026";if(t!=="start")return R(n,e);let r=e-1;return`\u2026${Q(n,h(n)-r,r,!0)}`}l(ee,"truncatePart");export{P as a,q as b,se as c,k as d,ue as e,U as f,Y as g,S as h,f as i};
|