@bastani/atomic 0.9.9-alpha.1 → 0.9.9-alpha.2
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 +8 -0
- package/dist/builtin/cursor/CHANGELOG.md +6 -0
- package/dist/builtin/cursor/package.json +3 -3
- package/dist/builtin/intercom/CHANGELOG.md +7 -0
- package/dist/builtin/intercom/package.json +3 -3
- package/dist/builtin/mcp/CHANGELOG.md +7 -0
- package/dist/builtin/mcp/package.json +4 -4
- package/dist/builtin/subagents/CHANGELOG.md +7 -0
- package/dist/builtin/subagents/package.json +5 -5
- package/dist/builtin/web-access/CHANGELOG.md +7 -0
- package/dist/builtin/web-access/package.json +3 -3
- package/dist/builtin/web-access/web-search-tool.ts +1 -2
- package/dist/builtin/workflows/CHANGELOG.md +7 -0
- package/dist/builtin/workflows/package.json +3 -3
- package/dist/builtin/workflows/src/shared/serializable.ts +1 -1
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/internal-intercom-broker.d.ts.map +1 -1
- package/dist/bun/register-bedrock.d.ts.map +1 -1
- package/dist/bun/restore-sandbox-env.d.ts.map +1 -1
- package/dist/bun/split-loader.d.ts.map +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/config-selector.d.ts.map +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/initial-message.d.ts.map +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/project-trust.d.ts.map +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/config-self-update.d.ts.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/core/agent-session-accessors.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-bash.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-export.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-skill-block.d.ts.map +1 -1
- package/dist/core/agent-session-state.d.ts.map +1 -1
- package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
- package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
- package/dist/core/agent-session-tree.d.ts.map +1 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
- package/dist/core/async/format.d.ts.map +1 -1
- package/dist/core/async/job-manager.d.ts.map +1 -1
- package/dist/core/async/session-manager.d.ts.map +1 -1
- package/dist/core/async/types.d.ts.map +1 -1
- package/dist/core/atomic-guide-command.d.ts.map +1 -1
- package/dist/core/auth-guidance.d.ts.map +1 -1
- package/dist/core/auth-storage-backends.d.ts.map +1 -1
- package/dist/core/auth-storage.d.ts +4 -0
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/builtin-packages.d.ts.map +1 -1
- package/dist/core/codex-fast-mode.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
- package/dist/core/compaction/compaction-parameters.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/range-planner.d.ts.map +1 -1
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/context-window.d.ts.map +1 -1
- package/dist/core/copilot-anthropic-sse-repair.d.ts.map +1 -1
- package/dist/core/copilot-errors.d.ts.map +1 -1
- package/dist/core/copilot-gemini-payload-sanitizer.d.ts.map +1 -1
- package/dist/core/copilot-gemini-reasoning.d.ts.map +1 -1
- package/dist/core/copilot-gemini-tool-arguments.d.ts.map +1 -1
- package/dist/core/copilot-hosts.d.ts.map +1 -1
- package/dist/core/copilot-model-catalog.d.ts.map +1 -1
- package/dist/core/copilot-model-static-fallbacks.d.ts.map +1 -1
- package/dist/core/copilot-model-synthesis.d.ts.map +1 -1
- package/dist/core/defaults.d.ts.map +1 -1
- package/dist/core/diagnostics.d.ts.map +1 -1
- package/dist/core/event-bus.d.ts.map +1 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/experimental.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/index.d.ts.map +1 -1
- package/dist/core/export-html/template-script.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/extensions/agent-events.d.ts.map +1 -1
- package/dist/core/extensions/api-types.d.ts.map +1 -1
- package/dist/core/extensions/command-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/event-results.d.ts.map +1 -1
- package/dist/core/extensions/event-types.d.ts.map +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/loader-api.d.ts.map +1 -1
- package/dist/core/extensions/loader-core.d.ts.map +1 -1
- package/dist/core/extensions/loader-discovery.d.ts.map +1 -1
- package/dist/core/extensions/loader-resources.d.ts.map +1 -1
- package/dist/core/extensions/loader-runtime.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/message-types.d.ts.map +1 -1
- package/dist/core/extensions/provider-types.d.ts.map +1 -1
- package/dist/core/extensions/reactive-widget.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-events.d.ts.map +1 -1
- package/dist/core/extensions/runner-handlers.d.ts.map +1 -1
- package/dist/core/extensions/runner-project-trust.d.ts.map +1 -1
- package/dist/core/extensions/runner-registries.d.ts.map +1 -1
- package/dist/core/extensions/runner-shortcuts.d.ts.map +1 -1
- package/dist/core/extensions/runner-ui.d.ts.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runtime-types.d.ts.map +1 -1
- package/dist/core/extensions/session-events.d.ts.map +1 -1
- package/dist/core/extensions/tool-events.d.ts.map +1 -1
- package/dist/core/extensions/tool-types.d.ts.map +1 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/ui-types.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/flattened-tool-arguments.d.ts.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/model-registry-auth.d.ts.map +1 -1
- package/dist/core/model-registry-builtins.d.ts.map +1 -1
- package/dist/core/model-registry-builtins.js.map +1 -1
- package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
- package/dist/core/model-registry-custom-loader.js.map +1 -1
- package/dist/core/model-registry-dynamic.d.ts.map +1 -1
- package/dist/core/model-registry-loader.d.ts.map +1 -1
- package/dist/core/model-registry-schemas.d.ts +65 -13
- package/dist/core/model-registry-schemas.d.ts.map +1 -1
- package/dist/core/model-registry-schemas.js +5 -1
- package/dist/core/model-registry-schemas.js.map +1 -1
- package/dist/core/model-registry-types.d.ts.map +1 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-resolver-cli.d.ts.map +1 -1
- package/dist/core/model-resolver-defaults.d.ts.map +1 -1
- package/dist/core/model-resolver-initial.d.ts.map +1 -1
- package/dist/core/model-resolver-patterns.d.ts.map +1 -1
- package/dist/core/model-resolver-scope.d.ts.map +1 -1
- package/dist/core/model-resolver-types.d.ts.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -1
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/package-manager-auto-resources.d.ts.map +1 -1
- package/dist/core/package-manager-command.d.ts.map +1 -1
- package/dist/core/package-manager-constants.d.ts.map +1 -1
- package/dist/core/package-manager-env.d.ts.map +1 -1
- package/dist/core/package-manager-git.d.ts.map +1 -1
- package/dist/core/package-manager-manifest.d.ts.map +1 -1
- package/dist/core/package-manager-npm.d.ts.map +1 -1
- package/dist/core/package-manager-operations.d.ts.map +1 -1
- package/dist/core/package-manager-paths.d.ts.map +1 -1
- package/dist/core/package-manager-progress.d.ts.map +1 -1
- package/dist/core/package-manager-resolver.d.ts.map +1 -1
- package/dist/core/package-manager-resource-accumulator.d.ts.map +1 -1
- package/dist/core/package-manager-resource-collector.d.ts.map +1 -1
- package/dist/core/package-manager-resource-files.d.ts.map +1 -1
- package/dist/core/package-manager-resource-patterns.d.ts.map +1 -1
- package/dist/core/package-manager-settings.d.ts.map +1 -1
- package/dist/core/package-manager-source.d.ts.map +1 -1
- package/dist/core/package-manager-types.d.ts.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/prompt-templates-async.d.ts.map +1 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/provider-attribution.d.ts.map +1 -1
- package/dist/core/provider-context-usage.d.ts.map +1 -1
- package/dist/core/provider-display-names.d.ts.map +1 -1
- package/dist/core/resolve-config-value.d.ts.map +1 -1
- package/dist/core/resource-loader-assets.d.ts.map +1 -1
- package/dist/core/resource-loader-context-files.d.ts.map +1 -1
- package/dist/core/resource-loader-core.d.ts.map +1 -1
- package/dist/core/resource-loader-discovery.d.ts.map +1 -1
- package/dist/core/resource-loader-extensions.d.ts.map +1 -1
- package/dist/core/resource-loader-helpers.d.ts.map +1 -1
- package/dist/core/resource-loader-internals.d.ts.map +1 -1
- package/dist/core/resource-loader-package-resources.d.ts.map +1 -1
- package/dist/core/resource-loader-paths.d.ts.map +1 -1
- package/dist/core/resource-loader-reload.d.ts.map +1 -1
- package/dist/core/resource-loader-source-info.d.ts.map +1 -1
- package/dist/core/resource-loader-types.d.ts.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/sdk-exports.d.ts.map +1 -1
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/session-cwd.d.ts.map +1 -1
- package/dist/core/session-entry-normalization.d.ts.map +1 -1
- package/dist/core/session-manager-archive.d.ts.map +1 -1
- package/dist/core/session-manager-classification.d.ts.map +1 -1
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-entries.d.ts.map +1 -1
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-list.d.ts.map +1 -1
- package/dist/core/session-manager-migrations.d.ts.map +1 -1
- package/dist/core/session-manager-paths.d.ts.map +1 -1
- package/dist/core/session-manager-storage.d.ts.map +1 -1
- package/dist/core/session-manager-types.d.ts.map +1 -1
- package/dist/core/session-manager-validation.d.ts.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-core.d.ts.map +1 -1
- package/dist/core/settings-manager-internals.d.ts.map +1 -1
- package/dist/core/settings-manager-resource-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-ui-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-merge.d.ts.map +1 -1
- package/dist/core/settings-storage.d.ts.map +1 -1
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/skills-async.d.ts.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/telemetry.d.ts.map +1 -1
- package/dist/core/thinking-blocks.d.ts.map +1 -1
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/tools/artifact-protocol.d.ts.map +1 -1
- package/dist/core/tools/artifacts.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/config.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/index.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/inline-input.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/key-router.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/row-intent.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/selectors/contract.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/selectors/derivations.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/selectors/focus.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/selectors/projections.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/state-reducer.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/state/state.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/tool/format-answer.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/tool/types.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/tool/validate-questionnaire.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/body-residual-spacer.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/component-binding.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/chat-row-view.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/option-list-view.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/preview-box-renderer.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/submit-picker.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/tab-bar.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/props-adapter.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/stateful-view.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/tab-components.d.ts.map +1 -1
- package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts.map +1 -1
- package/dist/core/tools/bash-async-execution.d.ts.map +1 -1
- package/dist/core/tools/bash-async-jobs.d.ts.map +1 -1
- package/dist/core/tools/bash-async-output.d.ts.map +1 -1
- package/dist/core/tools/bash-interceptor.d.ts.map +1 -1
- package/dist/core/tools/bash-leading-cd.d.ts.map +1 -1
- package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/block-resolver.d.ts.map +1 -1
- package/dist/core/tools/conflict-registry.d.ts.map +1 -1
- package/dist/core/tools/directory-tree.d.ts.map +1 -1
- package/dist/core/tools/edit-diff-preserve.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/fetch-url.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/glob-path-utils.d.ts.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/apply.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/block.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/diff-preview.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/format.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/fs.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/index.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/input.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/messages.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/mismatch.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/normalize.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/parser.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/patcher.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/prefixes.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/recovery.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/snapshots.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/stream.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/tokenizer.d.ts.map +1 -1
- package/dist/core/tools/hashline-engine/types.d.ts.map +1 -1
- package/dist/core/tools/hashline.d.ts.map +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/notebook.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/oversized-tool-result.d.ts.map +1 -1
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/read-document-extract.d.ts.map +1 -1
- package/dist/core/tools/read-selectors.d.ts.map +1 -1
- package/dist/core/tools/read-url.d.ts.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/resource-selectors.d.ts.map +1 -1
- package/dist/core/tools/search-details.d.ts.map +1 -1
- package/dist/core/tools/search-line-ranges.d.ts.map +1 -1
- package/dist/core/tools/search-native.d.ts.map +1 -1
- package/dist/core/tools/search.d.ts.map +1 -1
- package/dist/core/tools/structured-output.d.ts.map +1 -1
- package/dist/core/tools/todos-execute.d.ts.map +1 -1
- package/dist/core/tools/todos-locks.d.ts.map +1 -1
- package/dist/core/tools/todos-model.d.ts.map +1 -1
- package/dist/core/tools/todos-mutations.d.ts.map +1 -1
- package/dist/core/tools/todos-paths.d.ts.map +1 -1
- package/dist/core/tools/todos-render.d.ts.map +1 -1
- package/dist/core/tools/todos-storage.d.ts.map +1 -1
- package/dist/core/tools/todos-types.d.ts.map +1 -1
- package/dist/core/tools/todos-types.js +1 -1
- package/dist/core/tools/todos-types.js.map +1 -1
- package/dist/core/tools/todos.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +6 -2
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/tool-limits.d.ts.map +1 -1
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/url-ip-guards.d.ts.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/typebox-compat.d.ts +12 -0
- package/dist/core/typebox-compat.d.ts.map +1 -0
- package/dist/core/typebox-compat.js +10 -0
- package/dist/core/typebox-compat.js.map +1 -0
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main-app-mode.d.ts.map +1 -1
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-early-input.d.ts.map +1 -1
- package/dist/main-session-options.d.ts.map +1 -1
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-stdio.d.ts.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/migrations-config-values.d.ts.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/interactive/chat-input-actions.d.ts.map +1 -1
- package/dist/modes/interactive/components/armin.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/atomic-banner.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-terminal-cleanup.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-utils.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector-list.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/context-window-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
- package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/fast-mode-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-delete.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-header.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-tree.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-types.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-utils.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-handlers.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-options.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-component.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-help.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-label-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-list.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-model.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-types.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-viewport.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
- package/dist/modes/interactive/components/working-status.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-auth-login.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-auth-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-bash-compact.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-child-ordering.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-editor-actions.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-extension-context.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-extension-custom-ui.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-extension-dialogs.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-extension-widgets.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-hotkeys-debug.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-onboarding.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-resource-disclosure.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-resource-paths.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-resource-rendering.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-selectors.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-session-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-session-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-slash-commands.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/model-search.d.ts.map +1 -1
- package/dist/modes/interactive/theme/color-utils.d.ts.map +1 -1
- package/dist/modes/interactive/theme/export-colors.d.ts.map +1 -1
- package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/terminal-detection.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-loading.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-parse.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/tui-theme.d.ts.map +1 -1
- package/dist/modes/interactive/whimsical-messages.d.ts.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/rpc/jsonl.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-extension-ui.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-input.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-responses.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/package-manager-cli-parser.d.ts.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/rpc-entry.d.ts.map +1 -1
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-native.d.ts.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/deprecation.d.ts.map +1 -1
- package/dist/utils/event-loop.d.ts.map +1 -1
- package/dist/utils/exif-orientation.d.ts.map +1 -1
- package/dist/utils/frontmatter.d.ts.map +1 -1
- package/dist/utils/fs-watch.d.ts.map +1 -1
- package/dist/utils/git-env.d.ts.map +1 -1
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/html.d.ts.map +1 -1
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-process.d.ts.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-worker.d.ts.map +1 -1
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/json.d.ts.map +1 -1
- package/dist/utils/markit.d.ts.map +1 -1
- package/dist/utils/mime.d.ts.map +1 -1
- package/dist/utils/module-require.d.ts.map +1 -1
- package/dist/utils/open-browser.d.ts.map +1 -1
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/photon.d.ts.map +1 -1
- package/dist/utils/pi-user-agent.d.ts.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/sleep.d.ts.map +1 -1
- package/dist/utils/split-launcher.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/windows-self-update.d.ts.map +1 -1
- package/docs/custom-provider.md +7 -1
- package/docs/extensions.md +6 -4
- package/examples/extensions/README.md +3 -1
- package/examples/extensions/subagent/schemas.ts +1 -1
- package/examples/extensions/tic-tac-toe.ts +1 -2
- package/examples/extensions/todo.ts +1 -2
- package/npm-shrinkwrap.json +214 -98
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"directory-tree.d.ts","sourceRoot":"","sources":["../../../src/core/tools/directory-tree.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACnB;AAaD,UAAU,oBAAoB;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AA+DD,wBAAsB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAO3H"
|
|
1
|
+
{"version":3,"file":"directory-tree.d.ts","sourceRoot":"","sources":["../../../src/core/tools/directory-tree.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACnB;AAaD,UAAU,oBAAoB;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AA+DD,wBAAsB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAO3H"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff-preserve.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff-preserve.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CAChB;AA0CD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,eAAe,EAAE,EAAE,MAAM,SAAI,GAAG,MAAM,CAStG;AAED;;;;;;;;;GASG;AACH,wBAAgB,yCAAyC,CACxD,eAAe,EAAE,MAAM,EACvB,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,eAAe,EAAE,GAC7B,MAAM,CAqCR"
|
|
1
|
+
{"version":3,"file":"edit-diff-preserve.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff-preserve.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CAChB;AA0CD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,eAAe,EAAE,EAAE,MAAM,SAAI,GAAG,MAAM,CAStG;AAED;;;;;;;;;GASG;AACH,wBAAgB,yCAAyC,CACxD,eAAe,EAAE,MAAM,EACvB,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,eAAe,EAAE,GAC7B,MAAM,CAqCR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAYH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB3D;AAED,MAAM,WAAW,gBAAgB;IAChC,gCAAgC;IAChC,KAAK,EAAE,OAAO,CAAC;IACf,4FAA4F;IAC5F,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,cAAc,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,qBAAqB,EAAE,MAAM,CAAC;CAC9B;AAED,MAAM,WAAW,IAAI;IACpB,OAAO,EAAE,MAAM,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EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit and similar tools.\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport {\n\tapplyReplacements,\n\tapplyReplacementsPreservingUnchangedLines,\n\ttype TextReplacement,\n} from \"./edit-diff-preserve.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/**\n\t * The content to use for replacement operations.\n\t * When exact match: original content. When fuzzy match: normalized content.\n\t */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\ninterface MatchedEdit extends TextReplacement {\n\teditIndex: number;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * When fuzzy matching is used, the returned contentForReplacement is the\n * fuzzy-normalized version of the content (trailing whitespace stripped,\n * Unicode quotes/dashes normalized to ASCII).\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// When fuzzy matching, return offsets in normalized space. Callers can use\n\t// the normalized content to compute replacements, then decide how much of\n\t// that normalized output should be written back.\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: fuzzyContent,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. If any edit needs\n * fuzzy matching, the operation runs in fuzzy-normalized content space and then\n * overlays those line-level changes onto the original content so unchanged line\n * blocks keep their original bytes.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));\n\tconst usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch);\n\tconst replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent;\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(replacementBaseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = countOccurrences(replacementBaseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: matchResult.index,\n\t\t\tmatchLength: matchResult.matchLength,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\tconst newContent = usedFuzzyMatch\n\t\t? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits)\n\t\t: applyReplacements(replacementBaseContent, matchedEdits);\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAYH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB3D;AAED,MAAM,WAAW,gBAAgB;IAChC,gCAAgC;IAChC,KAAK,EAAE,OAAO,CAAC;IACf,4FAA4F;IAC5F,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,cAAc,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,qBAAqB,EAAE,MAAM,CAAC;CAC9B;AAED,MAAM,WAAW,IAAI;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CAChB;AAMD,MAAM,WAAW,kBAAkB;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,gBAAgB,CAsChF;AAED,uFAAuF;AACvF,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG;IAAE,GAAG,EAAE,MAAM,C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,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG7D,OAAO,EAAwF,KAAK,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAQjJ,QAAA,MAAM,UAAU;;EAGf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,cAAc;IAC9B,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAChD;AAQD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,aAAa,CAAC,EAAE,qBAAqB,CAAC;CACtC;AAwGD,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAoE/I;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { Filesystem, Patch, Patcher, type PatchSectionResult, type PreparedSection, type WriteResult } from \"./hashline-engine/index.ts\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { renderDiff } from \"../../modes/interactive/components/diff.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { generateDiffString, generateUnifiedPatch, normalizeToLF, stripBom } from \"./edit-diff.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { createHashlineSnapshotStore, formatCompactHashlineEditResult, recordHashlineSnapshot, type HashlineSnapshotStore } from \"./hashline.ts\";\nimport { invalidateNativeSearchCache } from \"./search-native.ts\";\nimport { isNotebookPath, readEditableNotebookText, serializeEditedNotebookText } from \"./notebook.ts\";\nimport { nativeBlockResolver } from \"./block-resolver.ts\";\nimport { resolveReadPath } from \"./path-utils.ts\";\nimport { renderToolPath } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst editSchema = Type.Object(\n\t{ input: Type.String({ description: \"One or more hashline file sections. Must start with [PATH#TAG]; tag comes from the latest read, search, write, or successful edit output.\" }) },\n\t{ additionalProperties: false },\n);\n\nexport type EditToolInput = Static<typeof editSchema>;\n\nexport interface EditToolDetails {\n\tdiff: string;\n\tpatch: string;\n\tfirstChangedLine?: number;\n}\n\nexport interface EditOperations {\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\taccess: (absolutePath: string) => Promise<void>;\n}\n\nconst defaultEditOperations: EditOperations = {\n\treadFile: (path) => fsReadFile(path),\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\taccess: (path) => fsAccess(path, constants.R_OK | constants.W_OK),\n};\n\nexport interface EditToolOptions {\n\toperations?: EditOperations;\n\thashlineStore?: HashlineSnapshotStore;\n}\n\ntype EditToolResultLike = {\n\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\tdetails?: EditToolDetails;\n};\n\nclass EditFilesystem extends Filesystem {\n\tprivate readonly cwd: string;\n\tprivate readonly operations: EditOperations;\n\tconstructor(cwd: string, operations: EditOperations) { super(); this.cwd = cwd; this.operations = operations; }\n\n\tcanonicalPath(path: string): string { return resolveReadPath(path, this.cwd); }\n\n\tasync preflightWrite(path: string): Promise<void> {\n\t\tconst absolutePath = this.canonicalPath(path);\n\t\ttry { await this.operations.access(absolutePath); }\n\t\tcatch (error: unknown) {\n\t\t\tconst message = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\tthrow new Error(`Could not edit file: ${path}. ${message}.`);\n\t\t}\n\t}\n\n\tasync readText(path: string): Promise<string> {\n\t\tconst absolutePath = this.canonicalPath(path);\n\t\treturn isNotebookPath(absolutePath) ? readEditableNotebookText(absolutePath, path) : (await this.operations.readFile(absolutePath)).toString(\"utf-8\");\n\t}\n\n\tasync writeText(path: string, content: string): Promise<WriteResult> {\n\t\tconst absolutePath = this.canonicalPath(path);\n\t\tconst persisted = isNotebookPath(absolutePath) ? serializeEditedNotebookText(absolutePath, path, normalizeToLF(stripBom(content).text)) : content;\n\t\tawait this.operations.writeFile(absolutePath, persisted);\n\t\treturn { text: persisted };\n\t}\n}\n\nfunction isFourDigitHexTag(value: string): boolean {\n\treturn value.length === 4 && [...value].every((char) => (char >= \"0\" && char <= \"9\") || (char >= \"a\" && char <= \"f\") || (char >= \"A\" && char <= \"F\"));\n}\n\nfunction extractFirstHeaderPath(input: string | undefined): string | undefined {\n\tif (!input) return undefined;\n\tfor (const line of input.split(\"\\n\")) {\n\t\tconst trimmed = line.trimStart();\n\t\tif (!trimmed.startsWith(\"[\")) continue;\n\t\tconst hashIndex = trimmed.indexOf(\"#\", 1);\n\t\tconst closeIndex = hashIndex >= 0 ? trimmed.indexOf(\"]\", hashIndex + 1) : -1;\n\t\tif (hashIndex <= 1 || closeIndex !== hashIndex + 5) continue;\n\t\tconst tag = trimmed.slice(hashIndex + 1, closeIndex);\n\t\tif (isFourDigitHexTag(tag)) return trimmed.slice(1, hashIndex);\n\t}\n\treturn undefined;\n}\n\nfunction formatEditCall(args: unknown, theme: Theme, cwd: string): string {\n\tconst input = args && typeof args === \"object\" && \"input\" in args ? (args as { input?: unknown }).input : undefined;\n\tconst pathDisplay = renderToolPath(extractFirstHeaderPath(typeof input === \"string\" ? input : undefined) ?? null, theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"edit\"))} ${pathDisplay}`;\n}\n\nfunction formatEditResult(result: EditToolResultLike, theme: Theme, isError: boolean): string | undefined {\n\tif (isError) {\n\t\tconst errorText = result.content.filter((c) => c.type === \"text\").map((c) => c.text || \"\").join(\"\\n\");\n\t\treturn errorText ? theme.fg(\"error\", errorText) : undefined;\n\t}\n\treturn result.details?.diff ? renderDiff(result.details.diff) : undefined;\n}\n\nasync function withFileMutationQueues<T>(filePaths: readonly string[], fn: () => Promise<T>): Promise<T> {\n\tconst sorted = [...new Set(filePaths)].sort();\n\tconst run = (index: number): Promise<T> => {\n\t\tconst filePath = sorted[index];\n\t\treturn filePath ? withFileMutationQueue(filePath, () => run(index + 1)) : fn();\n\t};\n\treturn run(0);\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n}\n\nfunction formatNoopMessage(path: string, count: number): string {\n\treturn `Edits to ${path} parsed and applied cleanly, but produced no change: your body row(s) are byte-identical to the file at the targeted lines. The bug is somewhere else — re-read the file before issuing another edit. Do NOT widen the payload or add lines; verify the anchor first.${count > 1 ? `\\nNo-op count for this identical payload: ${count}.` : \"\"}`;\n}\n\nfunction blockMessages(item: PreparedSection | PatchSectionResult): string[] {\n\tconst warnings = \"parseWarnings\" in item ? [...item.parseWarnings, ...(item.applyResult.warnings ?? [])] : item.warnings;\n\tconst resolutions = (\"applyResult\" in item ? item.applyResult.blockResolutions : item.blockResolutions)?.map((resolution) => {\n\t\tconst verb = resolution.op === \"insert_after\" ? \"insert after block\" : `${resolution.op} block`;\n\t\tconst lands = resolution.op === \"insert_after\" ? `; body lands after line ${resolution.end}` : \"\";\n\t\treturn `${verb} ${resolution.anchorLine} → resolved lines ${resolution.start}-${resolution.end} (${resolution.end - resolution.start + 1} lines)${lands}`;\n\t}) ?? [];\n\treturn [...warnings, ...resolutions];\n}\n\nfunction assertUniquePreparedPaths(prepared: readonly PreparedSection[]): void {\n\tconst seen = new Map<string, string>();\n\tfor (const entry of prepared) {\n\t\tconst previous = seen.get(entry.canonicalPath);\n\t\tif (previous) throw new Error(`Multiple hashline sections resolve to the same file (${previous} and ${entry.section.path}). Merge their ops under one header before applying.`);\n\t\tseen.set(entry.canonicalPath, entry.section.path);\n\t}\n}\n\nexport function createEditToolDefinition(cwd: string, options?: EditToolOptions): ToolDefinition<typeof editSchema, EditToolDetails | undefined> {\n\tconst ops = options?.operations ?? defaultEditOperations;\n\tconst hashlineStore = options?.hashlineStore ?? createHashlineSnapshotStore();\n\tconst fs = new EditFilesystem(cwd, ops);\n\tconst patcher = new Patcher({ fs, snapshots: hashlineStore.snapshots, blockResolver: nativeBlockResolver });\n\tconst noopCounts = new Map<string, number>();\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription: \"Edit existing files with the hashline patch language: each section starts with [PATH#TAG] (TAG is the 4-hex snapshot tag from your latest read/search), then hunk headers (replace N..M:, replace block N:, delete N..M, delete block N, insert before|after N:, insert after block N:, insert head:, insert tail:) followed by +TEXT body rows. Numbers refer to the original file. Use the write tool to create new files.\",\n\t\tpromptSnippet: \"Apply source edits with hashline patch input\",\n\t\tpromptGuidelines: [\n\t\t\t\"hashline edit format: a header ending in ':' is followed by '+'TEXT body rows; 'delete' has no body. Every section starts with [PATH#TAG]; TAG is REQUIRED (the 4-hex snapshot tag from your latest read/search) — there is no hashless form. Use the write tool to create new files.\",\n\t\t\t\"Ops: 'replace N..M:' replaces original lines N..M (INCLUSIVE — line M is consumed); 'replace block N:' replaces the whole syntactic block that BEGINS on line N (Atomic resolves the closing line with a brace/indent heuristic; point N at the opener); 'delete N..M' / 'delete block N' delete (no body); 'insert before N:' / 'insert after N:' insert relative to a line; 'insert after block N:' inserts after the END of the block beginning on N; 'insert head:' / 'insert tail:' insert at file start/end. Single line: 'replace N..N:' / 'delete N'. The range is the ORIGINAL lines you touch; body length is irrelevant.\",\n\t\t\t\"Body rows appear only under a ':' header. Every row is '+TEXT' (adds a literal line, leading whitespace kept; '+' alone adds a blank line). There is NO other body row kind — never write '-old' or a bare/context line. To keep a line, leave it out of every range. For a literal line starting with '-' or '+', prefix it: '+-x', '++x'.\",\n\t\t\t\"Numbers refer to the ORIGINAL file and do not shift as hunks apply; they die with the call — every applied edit mints a fresh #TAG and renumbers, so anchor the next edit on the edit response or a fresh read. Ranges are TIGHT: cover ONLY lines whose content changes; a stale wide range shreds everything it spans. Pure additions use 'insert', never a widened 'replace'. Whole construct → 'replace block N'; lines inside it → 'replace N..M'.\",\n\t\t\t\"On a stale-tag rejection or any surprising result: STOP and re-read before further edits. Never start or end a range mid-expression/mid-block, and never span a hunk across an elided ('…') region — read it first. Never use edit to reformat/restyle code; run the project formatter instead.\",\n\t\t],\n\t\tparameters: editSchema,\n\t\tasync execute(_toolCallId, input: EditToolInput, signal?: AbortSignal) {\n\t\t\tif (typeof input.input !== \"string\" || input.input.trim() === \"\") throw new Error(\"edit input must be a non-empty hashline script with [PATH#TAG] sections.\");\n\t\t\tconst patch = Patch.parse(input.input, { cwd });\n\t\t\tconst prepared: PreparedSection[] = [];\n\t\t\tfor (const section of patch.sections) { throwIfAborted(signal); prepared.push(await patcher.prepare(section)); }\n\t\t\tassertUniquePreparedPaths(prepared);\n\t\t\tconst noops = prepared.filter((item) => item.isNoop);\n\t\t\tif (noops.length > 0) {\n\t\t\t\tif (noops.length !== prepared.length) throw new Error(`Hashline edit for ${noops[0]!.section.path} did not change the file.`);\n\t\t\t\tconst key = prepared.map((item) => `${item.canonicalPath}\\0${item.applyResult.text}`).join(\"\\0\\0\");\n\t\t\t\tconst count = (noopCounts.get(key) ?? 0) + 1;\n\t\t\t\tnoopCounts.set(key, count);\n\t\t\t\tif (count >= 3) throw new Error(`STOP. ${formatNoopMessage(prepared[0]!.section.path, count)}`);\n\t\t\t\treturn { content: [{ type: \"text\", text: formatNoopMessage(prepared[0]!.section.path, count) }], details: { diff: \"\", patch: \"\" } };\n\t\t\t}\n\t\t\treturn withFileMutationQueues(prepared.map((item) => item.canonicalPath), async () => {\n\t\t\t\tfor (const item of prepared) if (normalizeToLF(stripBom(await fs.readText(item.section.path)).text) !== item.normalized) throw new Error(`Stale hashline tag for ${item.section.path}: file content changed before write. Re-read before editing.`);\n\t\t\t\tconst applyResult = await patcher.apply(patch);\n\t\t\t\tconst outputs: string[] = [];\n\t\t\t\tlet combinedDiff = \"\", combinedPatch = \"\";\n\t\t\t\tlet firstChangedLine: number | undefined;\n\t\t\t\tfor (const result of applyResult.sections) {\n\t\t\t\t\tthrowIfAborted(signal);\n\t\t\t\t\tinvalidateNativeSearchCache(result.canonicalPath);\n\t\t\t\t\tconst snapshot = recordHashlineSnapshot(result.canonicalPath, cwd, result.after, hashlineStore);\n\t\t\t\t\tconst diffResult = generateDiffString(result.before, result.after);\n\t\t\t\t\tcombinedDiff += `${combinedDiff ? \"\\n\" : \"\"}${diffResult.diff}`;\n\t\t\t\t\tcombinedPatch += `${combinedPatch ? \"\\n\" : \"\"}${generateUnifiedPatch(result.path, result.before, result.after)}`;\n\t\t\t\t\tfirstChangedLine ??= diffResult.firstChangedLine;\n\t\t\t\t\toutputs.push(formatCompactHashlineEditResult(snapshot, diffResult, blockMessages(result)));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputs.join(\"\\n\\n\") }], details: { diff: combinedDiff, patch: combinedPatch, firstChangedLine } };\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatEditCall(args, theme, context.cwd));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatEditResult(result as EditToolResultLike, theme, context.isError);\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tif (!output) return component;\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(output, 1, 0));\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createEditTool(cwd: string, options?: EditToolOptions): AgentTool<typeof editSchema> {\n\treturn wrapToolDefinition(createEditToolDefinition(cwd, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAK/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG7D,OAAO,EAAwF,KAAK,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAQjJ,QAAA,MAAM,UAAU;;EAGf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,cAAc;IAC9B,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAChD;AAQD,MAA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E,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,aAAa;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,kBAAkB,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,OAAO,CAAC;CACb;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,OAAO,CAAA;CAAE,EAAE,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,CAgB9K;AAED,wBAAsB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,OAAO,CAAA;CAAE,EAAE,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA+BlL;AAED,wBAAgB,iBAAiB,IAAI,IAAI,CAExC","sourcesContent":["/// <reference path=\"../../utils/turndown.d.ts\" />\n/**\n * URL fetch / cache / artifact / markdown-discovery pipeline, mirrored from\n * oh-my-pi's `packages/coding-agent/src/tools/fetch.ts` at 15b5c1397fc.\n *\n * Responsibilities:\n * - parseReadUrlTarget: URL + line selectors (:raw, :N, :A-B, :A+B, :A-B,C-D),\n * collapsed-scheme repair, host-port protection.\n * - session-scoped LRU cache keyed by `<scope>::<raw|rendered>::<normalizedUrl>`,\n * cached under both requested and final (redirected) URLs.\n * - renderUrl: markdown discovery (alternate <link>, .md suffix, content\n * negotiation, llms.txt/llms.md endpoints) + native HTML-to-markdown, with\n * quality gating.\n * - artifact persistence of the rendered output, with artifactId surfaced in\n * truncation metadata when the visible output is head-truncated.\n */\nimport { lookup } from \"node:dns/promises\";\nimport { ipFamily, isPrivateIpAddress, normalizeIpLiteralHost } from \"./url-ip-guards.ts\";\nimport { LRUCache } from \"lru-cache\";\nimport TurndownService from \"turndown\";\nimport { Agent, request as undiciRequest, type Dispatcher } from \"undici\";\nimport { getArtifactManager } from \"./artifacts.ts\";\nimport { extractDocumentMarkdown, isDocumentPath } from \"./read-document-extract.ts\";\nimport type { TruncationResult } from \"./truncate.ts\";\n\nexport const FETCH_DEFAULT_MAX_LINES = 300;\nexport const READ_URL_CACHE_MAX_ENTRIES = 100;\nconst REMOTE_FETCH_TIMEOUT_MS = 10_000;\nconst MAX_URL_REDIRECTS = 5;\nconst MAX_URL_RESPONSE_BYTES = 10 * 1024 * 1024;\nconst MIN_CONTENT_LENGTH = 100;\n\nexport interface LineRange { start: number; end?: number }\n\nexport interface ParsedReadUrlTarget {\n\turl: string;\n\traw: boolean;\n\toffset?: number;\n\tlimit?: number;\n\tranges?: readonly LineRange[];\n}\n\nexport interface ReadUrlToolDetails {\n\turl: string;\n\tfinalUrl: string;\n\tcontentType: string;\n\tmethod: string;\n\ttruncated: boolean;\n\tnotes: string[];\n\tmeta?: { artifactId?: string; truncation?: TruncationResult };\n}\n\ninterface ReadUrlCacheEntry {\n\tartifactId?: string;\n\tdetails: ReadUrlToolDetails;\n\toutput: string;\n}\n\nexport interface LoadedPage {\n\tok: boolean;\n\tstatus: number;\n\tcontent: string;\n\tcontentType: string;\n\tfinalUrl: string;\n}\n\nconst readUrlCache = new LRUCache<string, ReadUrlCacheEntry>({ max: READ_URL_CACHE_MAX_ENTRIES });\nlet turndown: TurndownService | undefined;\nfunction getTurndown(): TurndownService {\n\tif (!turndown) turndown = new TurndownService({ headingStyle: \"atx\", codeBlockStyle: \"fenced\", bulletListMarker: \"-\" });\n\treturn turndown;\n}\n\nexport function repairCollapsedScheme(url: string): string {\n\treturn url.replace(/^(https?):\\/([^/])/i, \"$1://$2\");\n}\n\nexport function isReadableUrlPath(readPath: string): boolean {\n\tconst repaired = repairCollapsedScheme(readPath);\n\treturn /^https?:\\/\\//i.test(repaired) || /^www\\./i.test(readPath);\n}\n\nfunction normalizeUrlForCache(url: string): string {\n\tconst repaired = repairCollapsedScheme(url);\n\tif (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(repaired)) return repaired;\n\treturn /^https?:\\/\\//i.test(repaired) ? repaired : `https://${repaired}`;\n}\nconst RANGE_TOKEN_RE = /^(raw|\\d+(?:\\+(?:\\d+)|(?:-|\\.\\.)\\d+)?)$/i;\nconst MULTI_RANGE_RE = /^\\d+(?:(?:-|\\.\\.|,|\\+)\\d+)*$/;\n\nfunction isUrlSelectorToken(token: string): boolean {\n\treturn /^raw$/i.test(token) || RANGE_TOKEN_RE.test(token) || MULTI_RANGE_RE.test(token);\n}\n\nfunction parseSingleRange(token: string): LineRange | undefined {\n\tconst plus = token.match(/^(\\d+)\\+(\\d+)$/);\n\tif (plus) {\n\t\tconst start = Number.parseInt(plus[1]!, 10), count = Number.parseInt(plus[2]!, 10);\n\t\treturn start < 1 || count < 1 ? undefined : { start, end: start + count - 1 };\n\t}\n\tconst range = token.match(/^(\\d+)(?:-|\\.\\.)(\\d+)$/);\n\tif (range) { const start = Number.parseInt(range[1]!, 10); const end = Number.parseInt(range[2]!, 10); return start < 1 || end < start ? undefined : { start, end }; }\n\tconst single = token.match(/^(\\d+)$/);\n\tif (single) { const start = Number.parseInt(single[1]!, 10); return start < 1 ? undefined : { start }; }\n\treturn undefined;\n}\n\nfunction parseRangeGroup(token: string): LineRange[] | undefined {\n\tconst groups = token.split(\",\");\n\tconst ranges: LineRange[] = [];\n\tfor (const group of groups) { const r = parseSingleRange(group); if (!r) return undefined; ranges.push(r); }\n\treturn ranges;\n}\n\nfunction tryExtractEmbeddedUrlSelector(readPath: string): { path: string; sels: string[] } | null {\n\tlet basePath = readPath;\n\tconst sels: string[] = [];\n\tfor (;;) {\n\t\tconst lastColonIndex = basePath.lastIndexOf(\":\");\n\t\tif (lastColonIndex <= 0) break;\n\t\tconst candidate = basePath.slice(lastColonIndex + 1);\n\t\tconst remainder = basePath.slice(0, lastColonIndex);\n\t\tif (!isReadableUrlPath(remainder) || !isUrlSelectorToken(candidate)) break;\n\t\ttry { new URL(remainder.startsWith(\"http://\") || remainder.startsWith(\"https://\") ? remainder : `https://${remainder}`); } catch { break; }\n\t\tsels.unshift(candidate);\n\t\tbasePath = remainder;\n\t}\n\treturn sels.length === 0 ? null : { path: basePath, sels };\n}\n\nexport function parseReadUrlTarget(readPath: string): ParsedReadUrlTarget | null {\n\tconst repaired = repairCollapsedScheme(readPath);\n\tconst embedded = tryExtractEmbeddedUrlSelector(repaired);\n\tconst urlPath = embedded?.path ?? repaired;\n\tif (!isReadableUrlPath(urlPath)) return null;\n\tlet raw = false;\n\tlet ranges: LineRange[] | undefined;\n\tfor (const sel of embedded?.sels ?? []) {\n\t\tif (/^raw$/i.test(sel)) { raw = true; continue; }\n\t\tif (ranges !== undefined) throw new Error(\"URL selector has multiple range groups; combine them with commas (e.g. `:5-10,20-30`).\");\n\t\tconst parsed = parseRangeGroup(sel);\n\t\tif (!parsed) throw new Error(`Invalid URL line selector: ${sel}`);\n\t\tranges = parsed;\n\t}\n\tif (!ranges || ranges.length === 0) return { url: urlPath, raw };\n\tif (ranges.length === 1) {\n\t\tconst r = ranges[0]!;\n\t\treturn { url: urlPath, raw, offset: r.start, limit: r.end !== undefined ? r.end - r.start + 1 : undefined };\n\t}\n\treturn { url: urlPath, raw, ranges };\n}\n\nexport function getReadUrlCacheKey(scope: string, requestedUrl: string, raw: boolean): string {\n\treturn `${scope}::${raw ? \"raw\" : \"rendered\"}::${normalizeUrlForCache(requestedUrl)}`;\n}\n\nfunction looksLikeHtml(text: string): boolean {\n\treturn /<html[\\s>]/i.test(text) || (/<head[\\s>]/i.test(text) && /<body[\\s>]/i.test(text));\n}\n\nfunction documentExtensionFromContentType(contentType: string): string | undefined {\n\tif (/pdf/i.test(contentType)) return \".pdf\";\n\tif (/msword/i.test(contentType)) return \".doc\";\n\tif (/wordprocessingml|officedocument\\.word/i.test(contentType)) return \".docx\";\n\tif (/presentationml|officedocument\\.presentation/i.test(contentType)) return \".pptx\";\n\tif (/ms-powerpoint|vnd\\.ms-powerpoint/i.test(contentType)) return \".ppt\";\n\tif (/spreadsheetml|officedocument\\.spreadsheet/i.test(contentType)) return \".xlsx\";\n\tif (/ms-excel|vnd\\.ms-excel/i.test(contentType)) return \".xls\";\n\tif (/epub/i.test(contentType)) return \".epub\";\n\tif (/\\bjson\\b|ipynb|jupyter/i.test(contentType)) return \".ipynb\";\n\tif (/rtf/i.test(contentType)) return \".rtf\";\n\treturn undefined;\n}\n\ninterface SafeFetchAddress { address: string; family: 4 | 6; /** True only when the address came from DNS resolution and must be pinned to prevent rebinding at connect time. */ pinned: boolean }\ntype LookupCallback = (error: NodeJS.ErrnoException | null, address: string | SafeFetchAddress[], family?: number) => void;\n\nfunction createPinnedDispatcher(pinned: SafeFetchAddress): Agent {\n\treturn new Agent({ connect: { lookup: (_hostname: string, options: { all?: boolean }, callback: LookupCallback) => { if (options.all) callback(null, [pinned]); else callback(null, pinned.address, pinned.family); } } });\n}\n\nasync function closePinnedDispatcher(dispatcher: Agent | undefined): Promise<void> {\n\tconst close = (dispatcher as { close?: () => Promise<void> | void } | undefined)?.close;\n\tif (typeof close === \"function\") await close.call(dispatcher);\n}\n/**\n * Fetch a URL through undici with the pinned dispatcher so the validated\n * address is the one actually connected to. Unlike `globalThis.fetch`, which\n * silently ignores the undici `dispatcher` option under Bun's compiled binary\n * (reopening a DNS-rebinding TOCTOU window for hostname targets), undici's own\n * client honors the dispatcher's custom `lookup` regardless of host runtime.\n * Adapts the undici response to the WHATWG-Response shape loadPage consumes.\n */\nasync function pinnedFetch(url: string, dispatcher: Dispatcher, options: { signal: AbortSignal; headers?: Record<string, string> }): Promise<Response> {\n\tconst result = await undiciRequest(url, { method: \"GET\", dispatcher, signal: options.signal, headers: options.headers });\n\tconst body = result.body;\n\tconst status = result.statusCode;\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(result.headers as Record<string, string | string[] | undefined>)) {\n\t\tif (value === undefined) continue;\n\t\tconst values = Array.isArray(value) ? value : [value];\n\t\tfor (const entry of values) headers.append(key, entry);\n\t}\n\tconst stream = new ReadableStream({\n\t\tstart(controller) { body.on(\"data\", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk))); body.on(\"end\", () => controller.close()); body.on(\"error\", (error: unknown) => controller.error(error)); },\n\t\tcancel() { body.destroy(); },\n\t});\n\treturn new Response(stream, { status, headers });\n}\n\n\nasync function assertSafeFetchUrl(url: string): Promise<SafeFetchAddress | undefined> {\n\tconst parsed = new URL(url);\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") throw new Error(`Unsupported URL protocol: ${parsed.protocol}`);\n\tif (process.env.ATOMIC_ALLOW_PRIVATE_URL_READS === \"1\") return undefined;\n\tconst hostname = parsed.hostname.replace(/^\\[|\\]$/g, \"\").replace(/\\.$/, \"\").toLowerCase();\n\tif (hostname === \"localhost\" || hostname.endsWith(\".localhost\") || hostname === \"metadata.google.internal\") throw new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\tconst literalAddress = normalizeIpLiteralHost(hostname);\n\tif (literalAddress) { if (isPrivateIpAddress(literalAddress)) throw new Error(`Refusing to fetch private or metadata URL: ${url}`); return { address: literalAddress, family: ipFamily(literalAddress), pinned: false }; }\n\tconst addresses = await lookup(hostname, { all: true }).catch((error: unknown) => { throw new Error(`Could not resolve URL host ${hostname}: ${error instanceof Error ? error.message : String(error)}`); });\n\tif (addresses.length === 0) throw new Error(`Could not resolve URL host ${hostname}: no addresses returned`);\n\tfor (const address of addresses) if (isPrivateIpAddress(address.address)) throw new Error(`Refusing to fetch private or metadata URL: ${url}`);\n\tconst first = addresses[0]!;\n\treturn { address: first.address, family: first.family === 6 ? 6 : 4, pinned: true };\n}\n\nasync function readResponseTextWithLimit(response: Response): Promise<string> {\n\tif (!response.body) { const buffer = Buffer.from(await response.arrayBuffer()); if (buffer.length > MAX_URL_RESPONSE_BYTES) throw new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit`); return buffer.toString(\"utf8\"); }\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tconst chunks: string[] = [];\n\tlet totalBytes = 0;\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_URL_RESPONSE_BYTES) { await reader.cancel(); throw new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit`); }\n\t\tchunks.push(decoder.decode(value, { stream: true }));\n\t}\n\tchunks.push(decoder.decode());\n\treturn chunks.join(\"\");\n}\nexport async function loadPage(url: string, timeoutMs: number, signal?: AbortSignal, accept?: string): Promise<LoadedPage> {\n\turl = normalizeUrlForCache(url);\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), Math.min(timeoutMs, REMOTE_FETCH_TIMEOUT_MS));\n\tconst onParentAbort = () => controller.abort();\n\tsignal?.addEventListener(\"abort\", onParentAbort, { once: true });\n\ttry {\n\t\tlet currentUrl = url;\n\t\tfor (let redirects = 0; redirects <= MAX_URL_REDIRECTS; redirects++) {\n\t\t\tconst pinned = await assertSafeFetchUrl(currentUrl);\n\t\t\t// Only a DNS-resolved hostname needs pinning: a literal-IP host is\n\t\t\t// validated directly and cannot be re-resolved at connect time, so\n\t\t\t// global fetch is sufficient and stays redirect/mock-friendly.\n\t\t\tconst dispatcher = pinned?.pinned ? createPinnedDispatcher(pinned) : undefined;\n\t\t\ttry {\n\t\t\t\tconst headers = accept ? { Accept: accept } : undefined;\n\t\t\t\t// Route pinned (hostname) fetches through undici directly so the\n\t\t\t\t// dispatcher's custom lookup is honored even under Bun's compiled\n\t\t\t\t// fetch, which silently ignores the `dispatcher` option.\n\t\t\t\tconst response = dispatcher\n\t\t\t\t\t? await pinnedFetch(currentUrl, dispatcher, { signal: controller.signal, headers })\n\t\t\t\t\t: await fetch(currentUrl, { signal: controller.signal, headers, redirect: \"manual\" });\n\t\t\t\tif (response.status >= 300 && response.status < 400 && response.headers.get(\"location\")) { await response.body?.cancel().catch(() => {}); currentUrl = new URL(response.headers.get(\"location\")!, currentUrl).href; continue; }\n\t\t\t\tconst contentLength = Number.parseInt(response.headers.get(\"content-length\") ?? \"0\", 10);\n\t\t\t\tif (contentLength > MAX_URL_RESPONSE_BYTES) throw new Error(`URL response exceeds ${MAX_URL_RESPONSE_BYTES} byte limit: ${currentUrl}`);\n\t\t\t\tconst contentType = response.headers.get(\"content-type\") ?? \"\";\n\t\t\t\tconst content = await readResponseTextWithLimit(response);\n\t\t\t\treturn { ok: response.ok, status: response.status, content, contentType, finalUrl: response.url || currentUrl };\n\t\t\t} finally {\n\t\t\t\tawait closePinnedDispatcher(dispatcher).catch(() => undefined);\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Too many redirects while fetching URL: ${url}`);\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tsignal?.removeEventListener(\"abort\", onParentAbort);\n\t}\n}\n\nfunction isLowQuality(content: string): boolean {\n\tconst lower = content.toLowerCase();\n\tif (/(enable javascript|javascript required|turn on javascript|please enable javascript|browser not supported)/.test(lower) && content.trim().length < 2000) return true;\n\tconst nonblank = content.split(\"\\n\").filter((line) => line.trim().length > 0);\n\tif (nonblank.length > 10 && nonblank.filter((line) => line.trim().length < 40).length / nonblank.length > 0.7) return true;\n\treturn false;\n}\n\nfunction buildLlmEndpointCandidates(url: string): string[] {\n\tconst parsed = (() => { try { return new URL(url); } catch { return undefined; } })();\n\tif (!parsed) return [];\n\tconst origin = parsed.origin;\n\tif (parsed.pathname === \"/\" || parsed.pathname === \"\") return [`${origin}/.well-known/llms.txt`, `${origin}/llms.txt`, `${origin}/llms.md`];\n\tconst trimmed = parsed.pathname.replace(/\\/+$/, \"\");\n\tconst segments = trimmed.split(\"/\").filter(Boolean);\n\tconst candidates: string[] = [];\n\tconst depth = parsed.pathname.endsWith(\"/\") ? segments.length : Math.max(segments.length - 1, 1);\n\tfor (let scope = Math.min(depth, segments.length); scope >= 1; scope--) {\n\t\tconst base = `${origin}/${segments.slice(0, scope).join(\"/\")}`;\n\t\tcandidates.push(`${base}/llms.txt`, `${base}/llms.md`);\n\t}\n\tcandidates.push(`${origin}/llms.txt`, `${origin}/llms.md`);\n\treturn [...new Set(candidates)];\n}\n\nasync function tryLlmEndpoints(url: string, signal?: AbortSignal): Promise<{ content: string; endpoint: string } | null> {\n\tfor (const endpoint of buildLlmEndpointCandidates(url)) {\n\t\ttry {\n\t\t\tconst page = await loadPage(endpoint, 5000, signal);\n\t\t\tif (page.ok && page.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(page.content)) return { content: page.content, endpoint };\n\t\t} catch {}\n\t}\n\treturn null;\n}\n\nfunction parseAlternateMarkdownLink(html: string, pageUrl: string): string | undefined {\n\tconst headEnd = html.toLowerCase().indexOf(\"</head>\");\n\tconst head = html.slice(0, headEnd >= 0 ? headEnd + 7 : html.length);\n\tconst links = [...head.matchAll(/<link\\b[^>]*>/gi)].map((m) => m[0] ?? \"\");\n\tfor (const tag of links) {\n\t\tconst rel = /rel=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tconst type = /type=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tconst href = /href=[\"']?([^\"'>]+)[\"']?/i.exec(tag)?.[1] ?? \"\";\n\t\tif (!/alternate/i.test(rel) || !href) continue;\n\t\tif (/RecentChanges|Special:|\\/feed\\/|action=feed/i.test(href)) continue;\n\t\tif (type.includes(\"markdown\") || href.endsWith(\".md\")) {\n\t\t\ttry { return new URL(href, pageUrl).href; } catch {}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nasync function tryMdSuffix(url: string, signal?: AbortSignal): Promise<string | null> {\n\tconst candidates: string[] = [];\n\tif (/\\/$/.test(url)) candidates.push(`${url}index.html.md`);\n\telse if (/\\.\\w+\\/?$/.test(url)) candidates.push(`${url}.md`);\n\telse candidates.push(`${url}.md`, `${url}/index.html.md`);\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst page = await loadPage(candidate, 5000, signal);\n\t\t\tif (page.ok && page.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(page.content)) return page.content;\n\t\t} catch {}\n\t}\n\treturn null;\n}\n\nasync function tryContentNegotiation(url: string, signal?: AbortSignal): Promise<string | null> {\n\ttry {\n\t\tconst page = await loadPage(url, 5000, signal, \"text/markdown, text/plain;q=0.9, text/html;q=0.8\");\n\t\tconst mime = page.contentType.toLowerCase();\n\t\tif (page.ok && page.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(page.content) && (mime.includes(\"markdown\") || mime.includes(\"text/plain\"))) return page.content;\n\t} catch {}\n\treturn null;\n}\n\nexport interface RenderedUrl {\n\tcontent: string;\n\tfinalUrl: string;\n\tcontentType: string;\n\tmethod: string;\n\tnotes: string[];\n\ttruncated: boolean;\n}\n\nexport async function renderUrl(url: string, raw: boolean, signal?: AbortSignal): Promise<RenderedUrl> {\n\tconst notes: string[] = [];\n\tlet method = \"text\";\n\tlet contentType = \"\";\n\tlet finalUrl: string;\n\tlet body = \"\";\n\tconst page = await loadPage(url, REMOTE_FETCH_TIMEOUT_MS, signal);\n\tfinalUrl = page.finalUrl;\n\tcontentType = page.contentType;\n\tif (!page.ok) return { content: page.content || `(request failed with status ${page.status})`, finalUrl, contentType, method: \"failed\", notes, truncated: false };\n\tif (raw) return { content: page.content, finalUrl, contentType, method: \"raw\", notes, truncated: false };\n\tconst buffer = Buffer.from(page.content, \"utf8\");\n\tconst docExt = documentExtensionFromContentType(contentType) ?? (isDocumentPath(finalUrl) ? (finalUrl.match(/\\.\\w+(?:$|[?#])/)?.[0] ?? \"\") : \"\");\n\tif (docExt) {\n\t\ttry { body = await extractDocumentMarkdown(buffer, `${finalUrl}${docExt}`); method = \"document\"; }\n\t\tcatch (error) { body = `[Cannot read ${docExt} file: ${error instanceof Error ? error.message : \"conversion failed\"}]`; method = \"document-error\"; }\n\t\treturn { content: body, finalUrl, contentType, method, notes, truncated: false };\n\t}\n\tconst isHtml = /html/i.test(contentType) || looksLikeHtml(page.content);\n\tif (isHtml) {\n\t\tconst altMd = parseAlternateMarkdownLink(page.content, finalUrl);\n\t\tif (altMd) { try { const alt = await loadPage(altMd, 5000, signal); if (alt.ok && alt.content.trim().length > MIN_CONTENT_LENGTH && !looksLikeHtml(alt.content)) { return { content: alt.content, finalUrl: alt.finalUrl, contentType: alt.contentType, method: \"alternate-markdown\", notes, truncated: false }; } } catch {} notes.push(\"alternate markdown link unusable\"); }\n\t\tconst md = await tryMdSuffix(finalUrl, signal); if (md) return { content: md, finalUrl, contentType: \"text/markdown\", method: \"md-suffix\", notes, truncated: false };\n\t\tconst neg = await tryContentNegotiation(finalUrl, signal); if (neg) return { content: neg, finalUrl, contentType: \"text/markdown\", method: \"content-negotiation\", notes, truncated: false };\n\t\tlet rendered = getTurndown().turndown(page.content).trim();\n\t\tmethod = \"native\";\n\t\tif (rendered.length <= MIN_CONTENT_LENGTH || isLowQuality(rendered)) {\n\t\t\tconst llms = await tryLlmEndpoints(finalUrl, signal);\n\t\t\tif (llms) { return { content: llms.content, finalUrl, contentType: \"text/plain\", method: `llms-txt (${llms.endpoint})`, notes, truncated: false }; }\n\t\t\tnotes.push(\"rendered content low quality; no markdown source discovered\");\n\t\t}\n\t\tbody = rendered;\n\t} else {\n\t\tbody = page.content;\n\t}\n\treturn { content: body, finalUrl, contentType, method, notes, truncated: false };\n}\n\nexport function buildUrlReadOutput(result: RenderedUrl): string {\n\tconst header = [`URL: ${result.finalUrl}`, `Content-Type: ${result.contentType}`, `Method: ${result.method}`, ...(result.notes.length ? [`Notes: ${result.notes.join(\"; \")}`] : [])].join(\"\\n\");\n\treturn `${header}\\n\\n---\\n\\n${result.content}`;\n}\n\nfunction persistReadUrlArtifact(artifactsDir: string | undefined, output: string): string | undefined {\n\tif (!artifactsDir) return undefined;\n\treturn getArtifactManager(artifactsDir).save(output, \"read\");\n}\n\nexport interface ExecuteReadUrlResult {\n\tcontent: string;\n\tdetails: ReadUrlToolDetails;\n\tartifactId?: string;\n}\n\nexport interface LoadedReadUrl {\n\toutput: string;\n\tdetails: ReadUrlToolDetails;\n\tartifactId?: string;\n\traw: boolean;\n}\n\n/**\n * Resolve a URL to its full rendered (or raw) output, using the session-scoped\n * cache and persisting the rendered body as a `read` artifact. Returns the\n * complete untruncated output so callers can apply their own line selection.\n */\nexport async function loadReadUrlOutput(scope: string, params: { path: string; raw?: boolean }, artifactsDir: string | undefined, signal?: AbortSignal): Promise<LoadedReadUrl> {\n\tconst parsed = parseReadUrlTarget(params.path);\n\tif (!parsed) throw new Error(`Not a readable URL: ${params.path}`);\n\tconst raw = params.raw ?? parsed.raw;\n\tconst key = getReadUrlCacheKey(scope, parsed.url, raw);\n\tlet entry = readUrlCache.get(key);\n\tif (!entry) {\n\t\tconst rendered = await renderUrl(parsed.url, raw, signal);\n\t\tconst output = raw ? rendered.content : buildUrlReadOutput(rendered);\n\t\tconst artifactId = persistReadUrlArtifact(artifactsDir, output);\n\t\tconst details: ReadUrlToolDetails = { url: parsed.url, finalUrl: rendered.finalUrl, contentType: rendered.contentType, method: rendered.method, truncated: rendered.truncated, notes: rendered.notes, meta: artifactId ? { artifactId } : undefined };\n\t\tentry = { artifactId, details, output };\n\t\treadUrlCache.set(key, entry);\n\t\treadUrlCache.set(getReadUrlCacheKey(scope, rendered.finalUrl, raw), entry);\n\t}\n\treturn { output: entry.output, details: entry.details, artifactId: entry.artifactId, raw };\n}\n\nexport async function executeReadUrl(scope: string, params: { path: string; raw?: boolean }, artifactsDir: string | undefined, signal?: AbortSignal): Promise<ExecuteReadUrlResult> {\n\tconst loaded = await loadReadUrlOutput(scope, params, artifactsDir, signal);\n\tconst entry = { output: loaded.output, details: loaded.details, artifactId: loaded.artifactId };\n\tconst fetchDefaultBytes = 50 * 1024;\n\tconst lines = entry.output.split(\"\\n\");\n\tconst visibleLines = lines.slice(0, FETCH_DEFAULT_MAX_LINES);\n\tlet content = visibleLines.join(\"\\n\");\n\tconst bytesBeforeByteClamp = Buffer.byteLength(content, \"utf8\");\n\tconst byteTruncated = bytesBeforeByteClamp > fetchDefaultBytes;\n\tconst lineTruncated = lines.length > FETCH_DEFAULT_MAX_LINES;\n\tif (byteTruncated) content = content.slice(0, fetchDefaultBytes);\n\tconst truncated = lineTruncated || byteTruncated;\n\tlet artifactId = entry.artifactId;\n\tif (truncated && !artifactId) artifactId = persistReadUrlArtifact(artifactsDir, entry.output);\n\tconst outputLines = content.length === 0 ? 0 : content.split(\"\\n\").length;\n\tconst truncation: TruncationResult | undefined = truncated ? {\n\t\tcontent,\n\t\ttruncated: true,\n\t\ttruncatedBy: byteTruncated ? \"bytes\" : \"lines\",\n\t\ttotalLines: lines.length,\n\t\ttotalBytes: Buffer.byteLength(entry.output, \"utf8\"),\n\t\toutputLines,\n\t\toutputBytes: Buffer.byteLength(content, \"utf8\"),\n\t\tlastLinePartial: byteTruncated,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines: FETCH_DEFAULT_MAX_LINES,\n\t\tmaxBytes: fetchDefaultBytes,\n\t} : undefined;\n\tconst details: ReadUrlToolDetails = { ...entry.details, truncated, meta: { ...(entry.details.meta ?? {}), ...(artifactId ? { artifactId } : {}), ...(truncation ? { truncation } : {}) } };\n\tif (truncated) content += `\\n\\n[Showing first ${visibleLines.length} of ${lines.length} lines.${artifactId ? ` Full output: artifact://${artifactId}` : \"\"}]`;\n\treturn { content, details, artifactId };\n}\n\nexport function resetReadUrlCache(): void {\n\treadUrlCache.clear();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fetch-url.d.ts","sourceRoot":"","sources":["../../../src/core/tools/fetch-url.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEtD,eAAO,MAAM,uBAAuB,MAAM,CAAC;AAC3C,eAAO,MAAM,0BAA0B,MAAM,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E,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA+BlL;AAED,wBAAgB,iBAAiB,IAAI,IAAI,CAExC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-mutation-queue.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"AA2BA;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CA6BjG"
|
|
1
|
+
{"version":3,"file":"file-mutation-queue.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"AA2BA;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CA6BjG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../../../src/core/tools/find.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAOtF,OAAO,EAAiC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEnG,QAAA,MAAM,UAAU;;;;;;EAMmB,CAAC;AACpC,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AA+FtD,MAAM,WAAW,eAAe;IAAG,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,E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AS,CAAC,CAmRhE;AACD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { statSync } from \"node:fs\";\nimport { stat as fsStat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { normalizePathLikeInput, splitPathLikeGlob } from \"./glob-path-utils.ts\";\nimport { loadNativeSearchBinding } from \"./search-native.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { resolveInternalSelector, type InternalResourceContext } from \"./resource-selectors.ts\";\nimport { getTextOutput } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\nconst toPosixPath = (value: string): string => value.split(path.sep).join(\"/\");\nconst findSchema = Type.Object({\n\tpaths: Type.Array(Type.String({ description: \"File, directory, or glob path to find.\" }), { description: \"Paths or glob paths to find.\", minItems: 1 }),\n\thidden: Type.Optional(Type.Boolean({ description: \"Include hidden files. Defaults to true.\" })),\n\tgitignore: Type.Optional(Type.Boolean({ description: \"Respect gitignore. Defaults to true.\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of results, clamped to 1-200.\", minimum: 1, maximum: 200 })),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds; default 5, clamped to 0.5..60.\", minimum: 0.5, maximum: 60 })),\n}, { additionalProperties: false });\nexport type FindToolInput = Static<typeof findSchema>;\nconst DEFAULT_LIMIT = 200;\nconst MAX_LIMIT = 200;\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst MIN_TIMEOUT_MS = 500;\nconst MAX_TIMEOUT_MS = 60_000;\ninterface FindTarget { searchPath: string; pattern: string; exactPathInput: boolean; inputPath: string }\nfunction normalizeLimit(limit: number | undefined): number { return limit === undefined || !Number.isFinite(limit) ? DEFAULT_LIMIT : Math.max(1, Math.min(MAX_LIMIT, Math.floor(limit))); }\nfunction normalizeTimeoutMs(timeout: number | undefined): number { return timeout === undefined || !Number.isFinite(timeout) ? DEFAULT_TIMEOUT_MS : Math.max(MIN_TIMEOUT_MS, Math.min(MAX_TIMEOUT_MS, Math.floor(timeout * 1000))); }\nfunction formatTimeoutSeconds(timeoutMs: number): string { const seconds = timeoutMs / 1000; return Number.isInteger(seconds) ? String(seconds) : seconds.toFixed(1); }\nasync function resolveFindInternal(input: string, cwd: string, ctx?: InternalResourceContext): Promise<string> { const parsed = splitPathLikeGlob(input); if (!/^[a-z]+:\\/\\//i.test(parsed.basePath)) return input; for (const resolve of [ctx?.internalRouter?.resolve, ctx?.internalResourceRouter?.resolve, ctx?.resolveInternalUrl]) { const resolved = await resolve?.(parsed.basePath); if (typeof resolved === \"string\") return parsed.glob ? `${resolved}/${parsed.glob}` : resolved; } const fallback = resolveInternalSelector(parsed.basePath, cwd); return fallback ? parsed.glob ? `${fallback}/${parsed.glob}` : fallback : input; }\nfunction isWindowsAbsolutePath(value: string): boolean { return /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith(\"\\\\\\\\\"); }\nfunction resolveFindBackendPath(input: string, cwd: string, customBackend: boolean): string { if (!customBackend) return resolveToCwd(input, cwd); if (input === \".\" || input === \"\") return cwd; if (input.startsWith(\"/\") || isWindowsAbsolutePath(input)) return input; if (cwd.includes(\"\\\\\") || isWindowsAbsolutePath(cwd)) return path.resolve(cwd, input); return `${cwd.replace(/\\/+$/, \"\")}/${input}`; }\nasync function delimiterInExistingGlobRoot(value: string, cwd: string, ops: FindOperations, customBackend: boolean): Promise<boolean> { const parsed = splitPathLikeGlob(value); return !!parsed.glob && /[;,\\s]/.test(parsed.basePath) && await ops.exists(resolveFindBackendPath(parsed.basePath, cwd, customBackend)); }\nasync function expandDelimitedFindPaths(pathsValue: string[] | undefined, cwd: string, ops: FindOperations, ctx?: InternalResourceContext, customBackend = false): Promise<string[]> {\n\tif (!pathsValue?.length) throw new Error(\"find.paths must include at least one path or glob.\"); const expanded: string[] = [];\n\tfor (const input of pathsValue) { const raw = normalizePathLikeInput(input); if (raw === \"\") throw new Error(\"find.paths entries must not be empty.\"); const resolvedRaw = await resolveFindInternal(raw, cwd, ctx); const rawParsed = splitPathLikeGlob(resolvedRaw);\n\t\tif ((rawParsed.glob === undefined && await ops.exists(resolveFindBackendPath(rawParsed.basePath, cwd, customBackend))) || await delimiterInExistingGlobRoot(resolvedRaw, cwd, ops, customBackend)) { expanded.push(resolvedRaw); continue; }\n\t\tconst parts = await Promise.all(raw.split(/[;,\\s]+/).map(normalizePathLikeInput).filter(Boolean).map((part) => resolveFindInternal(part, cwd, ctx)));\n\t\tconst delimiterCanSplit = /[;,]/.test(raw) ? (await Promise.all(parts.map((part) => ops.exists(resolveFindBackendPath(splitPathLikeGlob(part).basePath, cwd, customBackend))))).some(Boolean) : (await Promise.all(parts.map((part) => ops.exists(resolveFindBackendPath(splitPathLikeGlob(part).basePath, cwd, customBackend))))).every(Boolean);\n\t\tif (parts.length > 1 && delimiterCanSplit) expanded.push(...parts); else expanded.push(resolvedRaw);\n\t}\n\treturn expanded;\n}\nfunction normalizeFindTargets(cwd: string, pathsValue: string[] | undefined, customBackend = false): FindTarget[] {\n\tif (!pathsValue || pathsValue.length === 0) throw new Error(\"find.paths must include at least one path or glob.\");\n\treturn pathsValue.map((searchPath) => {\n\t\tconst parsed = splitPathLikeGlob(searchPath);\n\t\tconst target = { searchPath: resolveFindBackendPath(parsed.basePath, cwd, customBackend), pattern: parsed.glob ?? \"**/*\", exactPathInput: parsed.glob === undefined, inputPath: searchPath };\n\t\tif (path.parse(target.searchPath).root === target.searchPath) throw new Error(\"Refusing to search filesystem root with find; provide a narrower path.\");\n\t\treturn target;\n\t});\n}\nfunction relativizeFoundPath(foundPath: string, searchPath: string): string {\n\tconst hadTrailingSlash = foundPath.endsWith(\"/\") || foundPath.endsWith(\"\\\\\");\n\tconst relativePath = path.relative(searchPath, foundPath) || path.basename(foundPath);\n\tconst outputPath = hadTrailingSlash && !relativePath.endsWith(\"/\") ? `${relativePath}/` : relativePath;\n\treturn toPosixPath(outputPath);\n}\nfunction formatExactFoundPath(foundPath: string, cwd: string): string { return toPosixPath(path.relative(cwd, foundPath) || path.basename(foundPath)); }\nfunction containsHiddenSegment(value: string): boolean { return toPosixPath(value).split(\"/\").some((part) => part.startsWith(\".\") && part.length > 1); }\nfunction findTargetMentionsNodeModules(target: FindTarget): boolean { return target.pattern.includes(\"node_modules\") || toPosixPath(target.searchPath).split(\"/\").includes(\"node_modules\"); }\nfunction formatFoundPath(foundPath: string, searchPath: string, searchPaths: string[], cwd: string): string {\n\tlet absoluteFoundPath = path.isAbsolute(foundPath) ? foundPath : path.resolve(searchPath, foundPath);\n\tif (foundPath.endsWith(\"/\") && !absoluteFoundPath.endsWith(\"/\")) absoluteFoundPath += \"/\";\n\tconst relative = relativizeFoundPath(absoluteFoundPath, searchPath);\n\tif (searchPaths.length <= 1) return relative;\n\tconst rootLabel = toPosixPath(path.relative(cwd, searchPath) || path.basename(searchPath) || \".\");\n\treturn `${rootLabel}/${relative}`;\n}\ninterface FindTreeNode {\n\tfiles: Set<string>;\n\tdirs: Map<string, FindTreeNode>;\n}\nfunction createFindTreeNode(): FindTreeNode { return { files: new Set(), dirs: new Map() }; }\nfunction formatFindTree(relativized: string[]): string {\n\tconst root = createFindTreeNode();\n\tfor (const item of relativized) {\n\t\tconst isDir = item.endsWith(\"/\");\n\t\tconst parts = item.replace(/\\/+$/g, \"\").split(\"/\").filter(Boolean);\n\t\tif (parts.length === 0) continue;\n\t\tlet node = root;\n\t\tconst dirParts = isDir ? parts : parts.slice(0, -1);\n\t\tfor (const dir of dirParts) {\n\t\t\tlet child = node.dirs.get(dir);\n\t\t\tif (!child) {\n\t\t\t\tchild = createFindTreeNode();\n\t\t\t\tnode.dirs.set(dir, child);\n\t\t\t}\n\t\t\tnode = child;\n\t\t}\n\t\tif (!isDir) node.files.add(parts[parts.length - 1]!);\n\t}\n\tconst lines: string[] = [];\n\tconst collapse = (dir: string, node: FindTreeNode): { label: string; node: FindTreeNode } => {\n\t\tconst parts = [dir];\n\t\tlet current = node;\n\t\twhile (current.files.size === 0 && current.dirs.size === 1) {\n\t\t\tconst [[nextDir, nextNode]] = [...current.dirs.entries()];\n\t\t\tparts.push(nextDir!);\n\t\t\tcurrent = nextNode!;\n\t\t}\n\t\treturn { label: parts.join(\"/\"), node: current };\n\t};\n\tconst render = (node: FindTreeNode, depth: number): void => {\n\t\tfor (const file of [...node.files].sort()) lines.push(file);\n\t\tfor (const [dir, child] of [...node.dirs.entries()].sort(([a], [b]) => a.localeCompare(b))) {\n\t\t\tconst folded = collapse(dir, child);\n\t\t\tlines.push(`${\"#\".repeat(depth + 1)} ${folded.label}/`);\n\t\t\trender(folded.node, depth + 1);\n\t\t}\n\t};\n\trender(root, 0);\n\treturn lines.join(\"\\n\");\n}\nexport interface FindToolDetails { truncation?: TruncationResult; resultLimitReached?: number; timedOut?: boolean; truncated?: boolean; skippedMissingPaths?: string[]; missingPaths?: string[]; scopePath?: string; fileCount?: number; files?: string[]; meta?: { limits?: { resultLimit?: number }; truncation?: TruncationResult } }\nfunction buildFindResult(\n\trelativized: string[],\n\teffectiveLimit: number,\n\ttimedOut: boolean,\n\ttimeoutMs: number,\n\tskippedMissingPaths: string[] = [],\n\tresultLimitReached = false,\n): {\n\tcontent: Array<{ type: \"text\"; text: string }>;\n\tdetails: FindToolDetails | undefined;\n} {\n\tconst rawOutput = relativized.length > 0 ? formatFindTree(relativized) : \"No files found matching pattern\";\n\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\tlet resultOutput = truncation.content;\n\tconst details: FindToolDetails = { scopePath: \".\", fileCount: relativized.length, files: relativized, meta: { limits: { resultLimit: effectiveLimit } } };\n\tconst notices: string[] = [];\n\tif (resultLimitReached) {\n\t\tnotices.push(`${effectiveLimit} results limit reached. Refine pattern or path to narrow results`);\n\t\tdetails.resultLimitReached = effectiveLimit;\n\t}\n\tif (timedOut) { notices.push(`find timed out after ${formatTimeoutSeconds(timeoutMs)}s; returning ${relativized.length} partial matches — increase timeout or narrow pattern`); details.timedOut = true; details.truncated = true; }\n\tif (skippedMissingPaths.length > 0) {\n\t\tnotices.push(`Skipped missing paths: ${skippedMissingPaths.join(\", \")}`);\n\t\tdetails.skippedMissingPaths = skippedMissingPaths;\n\t\tdetails.missingPaths = skippedMissingPaths;\n\t}\n\tif (truncation.truncated) {\n\t\tnotices.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit reached`);\n\t\tdetails.truncation = truncation;\n\t\tdetails.meta = { ...(details.meta ?? {}), truncation };\n\t\tdetails.truncated = true;\n\t}\n\tif (notices.length > 0) {\n\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t}\n\treturn { content: [{ type: \"text\", text: resultOutput }], details };\n}\n/** Pluggable operations for remote/container find backends. */\nexport interface FindOperations {\n\tstat?: (path: string) => Promise<{ isFile: boolean; isDirectory: boolean }> | { isFile: boolean; isDirectory: boolean } | undefined;\n\texists: (path: string) => Promise<boolean> | boolean;\n\tglob: (pattern: string, cwd: string, options: { ignore: string[]; limit: number; hidden: boolean }) => Promise<string[]> | string[];\n}\nconst defaultFindOperations: FindOperations = {\n\texists: pathExists,\n\tglob: () => [],\n};\nexport interface FindToolOptions {\n\t/** Custom operations for find. Default: local filesystem plus fd */\n\toperations?: FindOperations;\n}\nfunction stripTrailingForwardSlashes(value: string): string { let end = value.length; while (end > 0 && value[end - 1] === \"/\") end--; return value.slice(0, end); }\n\nfunction formatFindCall(\n\targs: { paths?: string[]; limit?: number } | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.ts\").theme,\n): string {\n\tconst paths = Array.isArray(args?.paths) ? args.paths.map((item) => splitPathLikeGlob(item).glob ? item : `${stripTrailingForwardSlashes(item)}/**/*`).join(\", \") : \"<paths>\";\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"find\"))} ${theme.fg(\"accent\", paths)}`;\n\tif (args?.limit !== undefined) text += theme.fg(\"toolOutput\", ` (limit ${args.limit})`);\n\treturn text;\n}\nfunction formatFindResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: FindToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.ts\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"Expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\tconst resultLimit = result.details?.resultLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst timedOut = result.details?.timedOut;\n\tif (resultLimit || truncation?.truncated || timedOut) {\n\t\tconst warnings: string[] = [];\n\t\tif (resultLimit) warnings.push(`${resultLimit} results limit`);\n\t\tif (timedOut) warnings.push(\"timeout\");\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\nexport function createFindToolDefinition(\n\tcwd: string,\n\toptions?: FindToolOptions,\n): ToolDefinition<typeof findSchema, FindToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"find\",\n\t\tlabel: \"find\",\n\t\tdescription: \"Find filesystem paths by glob; use search when you need content matches instead of path matches.\",\n\t\tpromptSnippet: \"Find filesystem paths by glob.\",\n\t\tparameters: findSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\tparams: FindToolInput,\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tlet stopChild: (() => void) | undefined;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tstopChild = undefined;\n\t\t\t\t\tfn();\n\t\t\t\t};\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tstopChild?.();\n\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t};\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tconst { limit, hidden, gitignore, timeout } = params;\n\t\t\t\tconst paths = params.paths;\n\t\t\t\tconst resourceCtx = _ctx as InternalResourceContext | undefined;\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst ops = customOps ?? defaultFindOperations;\n\t\t\t\t\t\tconst targets = normalizeFindTargets(cwd, await expandDelimitedFindPaths(paths, cwd, ops, resourceCtx, !!customOps), !!customOps);\n\t\t\t\t\t\tconst searchPaths = targets.map((target) => target.searchPath);\n\t\t\t\t\t\tconst effectiveLimit = normalizeLimit(limit);\n\t\t\t\t\t\tconst timeoutMs = normalizeTimeoutMs(timeout);\n\t\t\t\t\t\tconst emitUpdate = (files: string[]) => _onUpdate?.({ content: [{ type: \"text\", text: files.join(\"\\n\") || \"No files found matching pattern\" }], details: { scopePath: \".\", files, fileCount: files.length, truncated: false } });\n\t\t\t\t\t\tconst exactFileResults: string[] = [];\n\t\t\t\t\t\tconst searchableTargets: FindTarget[] = [];\n\t\t\t\t\t\tconst skippedMissingPaths: string[] = [];\n\t\t\t\t\t\tfor (const target of targets) {\n\t\t\t\t\t\t\tif (target.searchPath === path.parse(target.searchPath).root) throw new Error(\"Refusing to search filesystem root with find; provide a narrower path.\");\n\t\t\t\t\t\t\tconst stat = customOps ? await customOps.stat?.(target.searchPath) : await fsStat(target.searchPath).catch(() => undefined);\n\t\t\t\t\t\t\tif (!stat && targets.length > 1 && !customOps) {\n\t\t\t\t\t\t\t\tskippedMissingPaths.push(target.inputPath);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!stat && targets.length === 1 && !customOps) {\n\t\t\t\t\t\t\t\tthrow new Error(`ENOENT: Path not found: ${target.searchPath}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (target.exactPathInput) {\n\t\t\t\t\t\t\t\tconst isFile = typeof stat?.isFile === \"function\" ? stat.isFile() : stat?.isFile;\n\t\t\t\t\t\t\t\tif (isFile) {\n\t\t\t\t\t\t\t\t\texactFileResults.push(formatExactFoundPath(target.searchPath, cwd));\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsearchableTargets.push(target);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (exactFileResults.length > effectiveLimit || searchableTargets.length === 0) {\n\t\t\t\t\t\t\tconst resultLimitReached = exactFileResults.length > effectiveLimit;\n\t\t\t\t\t\t\tsettle(() => resolve(buildFindResult(exactFileResults.slice(0, effectiveLimit), effectiveLimit, false, timeoutMs, skippedMissingPaths, resultLimitReached)));\n\t\t\t\t\t\t\temitUpdate(exactFileResults.slice(0, effectiveLimit));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (customOps?.glob) {\n\t\t\t\t\t\t\tconst deadline = Date.now() + timeoutMs;\n\t\t\t\t\t\t\tlet timedOut = false;\n\t\t\t\t\t\t\tconst relativized: string[] = [...exactFileResults];\n\t\t\t\t\t\t\tlet customLimitReached = false;\n\t\t\t\t\t\t\tfor (const target of searchableTargets) {\n\t\t\t\t\t\t\t\tif (!(await ops.exists(target.searchPath))) {\n\t\t\t\t\t\t\t\t\tif (targets.length > 1) {\n\t\t\t\t\t\t\t\t\t\tskippedMissingPaths.push(target.inputPath);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${target.searchPath}`)));\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst remaining = effectiveLimit - relativized.length;\n\t\t\t\t\t\t\t\tconst remainingMs = deadline - Date.now();\n\t\t\t\t\t\t\t\tif (remaining <= 0) {\n\t\t\t\t\t\t\t\t\tconst ignore = findTargetMentionsNodeModules(target) ? [\"**/.git/**\"] : [\"**/node_modules/**\", \"**/.git/**\"];\n\t\t\t\t\t\t\t\t\tconst probe = await Promise.resolve(ops.glob(target.pattern, target.searchPath, { ignore, limit: 1, hidden: hidden !== false }));\n\t\t\t\t\t\t\t\t\tif (probe.some((p) => hidden !== false || !containsHiddenSegment(p))) customLimitReached = true;\n\t\t\t\t\t\t\t\t\tif (customLimitReached) break;\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (remainingMs <= 0) {\n\t\t\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst timeoutResult = Symbol(\"find-timeout\");\n\t\t\t\t\t\t\t\tlet raceTimer: ReturnType<typeof setTimeout> | undefined;\n\t\t\t\t\t\t\t\tconst ignore = findTargetMentionsNodeModules(target) ? [\"**/.git/**\"] : [\"**/node_modules/**\", \"**/.git/**\"];\n\t\t\t\t\t\t\t\tconst results = await Promise.race<string[] | symbol>([\n\t\t\t\t\t\t\t\t\tPromise.resolve(ops.glob(target.pattern, target.searchPath, { ignore, limit: remaining + 1, hidden: hidden !== false })),\n\t\t\t\t\t\t\t\t\tnew Promise<typeof timeoutResult>((resolveTimeout) => {\n\t\t\t\t\t\t\t\t\t\traceTimer = setTimeout(() => resolveTimeout(timeoutResult), remainingMs);\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t\tif (raceTimer) clearTimeout(raceTimer);\n\t\t\t\t\t\t\t\tif (!Array.isArray(results)) {\n\t\t\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (target.exactPathInput && results.length === 0) { const stat = await customOps.stat?.(target.searchPath); if (!stat?.isDirectory) relativized.push(formatExactFoundPath(target.searchPath, cwd)); continue; }\n\t\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst visible = results.filter((p) => hidden !== false || !containsHiddenSegment(p));\n\t\t\t\t\t\t\t\tif (visible.length > remaining) customLimitReached = true;\n\t\t\t\t\t\t\t\trelativized.push(...visible.slice(0, remaining).map((p) => formatFoundPath(p, target.searchPath, searchPaths, cwd)));\n\t\t\t\t\t\t\t\temitUpdate(relativized);\n\t\t\t\t\t\t\t\tif (customLimitReached) break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() => resolve(buildFindResult(relativized, effectiveLimit, timedOut, timeoutMs, skippedMissingPaths, customLimitReached)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst nativeBinding = loadNativeSearchBinding();\n\t\t\t\t\t\tif (nativeBinding) {\n\t\t\t\t\t\t\tconst matches: { path: string; mtime: number }[] = exactFileResults.map((path) => ({ path, mtime: Number.POSITIVE_INFINITY }));\n\t\t\t\t\t\t\tlet timedOut = false;\n\t\t\t\t\t\t\tconst deadline = Date.now() + timeoutMs;\n\t\t\t\t\t\t\tfor (const target of searchableTargets) {\n\t\t\t\t\t\t\t\tconst remainingMs = deadline - Date.now();\n\t\t\t\t\t\t\t\tif (remainingMs <= 0) {\n\t\t\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst result = await nativeBinding.glob({\n\t\t\t\t\t\t\t\t\t\tpattern: target.pattern,\n\t\t\t\t\t\t\t\t\t\tpath: target.searchPath,\n\t\t\t\t\t\t\t\t\t\trecursive: false,\n\t\t\t\t\t\t\t\t\t\thidden: hidden !== false,\n\t\t\t\t\t\t\t\t\t\tgitignore: gitignore !== false,\n\t\t\t\t\t\t\t\t\t\tincludeNodeModules: findTargetMentionsNodeModules(target),\n\t\t\t\t\t\t\t\t\t\tmaxResults: effectiveLimit + 1,\n\t\t\t\t\t\t\t\t\t\tcache: false,\n\t\t\t\t\t\t\t\t\t\tsortByMtime: true,\n\t\t\t\t\t\t\t\t\t\ttimeoutMs: remainingMs,\n\t\t\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tmatches.push(...result.matches.map((match) => { const fileType = match.fileType ?? (match as { file_type?: number }).file_type; const isDir = (fileType === 2 || fileType === \"Dir\" || (fileType === undefined && statSync(path.resolve(target.searchPath, match.path), { throwIfNoEntry: false })?.isDirectory())) && !match.path.endsWith(\"/\"); const matchPath = isDir ? `${match.path}/` : match.path; return { path: formatFoundPath(matchPath, target.searchPath, searchPaths, cwd), mtime: match.mtime ?? 0 }; }));\n\t\t\t\t\t\t\t\t\temitUpdate(matches.map((match) => match.path));\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tif (String(error).toLowerCase().includes(\"timed out\")) {\n\t\t\t\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst uniqueMatches = [...matches.reduce((map, match) => { const previous = map.get(match.path); if (!previous || match.mtime > previous.mtime) map.set(match.path, match); return map; }, new Map<string, { path: string; mtime: number }>()).values()];\n\t\t\t\t\t\t\tuniqueMatches.sort((a, b) => b.mtime - a.mtime || a.path.localeCompare(b.path));\n\t\t\t\t\t\t\tconst resultLimitReached = uniqueMatches.length > effectiveLimit;\n\t\t\t\t\t\t\tsettle(() => resolve(buildFindResult(uniqueMatches.slice(0, effectiveLimit).map((match) => match.path), effectiveLimit, timedOut, timeoutMs, skippedMissingPaths, resultLimitReached)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst fdPath = await ensureTool(\"fd\", true);\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!fdPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"fd is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet timedOut = false;\n\t\t\t\t\t\tconst relativized: string[] = [...exactFileResults];\n\t\t\t\t\t\tconst deadline = Date.now() + timeoutMs;\n\t\t\t\t\t\tconst runFdForTarget = async (target: FindTarget, remaining: number): Promise<boolean> => {\n\t\t\t\t\t\t\tconst args: string[] = [\"--glob\", \"--color=never\", \"--no-require-git\", \"--max-results\", String(remaining + 1)];\n\t\t\t\t\t\t\tif (hidden !== false) args.push(\"--hidden\");\n\t\t\t\t\t\t\tif (gitignore === false) args.push(\"--no-ignore\");\n\t\t\t\t\t\t\tif (!findTargetMentionsNodeModules(target)) args.push(\"--exclude\", \"node_modules\");\n\t\t\t\t\t\t\tlet fdPattern = target.pattern;\n\t\t\t\t\t\t\tif (target.pattern.includes(\"/\")) {\n\t\t\t\t\t\t\t\targs.push(\"--full-path\");\n\t\t\t\t\t\t\t\tif (!target.pattern.startsWith(\"/\") && !target.pattern.startsWith(\"**/\") && target.pattern !== \"**\") fdPattern = `**/${target.pattern}`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\targs.push(\"--\", fdPattern, target.searchPath);\n\t\t\t\t\t\t\tconst remainingMs = deadline - Date.now();\n\t\t\t\t\t\t\tif (remainingMs <= 0) {\n\t\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await new Promise<boolean>((resolveTarget, rejectTarget) => {\n\t\t\t\t\t\t\t\tconst child = spawn(fdPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\t\t\tconst lines: string[] = [];\n\t\t\t\t\t\t\t\tstopChild = () => {\n\t\t\t\t\t\t\t\t\tif (!child.killed) child.kill();\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tconst targetTimer = setTimeout(() => {\n\t\t\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\t\t\tstopChild?.();\n\t\t\t\t\t\t\t\t}, remainingMs);\n\t\t\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\t\t\tclearTimeout(targetTimer);\n\t\t\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\trl.on(\"line\", (line) => lines.push(line));\n\t\t\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\t\t\trejectTarget(new Error(`Failed to run fd: ${error.message}`));\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\t\t\trejectTarget(new Error(\"Operation aborted\"));\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (!timedOut && code !== 0 && lines.length === 0) {\n\t\t\t\t\t\t\t\t\t\trejectTarget(new Error(stderr.trim() || `fd exited with code ${code}`));\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tfor (const rawLine of lines.slice(0, remaining)) {\n\t\t\t\t\t\t\t\t\t\tconst line = rawLine.replace(/\\r$/, \"\").trim();\n\t\t\t\t\t\t\t\t\t\tif (line) { const found = statSync(path.resolve(target.searchPath, line), { throwIfNoEntry: false })?.isDirectory() && !line.endsWith(\"/\") ? `${line}/` : line; relativized.push(formatFoundPath(found, target.searchPath, searchPaths, cwd)); }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\temitUpdate(relativized);\n\t\t\t\t\t\t\t\t\tresolveTarget(lines.length > Math.max(0, remaining));\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t};\n\t\t\t\t\t\tlet resultLimitReached = false;\n\t\t\t\t\t\tfor (const target of searchableTargets) {\n\t\t\t\t\t\t\tconst remaining = effectiveLimit - relativized.length;\n\t\t\t\t\t\t\tif (timedOut) break;\n\t\t\t\t\t\t\tif (remaining <= 0) { if (await runFdForTarget(target, 0)) { resultLimitReached = true; break; } continue; }\n\t\t\t\t\t\t\tconst targetLimitReached = await runFdForTarget(target, remaining);\n\t\t\t\t\t\t\tif (targetLimitReached) { resultLimitReached = true; break; }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsettle(() => resolve(buildFindResult(relativized.slice(0, effectiveLimit), effectiveLimit, timedOut, timeoutMs, skippedMissingPaths, resultLimitReached)));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\t\t\tsettle(() => reject(error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\nexport function createFindTool(cwd: string, options?: FindToolOptions): AgentTool<typeof findSchema> {\n\treturn wrapToolDefinition(createFindToolDefinition(cwd, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../../../src/core/tools/find.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAOtF,OAAO,EAAiC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEnG,QAAA,MAAM,UAAU;;;;;;EAMmB,CAAC;AACpC,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AA+FtD,MAAM,WAAW,eAAe;IAAG,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE;YAAE,WAAW,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;QAAC,UAAU,CAAC,EAAE,gBAAgB,CAAA;KAAE,CAAA;CAAE;AAsCxU,+DAA+D;AAC/D,MAAM,WAAW,cAAc;IAC9B,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,WAAW,EAAE,OAAO,CAAA;KAAE,CAAC,GAAG;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,WAAW,EAAE,OAAO,CAAA;KAAE,GAAG,SAAS,CAAC;IACpI,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IACrD,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,EAAE,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC;CACpI;AAKD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AA6CD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAmRhE;AACD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"glob-path-utils.d.ts","sourceRoot":"","sources":["../../../src/core/tools/glob-path-utils.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,iBAAiB;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAM5D;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAalE"
|
|
1
|
+
{"version":3,"file":"glob-path-utils.d.ts","sourceRoot":"","sources":["../../../src/core/tools/glob-path-utils.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,iBAAiB;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAM5D;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAalE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grep.d.ts","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAKtF,OAAO,EAIN,KAAK,gBAAgB,EAGrB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,UAAU;;;;;;;;;;;;;;;;;;EAsBmB,CAAC;AAEpC,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAGtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAeD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,mEAAmE;IACnE,WAAW,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAClE,2CAA2C;IAC3C,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;CAC7D;AAOD,MAAM,WAAW,eAAe;IAC/B,yEAAyE;IACzE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,2JAA2J;IAC3J,WAAW,CAAC,EAAE,OAAO,CAAC;CACtB;AAqED,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAsUhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { readFile as fsReadFile, stat as fsStat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { loadNativeSearchBinding, type NativeGrepMatch } from \"./search-native.ts\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\ttype: Type.Optional(Type.String({ description: \"File type filter for native grep.\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tcontextBefore: Type.Optional(Type.Number({ description: \"Lines to show before each match.\" })),\n\tcontextAfter: Type.Optional(Type.Number({ description: \"Lines to show after each match.\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n\toffset: Type.Optional(Type.Number({ description: \"Skip first N matches.\" })),\n\tmode: Type.Optional(Type.Union([Type.Literal(\"content\"), Type.Literal(\"count\"), Type.Literal(\"filesWithMatches\")])),\n\tmaxCountPerFile: Type.Optional(Type.Number({ description: \"Maximum matches per file.\" })),\n\thidden: Type.Optional(Type.Boolean({ description: \"Search hidden files (default true).\" })),\n\tcache: Type.Optional(Type.Boolean({ description: \"Use native cache.\" })),\n\ttimeoutMs: Type.Optional(Type.Number({ description: \"Native grep timeout in milliseconds.\" })),\n\tgitignore: Type.Optional(Type.Boolean({ description: \"Respect .gitignore files (default: true)\" })),\n}, { additionalProperties: false });\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\ntype RipgrepMatchEvent = {\n\ttype: \"match\";\n\tdata?: {\n\t\tpath?: { text?: unknown };\n\t\tline_number?: unknown;\n\t\tlines?: { text?: unknown };\n\t};\n};\n\nfunction isRipgrepMatchEvent(event: unknown): event is RipgrepMatchEvent {\n\treturn typeof event === \"object\" && event !== null && \"type\" in event && event.type === \"match\";\n}\n\n/**\n * Pluggable operations for the grep tool.\n * Override these to delegate search to remote systems (for example SSH).\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise<boolean> | boolean;\n\t/** Read file contents for context lines */\n\treadFile: (absolutePath: string) => Promise<string> | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: async (p) => (await fsStat(p)).isDirectory(),\n\treadFile: (p) => fsReadFile(p, \"utf-8\"),\n};\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n\t/** Enable shared native filesystem scan cache. Defaults to false; search callers also disable it to stay fresh across out-of-band filesystem mutations. */\n\tnativeCache?: boolean;\n}\n\nfunction formatGrepCall(\n\targs: { pattern: string; path?: string; glob?: string; limit?: number } | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.ts\").theme,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: GrepToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.ts\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"Expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nfunction formatNativeGrepMatch(match: NativeGrepMatch, displayPath: string): string[] {\n\tconst lines: string[] = [];\n\tfor (const contextLine of match.contextBefore ?? []) {\n\t\tlines.push(`${displayPath}-${contextLine.lineNumber}- ${contextLine.line}`);\n\t}\n\tlines.push(`${displayPath}:${match.lineNumber}: ${match.line}`);\n\tfor (const contextLine of match.contextAfter ?? []) {\n\t\tlines.push(`${displayPath}-${contextLine.lineNumber}- ${contextLine.line}`);\n\t}\n\treturn lines;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition<typeof grepSchema, GrepToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t\tgitignore,\n\t\t\t\ttype,\n\t\t\t\tcontextBefore,\n\t\t\t\tcontextAfter,\n\t\t\t\toffset,\n\t\t\t\tmode,\n\t\t\t\tmaxCountPerFile,\n\t\t\t\thidden,\n\t\t\t\tcache,\n\t\t\t\ttimeoutMs,\n\t\t\t}: GrepToolInput,\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst contextValue = context && context > 0 ? context : 0;\n\t\t\t\t\t\tconst contextBeforeValue = contextBefore ?? contextValue;\n\t\t\t\t\t\tconst contextAfterValue = contextAfter ?? contextValue;\n\t\t\t\t\t\tconst nativeCache = options?.nativeCache === true;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tif (!path.isAbsolute(filePath)) return filePath.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, filePath);\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) return relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tif (!customOps && !literal) {\n\t\t\t\t\t\t\tconst nativeBinding = loadNativeSearchBinding();\n\t\t\t\t\t\t\tif (nativeBinding) {\n\t\t\t\t\t\t\t\tconst nativeResult = await nativeBinding.grep({\n\t\t\t\t\t\t\t\t\tpattern,\n\t\t\t\t\t\t\t\t\tpath: searchPath,\n\t\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\t\tglob,\n\t\t\t\t\t\t\t\t\tignoreCase,\n\t\t\t\t\t\t\t\thidden: hidden ?? true,\n\t\t\t\t\t\t\t\tgitignore: gitignore !== false,\n\t\t\t\t\t\t\t\tcache: cache ?? nativeCache,\n\t\t\t\t\t\t\t\tmaxCount: mode === \"count\" ? undefined : effectiveLimit + 1,\n\t\t\t\t\t\t\t\toffset,\n\t\t\t\t\t\t\t\tcontext: contextBefore === undefined && contextAfter === undefined ? contextValue : undefined,\n\t\t\t\t\t\t\t\tcontextBefore,\n\t\t\t\t\t\t\t\tcontextAfter,\n\t\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\t\tmode,\n\t\t\t\t\t\t\t\tmaxCountPerFile,\n\t\t\t\t\t\t\t\tmaxColumns: GREP_MAX_LINE_LENGTH,\n\t\t\t\t\t\t\t\tmultiline: pattern.includes(\"\\n\") || pattern.includes(\"\\\\n\"),\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\ttimeoutMs: timeoutMs ?? 30_000,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (nativeResult.error) throw new Error(nativeResult.error);\n\t\t\t\t\t\t\t\tif (nativeResult.matches.length === 0) {\n\t\t\t\t\t\t\t\t\tsettle(() => resolve({ content: [{ type: \"text\", text: mode === \"count\" ? \"0\" : \"No matches found\" }], details: undefined }));\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst visibleMatches = nativeResult.matches.slice(0, effectiveLimit);\n\t\t\t\t\t\t\t\tconst filesOutput = mode === \"filesWithMatches\" && !isDirectory && (offset ?? 0) > 0 ? \"\" : visibleMatches.map((match) => formatPath(match.path)).join(\"\\n\");\n\t\t\t\t\t\t\t\tconst countOutput = String(Math.max(0, nativeResult.totalMatches - (offset ?? 0)));\n\t\t\t\t\t\t\t\tconst rawOutput = mode === \"count\" ? countOutput : mode === \"filesWithMatches\" ? (filesOutput || \"No matches found\") : visibleMatches.flatMap((match) => formatNativeGrepMatch(match, formatPath(match.path))).join(\"\\n\");\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\t\tif (nativeResult.matches.length > effectiveLimit || nativeResult.limitReached) {\n\t\t\t\t\t\t\t\t\tnotices.push(`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`);\n\t\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (visibleMatches.some((match) => match.truncated)) {\n\t\t\t\t\t\t\t\t\tnotices.push(`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`);\n\t\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t\tsettle(() => resolve({ content: [{ type: \"text\", text: output }], details: Object.keys(details).length > 0 ? details : undefined }));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\tconst fileCache = new Map<string, string[]>();\n\t\t\t\t\t\tconst getFileLines = async (filePath: string): Promise<string[]> => {\n\t\t\t\t\t\t\tlet lines = fileCache.get(filePath);\n\t\t\t\t\t\t\tif (!lines) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst content = await ops.readFile(filePath);\n\t\t\t\t\t\t\t\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\tlines = [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfileCache.set(filePath, lines);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn lines;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\", true);\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"ripgrep (rg) is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\"];\n\t\t\t\t\t\tif (hidden !== false) args.push(\"--hidden\");\n\t\t\t\t\t\tif (gitignore === false) args.push(\"--no-ignore\");\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\tif (pattern.includes(\"\\n\") || pattern.includes(\"\\\\n\")) args.push(\"--multiline\");\n\t\t\t\t\t\tif (type) args.push(\"--type\", type);\n\t\t\t\t\t\tif (maxCountPerFile !== undefined) args.push(\"--max-count\", String(maxCountPerFile));\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob);\n\t\t\t\t\t\targs.push(\"--\", pattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst timeoutTimer = timeoutMs !== undefined ? setTimeout(() => stopChild(), timeoutMs) : undefined;\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\tif (timeoutTimer) clearTimeout(timeoutTimer);\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tconst formatBlock = async (filePath: string, lineNumber: number): Promise<string[]> => {\n\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\tconst lines = await getFileLines(filePath);\n\t\t\t\t\t\t\tif (!lines.length) return [`${relativePath}:${lineNumber}: (unable to read file)`];\n\t\t\t\t\t\t\tconst block: string[] = [];\n\t\t\t\t\t\t\tconst start = contextBeforeValue > 0 ? Math.max(1, lineNumber - contextBeforeValue) : lineNumber;\n\t\t\t\t\t\t\tconst end = contextAfterValue > 0 ? Math.min(lines.length, lineNumber + contextAfterValue) : lineNumber;\n\t\t\t\t\t\t\tfor (let current = start; current <= end; current++) {\n\t\t\t\t\t\t\t\tconst lineText = lines[current - 1] ?? \"\";\n\t\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r/g, \"\");\n\t\t\t\t\t\t\t\tconst isMatchLine = current === lineNumber;\n\t\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\tif (isMatchLine) block.push(`${relativePath}:${current}: ${truncatedText}`);\n\t\t\t\t\t\t\t\telse block.push(`${relativePath}-${current}- ${truncatedText}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn block;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Collect matches during streaming, then format them after rg exits.\n\t\t\t\t\t\tconst matches: Array<{ filePath: string; lineNumber: number; lineText?: string }> = [];\n\t\t\t\t\t\tlet seenMatches = 0, seenFiles = 0; const seenFilePaths = new Set<string>(), filesWithMatches = new Set<string>();\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (!line.trim() || (mode !== \"count\" && mode !== \"filesWithMatches\" && matchCount >= effectiveLimit)) return;\n\t\t\t\t\t\t\tlet event: unknown;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line) as unknown;\n\t\t\t\t\t\t\t} catch { return; }\n\t\t\t\t\t\t\tif (isRipgrepMatchEvent(event)) {\n\t\t\t\t\t\t\t\tconst filePath = event.data?.path?.text;\n\t\t\t\t\t\t\t\tif (mode === \"filesWithMatches\") { if (typeof filePath === \"string\") { const formatted = formatPath(filePath); if (!seenFilePaths.has(formatted)) { seenFilePaths.add(formatted); seenFiles++; if (offset === undefined || seenFiles > offset) filesWithMatches.add(formatted); } } matchCount = filesWithMatches.size; if (matchCount >= effectiveLimit) { matchLimitReached = true; stopChild(true); } return; }\n\t\t\t\t\t\t\t\tseenMatches++;\n\t\t\t\t\t\t\t\tif (mode !== \"count\" && offset !== undefined && seenMatches <= offset) return;\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\t\tconst lineText = event.data?.lines?.text;\n\t\t\t\t\t\t\t\tif (typeof filePath === \"string\") filesWithMatches.add(formatPath(filePath));\n\t\t\t\t\t\t\t\tif (typeof filePath === \"string\" && typeof lineNumber === \"number\")\n\t\t\t\t\t\t\t\t\tmatches.push({ filePath, lineNumber, lineText: typeof lineText === \"string\" ? lineText : undefined });\n\t\t\t\t\t\t\t\tif (mode !== \"count\" && matchCount >= effectiveLimit) { matchLimitReached = true; stopChild(true); }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", async (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() => resolve({ content: [{ type: \"text\", text: mode === \"count\" ? \"0\" : \"No matches found\" }], details: undefined }));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (mode === \"count\" || mode === \"filesWithMatches\") {\n\t\t\t\t\t\t\t\tsettle(() => resolve({ content: [{ type: \"text\", text: mode === \"count\" ? String(Math.max(0, matchCount - (offset ?? 0))) : ([...filesWithMatches].join(\"\\n\") || \"No matches found\") }], details: matchLimitReached ? { matchLimitReached: effectiveLimit } : undefined }));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Format matches after streaming finishes so custom readFile() backends can be async.\n\t\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\t\tif (contextBeforeValue === 0 && contextAfterValue === 0 && match.lineText !== undefined) {\n\t\t\t\t\t\t\t\t\tconst relativePath = formatPath(match.filePath);\n\t\t\t\t\t\t\t\t\tconst sanitized = match.lineText\n\t\t\t\t\t\t\t\t\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t\t\t\t\t\t\t\t\t.replace(/\\r/g, \"\")\n\t\t\t\t\t\t\t\t\t\t.replace(/\\n$/, \"\");\n\t\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\t\toutputLines.push(`${relativePath}:${match.lineNumber}: ${truncatedText}`);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tconst block = await formatBlock(match.filePath, match.lineNumber);\n\t\t\t\t\t\t\t\t\toutputLines.push(...block);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"grep.d.ts","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAKtF,OAAO,EAIN,KAAK,gBAAgB,EAGrB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,UAAU;;;;;;;;;;;;;;;;;;EAsBmB,CAAC;AAEpC,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAGtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAeD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,mEAAmE;IACnE,WAAW,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAClE,2CAA2C;IAC3C,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;CAC7D;AAOD,MAAM,WAAW,eAAe;IAC/B,yEAAyE;IACzE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,2JAA2J;IAC3J,WAAW,CAAC,EAAE,OAAO,CAAC;CACtB;AAqED,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAsUhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/apply.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAU,WAAW,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAsHpE,iFAAiF;AACjF,eAAO,MAAM,oBAAoB,QAAyB,CAAC;AAklB3D;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,WAAW,CAqG5E","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Apply a parsed list of {@link Edit}s to a text body and return the\n * post-edit lines plus any diagnostic warnings. Pure function: no FS, no\n * mutation of the input.\n *\n * Replacement groups are first normalized by {@link repairReplacementBoundaries},\n * which absorbs common model mistakes where a payload restates unchanged range\n * boundaries or duplicates/drops structural closers.\n */\nimport { afterInsertLandingShiftWarning, blockInsertLandingShiftWarning, UNRESOLVED_BLOCK_INTERNAL } from \"./messages.js\";\nimport { cloneCursor } from \"./tokenizer.js\";\nimport type { Anchor, ApplyResult, Cursor, Edit } from \"./types.js\";\n\ntype LineOrigin = \"original\" | \"insert\" | \"replacement\";\n\ntype InsertEdit = Extract<Edit, { kind: \"insert\" }>;\ntype DeleteEdit = Extract<Edit, { kind: \"delete\" }>;\ntype AppliedEdit = InsertEdit | DeleteEdit;\n\ninterface IndexedEdit {\n\tedit: AppliedEdit;\n\tidx: number;\n}\n\nfunction isReplacementInsert(edit: Edit): edit is InsertEdit & { mode: \"replacement\" } {\n\treturn edit.kind === \"insert\" && edit.mode === \"replacement\";\n}\n\nfunction getCursorAnchors(cursor: Cursor): Anchor[] {\n\treturn cursor.kind === \"before_anchor\" || cursor.kind === \"after_anchor\" ? [cursor.anchor] : [];\n}\n\nfunction getEditAnchors(edit: AppliedEdit): Anchor[] {\n\tif (edit.kind === \"delete\") return [edit.anchor];\n\treturn getCursorAnchors(edit.cursor);\n}\n\nfunction trailingPhantomLine(fileLines: readonly string[]): number {\n\t// `split(\"\\n\")` on a newline-terminated file yields a trailing \"\" sentinel.\n\t// It is addressable for inserts (append-past-end), but it is not real\n\t// content. Deleting it only strips the file's final newline, so ignore delete\n\t// edits that land there; inclusive ranges ending at EOF then do the intended\n\t// thing and delete through the last concrete line.\n\treturn fileLines.length > 1 && fileLines[fileLines.length - 1] === \"\" ? fileLines.length : 0;\n}\n\nfunction dropTrailingPhantomDeletes(edits: AppliedEdit[], fileLines: readonly string[]): AppliedEdit[] {\n\tconst phantomLine = trailingPhantomLine(fileLines);\n\tif (phantomLine === 0) return edits;\n\treturn edits.filter(edit => edit.kind !== \"delete\" || edit.anchor.line !== phantomLine);\n}\n\n/**\n * Verify every anchored edit points at an existing line. File-version binding is\n * checked once per section via the header hash before this function runs.\n */\nfunction validateLineBounds(edits: readonly AppliedEdit[], fileLines: readonly string[]): void {\n\tfor (const edit of edits) {\n\t\tfor (const anchor of getEditAnchors(edit)) {\n\t\t\tif (anchor.line < 1 || anchor.line > fileLines.length) {\n\t\t\t\tthrow new Error(`Line ${anchor.line} does not exist (file has ${fileLines.length} lines)`);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction cloneAppliedEdit(edit: AppliedEdit, index: number): AppliedEdit {\n\tif (edit.kind === \"delete\") return { ...edit, anchor: { ...edit.anchor }, index };\n\treturn { ...edit, cursor: cloneCursor(edit.cursor), index };\n}\n\nfunction insertAtStart(fileLines: string[], lineOrigins: LineOrigin[], lines: string[]): void {\n\tif (lines.length === 0) return;\n\tconst origins = lines.map((): LineOrigin => \"insert\");\n\tif (fileLines.length === 1 && fileLines[0] === \"\") {\n\t\tfileLines.splice(0, 1, ...lines);\n\t\tlineOrigins.splice(0, 1, ...origins);\n\t\treturn;\n\t}\n\tfileLines.splice(0, 0, ...lines);\n\tlineOrigins.splice(0, 0, ...origins);\n}\n\nfunction insertAtEnd(fileLines: string[], lineOrigins: LineOrigin[], lines: string[]): number | undefined {\n\tif (lines.length === 0) return undefined;\n\tconst origins = lines.map((): LineOrigin => \"insert\");\n\tif (fileLines.length === 1 && fileLines[0] === \"\") {\n\t\tfileLines.splice(0, 1, ...lines);\n\t\tlineOrigins.splice(0, 1, ...origins);\n\t\treturn 1;\n\t}\n\tconst hasTrailingNewline = fileLines.length > 0 && fileLines[fileLines.length - 1] === \"\";\n\tconst insertIndex = hasTrailingNewline ? fileLines.length - 1 : fileLines.length;\n\tfileLines.splice(insertIndex, 0, ...lines);\n\tlineOrigins.splice(insertIndex, 0, ...origins);\n\treturn insertIndex + 1;\n}\n\nfunction bucketAnchorEditsByLine(edits: IndexedEdit[]): Map<number, IndexedEdit[]> {\n\tconst byLine = new Map<number, IndexedEdit[]>();\n\tfor (const entry of edits) {\n\t\tconst line =\n\t\t\tentry.edit.kind === \"delete\"\n\t\t\t\t? entry.edit.anchor.line\n\t\t\t\t: entry.edit.cursor.kind === \"before_anchor\" || entry.edit.cursor.kind === \"after_anchor\"\n\t\t\t\t\t? entry.edit.cursor.anchor.line\n\t\t\t\t\t: 0;\n\t\tconst bucket = byLine.get(line);\n\t\tif (bucket) bucket.push(entry);\n\t\telse byLine.set(line, [entry]);\n\t}\n\treturn byLine;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Replacement-boundary repair\n//\n// Models routinely miscount a replacement range's edges. Sometimes the payload\n// re-states unchanged lines that still live on both sides of the range\n// (duplicating a function header and final statement); sometimes it only\n// re-states or omits a structural closer, which leaves delimiter balance broken.\n//\n// A balance-neutral boundary-echo repair fires only when both the leading and\n// trailing payload edges are exact copies of the surviving lines outside the\n// range. One-sided content echoes are left alone unless delimiter-balance repair\n// proves they are duplicated structural boundaries. This preserves intended\n// duplicate statements while absorbing the common \"body includes the unchanged\n// wrapper\" mistake.\n\n/** A line that is nothing but closing delimiters: `}`, `)`, `];`, `})`, `},`. */\nexport const STRUCTURAL_CLOSER_RE = /^\\s*[)\\]}]+[;,]?\\s*$/;\n\ninterface DelimiterBalance {\n\tparen: number;\n\tbracket: number;\n\tbrace: number;\n}\n\n/**\n * Net `()` / `[]` / `{}` delta across `lines`, skipping delimiters inside line\n * comments (`//`), block comments, and string/template literals. Block-comment\n * and backtick-template state carry across lines; `\"` / `'` reset at EOL since\n * they cannot span lines. Deliberately language-light: constructs it cannot\n * classify (e.g. regex literals) are counted naively, which can only suppress a\n * repair (the safe direction), never force one.\n */\nfunction computeDelimiterBalance(lines: readonly string[]): DelimiterBalance {\n\tconst balance: DelimiterBalance = { paren: 0, bracket: 0, brace: 0 };\n\tlet inBlockComment = false;\n\tlet quote = \"\";\n\tfor (const line of lines) {\n\t\tfor (let i = 0; i < line.length; i++) {\n\t\t\tconst ch = line[i];\n\t\t\tif (inBlockComment) {\n\t\t\t\tif (ch === \"*\" && line[i + 1] === \"/\") {\n\t\t\t\t\tinBlockComment = false;\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (quote) {\n\t\t\t\tif (ch === \"\\\\\") i++;\n\t\t\t\telse if (ch === quote) quote = \"\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === '\"' || ch === \"'\" || ch === \"`\") {\n\t\t\t\tquote = ch;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"/\" && line[i + 1] === \"/\") break;\n\t\t\tif (ch === \"/\" && line[i + 1] === \"*\") {\n\t\t\t\tinBlockComment = true;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tswitch (ch) {\n\t\t\t\tcase \"(\":\n\t\t\t\t\tbalance.paren++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \")\":\n\t\t\t\t\tbalance.paren--;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"[\":\n\t\t\t\t\tbalance.bracket++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"]\":\n\t\t\t\t\tbalance.bracket--;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"{\":\n\t\t\t\t\tbalance.brace++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"}\":\n\t\t\t\t\tbalance.brace--;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// `\"` / `'` cannot span lines; only backtick templates and block comments do.\n\t\tif (quote === '\"' || quote === \"'\") quote = \"\";\n\t}\n\treturn balance;\n}\n\nfunction balanceDelta(a: DelimiterBalance, b: DelimiterBalance): DelimiterBalance {\n\treturn { paren: a.paren - b.paren, bracket: a.bracket - b.bracket, brace: a.brace - b.brace };\n}\n\nfunction balanceNegate(a: DelimiterBalance): DelimiterBalance {\n\treturn { paren: -a.paren, bracket: -a.bracket, brace: -a.brace };\n}\n\nfunction balanceEqual(a: DelimiterBalance, b: DelimiterBalance): boolean {\n\treturn a.paren === b.paren && a.bracket === b.bracket && a.brace === b.brace;\n}\n\nfunction balanceIsZero(a: DelimiterBalance): boolean {\n\treturn a.paren === 0 && a.bracket === 0 && a.brace === 0;\n}\n\ninterface ReplacementGroup {\n\t/** Positions in the edit array of the payload inserts, in payload order. */\n\tinsertIndices: number[];\n\t/** Positions in the edit array of the range deletes, ascending by line. */\n\tdeleteIndices: number[];\n\tpayload: string[];\n\t/** First deleted line (1-indexed). */\n\tstartLine: number;\n\t/** Last deleted line (1-indexed). */\n\tendLine: number;\n}\n\n/**\n * Detect a replacement group starting at `start`: a run of `before_anchor`\n * replacement inserts sharing one source op line, immediately followed by the\n * contiguous range deletes for that same op. Mirrors how the parser lowers an\n * `replace N..M:` hunk with a body.\n */\nfunction findReplacementGroup(edits: readonly AppliedEdit[], start: number): ReplacementGroup | undefined {\n\tconst first = edits[start];\n\tif (first?.kind !== \"insert\" || first.mode !== \"replacement\" || first.cursor.kind !== \"before_anchor\") {\n\t\treturn undefined;\n\t}\n\tconst { lineNum } = first;\n\tconst anchorLine = first.cursor.anchor.line;\n\tconst insertIndices: number[] = [];\n\tconst payload: string[] = [];\n\tlet i = start;\n\tfor (; i < edits.length; i++) {\n\t\tconst edit = edits[i];\n\t\tif (edit.kind !== \"insert\" || edit.mode !== \"replacement\" || edit.lineNum !== lineNum) break;\n\t\tif (edit.cursor.kind !== \"before_anchor\" || edit.cursor.anchor.line !== anchorLine) break;\n\t\tinsertIndices.push(i);\n\t\tpayload.push(edit.text);\n\t}\n\tconst deleteIndices: number[] = [];\n\tlet expectedLine = anchorLine;\n\tfor (; i < edits.length; i++) {\n\t\tconst edit = edits[i];\n\t\tif (edit.kind !== \"delete\" || edit.lineNum !== lineNum || edit.anchor.line !== expectedLine) break;\n\t\tdeleteIndices.push(i);\n\t\texpectedLine++;\n\t}\n\tif (deleteIndices.length === 0) return undefined;\n\treturn {\n\t\tinsertIndices,\n\t\tdeleteIndices,\n\t\tpayload,\n\t\tstartLine: anchorLine,\n\t\tendLine: anchorLine + deleteIndices.length - 1,\n\t};\n}\n\n/**\n * Largest `k` such that the payload's last `k` lines exactly equal the `k`\n * surviving file lines just below the range AND dropping them zeroes `delta`.\n * Requires a non-zero `delta`: a zero-balance candidate can never account for\n * the imbalance, so intentional duplicates of ordinary statements stay intact,\n * while duplicated structural lines (closers like `});`, openers like `foo(`)\n * are dropped when they exactly explain the imbalance.\n */\nfunction findDuplicateSuffix(group: ReplacementGroup, fileLines: readonly string[], delta: DelimiterBalance): number {\n\tif (balanceIsZero(delta)) return 0;\n\tconst { payload, endLine } = group;\n\tconst maxK = Math.min(payload.length, fileLines.length - endLine);\n\tfor (let k = maxK; k >= 1; k--) {\n\t\tlet matches = true;\n\t\tfor (let t = 0; t < k; t++) {\n\t\t\tif (payload[payload.length - k + t] !== fileLines[endLine + t]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!matches) continue;\n\t\tif (balanceEqual(computeDelimiterBalance(payload.slice(payload.length - k)), delta)) return k;\n\t}\n\treturn 0;\n}\n\n/**\n * Largest `j` such that the payload's first `j` lines exactly equal the `j`\n * surviving file lines just above the range AND dropping them zeroes `delta`.\n * Requires a non-zero `delta`; see {@link findDuplicateSuffix}.\n */\nfunction findDuplicatePrefix(group: ReplacementGroup, fileLines: readonly string[], delta: DelimiterBalance): number {\n\tif (balanceIsZero(delta)) return 0;\n\tconst { payload, startLine } = group;\n\tconst maxJ = Math.min(payload.length, startLine - 1);\n\tfor (let j = maxJ; j >= 1; j--) {\n\t\tlet matches = true;\n\t\tfor (let t = 0; t < j; t++) {\n\t\t\tif (payload[t] !== fileLines[startLine - 1 - j + t]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!matches) continue;\n\t\tif (balanceEqual(computeDelimiterBalance(payload.slice(0, j)), delta)) return j;\n\t}\n\treturn 0;\n}\n\n/**\n * Smallest `m` such that the range's last `m` deleted lines are all pure\n * structural closers and sparing them (keeping instead of deleting) zeroes\n * `delta`. The mirror mistake: a range that swallows a closing delimiter the\n * payload never restates.\n */\nfunction findDroppedSuffixClosers(\n\tgroup: ReplacementGroup,\n\tfileLines: readonly string[],\n\tdelta: DelimiterBalance,\n): number {\n\tconst wanted = balanceNegate(delta);\n\tconst maxM = group.deleteIndices.length;\n\tfor (let m = 1; m <= maxM; m++) {\n\t\tif (!STRUCTURAL_CLOSER_RE.test(fileLines[group.endLine - m] ?? \"\")) break;\n\t\tif (balanceEqual(computeDelimiterBalance(fileLines.slice(group.endLine - m, group.endLine)), wanted)) return m;\n\t}\n\treturn 0;\n}\n\ninterface BoundaryEcho {\n\tleading: number;\n\ttrailing: number;\n}\n\nfunction hasNonWhitespace(text: string): boolean {\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst code = text.charCodeAt(i);\n\t\tif (code !== 9 && code !== 10 && code !== 11 && code !== 12 && code !== 13 && code !== 32) return true;\n\t}\n\treturn false;\n}\n\nfunction countDuplicateLeadingBoundaryLines(group: ReplacementGroup, fileLines: readonly string[]): number {\n\tconst { payload, startLine } = group;\n\tconst max = Math.min(payload.length, startLine - 1);\n\tfor (let count = max; count >= 1; count--) {\n\t\tlet matches = true;\n\t\tlet hasContent = false;\n\t\tfor (let offset = 0; offset < count; offset++) {\n\t\t\tconst line = payload[offset];\n\t\t\tif (line !== fileLines[startLine - 1 - count + offset]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\thasContent ||= hasNonWhitespace(line);\n\t\t}\n\t\tif (matches && hasContent) return count;\n\t}\n\treturn 0;\n}\n\nfunction countDuplicateTrailingBoundaryLines(group: ReplacementGroup, fileLines: readonly string[]): number {\n\tconst { payload, endLine } = group;\n\tconst max = Math.min(payload.length, fileLines.length - endLine);\n\tfor (let count = max; count >= 1; count--) {\n\t\tlet matches = true;\n\t\tlet hasContent = false;\n\t\tfor (let offset = 0; offset < count; offset++) {\n\t\t\tconst line = payload[payload.length - count + offset];\n\t\t\tif (line !== fileLines[endLine + offset]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\thasContent ||= hasNonWhitespace(line);\n\t\t}\n\t\tif (matches && hasContent) return count;\n\t}\n\treturn 0;\n}\n\nfunction findBoundaryEcho(group: ReplacementGroup, fileLines: readonly string[]): BoundaryEcho | undefined {\n\tconst leadingMax = countDuplicateLeadingBoundaryLines(group, fileLines);\n\tif (leadingMax === 0) return undefined;\n\tconst trailingMax = countDuplicateTrailingBoundaryLines(group, fileLines);\n\tif (trailingMax === 0) return undefined;\n\t// Bail when every payload line could be claimed by a boundary echo: any\n\t// repair would strip explicit replacement content with no signal that the\n\t// payload was a mistake rather than an intentional duplication.\n\tif (leadingMax + trailingMax >= group.payload.length) return undefined;\n\t// Balance-neutrality guard (see header comment): the dropped echo lines must\n\t// either be delimiter-neutral on their own or exactly cancel the payload/range\n\t// balance delta. In brace-heavy code where bare closer lines repeat, an\n\t// \"echo\" that shifts delimiter balance is structural content the payload\n\t// placed intentionally — stripping it would corrupt the result.\n\tconst leadingBalance = computeDelimiterBalance(group.payload.slice(0, leadingMax));\n\tconst trailingBalance = computeDelimiterBalance(group.payload.slice(group.payload.length - trailingMax));\n\tconst droppedBalance = balanceDelta(leadingBalance, balanceNegate(trailingBalance));\n\tif (!balanceIsZero(droppedBalance)) {\n\t\tconst delta = balanceDelta(\n\t\t\tcomputeDelimiterBalance(group.payload),\n\t\t\tcomputeDelimiterBalance(fileLines.slice(group.startLine - 1, group.endLine)),\n\t\t);\n\t\tif (!balanceEqual(droppedBalance, delta)) return undefined;\n\t}\n\treturn { leading: leadingMax, trailing: trailingMax };\n}\n\nfunction describeBoundaryEchoRepair(group: ReplacementGroup, echo: BoundaryEcho): string {\n\treturn (\n\t\t`Auto-repaired a replacement boundary echo at line ${group.startLine}: ` +\n\t\t`dropped ${echo.leading} leading and ${echo.trailing} trailing payload line(s) already present outside the range. ` +\n\t\t`Issue the payload as the final desired content for the selected range only — never restate unchanged lines bordering the range.`\n\t);\n}\n\nfunction describeBoundaryRepair(group: ReplacementGroup, action: string): string {\n\treturn (\n\t\t`Auto-repaired a delimiter-balance mismatch in the replacement at line ${group.startLine}: ${action}. ` +\n\t\t`Issue the payload as the final desired content only — never restate or omit a closing bracket bordering the range.`\n\t);\n}\n\n/**\n * Normalize replacement groups so common off-by-one boundaries do not duplicate\n * unchanged surrounding lines or structural closers. Returns the repaired edit\n * list plus one warning per repaired group.\n */\nfunction repairReplacementBoundaries(\n\tedits: readonly AppliedEdit[],\n\tfileLines: readonly string[],\n): {\n\tedits: AppliedEdit[];\n\twarnings: string[];\n} {\n\tconst out: AppliedEdit[] = [];\n\tconst warnings: string[] = [];\n\tlet i = 0;\n\twhile (i < edits.length) {\n\t\tconst group = findReplacementGroup(edits, i);\n\t\tif (!group) {\n\t\t\tout.push(edits[i]);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst inserts = group.insertIndices.map(idx => edits[idx]);\n\t\tconst deletes = group.deleteIndices.map(idx => edits[idx]);\n\t\ti = group.deleteIndices[group.deleteIndices.length - 1] + 1;\n\n\t\tconst boundaryEcho = findBoundaryEcho(group, fileLines);\n\t\tif (boundaryEcho) {\n\t\t\twarnings.push(describeBoundaryEchoRepair(group, boundaryEcho));\n\t\t\tout.push(...inserts.slice(boundaryEcho.leading, inserts.length - boundaryEcho.trailing), ...deletes);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst delta = balanceDelta(\n\t\t\tcomputeDelimiterBalance(group.payload),\n\t\t\tcomputeDelimiterBalance(fileLines.slice(group.startLine - 1, group.endLine)),\n\t\t);\n\t\tif (balanceIsZero(delta)) {\n\t\t\tout.push(...inserts, ...deletes);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst dupSuffix = findDuplicateSuffix(group, fileLines, delta);\n\t\tif (dupSuffix > 0) {\n\t\t\twarnings.push(\n\t\t\t\tdescribeBoundaryRepair(\n\t\t\t\t\tgroup,\n\t\t\t\t\t`dropped ${dupSuffix} duplicated trailing payload line(s) already present below the range`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tout.push(...inserts.slice(0, inserts.length - dupSuffix), ...deletes);\n\t\t\tcontinue;\n\t\t}\n\t\tconst dupPrefix = findDuplicatePrefix(group, fileLines, delta);\n\t\tif (dupPrefix > 0) {\n\t\t\twarnings.push(\n\t\t\t\tdescribeBoundaryRepair(\n\t\t\t\t\tgroup,\n\t\t\t\t\t`dropped ${dupPrefix} duplicated leading payload line(s) already present above the range`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tout.push(...inserts.slice(dupPrefix), ...deletes);\n\t\t\tcontinue;\n\t\t}\n\t\tconst droppedClosers = findDroppedSuffixClosers(group, fileLines, delta);\n\t\tif (droppedClosers > 0) {\n\t\t\twarnings.push(\n\t\t\t\tdescribeBoundaryRepair(\n\t\t\t\t\tgroup,\n\t\t\t\t\t`kept ${droppedClosers} structural closing line(s) the range deleted without restating`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tout.push(...inserts, ...deletes.slice(0, deletes.length - droppedClosers));\n\t\t\tcontinue;\n\t\t}\n\t\tout.push(...inserts, ...deletes);\n\t}\n\treturn { edits: out, warnings };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// After-insert landing correction\n//\n// The body rows of an `insert after N:` hunk carry an implicit depth claim:\n// their leading indentation says how deep the author expects the new lines\n// to sit. Two corrections share that claim, in opposite directions:\n//\n// Outward (any after-insert): when the depth is shallower than line N itself,\n// the hunk is inserting a sibling of some enclosing construct while anchored\n// inside it — the common shape is anchoring on the last statement of a block\n// and writing the body at the parent's depth. Sliding the landing point\n// forward across the structural closer lines that follow (and nothing else —\n// content lines are never crossed) places the body at the depth its\n// indentation names.\n//\n// Inward (block-lowered inserts only): `insert after block N:` anchors on the\n// resolved block's closing line, but a body indented deeper than that closer\n// claims a depth inside the block — the common misreading of the op as\n// \"append at the end of block N's body\". Sliding the landing point backward\n// across the block's trailing closer lines places the body inside, at its\n// claimed depth. Scoped to block-lowered inserts because there the author\n// named the opener and never saw the closer; a plain `insert after M:` on a\n// closer line stays literal (the escape hatch for genuinely-after content\n// such as method-chain continuations).\n//\n// Both shifts are deliberately conservative: they fire only when the body\n// and anchor indentation are comparable (one is a prefix of the other),\n// cross only pure closing-delimiter lines, stop as soon as depth matches the\n// body's claim, and are abandoned when any other edit in the patch targets a\n// crossed line. Every shift is reported as a warning so the author can\n// re-issue when the original landing was intended.\n\n/** Leading run of tabs and spaces. */\nfunction leadingIndent(line: string): string {\n\tlet end = 0;\n\twhile (end < line.length) {\n\t\tconst code = line.charCodeAt(end);\n\t\tif (code !== 9 && code !== 32) break;\n\t\tend++;\n\t}\n\treturn line.slice(0, end);\n}\n\n/** `deeper` strictly extends `shallower` (same indent style, more depth). */\nfunction isIndentDeeper(deeper: string, shallower: string): boolean {\n\treturn deeper.length > shallower.length && deeper.startsWith(shallower);\n}\n\ninterface AfterInsertGroup {\n\t/** Anchor line shared by every insert row of the hunk. */\n\tanchor: number;\n\t/** Indices into the edit list, in patch order. */\n\tmembers: number[];\n\t/** First line of the resolved block when lowered from `insert after block N:`. */\n\tblockStart?: number;\n}\n\n/**\n * Depth of an after-insert hunk's body: the shallowest indentation across its\n * non-blank rows. Returns `undefined` when no depth claim can be made — an\n * all-blank or all-closer body, or rows whose indentation styles are not\n * mutually comparable (tabs vs spaces).\n */\nfunction bodyTargetIndent(rows: readonly string[]): string | undefined {\n\tconst nonBlank = rows.filter(hasNonWhitespace);\n\tif (nonBlank.length === 0) return undefined;\n\t// A body of pure closers re-balances delimiters; it claims no depth.\n\tif (nonBlank.every(row => STRUCTURAL_CLOSER_RE.test(row))) return undefined;\n\tlet target = leadingIndent(nonBlank[0] ?? \"\");\n\tfor (const row of nonBlank) {\n\t\tconst indent = leadingIndent(row);\n\t\tif (indent.startsWith(target)) continue;\n\t\tif (target.startsWith(indent)) target = indent;\n\t\telse return undefined;\n\t}\n\treturn target;\n}\n\n/**\n * Resolve where an after-insert hunk anchored on `group.anchor` should land\n * given its body depth `target`: the last structural closer line in the run\n * directly below the anchor whose indentation still covers `target`. Returns\n * `undefined` when the landing stays put.\n */\nfunction resolveShiftedLanding(\n\tgroup: AfterInsertGroup,\n\ttarget: string,\n\tfileLines: readonly string[],\n\ttargetedLines: ReadonlySet<number>,\n): { line: number; crossed: number } | undefined {\n\tconst anchorText = fileLines[group.anchor - 1];\n\tif (anchorText === undefined || !hasNonWhitespace(anchorText)) return undefined;\n\tif (!isIndentDeeper(leadingIndent(anchorText), target)) return undefined;\n\n\tlet landing = group.anchor;\n\tlet crossed = 0;\n\tfor (let line = group.anchor + 1; line <= fileLines.length; line++) {\n\t\tconst text = fileLines[line - 1] ?? \"\";\n\t\tif (!hasNonWhitespace(text)) continue; // look past blanks, never land on them\n\t\tif (!STRUCTURAL_CLOSER_RE.test(text)) break; // content is never crossed\n\t\tconst indent = leadingIndent(text);\n\t\tif (!indent.startsWith(target)) break; // shallower than the body — crossing would over-escape\n\t\tif (targetedLines.has(line)) return undefined; // another hunk owns this closer\n\t\tlanding = line;\n\t\tcrossed++;\n\t\tif (indent.length === target.length) break; // depth returned to the body's level\n\t}\n\treturn landing === group.anchor ? undefined : { line: landing, crossed };\n}\n\n/**\n * Resolve where a block-lowered after-insert anchored on the block's closing\n * line should land given a body depth `target` deeper than that closer: just\n * above the block's trailing run of closer lines, bounded below by\n * `blockStart` (an empty block lands the body right after its opener).\n * Returns `undefined` when the landing stays put.\n */\nfunction resolveInwardLanding(\n\tgroup: AfterInsertGroup,\n\ttarget: string,\n\tblockStart: number,\n\tfileLines: readonly string[],\n\ttargetedLines: ReadonlySet<number>,\n): number | undefined {\n\tconst anchorText = fileLines[group.anchor - 1];\n\tif (anchorText === undefined || !hasNonWhitespace(anchorText)) return undefined;\n\t// Fires only when the block ends in a pure closer the body out-indents.\n\t// Blocks ending in content (indentation-only languages) already land the\n\t// body inside the block — nothing to correct.\n\tif (!STRUCTURAL_CLOSER_RE.test(anchorText)) return undefined;\n\tif (!isIndentDeeper(target, leadingIndent(anchorText))) return undefined;\n\n\tlet landing = group.anchor;\n\tfor (let line = group.anchor; line > blockStart; line--) {\n\t\tconst text = fileLines[line - 1] ?? \"\";\n\t\tif (!hasNonWhitespace(text)) {\n\t\t\tlanding = line - 1; // look past trailing blanks, never land after one\n\t\t\tcontinue;\n\t\t}\n\t\tif (!STRUCTURAL_CLOSER_RE.test(text)) break; // content reached — land right after it\n\t\tconst indent = leadingIndent(text);\n\t\tif (!isIndentDeeper(target, indent)) break; // closer at the body's depth — land after it\n\t\t// Another hunk owns this closer (the group's own rows put the anchor\n\t\t// itself in `targetedLines`; that one is ours to cross).\n\t\tif (line !== group.anchor && targetedLines.has(line)) return undefined;\n\t\tlanding = line - 1;\n\t}\n\treturn landing === group.anchor ? undefined : landing;\n}\n\n/**\n * Slide mis-anchored after-insert hunks to the depth their body indentation\n * claims: outward past the structural closer lines that follow the anchor\n * when the body is shallower, or — for `insert after block N:` lowerings —\n * inward across the block's trailing closers when the body is deeper than\n * the block's closing line. Returns the corrected edit list plus one warning\n * per shifted hunk.\n */\nfunction repairAfterInsertLandings(\n\tedits: readonly AppliedEdit[],\n\tfileLines: readonly string[],\n): { edits: readonly AppliedEdit[]; warnings: string[] } {\n\t// Group plain (non-replacement) after-anchor inserts per authored hunk:\n\t// rows of one hunk share the anchor line and the patch header line.\n\tconst groups = new Map<string, AfterInsertGroup>();\n\tedits.forEach((edit, idx) => {\n\t\tif (edit.kind !== \"insert\" || edit.mode === \"replacement\") return;\n\t\tif (edit.cursor.kind !== \"after_anchor\") return;\n\t\tconst key = `${edit.cursor.anchor.line}:${edit.lineNum}`;\n\t\tconst group = groups.get(key);\n\t\tif (group === undefined)\n\t\t\tgroups.set(key, { anchor: edit.cursor.anchor.line, members: [idx], blockStart: edit.blockStart });\n\t\telse group.members.push(idx);\n\t});\n\tif (groups.size === 0) return { edits, warnings: [] };\n\n\t// Lines explicitly targeted by any edit; a shift never crosses them.\n\tconst targetedLines = new Set<number>();\n\tfor (const edit of edits) {\n\t\tif (edit.kind === \"delete\") targetedLines.add(edit.anchor.line);\n\t\telse if (edit.cursor.kind === \"before_anchor\" || edit.cursor.kind === \"after_anchor\")\n\t\t\ttargetedLines.add(edit.cursor.anchor.line);\n\t}\n\n\tlet out: AppliedEdit[] | undefined;\n\tconst warnings: string[] = [];\n\tconst retarget = (group: AfterInsertGroup, line: number): void => {\n\t\tout ??= [...edits];\n\t\tfor (const idx of group.members) {\n\t\t\tconst edit = out[idx] as InsertEdit;\n\t\t\tout[idx] = { ...edit, cursor: { kind: \"after_anchor\", anchor: { line } } };\n\t\t}\n\t};\n\tfor (const group of groups.values()) {\n\t\tconst target = bodyTargetIndent(group.members.map(idx => (edits[idx] as InsertEdit).text));\n\t\tif (target === undefined) continue;\n\t\tconst outward = resolveShiftedLanding(group, target, fileLines, targetedLines);\n\t\tif (outward !== undefined) {\n\t\t\tretarget(group, outward.line);\n\t\t\twarnings.push(afterInsertLandingShiftWarning(group.anchor, outward.line, outward.crossed));\n\t\t\tcontinue;\n\t\t}\n\t\tif (group.blockStart === undefined) continue;\n\t\tconst inward = resolveInwardLanding(group, target, group.blockStart, fileLines, targetedLines);\n\t\tif (inward === undefined) continue;\n\t\tretarget(group, inward);\n\t\twarnings.push(blockInsertLandingShiftWarning(group.blockStart, group.anchor, inward));\n\t}\n\treturn { edits: out ?? edits, warnings };\n}\n\n/**\n * Apply a parsed list of edits to a text body. Pure function — no I/O.\n *\n * Returns the post-edit text and the first changed line number (1-indexed).\n * Throws if an anchor is out of bounds.\n */\nexport function applyEdits(text: string, edits: readonly Edit[]): ApplyResult {\n\tif (edits.length === 0) return { text, firstChangedLine: undefined };\n\n\t// Block edits are deferred until `resolveBlockEdits` expands them into\n\t// concrete inserts + deletes. Reaching the applier with one still present\n\t// is an internal wiring bug, not authored-input error.\n\tfor (const edit of edits) {\n\t\tif (edit.kind === \"block\") throw new Error(UNRESOLVED_BLOCK_INTERNAL);\n\t}\n\tconst appliedEdits = edits as readonly AppliedEdit[];\n\n\tconst fileLines = text.split(\"\\n\");\n\tconst lineOrigins: LineOrigin[] = fileLines.map(() => \"original\");\n\n\tlet firstChangedLine: number | undefined;\n\tconst trackFirstChanged = (line: number) => {\n\t\tif (firstChangedLine === undefined || line < firstChangedLine) firstChangedLine = line;\n\t};\n\n\tconst targetEdits = dropTrailingPhantomDeletes(\n\t\tappliedEdits.map((edit, index) => cloneAppliedEdit(edit, index)),\n\t\tfileLines,\n\t);\n\tvalidateLineBounds(targetEdits, fileLines);\n\tconst { edits: repaired, warnings: boundaryWarnings } = repairReplacementBoundaries(targetEdits, fileLines);\n\tconst { edits: landed, warnings: landingWarnings } = repairAfterInsertLandings(repaired, fileLines);\n\tconst warnings = [...boundaryWarnings, ...landingWarnings];\n\n\t// Partition edits into bof, eof, and anchor-targeted buckets.\n\tconst bofLines: string[] = [];\n\tconst eofLines: string[] = [];\n\tconst anchorEdits: IndexedEdit[] = [];\n\tlanded.forEach((edit, idx) => {\n\t\tif (edit.kind === \"insert\" && edit.cursor.kind === \"bof\") {\n\t\t\tbofLines.push(edit.text);\n\t\t} else if (edit.kind === \"insert\" && edit.cursor.kind === \"eof\") {\n\t\t\teofLines.push(edit.text);\n\t\t} else {\n\t\t\tanchorEdits.push({ edit, idx });\n\t\t}\n\t});\n\n\t// Apply per-line buckets bottom-up so earlier indices stay valid.\n\tconst byLine = bucketAnchorEditsByLine(anchorEdits);\n\tfor (const line of [...byLine.keys()].sort((a, b) => b - a)) {\n\t\tconst bucket = byLine.get(line);\n\t\tif (!bucket) continue;\n\t\tbucket.sort((a, b) => a.idx - b.idx);\n\n\t\tconst idx = line - 1;\n\t\tconst currentLine = fileLines[idx] ?? \"\";\n\t\tconst beforeInsertLines: string[] = [];\n\t\tconst afterInsertLines: string[] = [];\n\t\tconst replacementLines: string[] = [];\n\t\tlet deleteLine = false;\n\n\t\tfor (const { edit } of bucket) {\n\t\t\tif (isReplacementInsert(edit)) {\n\t\t\t\treplacementLines.push(edit.text);\n\t\t\t} else if (edit.kind === \"insert\" && edit.cursor.kind === \"after_anchor\") {\n\t\t\t\tafterInsertLines.push(edit.text);\n\t\t\t} else if (edit.kind === \"insert\") {\n\t\t\t\tbeforeInsertLines.push(edit.text);\n\t\t\t} else if (edit.kind === \"delete\") {\n\t\t\t\tdeleteLine = true;\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tbeforeInsertLines.length === 0 &&\n\t\t\treplacementLines.length === 0 &&\n\t\t\tafterInsertLines.length === 0 &&\n\t\t\t!deleteLine\n\t\t)\n\t\t\tcontinue;\n\n\t\tconst replacement = deleteLine\n\t\t\t? [...beforeInsertLines, ...replacementLines, ...afterInsertLines]\n\t\t\t: [...beforeInsertLines, ...replacementLines, currentLine, ...afterInsertLines];\n\t\tconst origins: LineOrigin[] = [];\n\t\tfor (let i = 0; i < beforeInsertLines.length; i++) origins.push(\"insert\");\n\t\tfor (let i = 0; i < replacementLines.length; i++) origins.push(deleteLine ? \"replacement\" : \"insert\");\n\t\tif (!deleteLine) origins.push(lineOrigins[idx] ?? \"original\");\n\t\tfor (let i = 0; i < afterInsertLines.length; i++) origins.push(\"insert\");\n\n\t\tfileLines.splice(idx, 1, ...replacement);\n\t\tlineOrigins.splice(idx, 1, ...origins);\n\t\ttrackFirstChanged(line);\n\t}\n\n\tif (bofLines.length > 0) {\n\t\tinsertAtStart(fileLines, lineOrigins, bofLines);\n\t\ttrackFirstChanged(1);\n\t}\n\tconst eofChangedLine = insertAtEnd(fileLines, lineOrigins, eofLines);\n\tif (eofChangedLine !== undefined) trackFirstChanged(eofChangedLine);\n\n\treturn {\n\t\ttext: fileLines.join(\"\\n\"),\n\t\tfirstChangedLine,\n\t\t...(warnings.length > 0 ? { warnings } : {}),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/apply.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAU,WAAW,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAsHpE,iFAAiF;AACjF,eAAO,MAAM,oBAAoB,QAAyB,CAAC;AAklB3D;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,WAAW,CAqG5E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/block.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAE/E,MAAM,WAAW,wBAAwB;IACxC;;;;;;;;OAQG;IACH,YAAY,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAChC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI,CAAC;IACnD;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACtC;AAED,wEAAwE;AACxE,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,OAAO,CAE5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,aAAa,GAAG,SAAS,EACnC,OAAO,GAAE,wBAA6B,GACpC,SAAS,IAAI,EAAE,CAuFjB"
|
|
1
|
+
{"version":3,"file":"block.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/block.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAE/E,MAAM,WAAW,wBAAwB;IACxC;;;;;;;;OAQG;IACH,YAAY,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAChC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI,CAAC;IACnD;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACtC;AAED,wEAAwE;AACxE,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,OAAO,CAE5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,aAAa,GAAG,SAAS,EACnC,OAAO,GAAE,wBAA6B,GACpC,SAAS,IAAI,EAAE,CAuFjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diff-preview.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/diff-preview.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA+DzE,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,kBAAkB,CAgD1G"
|
|
1
|
+
{"version":3,"file":"diff-preview.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/diff-preview.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA+DzE,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,k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AC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAQ,GAAG,MAAM,CAErE;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAWzD;AAED,mEAAmE;AACnE,eAAO,MAAM,mBAAmB,IAAI,CAAC;AACrC,6FAA6F;AAC7F,eAAO,MAAM,mBAAmB,gBAAqC,CAAC;AACtE,yDAAyD;AACzD,eAAO,MAAM,2BAA2B,kBAA6B,CAAC;AACtE,yFAAyF;AACzF,eAAO,MAAM,uBAAuB,QAAgC,CAAC;AACrE;;;GAGG;AACH,eAAO,MAAM,qBAAqB,YAAI,MAAM,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAuEvE,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAIpD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,SAAK,GAAG,MAAM,CAG9D;AAED,yEAAyE;AACzE,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE/E;AAED,qDAAqD;AACrD,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3E;AAED,4EAA4E;AAC5E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,SAAI,GAAG,MAAM,CAGvE","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Hashline format primitives: sigils, separators, regex fragments, and\n * display helpers. These are the single source of truth for the parser, the\n * tokenizer, the prompt, and the formal grammar.\n */\n\nimport type { Cursor } from \"./types.js\";\n\n/** File-section header delimiters: `[path#hash]`. */\nexport const HL_FILE_PREFIX = \"[\";\nexport const HL_FILE_SUFFIX = \"]\";\n\n/** Payload sigil for literal body rows. */\nexport const HL_PAYLOAD_REPLACE = \"+\";\n\n/** Hunk-header keyword for concrete line replacement. */\nexport const HL_REPLACE_KEYWORD = \"replace\";\n/** Hunk-header sub-keyword: `replace block N:` resolves N to a tree-sitter block range. */\nexport const HL_BLOCK_KEYWORD = \"block\";\n/** Hunk-header keyword for concrete line deletion. */\nexport const HL_DELETE_KEYWORD = \"delete\";\n/** Hunk-header keyword for insertion operations. */\nexport const HL_INSERT_KEYWORD = \"insert\";\n/** Insert position keyword for inserting before a concrete line. */\nexport const HL_INSERT_BEFORE = \"before\";\n/** Insert position keyword for inserting after a concrete line. */\nexport const HL_INSERT_AFTER = \"after\";\n/** Insert position keyword for inserting at the start of the file. */\nexport const HL_INSERT_HEAD = \"head\";\n/** Insert position keyword for inserting at the end of the file. */\nexport const HL_INSERT_TAIL = \"tail\";\n/** Hunk-header terminator for body-bearing operations. */\nexport const HL_HEADER_COLON = \":\";\n\n/** Separator between a hashline file path and its opaque snapshot tag. */\nexport const HL_FILE_HASH_SEP = \"#\";\n\n/** Separator between two line numbers in a range, e.g. `5..10`. */\nexport const HL_RANGE_SEP = \"..\";\n\n/** Separator between a line number and displayed line content in hashline mode. */\nexport const HL_LINE_BODY_SEP = \":\";\n\nfunction regexEscape(str: string): string {\n\treturn str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/** Bare positive line-number Lid (no decorations, no captures, no anchors). */\nexport const HL_LINE_RE_RAW = `[1-9]\\\\d*`;\n\n/** Capture-group form of {@link HL_LINE_RE_RAW}. */\nexport const HL_LINE_CAPTURE_RE_RAW = `(${HL_LINE_RE_RAW})`;\n\n/** Format a concrete replacement hunk header. */\nexport function formatReplaceHeader(start: number, end: number): string {\n\treturn `${HL_REPLACE_KEYWORD} ${start}${HL_RANGE_SEP}${end}${HL_HEADER_COLON}`;\n}\n\n/** Format a concrete deletion hunk header. */\nexport function formatDeleteHeader(start: number, end = start): string {\n\treturn start === end ? `${HL_DELETE_KEYWORD} ${start}` : `${HL_DELETE_KEYWORD} ${start}${HL_RANGE_SEP}${end}`;\n}\n\n/** Format an insertion hunk header for a cursor position. */\nexport function formatInsertHeader(cursor: Cursor): string {\n\tswitch (cursor.kind) {\n\t\tcase \"before_anchor\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_BEFORE} ${cursor.anchor.line}${HL_HEADER_COLON}`;\n\t\tcase \"after_anchor\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_AFTER} ${cursor.anchor.line}${HL_HEADER_COLON}`;\n\t\tcase \"bof\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_HEAD}${HL_HEADER_COLON}`;\n\t\tcase \"eof\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_TAIL}${HL_HEADER_COLON}`;\n\t}\n}\n\n/** Number of hex characters in a content-derived file-hash tag. */\nexport const HL_FILE_HASH_LENGTH = 4;\n/** Canonical uppercase hexadecimal content-hash tag carried by a hashline section header. */\nexport const HL_FILE_HASH_RE_RAW = `[0-9A-F]{${HL_FILE_HASH_LENGTH}}`;\n/** Capture-group form of {@link HL_FILE_HASH_RE_RAW}. */\nexport const HL_FILE_HASH_CAPTURE_RE_RAW = `(${HL_FILE_HASH_RE_RAW})`;\n/** Regex-escaped form of {@link HL_LINE_BODY_SEP}, safe for embedding inside a regex. */\nexport const HL_LINE_BODY_SEP_RE_RAW = regexEscape(HL_LINE_BODY_SEP);\n/**\n * Representative file-hash tags for use in user-facing error messages and\n * prompt examples.\n */\nexport const HL_FILE_HASH_EXAMPLES = [\"1A2B\", \"3C4D\", \"9F3E\"] as const;\n/**\n * Normalize text before hashing: trim trailing `[ \\t\\r]` from every line (and\n * the final line) in a single pass so CRLF endings and display-trimmed lines\n * do not invalidate a tag.\n */\nfunction normalizeFileHashText(text: string): string {\n\treturn text.replace(/[ \\t\\r]+(?=\\n|$)/g, \"\");\n}\n/**\n * Compute the content-derived hash tag carried by a hashline section header.\n * The tag is a 4-hex fingerprint of the whole file's normalized text: any read\n * of byte-identical content mints the same tag, and a follow-up edit anchored\n * at any line validates whenever the live file still hashes to it.\n */\n// xxHash32 (canonical, seed 0) to match upstream Bun.hash.xxHash32 so section tags\n// are byte-identical to oh-my-pi for identical content. Pure-JS for Node runtime.\nconst XXH_PRIME32_1 = 0x9e3779b1;\nconst XXH_PRIME32_2 = 0x85ebca77;\nconst XXH_PRIME32_3 = 0xc2b2ae3d;\nconst XXH_PRIME32_4 = 0x27d4eb2f;\nconst XXH_PRIME32_5 = 0x165667b1;\nfunction xxhRotl(value: number, bits: number): number {\n\treturn (value << bits) | (value >>> (32 - bits));\n}\nfunction xxhRound(acc: number, input: number): number {\n\tacc = (acc + Math.imul(input, XXH_PRIME32_2)) | 0;\n\tacc = xxhRotl(acc, 13);\n\treturn Math.imul(acc, XXH_PRIME32_1) | 0;\n}\nfunction xxHash32(bytes: Uint8Array): number {\n\tconst len = bytes.length;\n\tlet index = 0;\n\tlet h32: number;\n\tconst readU32 = (offset: number): number =>\n\t\t(bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16) | (bytes[offset + 3]! << 24)) >>> 0;\n\tif (len >= 16) {\n\t\tlet v1 = (XXH_PRIME32_1 + XXH_PRIME32_2) | 0;\n\t\tlet v2 = XXH_PRIME32_2 | 0;\n\t\tlet v3 = 0;\n\t\tlet v4 = -XXH_PRIME32_1 | 0;\n\t\tconst limit = len - 16;\n\t\twhile (index <= limit) {\n\t\t\tv1 = xxhRound(v1, readU32(index)); index += 4;\n\t\t\tv2 = xxhRound(v2, readU32(index)); index += 4;\n\t\t\tv3 = xxhRound(v3, readU32(index)); index += 4;\n\t\t\tv4 = xxhRound(v4, readU32(index)); index += 4;\n\t\t}\n\t\th32 = (xxhRotl(v1, 1) + xxhRotl(v2, 7) + xxhRotl(v3, 12) + xxhRotl(v4, 18)) | 0;\n\t} else {\n\t\th32 = XXH_PRIME32_5 | 0;\n\t}\n\th32 = (h32 + len) | 0;\n\twhile (index + 4 <= len) {\n\t\th32 = (h32 + Math.imul(readU32(index), XXH_PRIME32_3)) | 0;\n\t\th32 = Math.imul(xxhRotl(h32, 17), XXH_PRIME32_4) | 0;\n\t\tindex += 4;\n\t}\n\twhile (index < len) {\n\t\th32 = (h32 + Math.imul(bytes[index]!, XXH_PRIME32_5)) | 0;\n\t\th32 = Math.imul(xxhRotl(h32, 11), XXH_PRIME32_1) | 0;\n\t\tindex += 1;\n\t}\n\th32 ^= h32 >>> 15;\n\th32 = Math.imul(h32, XXH_PRIME32_2);\n\th32 ^= h32 >>> 13;\n\th32 = Math.imul(h32, XXH_PRIME32_3);\n\th32 ^= h32 >>> 16;\n\treturn h32 >>> 0;\n}\nconst xxhEncoder = new TextEncoder();\nexport function computeFileHash(text: string): string {\n\tconst normalized = normalizeFileHashText(text);\n\tconst low16 = xxHash32(xxhEncoder.encode(normalized)) & 0xffff;\n\treturn low16.toString(16).padStart(HL_FILE_HASH_LENGTH, \"0\").toUpperCase();\n}\n\n/**\n * Format a comma-separated list of example anchors with an optional line-number\n * prefix, quoted for inclusion in error messages: `\"160\", \"42\", \"7\"`.\n */\nexport function describeAnchorExamples(linePrefix = \"\"): string {\n\tconst examples = linePrefix ? [linePrefix, `${linePrefix.slice(0, -1) || \"4\"}2`, \"7\"] : [\"160\", \"42\", \"7\"];\n\treturn examples.map(e => `\"${e}\"`).join(\", \");\n}\n\n/** Format a hashline section header for a file path and snapshot tag. */\nexport function formatHashlineHeader(filePath: string, fileHash: string): string {\n\treturn `${HL_FILE_PREFIX}${filePath}${HL_FILE_HASH_SEP}${fileHash}${HL_FILE_SUFFIX}`;\n}\n\n/** Formats a single numbered line as `LINE:TEXT`. */\nexport function formatNumberedLine(lineNumber: number, line: string): string {\n\treturn `${lineNumber}${HL_LINE_BODY_SEP}${line}`;\n}\n\n/** Format file text with hashline-mode line-number prefixes for display. */\nexport function formatNumberedLines(text: string, startLine = 1): string {\n\tconst lines = text.split(\"\\n\");\n\treturn lines.map((line, i) => formatNumberedLine(startLine + i, line)).join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/format.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC,qDAAqD;AACrD,eAAO,MAAM,cAAc,MAAM,CAAC;AAClC,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,2CAA2C;AAC3C,eAAO,MAAM,kBAAkB,MAAM,CAAC;AAEtC,yDAAyD;AACzD,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAC5C,2FAA2F;AAC3F,eAAO,MAAM,gBAAgB,UAAU,CAAC;AACxC,sDAAsD;AACtD,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,oDAAoD;AACpD,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,WAAW,CAAC;AACzC,mEAAmE;AACnE,eAAO,MAAM,eAAe,UAAU,CAAC;AACvC,sEAAsE;AACtE,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,oEAAoE;AACpE,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,0DAA0D;AAC1D,eAAO,MAAM,eAAe,MAAM,CAAC;AAEnC,0EAA0E;AAC1E,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC,mEAAmE;AACnE,eAAO,MAAM,YAAY,OAAO,CAAC;AAEjC,mFAAmF;AACnF,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAMpC,+EAA+E;AAC/E,eAAO,MAAM,cAAc,cAAc,CAAC;AAE1C,oDAAoD;AACpD,eAAO,MAAM,sBAAsB,gBAAwB,CAAC;AAE5D,iDAAiD;AACjD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,M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