@caupulican/pi-adaptative 0.85.0 → 0.85.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/arithmetic.py +364 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +2 -1
- package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +16 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +137 -14
- package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +23 -2
- package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +134 -6
- package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +25 -2
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +6 -5
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +84 -87
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-guidance.d.ts.map +1 -1
- package/dist/core/auth-guidance.js +3 -0
- package/dist/core/auth-guidance.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +2 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +4 -3
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +4 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +2 -0
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/background-tool-task-controller.d.ts +12 -7
- package/dist/core/background-tool-task-controller.d.ts.map +1 -1
- package/dist/core/background-tool-task-controller.js +55 -19
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/bedrock-scope.d.ts +26 -0
- package/dist/core/bedrock-scope.d.ts.map +1 -0
- package/dist/core/bedrock-scope.js +178 -0
- package/dist/core/bedrock-scope.js.map +1 -0
- package/dist/core/compaction-controller.d.ts +2 -0
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +35 -13
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +6 -0
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +3 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/failure-corpus.d.ts +26 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +17 -0
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/foreground-recovery-controller.d.ts +25 -2
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +111 -2
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts +27 -0
- package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -0
- package/dist/core/foreground-terminal-handoff-controller.js +56 -0
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -0
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +5 -0
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.d.ts +3 -0
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +28 -7
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- package/dist/core/human-input-controller.d.ts +9 -0
- package/dist/core/human-input-controller.d.ts.map +1 -1
- package/dist/core/human-input-controller.js +60 -5
- package/dist/core/human-input-controller.js.map +1 -1
- package/dist/core/human-input.d.ts +12 -0
- package/dist/core/human-input.d.ts.map +1 -1
- package/dist/core/human-input.js +59 -12
- package/dist/core/human-input.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +15 -9
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts +1 -0
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +252 -125
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/model-capability.d.ts +15 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +24 -1
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-registry.d.ts +5 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +18 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-router-controller.d.ts +6 -6
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +5 -5
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-tool-protocol.d.ts +3 -2
- package/dist/core/model-tool-protocol.d.ts.map +1 -1
- package/dist/core/model-tool-protocol.js +5 -1
- package/dist/core/model-tool-protocol.js.map +1 -1
- package/dist/core/models/context-sizing.d.ts +1 -0
- package/dist/core/models/context-sizing.d.ts.map +1 -1
- package/dist/core/models/context-sizing.js +4 -1
- package/dist/core/models/context-sizing.js.map +1 -1
- package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
- package/dist/core/models/default-model-suggestions.js +20 -10
- package/dist/core/models/default-model-suggestions.js.map +1 -1
- package/dist/core/models/llamacpp-runtime.d.ts +32 -11
- package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
- package/dist/core/models/llamacpp-runtime.js +79 -28
- package/dist/core/models/llamacpp-runtime.js.map +1 -1
- package/dist/core/models/local-execution-planner.d.ts +24 -0
- package/dist/core/models/local-execution-planner.d.ts.map +1 -0
- package/dist/core/models/local-execution-planner.js +119 -0
- package/dist/core/models/local-execution-planner.js.map +1 -0
- package/dist/core/models/local-inference-profile.d.ts +34 -0
- package/dist/core/models/local-inference-profile.d.ts.map +1 -0
- package/dist/core/models/local-inference-profile.js +74 -0
- package/dist/core/models/local-inference-profile.js.map +1 -0
- package/dist/core/models/local-runtime.d.ts +23 -4
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +11 -8
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/managed-ollama-model.d.ts +26 -0
- package/dist/core/models/managed-ollama-model.d.ts.map +1 -0
- package/dist/core/models/managed-ollama-model.js +59 -0
- package/dist/core/models/managed-ollama-model.js.map +1 -0
- package/dist/core/models/model-ref.js +11 -11
- package/dist/core/models/model-ref.js.map +1 -1
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts +10 -20
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -1
- package/dist/core/models/prism-llamacpp-lifecycle.js +11 -31
- package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -1
- package/dist/core/models/prism-llamacpp-server-probe.d.ts +10 -0
- package/dist/core/models/prism-llamacpp-server-probe.d.ts.map +1 -0
- package/dist/core/models/prism-llamacpp-server-probe.js +36 -0
- package/dist/core/models/prism-llamacpp-server-probe.js.map +1 -0
- package/dist/core/models/runtime-arbiter.d.ts +3 -0
- package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
- package/dist/core/models/runtime-arbiter.js +2 -1
- package/dist/core/models/runtime-arbiter.js.map +1 -1
- package/dist/core/models/runtime-process.d.ts +7 -1
- package/dist/core/models/runtime-process.d.ts.map +1 -1
- package/dist/core/models/runtime-process.js +4 -2
- package/dist/core/models/runtime-process.js.map +1 -1
- package/dist/core/process-matrix/runtime.js +43 -11
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/research/research-lane-controller.d.ts.map +1 -1
- package/dist/core/research/research-lane-controller.js +14 -5
- package/dist/core/research/research-lane-controller.js.map +1 -1
- package/dist/core/resource-loader.d.ts +2 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +18 -6
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +5 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +37 -4
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +3 -2
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +1 -0
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +10 -8
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +13 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +59 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +5 -2
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +22 -10
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +3 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +181 -55
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tool-protocol-controller.d.ts.map +1 -1
- package/dist/core/tool-protocol-controller.js +5 -3
- package/dist/core/tool-protocol-controller.js.map +1 -1
- package/dist/core/tool-recovery-log-records.d.ts +33 -1
- package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
- package/dist/core/tool-recovery-log-records.js +59 -12
- package/dist/core/tool-recovery-log-records.js.map +1 -1
- package/dist/core/tool-recovery-logger.d.ts +12 -1
- package/dist/core/tool-recovery-logger.d.ts.map +1 -1
- package/dist/core/tool-recovery-logger.js +24 -1
- package/dist/core/tool-recovery-logger.js.map +1 -1
- package/dist/core/tool-repair-health.d.ts.map +1 -1
- package/dist/core/tool-repair-health.js +6 -0
- package/dist/core/tool-repair-health.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +2 -2
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +2 -0
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +9 -1
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +5 -8
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +88 -55
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/file-mutation-intent.d.ts +42 -15
- package/dist/core/tools/file-mutation-intent.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-intent.js +271 -77
- package/dist/core/tools/file-mutation-intent.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +2 -6
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +2 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +2 -6
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/managed-search-tool.d.ts +8 -0
- package/dist/core/tools/managed-search-tool.d.ts.map +1 -0
- package/dist/core/tools/managed-search-tool.js +10 -0
- package/dist/core/tools/managed-search-tool.js.map +1 -0
- package/dist/core/tools/shell-command-parser.d.ts +4 -3
- package/dist/core/tools/shell-command-parser.d.ts.map +1 -1
- package/dist/core/tools/shell-command-parser.js +32 -7
- package/dist/core/tools/shell-command-parser.js.map +1 -1
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
- package/dist/core/tools/shell-contract-router.js +23 -1
- package/dist/core/tools/shell-contract-router.js.map +1 -1
- package/dist/core/tools/windows-shell-engine.js +1 -1
- package/dist/core/tools/windows-shell-engine.js.map +1 -1
- package/dist/core/tools/write.d.ts +5 -10
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +92 -73
- package/dist/core/tools/write.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.d.ts +6 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.js +59 -12
- package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +51 -8
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/dist/utils/paths.js +1 -1
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +18 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +73 -43
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/models.md +1 -1
- package/docs/providers.md +34 -10
- package/docs/settings.md +1 -1
- package/docs/tool-boundary-performance-roadmap-2026-08-02.md +21 -18
- package/docs/tool-repair.md +3 -3
- package/docs/windows.md +7 -5
- package/examples/extensions/built-in-tool-renderer.ts +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/minimal-mode.ts +1 -1
- package/examples/extensions/prompt-customizer.ts +2 -2
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/ssh.ts +17 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +240 -260
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.js","sourceRoot":"","s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AAC,SAAS,EAAE,MAAa,EAAE,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;YACxF,SAAS,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB;IAEzB,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC;IACvD,OAAO,yBAAyB,CAAC,GAAG,EAAE,wBAAwB,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;AAC9F,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { type AgentTool, createSilenceWatchdog } from \"@caupulican/pi-agent-core\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n} from \"@caupulican/pi-agent-core/node\";\nimport { Container, Text, truncateToWidth } from \"@caupulican/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport {\n\tgetPlatformShellToolName,\n\tgetShellConfig,\n\tgetShellEnv,\n\ttype PlatformShellToolName,\n\tprefixPowerShellCommand,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withExclusiveMutationBarrier } from \"./file-mutation-queue.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./git-filter.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { assessShellSearchScope, BROAD_SEARCH_OUTPUT_ROUTE } from \"./search-command-guard.ts\";\nimport { routeShellContract } from \"./shell-contract-router.ts\";\nimport {\n\tcreateShellOutputProjector,\n\ttype ShellOutputProjection,\n\ttype ShellOutputProjectionDetails,\n} from \"./shell-output-projection.ts\";\nimport { acquirePersistentShellSession } from \"./shell-session.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { createWindowsShellEngineOperations, type WindowsShellEngineOptions } from \"./windows-shell-engine.ts\";\nimport { getOrCreateWindowsShellState, mergeEffectiveEnv, resolveEffectiveCwd } from \"./windows-shell-state.ts\";\n\n/** Low-level silence bound retained for direct shell-operation consumers. Agent tool calls always pass a wall-clock bound. */\nconst DEFAULT_COMMAND_SILENCE_MS = 600_000;\n/** Agent-facing wall-clock bound: continuously producing output must not make a command immortal. */\nexport const DEFAULT_COMMAND_TIMEOUT_SECONDS = 120;\nexport const MAX_COMMAND_TIMEOUT_SECONDS = 3600;\nconst MIN_COMMAND_TIMEOUT_SECONDS = 0.1;\nlet commandSilenceMsOverride: number | undefined;\nlet commandTimeoutMsOverride: number | undefined;\n\n/** Test hook: override the low-level silence threshold. Pass undefined to restore the default. */\nexport function setCommandSilenceMsForTests(ms: number | undefined): void {\n\tcommandSilenceMsOverride = ms;\n}\n\n/** Test hook: override the agent tool's default wall-clock bound. Pass undefined to restore it. */\nexport function setCommandTimeoutMsForTests(ms: number | undefined): void {\n\tcommandTimeoutMsOverride = ms;\n}\n\nexport function resolveCommandTimeoutSeconds(timeout: number | undefined): number {\n\tif (typeof timeout !== \"number\" || !Number.isFinite(timeout) || timeout <= 0) {\n\t\treturn DEFAULT_COMMAND_TIMEOUT_SECONDS;\n\t}\n\treturn Math.max(MIN_COMMAND_TIMEOUT_SECONDS, Math.min(timeout, MAX_COMMAND_TIMEOUT_SECONDS));\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(\n\t\tType.Number({\n\t\t\tdescription: `Wall-clock timeout in seconds. Defaults to ${DEFAULT_COMMAND_TIMEOUT_SECONDS}; positive overrides are capped at ${MAX_COMMAND_TIMEOUT_SECONDS}. Zero or negative values use the default.`,\n\t\t}),\n\t),\n\tbroadSearch: Type.Optional(\n\t\tType.Literal(BROAD_SEARCH_OUTPUT_ROUTE, {\n\t\t\tdescription:\n\t\t\t\t\"Explicit override for a broad rg/grep/find/fd scan that cannot be narrowed. The command runs, but its complete output is routed to a file and excluded from model context.\",\n\t\t}),\n\t),\n});\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\tfullOutputError?: string;\n\tpersistedOutputTruncated?: boolean;\n\tpersistedOutputBytes?: number;\n\tpreview?: {\n\t\tcontent: string;\n\t\tskippedLines: number;\n\t};\n\toutputProjection?: ShellOutputProjectionDetails;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\nfunction createLocalShellOperations(\n\tshellName: PlatformShellToolName,\n\toptions?: { shellPath?: string; sessionKey?: string },\n): BashOperations {\n\t// A session key selects the persistent per-agent backend. An explicit custom shell path keeps\n\t// per-command spawning: persistent sessions assume the resolved platform shell's flag set.\n\tconst sessionKey = options?.sessionKey;\n\tif (sessionKey !== undefined && !options?.shellPath) {\n\t\treturn {\n\t\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t\t}\n\t\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\t\tconst session = acquirePersistentShellSession(sessionKey, shellName);\n\t\t\t\tconst silenceMs = commandSilenceMsOverride ?? DEFAULT_COMMAND_SILENCE_MS;\n\t\t\t\tconst hasWallClock = timeout !== undefined && timeout > 0;\n\t\t\t\treturn session.exec(command, cwd, {\n\t\t\t\t\tonData,\n\t\t\t\t\tsignal,\n\t\t\t\t\tenv,\n\t\t\t\t\ttimeoutSeconds: hasWallClock ? timeout : undefined,\n\t\t\t\t\tsilenceMs: !hasWallClock && silenceMs > 0 ? silenceMs : undefined,\n\t\t\t\t});\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst { shell, args } = getShellConfig(options?.shellPath, shellName);\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\n\t\t\tconst child = spawn(shell, [...args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tconst terminationController = new AbortController();\n\t\t\tconst onAbort = () => terminationController.abort();\n\t\t\tlet silenceKilled = false;\n\t\t\tconst silenceMs = commandSilenceMsOverride ?? DEFAULT_COMMAND_SILENCE_MS;\n\t\t\tconst silenceWatchdog =\n\t\t\t\t(timeout === undefined || timeout <= 0) && silenceMs > 0\n\t\t\t\t\t? createSilenceWatchdog({\n\t\t\t\t\t\t\tsilenceMs,\n\t\t\t\t\t\t\tonSilence: () => {\n\t\t\t\t\t\t\t\tsilenceKilled = true;\n\t\t\t\t\t\t\t\tterminationController.abort();\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tconst onChunk = (data: Buffer) => {\n\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\tonData(data);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tchild.stdout?.on(\"data\", onChunk);\n\t\t\t\tchild.stderr?.on(\"data\", onChunk);\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\t\t\tsignal: terminationController.signal,\n\t\t\t\t\ttimeoutMs: timeout !== undefined && timeout > 0 ? timeout * 1000 : undefined,\n\t\t\t\t\tkillGraceMs: 2_000,\n\t\t\t\t});\n\t\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\t\tif (terminal.reason === \"timeout\") throw new Error(`timeout:${timeout}`);\n\t\t\t\tif (silenceKilled) throw new Error(`silence:${silenceMs / 1000}`);\n\t\t\t\treturn { exitCode: terminal.code };\n\t\t\t} finally {\n\t\t\t\tsilenceWatchdog?.disarm();\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string; sessionKey?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", options);\n}\n\n/** Create PowerShell operations using pi's built-in local execution backend. */\nexport function createLocalPowerShellOperations(options?: { shellPath?: string; sessionKey?: string }): BashOperations {\n\treturn createLocalShellOperations(\"powershell\", options);\n}\n\n/** Create the platform shell backend without requiring callers or the model to choose a shell. */\nexport function createLocalPlatformShellOperations(\n\toptions: {\n\t\tshellPath?: string;\n\t\tcommandPrefix?: string;\n\t\toperations?: BashOperations;\n\t\tsessionKey?: string;\n\t\t/** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */\n\t\tpythonEngine?: boolean;\n\t\t/** Test/embedding hook: overrides the engine tier's runtime/spawn/state resolution. */\n\t\tengineOptions?: WindowsShellEngineOptions;\n\t} = {},\n\tplatform: NodeJS.Platform = process.platform,\n): BashOperations {\n\tconst operations =\n\t\toptions.operations ??\n\t\tcreateLocalShellOperations(getPlatformShellToolName(platform), {\n\t\t\tshellPath: options.shellPath,\n\t\t\tsessionKey: options.sessionKey,\n\t\t});\n\tconst pythonEngineEnabled = options.pythonEngine !== false;\n\t// One factory instance is one fallback tenant. Production agent sessions always pass their\n\t// stable key; standalone callers that omit it must never collapse into a process-global engine.\n\tconst engineSessionKey = options.sessionKey ?? `platform-shell-operations:${randomUUID()}`;\n\tconst engineOperations = createWindowsShellEngineOperations(engineSessionKey, options.engineOptions);\n\treturn {\n\t\tasync exec(command, cwd, execOptions) {\n\t\t\tlet resolvedCommand = command;\n\t\t\tlet resolvedCwd = cwd;\n\t\t\tlet resolvedExecOptions = execOptions;\n\t\t\tif (platform === \"win32\") {\n\t\t\t\tconst route = routeShellContract(command, platform, { pythonEngine: pythonEngineEnabled });\n\t\t\t\tif (route.kind === \"unsupported\") throw new Error(route.error);\n\t\t\t\t// The engine is the sole state mutator (D4); every Windows call — engine or PS\n\t\t\t\t// tier — reads the SAME session state so a `cd`/`export` in one call is observed\n\t\t\t\t// by the very next call regardless of which tier runs it.\n\t\t\t\tconst state = getOrCreateWindowsShellState(engineSessionKey);\n\t\t\t\tresolvedCwd = resolveEffectiveCwd(state, cwd);\n\t\t\t\tresolvedExecOptions = { ...execOptions, env: mergeEffectiveEnv(state, execOptions.env ?? getShellEnv()) };\n\t\t\t\tif (route.kind === \"python-engine\") {\n\t\t\t\t\t// The engine owns the state transition and resolves the original host cwd\n\t\t\t\t\t// exactly once. Passing the already state-adjusted cwd here would make the\n\t\t\t\t\t// engine mistake its own `cd` result for a host cwd change on the next call.\n\t\t\t\t\treturn engineOperations.exec(route.command, cwd, execOptions);\n\t\t\t\t}\n\t\t\t\tif (route.kind === \"powershell\") resolvedCommand = route.command;\n\t\t\t}\n\t\t\tif (options.commandPrefix) resolvedCommand = `${options.commandPrefix}\\n${resolvedCommand}`;\n\t\t\tif (platform === \"win32\") resolvedCommand = prefixPowerShellCommand(resolvedCommand);\n\t\t\treturn operations.exec(resolvedCommand, resolvedCwd, resolvedExecOptions);\n\t\t},\n\t};\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(command: string, cwd: string, spawnHook?: BashSpawnHook): BashSpawnContext {\n\tconst baseContext: BashSpawnContext = { command, cwd, env: { ...getShellEnv() } };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Platform used to choose the default backend and contract router. Defaults to process.platform. */\n\tplatform?: NodeJS.Platform;\n\t/** Custom operations for command execution. Default: local platform shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n\t/**\n\t * Stable key for this agent's persistent shell session. The host passes its per-agent key so\n\t * the session survives runtime reloads and user `!` commands share it; separately created\n\t * tool instances (subagents) auto-generate their own key and stay isolated.\n\t */\n\tsessionKey?: string;\n\t/** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */\n\twindowsShellPythonEngine?: boolean;\n\t/** Test/embedding hook: overrides the engine tier's runtime/spawn/state resolution. */\n\twindowsShellEngineOptions?: WindowsShellEngineOptions;\n\t/** Test/embedding hook: override the managed directory used for complete command output. */\n\toutputDirectory?: string;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_PREVIEW_BYTES = 8 * 1024;\nconst BASH_UPDATE_THROTTLE_MS = 100;\nconst BROAD_SEARCH_MAX_PERSISTED_BYTES = 8 * 1024 * 1024;\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatBashCall(\n\targs: { command?: string; timeout?: number } | undefined,\n\tshellName: PlatformShellToolName,\n): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\tconst prompt = shellName === \"powershell\" ? \"PS>\" : \"$\";\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tconst renderPreview = !options.expanded ? result.details?.preview : undefined;\n\tlet output = (renderPreview ? renderPreview.content : getTextOutput(result as any, showImages)).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tconst fullOutputError = result.details?.fullOutputError;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tif (options.expanded) {\n\t\t\tconst styledOutput = output\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(output, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines.map((line) => theme.fg(\"toolOutput\", line));\n\t\t\t\t\t\tstate.cachedSkipped = (result.details?.preview?.skippedLines ?? 0) + preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath || fullOutputError) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t} else if (fullOutputError) {\n\t\t\twarnings.push(`Full output unavailable: ${fullOutputError}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n}\n\nfunction createShellToolDefinition(\n\tcwd: string,\n\tbackendShell: PlatformShellToolName,\n\tcontractPlatform: NodeJS.Platform,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined> {\n\tconst toolName = \"bash\";\n\tconst sessionKey = options?.sessionKey ?? `bash-tool:${randomUUID()}`;\n\tconst ops =\n\t\toptions?.operations ??\n\t\t(backendShell === \"powershell\"\n\t\t\t? createLocalPowerShellOperations({ shellPath: options?.shellPath, sessionKey })\n\t\t\t: createLocalBashOperations({ shellPath: options?.shellPath, sessionKey }));\n\tconst commandPrefix = options?.commandPrefix;\n\tconst spawnHook = options?.spawnHook;\n\tconst hasExecutionOverrides = Boolean(options?.operations || options?.shellPath || commandPrefix || spawnHook);\n\tconst canFilterCommand = !hasExecutionOverrides;\n\tconst routesWindowsContract = contractPlatform === \"win32\";\n\tconst pythonEngineEnabled = options?.windowsShellPythonEngine !== false;\n\tconst engineOperations = routesWindowsContract\n\t\t? createWindowsShellEngineOperations(sessionKey, options?.windowsShellEngineOptions)\n\t\t: undefined;\n\tconst contractDescription = routesWindowsContract\n\t\t? \"Execute Pi's stable Bash-like command contract in a persistent per-agent shell session (current directory and environment variables persist across calls, including across the PowerShell and Python engine tiers). On Windows, a deterministic router converts simple commands directly to PowerShell and routes pipelines, redirection, expansion, chaining, and state-mutating commands (cd/export/unset) through a bundled Python engine that implements the supported Bash grammar; named unsupported constructs (job control, process substitution, heredocs, nested shells, and similar) fail closed instead of being guessed.\"\n\t\t: \"Execute a Bash command in a persistent per-agent shell session: the current directory and environment variables persist across calls, and a timed-out or aborted command resets the session.\";\n\treturn {\n\t\tname: toolName,\n\t\tlabel: toolName,\n\t\tdescription: `${contractDescription} Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a managed file. Recognized test runners return a bounded failure/summary projection when it is materially smaller, with exact output saved to a managed file. Broad rg/grep/find/fd scans are rejected before execution; when an exhaustive scan is unavoidable, set broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\" to route all output to a managed file instead of model context. Commands have a ${DEFAULT_COMMAND_TIMEOUT_SECONDS}-second wall-clock default, including commands that keep producing output; use a positive timeout only when a scoped operation justifies a larger bound (maximum ${MAX_COMMAND_TIMEOUT_SECONDS} seconds).`,\n\t\tpromptSnippet: routesWindowsContract\n\t\t\t? \"Execute Bash-like commands; Pi routes them deterministically to PowerShell or a bundled Python engine on Windows\"\n\t\t\t: \"Execute Bash commands (ls, grep, find, etc.)\",\n\t\tpromptGuidelines: routesWindowsContract\n\t\t\t? [\n\t\t\t\t\t\"Use ordinary Bash-like commands on Windows; do not write PowerShell or ask the user to choose a shell.\",\n\t\t\t\t\t\"Pipelines, redirection, expansion (variables, command substitution, globs), chaining (&&/||/;), and cd/export/unset are supported and routed to a bundled Python engine; a fixed set of named constructs (job control, process substitution, heredocs, arithmetic expansion, nested shells, and similar) fail closed with an actionable message instead of being guessed.\",\n\t\t\t\t\t\"Working directory and environment changes from cd/export/unset persist across subsequent bash calls, including calls that route to the PowerShell tier.\",\n\t\t\t\t\t\"Supported Bash-like file commands are converted with literal-path operations; verify targets before recursive rm, cp, or mv calls.\",\n\t\t\t\t\t`Keep searches scoped and purpose-driven: discover paths first, pass an explicit root and filters, and prefer the bounded grep/find tools. Broad shell searches are rejected; use broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\" only for an unavoidable exhaustive scan, then inspect the returned file with bounded reads or narrower searches.`,\n\t\t\t\t]\n\t\t\t: [\n\t\t\t\t\t`Keep searches scoped and purpose-driven: discover paths first, pass an explicit root and filters, and prefer the bounded grep/find tools. Broad shell searches are rejected; use broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\" only for an unavoidable exhaustive scan, then inspect the returned file with bounded reads or narrower searches.`,\n\t\t\t\t],\n\t\tparameters: bashSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tcommand,\n\t\t\t\ttimeout,\n\t\t\t\tbroadSearch,\n\t\t\t}: { command: string; timeout?: number; broadSearch?: typeof BROAD_SEARCH_OUTPUT_ROUTE },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst searchScope = assessShellSearchScope(command, cwd);\n\t\t\tif (searchScope.kind === \"broad\" && broadSearch !== BROAD_SEARCH_OUTPUT_ROUTE) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Broad search blocked before execution: ${searchScope.reason}. Narrow the path, glob, type, or pattern; prefer the grep/find tool with explicit path/glob/limit. If an exhaustive scan is required, retry with broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\"; Pi will keep its output out of context and return a managed file path for bounded read or search follow-up.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst routeBroadSearchOutput = searchScope.kind === \"broad\";\n\t\t\tlet outputProjector =\n\t\t\t\trouteBroadSearchOutput || commandPrefix || spawnHook ? undefined : createShellOutputProjector(command);\n\t\t\tconst output = new OutputAccumulator({\n\t\t\t\ttempFilePrefix: `pi-${toolName}`,\n\t\t\t\ttempDirectory: options?.outputDirectory,\n\t\t\t\tpersistAllOutput: routeBroadSearchOutput,\n\t\t\t\tmaxPersistedBytes: routeBroadSearchOutput ? BROAD_SEARCH_MAX_PERSISTED_BYTES : undefined,\n\t\t\t});\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.previewSnapshot(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES, {\n\t\t\t\t\tpersistIfFullTruncated: true,\n\t\t\t\t});\n\t\t\t\tif (routeBroadSearchOutput) {\n\t\t\t\t\tconst notice = snapshot.fullOutputPath\n\t\t\t\t\t\t? `Broad search running. Output is being routed to ${snapshot.fullOutputPath}`\n\t\t\t\t\t\t: \"Broad search running. Output is being routed to a managed file\";\n\t\t\t\t\tonUpdate({\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: notice }],\n\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\t\tpersistedOutputTruncated: snapshot.persistedOutputTruncated,\n\t\t\t\t\t\t\tpersistedOutputBytes: snapshot.persistedOutputBytes,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst preview = {\n\t\t\t\t\tcontent: snapshot.content.replace(/\\r/g, \"\"),\n\t\t\t\t\tskippedLines: Math.max(0, snapshot.truncation.totalLines - snapshot.truncation.outputLines),\n\t\t\t\t};\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: preview.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\tpreview,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\toutput.append(data);\n\t\t\t\tif (outputProjector) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\toutputProjector.append(data);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Projection is opportunistic. Raw output remains authoritative.\n\t\t\t\t\t\toutputProjector = undefined;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async (persistAlways = false) => {\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\treturn output.snapshot({ persistIfTruncated: true, persistAlways });\n\t\t\t};\n\n\t\t\tconst finishProjection = (exitCode: number | null): ShellOutputProjection | undefined => {\n\t\t\t\tif (!outputProjector) return undefined;\n\t\t\t\ttry {\n\t\t\t\t\treturn outputProjector.finish(exitCode);\n\t\t\t\t} catch {\n\t\t\t\t\toutputProjector = undefined;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst formatOutput = (\n\t\t\t\tsnapshot: Awaited<ReturnType<typeof finishOutput>>,\n\t\t\t\temptyText = \"(no output)\",\n\t\t\t\tprojection?: ShellOutputProjection,\n\t\t\t) => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tif (routeBroadSearchOutput) {\n\t\t\t\t\tif (snapshot.fullOutputPath) {\n\t\t\t\t\t\tconst persistenceNotice = snapshot.persistedOutputTruncated\n\t\t\t\t\t\t\t? `The managed ${formatSize(BROAD_SEARCH_MAX_PERSISTED_BYTES)} file limit was reached; later output was discarded.`\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: `Broad search output routed to ${snapshot.fullOutputPath}. ${persistenceNotice} Inspect it with bounded read offsets or a narrower search.`,\n\t\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t\t...(truncation.truncated ? { truncation } : {}),\n\t\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\t\tpersistedOutputTruncated: snapshot.persistedOutputTruncated,\n\t\t\t\t\t\t\t\tpersistedOutputBytes: snapshot.persistedOutputBytes,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst boundedTail = snapshot.content.replace(/\\r/g, \"\") || emptyText;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: `Broad search output could not be routed to a managed file${snapshot.fullOutputError ? `: ${snapshot.fullOutputError}` : \"\"}. Bounded tail:\\n${boundedTail}`,\n\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t...(truncation.truncated ? { truncation } : {}),\n\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError ?? \"managed output file unavailable\",\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet text = (projection?.content ?? snapshot.content).replace(/\\r/g, \"\") || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tconst preview = projection\n\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\tconst lines = projection.content.split(\"\\n\");\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: lines.slice(-BASH_PREVIEW_LINES).join(\"\\n\"),\n\t\t\t\t\t\t\t\tskippedLines: Math.max(0, lines.length - BASH_PREVIEW_LINES),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t})()\n\t\t\t\t\t: output.preview(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES);\n\t\t\t\tconst fullOutputNotice = snapshot.fullOutputPath\n\t\t\t\t\t? `Full output: ${snapshot.fullOutputPath}`\n\t\t\t\t\t: snapshot.fullOutputError\n\t\t\t\t\t\t? `Full output unavailable: ${snapshot.fullOutputError}`\n\t\t\t\t\t\t: \"Full output unavailable\";\n\t\t\t\tif (truncation.truncated || preview.skippedLines > 0 || projection) {\n\t\t\t\t\tdetails = { preview };\n\t\t\t\t}\n\t\t\t\tif (snapshot.fullOutputPath || snapshot.fullOutputError) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\ttruncation,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t\tif (!projection) {\n\t\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). ${fullOutputNotice}]`;\n\t\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. ${fullOutputNotice}]`;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). ${fullOutputNotice}]`;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (projection) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\toutputProjection: {\n\t\t\t\t\t\t\tkind: projection.kind,\n\t\t\t\t\t\t\tinputLines: projection.inputLines,\n\t\t\t\t\t\t\tinputBytes: projection.inputBytes,\n\t\t\t\t\t\t\toutputLines: projection.outputLines,\n\t\t\t\t\t\t\toutputBytes: projection.outputBytes,\n\t\t\t\t\t\t\tomittedLines: projection.omittedLines,\n\t\t\t\t\t\t\tcollapsedPassingLines: projection.collapsedPassingLines,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tconst passingNotice =\n\t\t\t\t\t\tprojection.collapsedPassingLines > 0\n\t\t\t\t\t\t\t? ` ${projection.collapsedPassingLines} passing/progress lines collapsed.`\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\ttext += `\\n\\n[Test output filtered: retained ${projection.inputLines - projection.omittedLines} of ${projection.inputLines} lines.${passingNotice} ${fullOutputNotice}]`;\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst effectiveTimeoutSeconds =\n\t\t\t\ttypeof timeout === \"number\" && Number.isFinite(timeout) && timeout > 0\n\t\t\t\t\t? resolveCommandTimeoutSeconds(timeout)\n\t\t\t\t\t: (commandTimeoutMsOverride ?? DEFAULT_COMMAND_TIMEOUT_SECONDS * 1000) / 1000;\n\n\t\t\ttry {\n\t\t\t\tif (canFilterCommand) {\n\t\t\t\t\tconst classification = classifyGitCommand(command, getShellEnv());\n\t\t\t\t\tif (classification.eligible && classification.subcommand) {\n\t\t\t\t\t\tconst res = await executeFilteredGit(\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tclassification.subcommand,\n\t\t\t\t\t\t\tclassification.globalOptions || [],\n\t\t\t\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t\t\t\t{ signal, timeout: effectiveTimeoutSeconds },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (res.exitCode !== -100) {\n\t\t\t\t\t\t\toutput.append(res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\"));\n\t\t\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\t\t\tif (res.exitCode !== 0) {\n\t\t\t\t\t\t\t\tconst { text: rawOutputText } = formatOutput(snapshot);\n\t\t\t\t\t\t\t\tthrow new Error(appendStatus(rawOutputText, `Command exited with code ${res.exitCode}`));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst details = snapshot.truncation.truncated\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttruncation: snapshot.truncation,\n\t\t\t\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: snapshot.fullOutputPath || snapshot.fullOutputError\n\t\t\t\t\t\t\t\t\t? { fullOutputPath: snapshot.fullOutputPath, fullOutputError: snapshot.fullOutputError }\n\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\treturn { content: [{ type: \"text\", text: res.output }], details };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet backendCommand = command;\n\t\t\t\tlet engineRoute = false;\n\t\t\t\tlet effectiveCwd = cwd;\n\t\t\t\tif (routesWindowsContract) {\n\t\t\t\t\tconst route = routeShellContract(command, contractPlatform, { pythonEngine: pythonEngineEnabled });\n\t\t\t\t\tif (route.kind === \"unsupported\") throw new Error(route.error);\n\t\t\t\t\tif (route.kind === \"python-engine\") engineRoute = true;\n\t\t\t\t\tbackendCommand = route.command;\n\t\t\t\t\t// The engine is the sole state mutator (D4); every Windows call — engine or PS\n\t\t\t\t\t// tier — reads the SAME session state so a `cd`/`export` in one call is observed\n\t\t\t\t\t// by the very next call regardless of which tier runs it.\n\t\t\t\t\teffectiveCwd = resolveEffectiveCwd(getOrCreateWindowsShellState(sessionKey), cwd);\n\t\t\t\t}\n\t\t\t\t// The engine executes the RAW Bash source unchanged: no commandPrefix (arbitrary\n\t\t\t\t// PowerShell setup would not parse as Bash grammar) and no PowerShell UTF-8 prefix.\n\t\t\t\tconst resolvedCommand = engineRoute\n\t\t\t\t\t? backendCommand\n\t\t\t\t\t: backendShell === \"powershell\"\n\t\t\t\t\t\t? prefixPowerShellCommand(commandPrefix ? `${commandPrefix}\\n${backendCommand}` : backendCommand)\n\t\t\t\t\t\t: commandPrefix\n\t\t\t\t\t\t\t? `${commandPrefix}\\n${backendCommand}`\n\t\t\t\t\t\t\t: backendCommand;\n\t\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, effectiveCwd, spawnHook);\n\t\t\t\tif (routesWindowsContract) {\n\t\t\t\t\tspawnContext.env = mergeEffectiveEnv(getOrCreateWindowsShellState(sessionKey), spawnContext.env);\n\t\t\t\t}\n\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\t// Shell commands cannot statically declare which files they mutate, so the\n\t\t\t\t\t// actual execution takes the coarse exclusive barrier: it waits for\n\t\t\t\t\t// in-flight edit/write mutations to drain and blocks new ones meanwhile.\n\t\t\t\t\tconst result = await withExclusiveMutationBarrier(() =>\n\t\t\t\t\t\t(engineRoute && engineOperations ? engineOperations : ops).exec(\n\t\t\t\t\t\t\tspawnContext.command,\n\t\t\t\t\t\t\tspawnContext.cwd,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\ttimeout: effectiveTimeoutSeconds,\n\t\t\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\t\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\t\t\t\tconst recovery =\n\t\t\t\t\t\t\tbackendShell === \"bash\"\n\t\t\t\t\t\t\t\t? \"re-run it with an explicit timeout, or run it in the background with '&'.\"\n\t\t\t\t\t\t\t\t: \"re-run it with an explicit timeout.\";\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tappendStatus(\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, ${recovery}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst candidateProjection = finishProjection(exitCode);\n\t\t\t\tconst snapshot = await finishOutput(candidateProjection !== undefined);\n\t\t\t\tconst projection = candidateProjection && snapshot.fullOutputPath ? candidateProjection : undefined;\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot, \"(no output)\", projection);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t\tawait output.closeTempFile();\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(formatBashCall(args, toolName));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(component, result as any, options, context.showImages);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined> {\n\tconst platform = options?.platform ?? process.platform;\n\treturn createShellToolDefinition(cwd, getPlatformShellToolName(platform), platform, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\treturn wrapToolDefinition(createBashToolDefinition(cwd, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAkB,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClF,OAAO,EACN,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,GAEV,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACtE,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uDAAuD,CAAC;AAC9F,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EACN,wBAAwB,EACxB,cAAc,EACd,WAAW,EAEX,uBAAuB,EACvB,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,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AI,CAAC;QACb,CAAC;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO;YAC5C,MAAM,SAAS,GACb,OAAO,CAAC,aAAuD,IAAI,IAAI,yBAAyB,EAAE,CAAC;YACrG,gCAAgC,CAAC,SAAS,EAAE,MAAa,EAAE,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;YACxF,SAAS,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB;IAEzB,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC;IACvD,OAAO,yBAAyB,CAAC,GAAG,EAAE,wBAAwB,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;AAC9F,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { type AgentTool, createSilenceWatchdog } from \"@caupulican/pi-agent-core\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n} from \"@caupulican/pi-agent-core/node\";\nimport { Container, Text, truncateToWidth } from \"@caupulican/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport {\n\tgetPlatformShellToolName,\n\tgetShellConfig,\n\tgetShellEnv,\n\ttype PlatformShellToolName,\n\tprefixPowerShellCommand,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withExclusiveMutationBarrier } from \"./file-mutation-queue.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./git-filter.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { assessShellSearchScope, BROAD_SEARCH_OUTPUT_ROUTE } from \"./search-command-guard.ts\";\nimport { routeShellContract } from \"./shell-contract-router.ts\";\nimport {\n\tcreateShellOutputProjector,\n\ttype ShellOutputProjection,\n\ttype ShellOutputProjectionDetails,\n} from \"./shell-output-projection.ts\";\nimport { acquirePersistentShellSession } from \"./shell-session.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { createWindowsShellEngineOperations, type WindowsShellEngineOptions } from \"./windows-shell-engine.ts\";\nimport { getOrCreateWindowsShellState, mergeEffectiveEnv, resolveEffectiveCwd } from \"./windows-shell-state.ts\";\n\n/** Low-level silence bound retained for direct shell-operation consumers. Agent tool calls always pass a wall-clock bound. */\nconst DEFAULT_COMMAND_SILENCE_MS = 600_000;\n/** Agent-facing wall-clock bound: continuously producing output must not make a command immortal. */\nexport const DEFAULT_COMMAND_TIMEOUT_SECONDS = 120;\nexport const MAX_COMMAND_TIMEOUT_SECONDS = 3600;\nconst MIN_COMMAND_TIMEOUT_SECONDS = 0.1;\nlet commandSilenceMsOverride: number | undefined;\nlet commandTimeoutMsOverride: number | undefined;\n\n/** Test hook: override the low-level silence threshold. Pass undefined to restore the default. */\nexport function setCommandSilenceMsForTests(ms: number | undefined): void {\n\tcommandSilenceMsOverride = ms;\n}\n\n/** Test hook: override the agent tool's default wall-clock bound. Pass undefined to restore it. */\nexport function setCommandTimeoutMsForTests(ms: number | undefined): void {\n\tcommandTimeoutMsOverride = ms;\n}\n\nexport function resolveCommandTimeoutSeconds(timeout: number | undefined): number {\n\tif (typeof timeout !== \"number\" || !Number.isFinite(timeout) || timeout <= 0) {\n\t\treturn DEFAULT_COMMAND_TIMEOUT_SECONDS;\n\t}\n\treturn Math.max(MIN_COMMAND_TIMEOUT_SECONDS, Math.min(timeout, MAX_COMMAND_TIMEOUT_SECONDS));\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(\n\t\tType.Number({\n\t\t\tdescription: `Wall-clock timeout in seconds. Defaults to ${DEFAULT_COMMAND_TIMEOUT_SECONDS}; positive overrides are capped at ${MAX_COMMAND_TIMEOUT_SECONDS}. Zero or negative values use the default.`,\n\t\t}),\n\t),\n\tbroadSearch: Type.Optional(\n\t\tType.Literal(BROAD_SEARCH_OUTPUT_ROUTE, {\n\t\t\tdescription:\n\t\t\t\t\"Explicit override for a broad rg/grep/find/fd scan that cannot be narrowed. The command runs, but its complete output is routed to a file and excluded from model context.\",\n\t\t}),\n\t),\n});\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\tfullOutputError?: string;\n\tpersistedOutputTruncated?: boolean;\n\tpersistedOutputBytes?: number;\n\tpreview?: {\n\t\tcontent: string;\n\t\tskippedLines: number;\n\t};\n\toutputProjection?: ShellOutputProjectionDetails;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\nfunction createLocalShellOperations(\n\tshellName: PlatformShellToolName,\n\toptions?: { shellPath?: string; sessionKey?: string },\n): BashOperations {\n\t// A session key selects the persistent per-agent backend. An explicit custom shell path keeps\n\t// per-command spawning: persistent sessions assume the resolved platform shell's flag set.\n\tconst sessionKey = options?.sessionKey;\n\tif (sessionKey !== undefined && !options?.shellPath) {\n\t\treturn {\n\t\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t\t}\n\t\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\t\tconst session = acquirePersistentShellSession(sessionKey, shellName);\n\t\t\t\tconst silenceMs = commandSilenceMsOverride ?? DEFAULT_COMMAND_SILENCE_MS;\n\t\t\t\tconst hasWallClock = timeout !== undefined && timeout > 0;\n\t\t\t\treturn session.exec(command, cwd, {\n\t\t\t\t\tonData,\n\t\t\t\t\tsignal,\n\t\t\t\t\tenv,\n\t\t\t\t\ttimeoutSeconds: hasWallClock ? timeout : undefined,\n\t\t\t\t\tsilenceMs: !hasWallClock && silenceMs > 0 ? silenceMs : undefined,\n\t\t\t\t});\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst { shell, args } = getShellConfig(options?.shellPath, shellName);\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\n\t\t\tconst child = spawn(shell, [...args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tconst terminationController = new AbortController();\n\t\t\tconst onAbort = () => terminationController.abort();\n\t\t\tlet silenceKilled = false;\n\t\t\tconst silenceMs = commandSilenceMsOverride ?? DEFAULT_COMMAND_SILENCE_MS;\n\t\t\tconst silenceWatchdog =\n\t\t\t\t(timeout === undefined || timeout <= 0) && silenceMs > 0\n\t\t\t\t\t? createSilenceWatchdog({\n\t\t\t\t\t\t\tsilenceMs,\n\t\t\t\t\t\t\tonSilence: () => {\n\t\t\t\t\t\t\t\tsilenceKilled = true;\n\t\t\t\t\t\t\t\tterminationController.abort();\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tconst onChunk = (data: Buffer) => {\n\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\tonData(data);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tchild.stdout?.on(\"data\", onChunk);\n\t\t\t\tchild.stderr?.on(\"data\", onChunk);\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\t\t\tsignal: terminationController.signal,\n\t\t\t\t\ttimeoutMs: timeout !== undefined && timeout > 0 ? timeout * 1000 : undefined,\n\t\t\t\t\tkillGraceMs: 2_000,\n\t\t\t\t});\n\t\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\t\tif (terminal.reason === \"timeout\") throw new Error(`timeout:${timeout}`);\n\t\t\t\tif (silenceKilled) throw new Error(`silence:${silenceMs / 1000}`);\n\t\t\t\treturn { exitCode: terminal.code };\n\t\t\t} finally {\n\t\t\t\tsilenceWatchdog?.disarm();\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string; sessionKey?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", options);\n}\n\n/** Create PowerShell operations using pi's built-in local execution backend. */\nexport function createLocalPowerShellOperations(options?: { shellPath?: string; sessionKey?: string }): BashOperations {\n\treturn createLocalShellOperations(\"powershell\", options);\n}\n\n/** Create the platform shell backend without requiring callers or the model to choose a shell. */\nexport function createLocalPlatformShellOperations(\n\toptions: {\n\t\tshellPath?: string;\n\t\tcommandPrefix?: string;\n\t\toperations?: BashOperations;\n\t\tsessionKey?: string;\n\t\t/** Route complex/state-mutating Bash constructs and portable builtins to the Python engine on Windows. Default: true. */\n\t\tpythonEngine?: boolean;\n\t\t/** Test/embedding hook: overrides the engine tier's runtime/spawn/state resolution. */\n\t\tengineOptions?: WindowsShellEngineOptions;\n\t} = {},\n\tplatform: NodeJS.Platform = process.platform,\n): BashOperations {\n\tconst operations =\n\t\toptions.operations ??\n\t\tcreateLocalShellOperations(getPlatformShellToolName(platform), {\n\t\t\tshellPath: options.shellPath,\n\t\t\tsessionKey: options.sessionKey,\n\t\t});\n\tconst pythonEngineEnabled = options.pythonEngine !== false;\n\t// One factory instance is one fallback tenant. Production agent sessions always pass their\n\t// stable key; standalone callers that omit it must never collapse into a process-global engine.\n\tconst engineSessionKey = options.sessionKey ?? `platform-shell-operations:${randomUUID()}`;\n\tconst engineOperations = createWindowsShellEngineOperations(engineSessionKey, options.engineOptions);\n\treturn {\n\t\tasync exec(command, cwd, execOptions) {\n\t\t\tlet resolvedCommand = command;\n\t\t\tlet resolvedCwd = cwd;\n\t\t\tlet resolvedExecOptions = execOptions;\n\t\t\tif (platform === \"win32\") {\n\t\t\t\tconst route = routeShellContract(command, platform, { pythonEngine: pythonEngineEnabled });\n\t\t\t\tif (route.kind === \"unsupported\") throw new Error(route.error);\n\t\t\t\t// The engine is the sole state mutator (D4); every Windows call — engine or PS\n\t\t\t\t// tier — reads the SAME session state so a `cd`/`export` in one call is observed\n\t\t\t\t// by the very next call regardless of which tier runs it.\n\t\t\t\tconst state = getOrCreateWindowsShellState(engineSessionKey);\n\t\t\t\tresolvedCwd = resolveEffectiveCwd(state, cwd);\n\t\t\t\tresolvedExecOptions = { ...execOptions, env: mergeEffectiveEnv(state, execOptions.env ?? getShellEnv()) };\n\t\t\t\tif (route.kind === \"python-engine\") {\n\t\t\t\t\t// The engine owns the state transition and resolves the original host cwd\n\t\t\t\t\t// exactly once. Passing the already state-adjusted cwd here would make the\n\t\t\t\t\t// engine mistake its own `cd` result for a host cwd change on the next call.\n\t\t\t\t\treturn engineOperations.exec(route.command, cwd, execOptions);\n\t\t\t\t}\n\t\t\t\tif (route.kind === \"powershell\") resolvedCommand = route.command;\n\t\t\t}\n\t\t\tif (options.commandPrefix) resolvedCommand = `${options.commandPrefix}\\n${resolvedCommand}`;\n\t\t\tif (platform === \"win32\") resolvedCommand = prefixPowerShellCommand(resolvedCommand);\n\t\t\treturn operations.exec(resolvedCommand, resolvedCwd, resolvedExecOptions);\n\t\t},\n\t};\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(command: string, cwd: string, spawnHook?: BashSpawnHook): BashSpawnContext {\n\tconst baseContext: BashSpawnContext = { command, cwd, env: { ...getShellEnv() } };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Platform used to choose the default backend and contract router. Defaults to process.platform. */\n\tplatform?: NodeJS.Platform;\n\t/** Custom operations for command execution. Default: local platform shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n\t/**\n\t * Stable key for this agent's persistent shell session. The host passes its per-agent key so\n\t * the session survives runtime reloads and user `!` commands share it; separately created\n\t * tool instances (subagents) auto-generate their own key and stay isolated.\n\t */\n\tsessionKey?: string;\n\t/** Route complex/state-mutating Bash constructs and portable builtins to the Python engine on Windows. Default: true. */\n\twindowsShellPythonEngine?: boolean;\n\t/** Test/embedding hook: overrides the engine tier's runtime/spawn/state resolution. */\n\twindowsShellEngineOptions?: WindowsShellEngineOptions;\n\t/** Test/embedding hook: override the managed directory used for complete command output. */\n\toutputDirectory?: string;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_PREVIEW_BYTES = 8 * 1024;\nconst BASH_UPDATE_THROTTLE_MS = 100;\nconst BROAD_SEARCH_MAX_PERSISTED_BYTES = 8 * 1024 * 1024;\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatBashCall(\n\targs: { command?: string; timeout?: number } | undefined,\n\tshellName: PlatformShellToolName,\n): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\tconst prompt = shellName === \"powershell\" ? \"PS>\" : \"$\";\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tconst renderPreview = !options.expanded ? result.details?.preview : undefined;\n\tlet output = (renderPreview ? renderPreview.content : getTextOutput(result as any, showImages)).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tconst fullOutputError = result.details?.fullOutputError;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tif (options.expanded) {\n\t\t\tconst styledOutput = output\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(output, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines.map((line) => theme.fg(\"toolOutput\", line));\n\t\t\t\t\t\tstate.cachedSkipped = (result.details?.preview?.skippedLines ?? 0) + preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath || fullOutputError) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t} else if (fullOutputError) {\n\t\t\twarnings.push(`Full output unavailable: ${fullOutputError}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n}\n\nfunction createShellToolDefinition(\n\tcwd: string,\n\tbackendShell: PlatformShellToolName,\n\tcontractPlatform: NodeJS.Platform,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined> {\n\tconst toolName = \"bash\";\n\tconst sessionKey = options?.sessionKey ?? `bash-tool:${randomUUID()}`;\n\tconst ops =\n\t\toptions?.operations ??\n\t\t(backendShell === \"powershell\"\n\t\t\t? createLocalPowerShellOperations({ shellPath: options?.shellPath, sessionKey })\n\t\t\t: createLocalBashOperations({ shellPath: options?.shellPath, sessionKey }));\n\tconst commandPrefix = options?.commandPrefix;\n\tconst spawnHook = options?.spawnHook;\n\tconst hasExecutionOverrides = Boolean(options?.operations || options?.shellPath || commandPrefix || spawnHook);\n\tconst canFilterCommand = !hasExecutionOverrides;\n\tconst routesWindowsContract = contractPlatform === \"win32\";\n\tconst pythonEngineEnabled = options?.windowsShellPythonEngine !== false;\n\tconst engineOperations = routesWindowsContract\n\t\t? createWindowsShellEngineOperations(sessionKey, options?.windowsShellEngineOptions)\n\t\t: undefined;\n\tconst contractDescription = routesWindowsContract\n\t\t? \"Execute Pi's stable Bash-like command contract in a persistent per-agent shell session (current directory and environment variables persist across calls, including across the PowerShell and Python engine tiers). On Windows, a deterministic router converts simple commands directly to PowerShell and routes word-list and arithmetic for loops, break/continue, portable builtins such as printf, pipelines, redirection, expansion, chaining, and state-mutating commands (cd/export/unset) through a bundled Python engine that implements the supported Bash grammar; named unsupported constructs (job control, process substitution, heredocs, nested shells, and similar) fail closed instead of being guessed.\"\n\t\t: \"Execute a Bash command in a persistent per-agent shell session: the current directory and environment variables persist across calls, and a timed-out or aborted command resets the session.\";\n\treturn {\n\t\tname: toolName,\n\t\tlabel: toolName,\n\t\tdescription: `${contractDescription} Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a managed file. Recognized test runners return a bounded failure/summary projection when it is materially smaller, with exact output saved to a managed file. Broad rg/grep/find/fd scans are rejected before execution; when an exhaustive scan is unavoidable, set broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\" to route all output to a managed file instead of model context. Commands have a ${DEFAULT_COMMAND_TIMEOUT_SECONDS}-second wall-clock default, including commands that keep producing output; use a positive timeout only when a scoped operation justifies a larger bound (maximum ${MAX_COMMAND_TIMEOUT_SECONDS} seconds).`,\n\t\tpromptSnippet: routesWindowsContract\n\t\t\t? \"Execute Bash-like commands; Pi routes them deterministically to PowerShell or a bundled Python engine on Windows\"\n\t\t\t: \"Execute Bash commands (ls, grep, find, etc.)\",\n\t\tpromptGuidelines: routesWindowsContract\n\t\t\t? [\n\t\t\t\t\t\"Use ordinary Bash-like commands on Windows; do not write PowerShell or ask the user to choose a shell.\",\n\t\t\t\t\t\"Word-list and arithmetic for loops, nested break/continue, printf and the documented portable builtins, pipelines, redirection, expansion (variables, command substitution, globs), chaining (&&/||/;), and cd/export/unset are supported and routed to a bundled Python engine; shell arithmetic expansion outside a for header, job control, process substitution, heredocs, nested shells, and other named constructs fail closed with an actionable message instead of being guessed.\",\n\t\t\t\t\t\"Working directory and environment changes from cd/export/unset persist across subsequent bash calls, including calls that route to the PowerShell tier.\",\n\t\t\t\t\t\"Supported Bash-like file commands are converted with literal-path operations; verify targets before recursive rm, cp, or mv calls.\",\n\t\t\t\t\t`Keep searches scoped and purpose-driven: discover paths first, pass an explicit root and filters, and prefer the bounded grep/find tools. Broad shell searches are rejected; use broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\" only for an unavoidable exhaustive scan, then inspect the returned file with bounded reads or narrower searches.`,\n\t\t\t\t]\n\t\t\t: [\n\t\t\t\t\t`Keep searches scoped and purpose-driven: discover paths first, pass an explicit root and filters, and prefer the bounded grep/find tools. Broad shell searches are rejected; use broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\" only for an unavoidable exhaustive scan, then inspect the returned file with bounded reads or narrower searches.`,\n\t\t\t\t],\n\t\tparameters: bashSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tcommand,\n\t\t\t\ttimeout,\n\t\t\t\tbroadSearch,\n\t\t\t}: { command: string; timeout?: number; broadSearch?: typeof BROAD_SEARCH_OUTPUT_ROUTE },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst searchScope = assessShellSearchScope(command, cwd);\n\t\t\tif (searchScope.kind === \"broad\" && broadSearch !== BROAD_SEARCH_OUTPUT_ROUTE) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Broad search blocked before execution: ${searchScope.reason}. Narrow the path, glob, type, or pattern; prefer the grep/find tool with explicit path/glob/limit. If an exhaustive scan is required, retry with broadSearch=\"${BROAD_SEARCH_OUTPUT_ROUTE}\"; Pi will keep its output out of context and return a managed file path for bounded read or search follow-up.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst routeBroadSearchOutput = searchScope.kind === \"broad\";\n\t\t\tlet outputProjector =\n\t\t\t\trouteBroadSearchOutput || commandPrefix || spawnHook ? undefined : createShellOutputProjector(command);\n\t\t\tconst output = new OutputAccumulator({\n\t\t\t\ttempFilePrefix: `pi-${toolName}`,\n\t\t\t\ttempDirectory: options?.outputDirectory,\n\t\t\t\tpersistAllOutput: routeBroadSearchOutput,\n\t\t\t\tmaxPersistedBytes: routeBroadSearchOutput ? BROAD_SEARCH_MAX_PERSISTED_BYTES : undefined,\n\t\t\t});\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.previewSnapshot(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES, {\n\t\t\t\t\tpersistIfFullTruncated: true,\n\t\t\t\t});\n\t\t\t\tif (routeBroadSearchOutput) {\n\t\t\t\t\tconst notice = snapshot.fullOutputPath\n\t\t\t\t\t\t? `Broad search running. Output is being routed to ${snapshot.fullOutputPath}`\n\t\t\t\t\t\t: \"Broad search running. Output is being routed to a managed file\";\n\t\t\t\t\tonUpdate({\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: notice }],\n\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\t\tpersistedOutputTruncated: snapshot.persistedOutputTruncated,\n\t\t\t\t\t\t\tpersistedOutputBytes: snapshot.persistedOutputBytes,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst preview = {\n\t\t\t\t\tcontent: snapshot.content.replace(/\\r/g, \"\"),\n\t\t\t\t\tskippedLines: Math.max(0, snapshot.truncation.totalLines - snapshot.truncation.outputLines),\n\t\t\t\t};\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: preview.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\tpreview,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\toutput.append(data);\n\t\t\t\tif (outputProjector) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\toutputProjector.append(data);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Projection is opportunistic. Raw output remains authoritative.\n\t\t\t\t\t\toutputProjector = undefined;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async (persistAlways = false) => {\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\treturn output.snapshot({ persistIfTruncated: true, persistAlways });\n\t\t\t};\n\n\t\t\tconst finishProjection = (exitCode: number | null): ShellOutputProjection | undefined => {\n\t\t\t\tif (!outputProjector) return undefined;\n\t\t\t\ttry {\n\t\t\t\t\treturn outputProjector.finish(exitCode);\n\t\t\t\t} catch {\n\t\t\t\t\toutputProjector = undefined;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst formatOutput = (\n\t\t\t\tsnapshot: Awaited<ReturnType<typeof finishOutput>>,\n\t\t\t\temptyText = \"(no output)\",\n\t\t\t\tprojection?: ShellOutputProjection,\n\t\t\t) => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tif (routeBroadSearchOutput) {\n\t\t\t\t\tif (snapshot.fullOutputPath) {\n\t\t\t\t\t\tconst persistenceNotice = snapshot.persistedOutputTruncated\n\t\t\t\t\t\t\t? `The managed ${formatSize(BROAD_SEARCH_MAX_PERSISTED_BYTES)} file limit was reached; later output was discarded.`\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: `Broad search output routed to ${snapshot.fullOutputPath}. ${persistenceNotice} Inspect it with bounded read offsets or a narrower search.`,\n\t\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t\t...(truncation.truncated ? { truncation } : {}),\n\t\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\t\tpersistedOutputTruncated: snapshot.persistedOutputTruncated,\n\t\t\t\t\t\t\t\tpersistedOutputBytes: snapshot.persistedOutputBytes,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst boundedTail = snapshot.content.replace(/\\r/g, \"\") || emptyText;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: `Broad search output could not be routed to a managed file${snapshot.fullOutputError ? `: ${snapshot.fullOutputError}` : \"\"}. Bounded tail:\\n${boundedTail}`,\n\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t...(truncation.truncated ? { truncation } : {}),\n\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError ?? \"managed output file unavailable\",\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet text = (projection?.content ?? snapshot.content).replace(/\\r/g, \"\") || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tconst preview = projection\n\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\tconst lines = projection.content.split(\"\\n\");\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: lines.slice(-BASH_PREVIEW_LINES).join(\"\\n\"),\n\t\t\t\t\t\t\t\tskippedLines: Math.max(0, lines.length - BASH_PREVIEW_LINES),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t})()\n\t\t\t\t\t: output.preview(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES);\n\t\t\t\tconst fullOutputNotice = snapshot.fullOutputPath\n\t\t\t\t\t? `Full output: ${snapshot.fullOutputPath}`\n\t\t\t\t\t: snapshot.fullOutputError\n\t\t\t\t\t\t? `Full output unavailable: ${snapshot.fullOutputError}`\n\t\t\t\t\t\t: \"Full output unavailable\";\n\t\t\t\tif (truncation.truncated || preview.skippedLines > 0 || projection) {\n\t\t\t\t\tdetails = { preview };\n\t\t\t\t}\n\t\t\t\tif (snapshot.fullOutputPath || snapshot.fullOutputError) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\ttruncation,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t\tif (!projection) {\n\t\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). ${fullOutputNotice}]`;\n\t\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. ${fullOutputNotice}]`;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). ${fullOutputNotice}]`;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (projection) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\toutputProjection: {\n\t\t\t\t\t\t\tkind: projection.kind,\n\t\t\t\t\t\t\tinputLines: projection.inputLines,\n\t\t\t\t\t\t\tinputBytes: projection.inputBytes,\n\t\t\t\t\t\t\toutputLines: projection.outputLines,\n\t\t\t\t\t\t\toutputBytes: projection.outputBytes,\n\t\t\t\t\t\t\tomittedLines: projection.omittedLines,\n\t\t\t\t\t\t\tcollapsedPassingLines: projection.collapsedPassingLines,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t\tconst passingNotice =\n\t\t\t\t\t\tprojection.collapsedPassingLines > 0\n\t\t\t\t\t\t\t? ` ${projection.collapsedPassingLines} passing/progress lines collapsed.`\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\ttext += `\\n\\n[Test output filtered: retained ${projection.inputLines - projection.omittedLines} of ${projection.inputLines} lines.${passingNotice} ${fullOutputNotice}]`;\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst effectiveTimeoutSeconds =\n\t\t\t\ttypeof timeout === \"number\" && Number.isFinite(timeout) && timeout > 0\n\t\t\t\t\t? resolveCommandTimeoutSeconds(timeout)\n\t\t\t\t\t: (commandTimeoutMsOverride ?? DEFAULT_COMMAND_TIMEOUT_SECONDS * 1000) / 1000;\n\n\t\t\ttry {\n\t\t\t\tif (canFilterCommand) {\n\t\t\t\t\tconst classification = classifyGitCommand(command, getShellEnv());\n\t\t\t\t\tif (classification.eligible && classification.subcommand) {\n\t\t\t\t\t\tconst res = await executeFilteredGit(\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tclassification.subcommand,\n\t\t\t\t\t\t\tclassification.globalOptions || [],\n\t\t\t\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t\t\t\t{ signal, timeout: effectiveTimeoutSeconds },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (res.exitCode !== -100) {\n\t\t\t\t\t\t\toutput.append(res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\"));\n\t\t\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\t\t\tif (res.exitCode !== 0) {\n\t\t\t\t\t\t\t\tconst { text: rawOutputText } = formatOutput(snapshot);\n\t\t\t\t\t\t\t\tthrow new Error(appendStatus(rawOutputText, `Command exited with code ${res.exitCode}`));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst details = snapshot.truncation.truncated\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttruncation: snapshot.truncation,\n\t\t\t\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: snapshot.fullOutputPath || snapshot.fullOutputError\n\t\t\t\t\t\t\t\t\t? { fullOutputPath: snapshot.fullOutputPath, fullOutputError: snapshot.fullOutputError }\n\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\treturn { content: [{ type: \"text\", text: res.output }], details };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet backendCommand = command;\n\t\t\t\tlet engineRoute = false;\n\t\t\t\tlet effectiveCwd = cwd;\n\t\t\t\tif (routesWindowsContract) {\n\t\t\t\t\tconst route = routeShellContract(command, contractPlatform, { pythonEngine: pythonEngineEnabled });\n\t\t\t\t\tif (route.kind === \"unsupported\") throw new Error(route.error);\n\t\t\t\t\tif (route.kind === \"python-engine\") engineRoute = true;\n\t\t\t\t\tbackendCommand = route.command;\n\t\t\t\t\t// The engine is the sole state mutator (D4); every Windows call — engine or PS\n\t\t\t\t\t// tier — reads the SAME session state so a `cd`/`export` in one call is observed\n\t\t\t\t\t// by the very next call regardless of which tier runs it.\n\t\t\t\t\teffectiveCwd = resolveEffectiveCwd(getOrCreateWindowsShellState(sessionKey), cwd);\n\t\t\t\t}\n\t\t\t\t// The engine executes the RAW Bash source unchanged: no commandPrefix (arbitrary\n\t\t\t\t// PowerShell setup would not parse as Bash grammar) and no PowerShell UTF-8 prefix.\n\t\t\t\tconst resolvedCommand = engineRoute\n\t\t\t\t\t? backendCommand\n\t\t\t\t\t: backendShell === \"powershell\"\n\t\t\t\t\t\t? prefixPowerShellCommand(commandPrefix ? `${commandPrefix}\\n${backendCommand}` : backendCommand)\n\t\t\t\t\t\t: commandPrefix\n\t\t\t\t\t\t\t? `${commandPrefix}\\n${backendCommand}`\n\t\t\t\t\t\t\t: backendCommand;\n\t\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, effectiveCwd, spawnHook);\n\t\t\t\tif (routesWindowsContract) {\n\t\t\t\t\tspawnContext.env = mergeEffectiveEnv(getOrCreateWindowsShellState(sessionKey), spawnContext.env);\n\t\t\t\t}\n\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\t// Shell commands cannot statically declare which files they mutate, so the\n\t\t\t\t\t// actual execution takes the coarse exclusive barrier: it waits for\n\t\t\t\t\t// in-flight edit/write mutations to drain and blocks new ones meanwhile.\n\t\t\t\t\tconst result = await withExclusiveMutationBarrier(() =>\n\t\t\t\t\t\t(engineRoute && engineOperations ? engineOperations : ops).exec(\n\t\t\t\t\t\t\tspawnContext.command,\n\t\t\t\t\t\t\tspawnContext.cwd,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\ttimeout: effectiveTimeoutSeconds,\n\t\t\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\t\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\t\t\t\tconst recovery =\n\t\t\t\t\t\t\tbackendShell === \"bash\"\n\t\t\t\t\t\t\t\t? \"re-run it with an explicit timeout, or run it in the background with '&'.\"\n\t\t\t\t\t\t\t\t: \"re-run it with an explicit timeout.\";\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tappendStatus(\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, ${recovery}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst candidateProjection = finishProjection(exitCode);\n\t\t\t\tconst snapshot = await finishOutput(candidateProjection !== undefined);\n\t\t\t\tconst projection = candidateProjection && snapshot.fullOutputPath ? candidateProjection : undefined;\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot, \"(no output)\", projection);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t\tawait output.closeTempFile();\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(formatBashCall(args, toolName));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(component, result as any, options, context.showImages);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined> {\n\tconst platform = options?.platform ?? process.platform;\n\treturn createShellToolDefinition(cwd, getPlatformShellToolName(platform), platform, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\treturn wrapToolDefinition(createBashToolDefinition(cwd, options));\n}\n"]}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export declare function detectLineEnding(content: string): "\r\n" | "\n";
|
|
6
6
|
export declare function normalizeToLF(text: string): string;
|
|
7
|
+
export declare function digestNormalizedEditSource(content: string): string;
|
|
7
8
|
export declare function restoreLineEndings(text: string, ending: "\r\n" | "\n"): string;
|
|
8
9
|
/**
|
|
9
10
|
* Normalize text for fuzzy matching. Applies progressive transformations:
|
|
@@ -94,6 +95,7 @@ export interface EditDiffError {
|
|
|
94
95
|
}
|
|
95
96
|
export interface EditPlannedDiffResult extends EditDiffResult {
|
|
96
97
|
plan: EditMatchPlan;
|
|
98
|
+
sourceDigest: string;
|
|
97
99
|
}
|
|
98
100
|
/**
|
|
99
101
|
* Compute the diff for one or more edit operations without applying them.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,M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,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,qBAAqB,GAAG,aAAa,CAAC,CA8BhD;AAED,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,IAAI,EAAE,EACb,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAIzC;AAED;;;GAGG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Shared diff computation utilities for the edit tool.
|
|
3
3
|
* Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).
|
|
4
4
|
*/
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
5
6
|
import * as Diff from "diff";
|
|
6
7
|
import { constants } from "fs";
|
|
7
8
|
import { access, readFile } from "fs/promises";
|
|
@@ -18,6 +19,9 @@ export function detectLineEnding(content) {
|
|
|
18
19
|
export function normalizeToLF(text) {
|
|
19
20
|
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
20
21
|
}
|
|
22
|
+
export function digestNormalizedEditSource(content) {
|
|
23
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
24
|
+
}
|
|
21
25
|
export function restoreLineEndings(text, ending) {
|
|
22
26
|
return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
|
|
23
27
|
}
|
|
@@ -443,7 +447,11 @@ export async function computeEditsPlannedDiff(path, edits, cwd) {
|
|
|
443
447
|
const plan = planEditsToNormalizedContent(normalizedContent, edits, path);
|
|
444
448
|
const { baseContent, newContent } = applyEditMatchPlan(normalizedContent, plan, path);
|
|
445
449
|
// Generate the diff
|
|
446
|
-
return {
|
|
450
|
+
return {
|
|
451
|
+
...generateDiffString(baseContent, newContent),
|
|
452
|
+
plan,
|
|
453
|
+
sourceDigest: digestNormalizedEditSource(normalizedContent),
|
|
454
|
+
};
|
|
447
455
|
}
|
|
448
456
|
catch (err) {
|
|
449
457
|
return { error: err instanceof Error ? err.message : String(err) };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff.js","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC/C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxC,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IAC9B,IAAI,OAAO,KAAK,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IAChC,OAAO,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,IAAY;IACzC,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACzD,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,MAAqB;IACrE,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,C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IAAI,OAAO,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IACrC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,EAAE,CAAC;AACzE,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACpC,IAAY,EACZ,OAAe,EACf,OAAe,EACf,GAAW;IAEX,OAAO,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/**\n * Shared diff computation utilities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\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 normalizeFuzzyCharacters(text).replace(/[^\\S\\n]+(?=\\n|$)/gu, \"\");\n}\n\nfunction normalizeFuzzyCharacters(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\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/** The original content replacements should be applied to. */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n\t/** Inclusive 1-based line bounds from the read that supplied oldText. */\n\trange?: EditRange;\n}\n\nexport interface EditRange {\n\tstartLine: number;\n\tendLine: number;\n}\n\ninterface PlannedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n\texpectedText: string;\n}\n\nexport interface EditMatchPlan {\n\t/** Length of the LF-normalized source against which this plan was validated. */\n\tbaseLength: number;\n\teditCount: number;\n\t/** Compact, source-ordered replacement spans; the source body is not retained. */\n\tedits: readonly PlannedEdit[];\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 * Fuzzy matching searches normalized text, but returned spans still refer to\n * the original content so replacement does not normalize unrelated text.\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\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: content,\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 countExactOccurrences(content: string, oldText: string): number {\n\tif (oldText.length === 0) return 0;\n\tlet count = 0;\n\tlet searchFrom = 0;\n\twhile (searchFrom <= content.length - oldText.length) {\n\t\tconst index = content.indexOf(oldText, searchFrom);\n\t\tif (index === -1) break;\n\t\tcount++;\n\t\tsearchFrom = index + 1;\n\t}\n\treturn count;\n}\n\nfunction getLineStarts(content: string): number[] {\n\tconst starts = [0];\n\tfor (let i = 0; i < content.length; i++) {\n\t\tif (content[i] === \"\\n\") starts.push(i + 1);\n\t}\n\treturn starts;\n}\n\nfunction lineColumnAt(lineStarts: number[], index: number): { lineIndex: number; column: number } {\n\tlet low = 0;\n\tlet high = lineStarts.length - 1;\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tif (lineStarts[mid] <= index) low = mid + 1;\n\t\telse high = mid - 1;\n\t}\n\tconst lineIndex = Math.max(0, high);\n\treturn { lineIndex, column: index - lineStarts[lineIndex] };\n}\n\nfunction lineTextAt(content: string, lineStarts: number[], lineIndex: number): string {\n\tconst start = lineStarts[lineIndex];\n\tconst nextStart = lineStarts[lineIndex + 1] ?? content.length;\n\tconst end = nextStart > start && content[nextStart - 1] === \"\\n\" ? nextStart - 1 : nextStart;\n\treturn content.slice(start, end);\n}\n\nfunction normalizedColumnToOriginalColumn(line: string, normalizedColumn: number): number {\n\tif (normalizedColumn <= 0) return 0;\n\tconst boundaries = [0];\n\tfor (let index = 0; index < line.length; ) {\n\t\tconst codePoint = line.codePointAt(index);\n\t\tindex += codePoint !== undefined && codePoint > 0xffff ? 2 : 1;\n\t\tboundaries.push(index);\n\t}\n\n\tlet low = 1;\n\tlet high = boundaries.length - 1;\n\twhile (low < high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tif (normalizeForFuzzyMatch(line.slice(0, boundaries[mid])).length >= normalizedColumn) high = mid;\n\t\telse low = mid + 1;\n\t}\n\treturn boundaries[low] ?? line.length;\n}\n\nfunction mapFuzzySpanToOriginal(\n\toriginalContent: string,\n\toriginalLineStarts: number[],\n\tfuzzyLineStarts: number[],\n\tnormalizedIndex: number,\n\tnormalizedLength: number,\n): { index: number; length: number } {\n\tconst start = lineColumnAt(fuzzyLineStarts, normalizedIndex);\n\tconst end = lineColumnAt(fuzzyLineStarts, normalizedIndex + normalizedLength);\n\tconst startLine = lineTextAt(originalContent, originalLineStarts, start.lineIndex);\n\tconst endLine = lineTextAt(originalContent, originalLineStarts, end.lineIndex);\n\tconst originalStart =\n\t\toriginalLineStarts[start.lineIndex] + normalizedColumnToOriginalColumn(startLine, start.column);\n\tconst originalEnd = originalLineStarts[end.lineIndex] + normalizedColumnToOriginalColumn(endLine, end.column);\n\treturn { index: originalStart, length: originalEnd - originalStart };\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number, range?: EditRange): Error {\n\tconst rangeSuffix = range ? ` within lines ${range.startLine}-${range.endLine}` : \"\";\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}${rangeSuffix}. 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}${rangeSuffix}. 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\ninterface MatchWindow {\n\tstart: number;\n\tend: number;\n}\n\nfunction validateRange(\n\trange: EditRange | undefined,\n\tlineStarts: number[] | undefined,\n\tcontentLength: number,\n\tpath: string,\n\teditIndex: number,\n\ttotalEdits: number,\n): MatchWindow {\n\tif (!range) return { start: 0, end: contentLength };\n\tconst label = totalEdits === 1 ? \"range\" : `edits[${editIndex}].range`;\n\tif (\n\t\t!Number.isSafeInteger(range.startLine) ||\n\t\t!Number.isSafeInteger(range.endLine) ||\n\t\trange.startLine < 1 ||\n\t\trange.endLine < range.startLine\n\t) {\n\t\tthrow new Error(`${label} in ${path} must contain inclusive positive line numbers with startLine <= endLine.`);\n\t}\n\tif (!lineStarts || range.endLine > lineStarts.length) {\n\t\tthrow new Error(`${label} in ${path} exceeds the file's ${lineStarts?.length ?? 0} lines.`);\n\t}\n\treturn {\n\t\tstart: lineStarts[range.startLine - 1],\n\t\tend: lineStarts[range.endLine] ?? contentLength,\n\t};\n}\n\nfunction findWithin(content: string, oldText: string, window: MatchWindow): number {\n\tif (oldText.length === 0 || oldText.length > window.end - window.start) return -1;\n\tconst index = content.indexOf(oldText, window.start);\n\treturn index !== -1 && index + oldText.length <= window.end ? index : -1;\n}\n\nfunction rangesOverlap(previous: PlannedEdit, current: PlannedEdit): boolean {\n\treturn previous.matchIndex + previous.matchLength > current.matchIndex;\n}\n\n/**\n * Match and validate one or more replacements against LF-normalized content.\n *\n * The returned plan retains only the validated spans and their replacement\n * text. Exact matching uses native substring search, bounded by optional line\n * ranges, while uniqueness is still proven across the whole source.\n */\nexport function planEditsToNormalizedContent(normalizedContent: string, edits: Edit[], path: string): EditMatchPlan {\n\tlet originalLineStarts: number[] | undefined;\n\tlet fuzzyContent: string | undefined;\n\tlet fuzzyLineStarts: number[] | undefined;\n\tconst needsLineStarts = edits.some((edit) => edit.range !== undefined);\n\tif (needsLineStarts) originalLineStarts = getLineStarts(normalizedContent);\n\n\tconst matchedEdits: PlannedEdit[] = [];\n\tfor (let i = 0; i < edits.length; i++) {\n\t\tconst sourceEdit = edits[i];\n\t\tconst oldText = normalizeToLF(sourceEdit.oldText);\n\t\tconst newText = normalizeToLF(sourceEdit.newText);\n\t\tif (oldText.length === 0) throw getEmptyOldTextError(path, i, edits.length);\n\n\t\tconst exactWindow = validateRange(\n\t\t\tsourceEdit.range,\n\t\t\toriginalLineStarts,\n\t\t\tnormalizedContent.length,\n\t\t\tpath,\n\t\t\ti,\n\t\t\tedits.length,\n\t\t);\n\t\tlet matchIndex = findWithin(normalizedContent, oldText, exactWindow);\n\t\tlet matchLength = oldText.length;\n\t\tlet occurrences: number;\n\n\t\tif (matchIndex !== -1) {\n\t\t\toccurrences = countExactOccurrences(normalizedContent, oldText);\n\t\t} else {\n\t\t\tfuzzyContent ??= normalizeForFuzzyMatch(normalizedContent);\n\t\t\tfuzzyLineStarts ??= getLineStarts(fuzzyContent);\n\t\t\toriginalLineStarts ??= getLineStarts(normalizedContent);\n\t\t\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\t\t\tconst fuzzyWindow = validateRange(\n\t\t\t\tsourceEdit.range,\n\t\t\t\tfuzzyLineStarts,\n\t\t\t\tfuzzyContent.length,\n\t\t\t\tpath,\n\t\t\t\ti,\n\t\t\t\tedits.length,\n\t\t\t);\n\t\t\tconst fuzzyIndex = findWithin(fuzzyContent, fuzzyOldText, fuzzyWindow);\n\t\t\tif (fuzzyIndex === -1) throw getNotFoundError(path, i, edits.length, sourceEdit.range);\n\t\t\toccurrences = countExactOccurrences(fuzzyContent, fuzzyOldText);\n\t\t\tconst replacementSpan = mapFuzzySpanToOriginal(\n\t\t\t\tnormalizedContent,\n\t\t\t\toriginalLineStarts,\n\t\t\t\tfuzzyLineStarts,\n\t\t\t\tfuzzyIndex,\n\t\t\t\tfuzzyOldText.length,\n\t\t\t);\n\t\t\tmatchIndex = replacementSpan.index;\n\t\t\tmatchLength = replacementSpan.length;\n\t\t}\n\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, edits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex,\n\t\t\tmatchLength,\n\t\t\tnewText,\n\t\t\texpectedText: normalizedContent.slice(matchIndex, matchIndex + matchLength),\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 (rangesOverlap(previous, current)) {\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\treturn { baseLength: normalizedContent.length, editCount: edits.length, edits: matchedEdits };\n}\n\n/** Apply a validated match plan to the same LF-normalized source in one linear join. */\nexport function applyEditMatchPlan(normalizedContent: string, plan: EditMatchPlan, path: string): AppliedEditsResult {\n\tif (normalizedContent.length !== plan.baseLength) {\n\t\tthrow new Error(`The validated edit plan for ${path} is stale because the source length changed.`);\n\t}\n\n\tconst parts: string[] = [];\n\tlet sourceIndex = 0;\n\tfor (const edit of plan.edits) {\n\t\tif (!normalizedContent.startsWith(edit.expectedText, edit.matchIndex)) {\n\t\t\tthrow new Error(`The validated edit plan for ${path} is stale at edits[${edit.editIndex}].`);\n\t\t}\n\t\tparts.push(normalizedContent.slice(sourceIndex, edit.matchIndex), edit.newText);\n\t\tsourceIndex = edit.matchIndex + edit.matchLength;\n\t}\n\tparts.push(normalizedContent.slice(sourceIndex));\n\tconst newContent = parts.join(\"\");\n\n\tif (normalizedContent === newContent) throw getNoChangeError(path, plan.editCount);\n\treturn { baseContent: normalizedContent, newContent };\n}\n\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\treturn applyEditMatchPlan(normalizedContent, planEditsToNormalizedContent(normalizedContent, edits, path), path);\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\nexport interface EditPlannedDiffResult extends EditDiffResult {\n\tplan: EditMatchPlan;\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 computeEditsPlannedDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditPlannedDiffResult | 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 plan = planEditsToNormalizedContent(normalizedContent, edits, path);\n\t\tconst { baseContent, newContent } = applyEditMatchPlan(normalizedContent, plan, path);\n\n\t\t// Generate the diff\n\t\treturn { ...generateDiffString(baseContent, newContent), plan };\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst result = await computeEditsPlannedDiff(path, edits, cwd);\n\tif (\"error\" in result) return result;\n\treturn { diff: result.diff, firstChangedLine: result.firstChangedLine };\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.js","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC/C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAA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ities for the edit tool.\n * Used by both edit.ts (for execution) and tool-execution.ts (for preview rendering).\n */\n\nimport { createHash } from \"node:crypto\";\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\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 digestNormalizedEditSource(content: string): string {\n\treturn createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\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 normalizeFuzzyCharacters(text).replace(/[^\\S\\n]+(?=\\n|$)/gu, \"\");\n}\n\nfunction normalizeFuzzyCharacters(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\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/** The original content replacements should be applied to. */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n\t/** Inclusive 1-based line bounds from the read that supplied oldText. */\n\trange?: EditRange;\n}\n\nexport interface EditRange {\n\tstartLine: number;\n\tendLine: number;\n}\n\ninterface PlannedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n\texpectedText: string;\n}\n\nexport interface EditMatchPlan {\n\t/** Length of the LF-normalized source against which this plan was validated. */\n\tbaseLength: number;\n\teditCount: number;\n\t/** Compact, source-ordered replacement spans; the source body is not retained. */\n\tedits: readonly PlannedEdit[];\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 * Fuzzy matching searches normalized text, but returned spans still refer to\n * the original content so replacement does not normalize unrelated text.\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\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: content,\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 countExactOccurrences(content: string, oldText: string): number {\n\tif (oldText.length === 0) return 0;\n\tlet count = 0;\n\tlet searchFrom = 0;\n\twhile (searchFrom <= content.length - oldText.length) {\n\t\tconst index = content.indexOf(oldText, searchFrom);\n\t\tif (index === -1) break;\n\t\tcount++;\n\t\tsearchFrom = index + 1;\n\t}\n\treturn count;\n}\n\nfunction getLineStarts(content: string): number[] {\n\tconst starts = [0];\n\tfor (let i = 0; i < content.length; i++) {\n\t\tif (content[i] === \"\\n\") starts.push(i + 1);\n\t}\n\treturn starts;\n}\n\nfunction lineColumnAt(lineStarts: number[], index: number): { lineIndex: number; column: number } {\n\tlet low = 0;\n\tlet high = lineStarts.length - 1;\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tif (lineStarts[mid] <= index) low = mid + 1;\n\t\telse high = mid - 1;\n\t}\n\tconst lineIndex = Math.max(0, high);\n\treturn { lineIndex, column: index - lineStarts[lineIndex] };\n}\n\nfunction lineTextAt(content: string, lineStarts: number[], lineIndex: number): string {\n\tconst start = lineStarts[lineIndex];\n\tconst nextStart = lineStarts[lineIndex + 1] ?? content.length;\n\tconst end = nextStart > start && content[nextStart - 1] === \"\\n\" ? nextStart - 1 : nextStart;\n\treturn content.slice(start, end);\n}\n\nfunction normalizedColumnToOriginalColumn(line: string, normalizedColumn: number): number {\n\tif (normalizedColumn <= 0) return 0;\n\tconst boundaries = [0];\n\tfor (let index = 0; index < line.length; ) {\n\t\tconst codePoint = line.codePointAt(index);\n\t\tindex += codePoint !== undefined && codePoint > 0xffff ? 2 : 1;\n\t\tboundaries.push(index);\n\t}\n\n\tlet low = 1;\n\tlet high = boundaries.length - 1;\n\twhile (low < high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tif (normalizeForFuzzyMatch(line.slice(0, boundaries[mid])).length >= normalizedColumn) high = mid;\n\t\telse low = mid + 1;\n\t}\n\treturn boundaries[low] ?? line.length;\n}\n\nfunction mapFuzzySpanToOriginal(\n\toriginalContent: string,\n\toriginalLineStarts: number[],\n\tfuzzyLineStarts: number[],\n\tnormalizedIndex: number,\n\tnormalizedLength: number,\n): { index: number; length: number } {\n\tconst start = lineColumnAt(fuzzyLineStarts, normalizedIndex);\n\tconst end = lineColumnAt(fuzzyLineStarts, normalizedIndex + normalizedLength);\n\tconst startLine = lineTextAt(originalContent, originalLineStarts, start.lineIndex);\n\tconst endLine = lineTextAt(originalContent, originalLineStarts, end.lineIndex);\n\tconst originalStart =\n\t\toriginalLineStarts[start.lineIndex] + normalizedColumnToOriginalColumn(startLine, start.column);\n\tconst originalEnd = originalLineStarts[end.lineIndex] + normalizedColumnToOriginalColumn(endLine, end.column);\n\treturn { index: originalStart, length: originalEnd - originalStart };\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number, range?: EditRange): Error {\n\tconst rangeSuffix = range ? ` within lines ${range.startLine}-${range.endLine}` : \"\";\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}${rangeSuffix}. 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}${rangeSuffix}. 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\ninterface MatchWindow {\n\tstart: number;\n\tend: number;\n}\n\nfunction validateRange(\n\trange: EditRange | undefined,\n\tlineStarts: number[] | undefined,\n\tcontentLength: number,\n\tpath: string,\n\teditIndex: number,\n\ttotalEdits: number,\n): MatchWindow {\n\tif (!range) return { start: 0, end: contentLength };\n\tconst label = totalEdits === 1 ? \"range\" : `edits[${editIndex}].range`;\n\tif (\n\t\t!Number.isSafeInteger(range.startLine) ||\n\t\t!Number.isSafeInteger(range.endLine) ||\n\t\trange.startLine < 1 ||\n\t\trange.endLine < range.startLine\n\t) {\n\t\tthrow new Error(`${label} in ${path} must contain inclusive positive line numbers with startLine <= endLine.`);\n\t}\n\tif (!lineStarts || range.endLine > lineStarts.length) {\n\t\tthrow new Error(`${label} in ${path} exceeds the file's ${lineStarts?.length ?? 0} lines.`);\n\t}\n\treturn {\n\t\tstart: lineStarts[range.startLine - 1],\n\t\tend: lineStarts[range.endLine] ?? contentLength,\n\t};\n}\n\nfunction findWithin(content: string, oldText: string, window: MatchWindow): number {\n\tif (oldText.length === 0 || oldText.length > window.end - window.start) return -1;\n\tconst index = content.indexOf(oldText, window.start);\n\treturn index !== -1 && index + oldText.length <= window.end ? index : -1;\n}\n\nfunction rangesOverlap(previous: PlannedEdit, current: PlannedEdit): boolean {\n\treturn previous.matchIndex + previous.matchLength > current.matchIndex;\n}\n\n/**\n * Match and validate one or more replacements against LF-normalized content.\n *\n * The returned plan retains only the validated spans and their replacement\n * text. Exact matching uses native substring search, bounded by optional line\n * ranges, while uniqueness is still proven across the whole source.\n */\nexport function planEditsToNormalizedContent(normalizedContent: string, edits: Edit[], path: string): EditMatchPlan {\n\tlet originalLineStarts: number[] | undefined;\n\tlet fuzzyContent: string | undefined;\n\tlet fuzzyLineStarts: number[] | undefined;\n\tconst needsLineStarts = edits.some((edit) => edit.range !== undefined);\n\tif (needsLineStarts) originalLineStarts = getLineStarts(normalizedContent);\n\n\tconst matchedEdits: PlannedEdit[] = [];\n\tfor (let i = 0; i < edits.length; i++) {\n\t\tconst sourceEdit = edits[i];\n\t\tconst oldText = normalizeToLF(sourceEdit.oldText);\n\t\tconst newText = normalizeToLF(sourceEdit.newText);\n\t\tif (oldText.length === 0) throw getEmptyOldTextError(path, i, edits.length);\n\n\t\tconst exactWindow = validateRange(\n\t\t\tsourceEdit.range,\n\t\t\toriginalLineStarts,\n\t\t\tnormalizedContent.length,\n\t\t\tpath,\n\t\t\ti,\n\t\t\tedits.length,\n\t\t);\n\t\tlet matchIndex = findWithin(normalizedContent, oldText, exactWindow);\n\t\tlet matchLength = oldText.length;\n\t\tlet occurrences: number;\n\n\t\tif (matchIndex !== -1) {\n\t\t\toccurrences = countExactOccurrences(normalizedContent, oldText);\n\t\t} else {\n\t\t\tfuzzyContent ??= normalizeForFuzzyMatch(normalizedContent);\n\t\t\tfuzzyLineStarts ??= getLineStarts(fuzzyContent);\n\t\t\toriginalLineStarts ??= getLineStarts(normalizedContent);\n\t\t\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\t\t\tconst fuzzyWindow = validateRange(\n\t\t\t\tsourceEdit.range,\n\t\t\t\tfuzzyLineStarts,\n\t\t\t\tfuzzyContent.length,\n\t\t\t\tpath,\n\t\t\t\ti,\n\t\t\t\tedits.length,\n\t\t\t);\n\t\t\tconst fuzzyIndex = findWithin(fuzzyContent, fuzzyOldText, fuzzyWindow);\n\t\t\tif (fuzzyIndex === -1) throw getNotFoundError(path, i, edits.length, sourceEdit.range);\n\t\t\toccurrences = countExactOccurrences(fuzzyContent, fuzzyOldText);\n\t\t\tconst replacementSpan = mapFuzzySpanToOriginal(\n\t\t\t\tnormalizedContent,\n\t\t\t\toriginalLineStarts,\n\t\t\t\tfuzzyLineStarts,\n\t\t\t\tfuzzyIndex,\n\t\t\t\tfuzzyOldText.length,\n\t\t\t);\n\t\t\tmatchIndex = replacementSpan.index;\n\t\t\tmatchLength = replacementSpan.length;\n\t\t}\n\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, edits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex,\n\t\t\tmatchLength,\n\t\t\tnewText,\n\t\t\texpectedText: normalizedContent.slice(matchIndex, matchIndex + matchLength),\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 (rangesOverlap(previous, current)) {\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\treturn { baseLength: normalizedContent.length, editCount: edits.length, edits: matchedEdits };\n}\n\n/** Apply a validated match plan to the same LF-normalized source in one linear join. */\nexport function applyEditMatchPlan(normalizedContent: string, plan: EditMatchPlan, path: string): AppliedEditsResult {\n\tif (normalizedContent.length !== plan.baseLength) {\n\t\tthrow new Error(`The validated edit plan for ${path} is stale because the source length changed.`);\n\t}\n\n\tconst parts: string[] = [];\n\tlet sourceIndex = 0;\n\tfor (const edit of plan.edits) {\n\t\tif (!normalizedContent.startsWith(edit.expectedText, edit.matchIndex)) {\n\t\t\tthrow new Error(`The validated edit plan for ${path} is stale at edits[${edit.editIndex}].`);\n\t\t}\n\t\tparts.push(normalizedContent.slice(sourceIndex, edit.matchIndex), edit.newText);\n\t\tsourceIndex = edit.matchIndex + edit.matchLength;\n\t}\n\tparts.push(normalizedContent.slice(sourceIndex));\n\tconst newContent = parts.join(\"\");\n\n\tif (normalizedContent === newContent) throw getNoChangeError(path, plan.editCount);\n\treturn { baseContent: normalizedContent, newContent };\n}\n\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\treturn applyEditMatchPlan(normalizedContent, planEditsToNormalizedContent(normalizedContent, edits, path), path);\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\nexport interface EditPlannedDiffResult extends EditDiffResult {\n\tplan: EditMatchPlan;\n\tsourceDigest: 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 computeEditsPlannedDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditPlannedDiffResult | 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 plan = planEditsToNormalizedContent(normalizedContent, edits, path);\n\t\tconst { baseContent, newContent } = applyEditMatchPlan(normalizedContent, plan, path);\n\n\t\t// Generate the diff\n\t\treturn {\n\t\t\t...generateDiffString(baseContent, newContent),\n\t\t\tplan,\n\t\t\tsourceDigest: digestNormalizedEditSource(normalizedContent),\n\t\t};\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise<EditDiffResult | EditDiffError> {\n\tconst result = await computeEditsPlannedDiff(path, edits, cwd);\n\tif (\"error\" in result) return result;\n\treturn { diff: result.diff, firstChangedLine: result.firstChangedLine };\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"]}
|