strands-darwin 0.0.3
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/README.md +140 -0
- package/README.zh-CN.md +140 -0
- package/dist/patches/@strands-agents+sdk+1.16.0.patch +1443 -0
- package/dist/src/agent/background-delegation.d.ts +67 -0
- package/dist/src/agent/background-delegation.js +159 -0
- package/dist/src/agent/background-delegation.js.map +1 -0
- package/dist/src/agent/call-stats.d.ts +118 -0
- package/dist/src/agent/call-stats.js +128 -0
- package/dist/src/agent/call-stats.js.map +1 -0
- package/dist/src/agent/compact.d.ts +108 -0
- package/dist/src/agent/compact.js +192 -0
- package/dist/src/agent/compact.js.map +1 -0
- package/dist/src/agent/context-anchor.d.ts +64 -0
- package/dist/src/agent/context-anchor.js +43 -0
- package/dist/src/agent/context-anchor.js.map +1 -0
- package/dist/src/agent/cost.d.ts +56 -0
- package/dist/src/agent/cost.js +44 -0
- package/dist/src/agent/cost.js.map +1 -0
- package/dist/src/agent/diagnostics.d.ts +212 -0
- package/dist/src/agent/diagnostics.js +374 -0
- package/dist/src/agent/diagnostics.js.map +1 -0
- package/dist/src/agent/instructions.d.ts +54 -0
- package/dist/src/agent/instructions.js +118 -0
- package/dist/src/agent/instructions.js.map +1 -0
- package/dist/src/agent/max-tokens-recovery.d.ts +17 -0
- package/dist/src/agent/max-tokens-recovery.js +65 -0
- package/dist/src/agent/max-tokens-recovery.js.map +1 -0
- package/dist/src/agent/model-call-budget.d.ts +8 -0
- package/dist/src/agent/model-call-budget.js +24 -0
- package/dist/src/agent/model-call-budget.js.map +1 -0
- package/dist/src/agent/model-retry.d.ts +134 -0
- package/dist/src/agent/model-retry.js +256 -0
- package/dist/src/agent/model-retry.js.map +1 -0
- package/dist/src/agent/permission-rules.d.ts +47 -0
- package/dist/src/agent/permission-rules.js +260 -0
- package/dist/src/agent/permission-rules.js.map +1 -0
- package/dist/src/agent/permission.d.ts +361 -0
- package/dist/src/agent/permission.js +797 -0
- package/dist/src/agent/permission.js.map +1 -0
- package/dist/src/agent/prompt-cache.d.ts +66 -0
- package/dist/src/agent/prompt-cache.js +194 -0
- package/dist/src/agent/prompt-cache.js.map +1 -0
- package/dist/src/agent/refusal.d.ts +20 -0
- package/dist/src/agent/refusal.js +23 -0
- package/dist/src/agent/refusal.js.map +1 -0
- package/dist/src/agent/retry-guard.d.ts +26 -0
- package/dist/src/agent/retry-guard.js +193 -0
- package/dist/src/agent/retry-guard.js.map +1 -0
- package/dist/src/agent/rewind.d.ts +29 -0
- package/dist/src/agent/rewind.js +118 -0
- package/dist/src/agent/rewind.js.map +1 -0
- package/dist/src/agent/runtime.d.ts +814 -0
- package/dist/src/agent/runtime.js +1596 -0
- package/dist/src/agent/runtime.js.map +1 -0
- package/dist/src/agent/safety-classifier.d.ts +11 -0
- package/dist/src/agent/safety-classifier.js +0 -0
- package/dist/src/agent/safety-classifier.js.map +1 -0
- package/dist/src/agent/sdk-logging.d.ts +49 -0
- package/dist/src/agent/sdk-logging.js +110 -0
- package/dist/src/agent/sdk-logging.js.map +1 -0
- package/dist/src/agent/session.d.ts +102 -0
- package/dist/src/agent/session.js +244 -0
- package/dist/src/agent/session.js.map +1 -0
- package/dist/src/agent/stream-resumption.d.ts +16 -0
- package/dist/src/agent/stream-resumption.js +33 -0
- package/dist/src/agent/stream-resumption.js.map +1 -0
- package/dist/src/agent/system-prompt.d.ts +50 -0
- package/dist/src/agent/system-prompt.js +161 -0
- package/dist/src/agent/system-prompt.js.map +1 -0
- package/dist/src/agent/thinking.d.ts +99 -0
- package/dist/src/agent/thinking.js +145 -0
- package/dist/src/agent/thinking.js.map +1 -0
- package/dist/src/agent/usage.d.ts +132 -0
- package/dist/src/agent/usage.js +233 -0
- package/dist/src/agent/usage.js.map +1 -0
- package/dist/src/agent/working-context.d.ts +51 -0
- package/dist/src/agent/working-context.js +160 -0
- package/dist/src/agent/working-context.js.map +1 -0
- package/dist/src/agents/child-recipe.d.ts +33 -0
- package/dist/src/agents/child-recipe.js +98 -0
- package/dist/src/agents/child-recipe.js.map +1 -0
- package/dist/src/agents/concurrency-limit.d.ts +25 -0
- package/dist/src/agents/concurrency-limit.js +43 -0
- package/dist/src/agents/concurrency-limit.js.map +1 -0
- package/dist/src/agents/dispatch-registry.d.ts +180 -0
- package/dist/src/agents/dispatch-registry.js +289 -0
- package/dist/src/agents/dispatch-registry.js.map +1 -0
- package/dist/src/agents/failed-child-text.d.ts +44 -0
- package/dist/src/agents/failed-child-text.js +69 -0
- package/dist/src/agents/failed-child-text.js.map +1 -0
- package/dist/src/agents/loader.d.ts +26 -0
- package/dist/src/agents/loader.js +134 -0
- package/dist/src/agents/loader.js.map +1 -0
- package/dist/src/agents/report-projection.d.ts +31 -0
- package/dist/src/agents/report-projection.js +125 -0
- package/dist/src/agents/report-projection.js.map +1 -0
- package/dist/src/agents/subagent-tool.d.ts +61 -0
- package/dist/src/agents/subagent-tool.js +180 -0
- package/dist/src/agents/subagent-tool.js.map +1 -0
- package/dist/src/agents/workflow-tool.d.ts +85 -0
- package/dist/src/agents/workflow-tool.js +530 -0
- package/dist/src/agents/workflow-tool.js.map +1 -0
- package/dist/src/cli-args.d.ts +39 -0
- package/dist/src/cli-args.js +198 -0
- package/dist/src/cli-args.js.map +1 -0
- package/dist/src/cli-doctor.d.ts +26 -0
- package/dist/src/cli-doctor.js +398 -0
- package/dist/src/cli-doctor.js.map +1 -0
- package/dist/src/cli-main.d.ts +1 -0
- package/dist/src/cli-main.js +279 -0
- package/dist/src/cli-main.js.map +1 -0
- package/dist/src/cli-sessions.d.ts +17 -0
- package/dist/src/cli-sessions.js +136 -0
- package/dist/src/cli-sessions.js.map +1 -0
- package/dist/src/cli-trajectory.d.ts +37 -0
- package/dist/src/cli-trajectory.js +303 -0
- package/dist/src/cli-trajectory.js.map +1 -0
- package/dist/src/cli-usage.d.ts +18 -0
- package/dist/src/cli-usage.js +53 -0
- package/dist/src/cli-usage.js.map +1 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +29 -0
- package/dist/src/cli.js.map +1 -0
- package/dist/src/commands/custom-commands.d.ts +43 -0
- package/dist/src/commands/custom-commands.js +155 -0
- package/dist/src/commands/custom-commands.js.map +1 -0
- package/dist/src/commands/workflow-command.d.ts +26 -0
- package/dist/src/commands/workflow-command.js +56 -0
- package/dist/src/commands/workflow-command.js.map +1 -0
- package/dist/src/config.d.ts +463 -0
- package/dist/src/config.js +1457 -0
- package/dist/src/config.js.map +1 -0
- package/dist/src/context-overflow-error.d.ts +7 -0
- package/dist/src/context-overflow-error.js +26 -0
- package/dist/src/context-overflow-error.js.map +1 -0
- package/dist/src/dev-repl.d.ts +1 -0
- package/dist/src/dev-repl.js +365 -0
- package/dist/src/dev-repl.js.map +1 -0
- package/dist/src/headless-protocol.d.ts +147 -0
- package/dist/src/headless-protocol.js +359 -0
- package/dist/src/headless-protocol.js.map +1 -0
- package/dist/src/headless-runner.d.ts +30 -0
- package/dist/src/headless-runner.js +405 -0
- package/dist/src/headless-runner.js.map +1 -0
- package/dist/src/headless-stdin.d.ts +28 -0
- package/dist/src/headless-stdin.js +78 -0
- package/dist/src/headless-stdin.js.map +1 -0
- package/dist/src/headless.d.ts +106 -0
- package/dist/src/headless.js +229 -0
- package/dist/src/headless.js.map +1 -0
- package/dist/src/hooks/codex-hook-runner.d.ts +92 -0
- package/dist/src/hooks/codex-hook-runner.js +446 -0
- package/dist/src/hooks/codex-hook-runner.js.map +1 -0
- package/dist/src/hooks/codex-hooks.d.ts +23 -0
- package/dist/src/hooks/codex-hooks.js +152 -0
- package/dist/src/hooks/codex-hooks.js.map +1 -0
- package/dist/src/hooks/hook-process.d.ts +23 -0
- package/dist/src/hooks/hook-process.js +241 -0
- package/dist/src/hooks/hook-process.js.map +1 -0
- package/dist/src/hooks/lifecycle-hooks.d.ts +37 -0
- package/dist/src/hooks/lifecycle-hooks.js +153 -0
- package/dist/src/hooks/lifecycle-hooks.js.map +1 -0
- package/dist/src/hooks/tool-hooks.d.ts +63 -0
- package/dist/src/hooks/tool-hooks.js +350 -0
- package/dist/src/hooks/tool-hooks.js.map +1 -0
- package/dist/src/mcp/codegraph-preflight.d.ts +29 -0
- package/dist/src/mcp/codegraph-preflight.js +232 -0
- package/dist/src/mcp/codegraph-preflight.js.map +1 -0
- package/dist/src/mcp/registry.d.ts +133 -0
- package/dist/src/mcp/registry.js +209 -0
- package/dist/src/mcp/registry.js.map +1 -0
- package/dist/src/mcp/web-search-empty-results.d.ts +14 -0
- package/dist/src/mcp/web-search-empty-results.js +94 -0
- package/dist/src/mcp/web-search-empty-results.js.map +1 -0
- package/dist/src/memory/command.d.ts +11 -0
- package/dist/src/memory/command.js +253 -0
- package/dist/src/memory/command.js.map +1 -0
- package/dist/src/memory/controller.d.ts +51 -0
- package/dist/src/memory/controller.js +316 -0
- package/dist/src/memory/controller.js.map +1 -0
- package/dist/src/memory/prompt.d.ts +4 -0
- package/dist/src/memory/prompt.js +22 -0
- package/dist/src/memory/prompt.js.map +1 -0
- package/dist/src/memory/scheduler.d.ts +33 -0
- package/dist/src/memory/scheduler.js +134 -0
- package/dist/src/memory/scheduler.js.map +1 -0
- package/dist/src/memory/state.d.ts +112 -0
- package/dist/src/memory/state.js +355 -0
- package/dist/src/memory/state.js.map +1 -0
- package/dist/src/memory/store.d.ts +19 -0
- package/dist/src/memory/store.js +130 -0
- package/dist/src/memory/store.js.map +1 -0
- package/dist/src/memory/tools.d.ts +29 -0
- package/dist/src/memory/tools.js +22 -0
- package/dist/src/memory/tools.js.map +1 -0
- package/dist/src/memory/validation.d.ts +33 -0
- package/dist/src/memory/validation.js +159 -0
- package/dist/src/memory/validation.js.map +1 -0
- package/dist/src/npm-package/generate-patch.d.ts +23 -0
- package/dist/src/npm-package/generate-patch.js +88 -0
- package/dist/src/npm-package/generate-patch.js.map +1 -0
- package/dist/src/npm-package/patch-package-format.d.ts +43 -0
- package/dist/src/npm-package/patch-package-format.js +66 -0
- package/dist/src/npm-package/patch-package-format.js.map +1 -0
- package/dist/src/paths.d.ts +39 -0
- package/dist/src/paths.js +105 -0
- package/dist/src/paths.js.map +1 -0
- package/dist/src/pricing/cost.d.ts +182 -0
- package/dist/src/pricing/cost.js +215 -0
- package/dist/src/pricing/cost.js.map +1 -0
- package/dist/src/pricing/model-prices.d.ts +112 -0
- package/dist/src/pricing/model-prices.js +320 -0
- package/dist/src/pricing/model-prices.js.map +1 -0
- package/dist/src/sdk-patch-preflight.d.ts +23 -0
- package/dist/src/sdk-patch-preflight.js +71 -0
- package/dist/src/sdk-patch-preflight.js.map +1 -0
- package/dist/src/skills/builtin/commit-message/SKILL.md +45 -0
- package/dist/src/skills/builtin/commit-message/references/types.md +8 -0
- package/dist/src/skills/builtin/developer/SKILL.md +107 -0
- package/dist/src/skills/builtin/self-evolution-research/SKILL.md +150 -0
- package/dist/src/skills/builtin/self-evolution-research/scripts/roll-research-path.mjs +208 -0
- package/dist/src/skills/builtin/self-reflection/SKILL.md +172 -0
- package/dist/src/skills/builtin/self-reflection/references/reflection-template.md +90 -0
- package/dist/src/skills/builtin/self-reflection/scripts/locate-trajectory.mjs +175 -0
- package/dist/src/skills/loader.d.ts +26 -0
- package/dist/src/skills/loader.js +186 -0
- package/dist/src/skills/loader.js.map +1 -0
- package/dist/src/skills/plugin.d.ts +34 -0
- package/dist/src/skills/plugin.js +137 -0
- package/dist/src/skills/plugin.js.map +1 -0
- package/dist/src/skills/prompt.d.ts +8 -0
- package/dist/src/skills/prompt.js +214 -0
- package/dist/src/skills/prompt.js.map +1 -0
- package/dist/src/skills/resource-safety.d.ts +15 -0
- package/dist/src/skills/resource-safety.js +149 -0
- package/dist/src/skills/resource-safety.js.map +1 -0
- package/dist/src/tools/background-bash.d.ts +95 -0
- package/dist/src/tools/background-bash.js +639 -0
- package/dist/src/tools/background-bash.js.map +1 -0
- package/dist/src/tools/background-tail.d.ts +28 -0
- package/dist/src/tools/background-tail.js +75 -0
- package/dist/src/tools/background-tail.js.map +1 -0
- package/dist/src/tools/background-wait-contract.d.ts +4 -0
- package/dist/src/tools/background-wait-contract.js +7 -0
- package/dist/src/tools/background-wait-contract.js.map +1 -0
- package/dist/src/tools/file-editor-serial.d.ts +24 -0
- package/dist/src/tools/file-editor-serial.js +99 -0
- package/dist/src/tools/file-editor-serial.js.map +1 -0
- package/dist/src/tools/image-viewer.d.ts +43 -0
- package/dist/src/tools/image-viewer.js +256 -0
- package/dist/src/tools/image-viewer.js.map +1 -0
- package/dist/src/tools/update-plan.d.ts +30 -0
- package/dist/src/tools/update-plan.js +65 -0
- package/dist/src/tools/update-plan.js.map +1 -0
- package/dist/src/tools/web-fetch.d.ts +70 -0
- package/dist/src/tools/web-fetch.js +667 -0
- package/dist/src/tools/web-fetch.js.map +1 -0
- package/dist/src/trajectory/export.d.ts +31 -0
- package/dist/src/trajectory/export.js +116 -0
- package/dist/src/trajectory/export.js.map +1 -0
- package/dist/src/trajectory/fork.d.ts +19 -0
- package/dist/src/trajectory/fork.js +110 -0
- package/dist/src/trajectory/fork.js.map +1 -0
- package/dist/src/trajectory/memory-tool.d.ts +20 -0
- package/dist/src/trajectory/memory-tool.js +98 -0
- package/dist/src/trajectory/memory-tool.js.map +1 -0
- package/dist/src/trajectory/prompt-history.d.ts +62 -0
- package/dist/src/trajectory/prompt-history.js +256 -0
- package/dist/src/trajectory/prompt-history.js.map +1 -0
- package/dist/src/trajectory/reader.d.ts +21 -0
- package/dist/src/trajectory/reader.js +62 -0
- package/dist/src/trajectory/reader.js.map +1 -0
- package/dist/src/trajectory/record.d.ts +417 -0
- package/dist/src/trajectory/record.js +394 -0
- package/dist/src/trajectory/record.js.map +1 -0
- package/dist/src/trajectory/replay.d.ts +74 -0
- package/dist/src/trajectory/replay.js +285 -0
- package/dist/src/trajectory/replay.js.map +1 -0
- package/dist/src/trajectory/resume-recap.d.ts +43 -0
- package/dist/src/trajectory/resume-recap.js +68 -0
- package/dist/src/trajectory/resume-recap.js.map +1 -0
- package/dist/src/trajectory/search.d.ts +40 -0
- package/dist/src/trajectory/search.js +127 -0
- package/dist/src/trajectory/search.js.map +1 -0
- package/dist/src/trajectory/spend.d.ts +157 -0
- package/dist/src/trajectory/spend.js +264 -0
- package/dist/src/trajectory/spend.js.map +1 -0
- package/dist/src/trajectory/stream.d.ts +30 -0
- package/dist/src/trajectory/stream.js +30 -0
- package/dist/src/trajectory/stream.js.map +1 -0
- package/dist/src/trajectory/writer.d.ts +310 -0
- package/dist/src/trajectory/writer.js +636 -0
- package/dist/src/trajectory/writer.js.map +1 -0
- package/dist/src/tui/App.d.ts +109 -0
- package/dist/src/tui/App.js +2660 -0
- package/dist/src/tui/App.js.map +1 -0
- package/dist/src/tui/InputBox.d.ts +90 -0
- package/dist/src/tui/InputBox.js +129 -0
- package/dist/src/tui/InputBox.js.map +1 -0
- package/dist/src/tui/MarkdownText.d.ts +16 -0
- package/dist/src/tui/MarkdownText.js +117 -0
- package/dist/src/tui/MarkdownText.js.map +1 -0
- package/dist/src/tui/MessageList.d.ts +27 -0
- package/dist/src/tui/MessageList.js +61 -0
- package/dist/src/tui/MessageList.js.map +1 -0
- package/dist/src/tui/PermissionPrompt.d.ts +18 -0
- package/dist/src/tui/PermissionPrompt.js +114 -0
- package/dist/src/tui/PermissionPrompt.js.map +1 -0
- package/dist/src/tui/PlanChecklist.d.ts +7 -0
- package/dist/src/tui/PlanChecklist.js +12 -0
- package/dist/src/tui/PlanChecklist.js.map +1 -0
- package/dist/src/tui/QueuedMessages.d.ts +8 -0
- package/dist/src/tui/QueuedMessages.js +24 -0
- package/dist/src/tui/QueuedMessages.js.map +1 -0
- package/dist/src/tui/StartupScreen.d.ts +25 -0
- package/dist/src/tui/StartupScreen.js +51 -0
- package/dist/src/tui/StartupScreen.js.map +1 -0
- package/dist/src/tui/ToolCallPanel.d.ts +33 -0
- package/dist/src/tui/ToolCallPanel.js +112 -0
- package/dist/src/tui/ToolCallPanel.js.map +1 -0
- package/dist/src/tui/WelcomeHeader.d.ts +30 -0
- package/dist/src/tui/WelcomeHeader.js +69 -0
- package/dist/src/tui/WelcomeHeader.js.map +1 -0
- package/dist/src/tui/background-tool-presentation.d.ts +22 -0
- package/dist/src/tui/background-tool-presentation.js +209 -0
- package/dist/src/tui/background-tool-presentation.js.map +1 -0
- package/dist/src/tui/busy-suffix.d.ts +37 -0
- package/dist/src/tui/busy-suffix.js +39 -0
- package/dist/src/tui/busy-suffix.js.map +1 -0
- package/dist/src/tui/clipboard-image.d.ts +18 -0
- package/dist/src/tui/clipboard-image.js +109 -0
- package/dist/src/tui/clipboard-image.js.map +1 -0
- package/dist/src/tui/context-format.d.ts +43 -0
- package/dist/src/tui/context-format.js +71 -0
- package/dist/src/tui/context-format.js.map +1 -0
- package/dist/src/tui/copy-command.d.ts +68 -0
- package/dist/src/tui/copy-command.js +182 -0
- package/dist/src/tui/copy-command.js.map +1 -0
- package/dist/src/tui/edit-diff.d.ts +135 -0
- package/dist/src/tui/edit-diff.js +356 -0
- package/dist/src/tui/edit-diff.js.map +1 -0
- package/dist/src/tui/frame-budget.d.ts +351 -0
- package/dist/src/tui/frame-budget.js +446 -0
- package/dist/src/tui/frame-budget.js.map +1 -0
- package/dist/src/tui/help-format.d.ts +17 -0
- package/dist/src/tui/help-format.js +38 -0
- package/dist/src/tui/help-format.js.map +1 -0
- package/dist/src/tui/live-text.d.ts +51 -0
- package/dist/src/tui/live-text.js +154 -0
- package/dist/src/tui/live-text.js.map +1 -0
- package/dist/src/tui/markdown.d.ts +62 -0
- package/dist/src/tui/markdown.js +244 -0
- package/dist/src/tui/markdown.js.map +1 -0
- package/dist/src/tui/mcp-format.d.ts +28 -0
- package/dist/src/tui/mcp-format.js +67 -0
- package/dist/src/tui/mcp-format.js.map +1 -0
- package/dist/src/tui/path-completion.d.ts +119 -0
- package/dist/src/tui/path-completion.js +305 -0
- package/dist/src/tui/path-completion.js.map +1 -0
- package/dist/src/tui/permission-queue.d.ts +61 -0
- package/dist/src/tui/permission-queue.js +129 -0
- package/dist/src/tui/permission-queue.js.map +1 -0
- package/dist/src/tui/plan-format.d.ts +9 -0
- package/dist/src/tui/plan-format.js +30 -0
- package/dist/src/tui/plan-format.js.map +1 -0
- package/dist/src/tui/prompt-completion.d.ts +22 -0
- package/dist/src/tui/prompt-completion.js +46 -0
- package/dist/src/tui/prompt-completion.js.map +1 -0
- package/dist/src/tui/prompt-editor.d.ts +102 -0
- package/dist/src/tui/prompt-editor.js +379 -0
- package/dist/src/tui/prompt-editor.js.map +1 -0
- package/dist/src/tui/prompt-history-search.d.ts +53 -0
- package/dist/src/tui/prompt-history-search.js +123 -0
- package/dist/src/tui/prompt-history-search.js.map +1 -0
- package/dist/src/tui/prompt-queue.d.ts +58 -0
- package/dist/src/tui/prompt-queue.js +74 -0
- package/dist/src/tui/prompt-queue.js.map +1 -0
- package/dist/src/tui/prompt-recall.d.ts +74 -0
- package/dist/src/tui/prompt-recall.js +90 -0
- package/dist/src/tui/prompt-recall.js.map +1 -0
- package/dist/src/tui/react-environment.d.ts +11 -0
- package/dist/src/tui/react-environment.js +24 -0
- package/dist/src/tui/react-environment.js.map +1 -0
- package/dist/src/tui/rewind-search.d.ts +34 -0
- package/dist/src/tui/rewind-search.js +68 -0
- package/dist/src/tui/rewind-search.js.map +1 -0
- package/dist/src/tui/shell-command.d.ts +114 -0
- package/dist/src/tui/shell-command.js +310 -0
- package/dist/src/tui/shell-command.js.map +1 -0
- package/dist/src/tui/spend-advisory.d.ts +52 -0
- package/dist/src/tui/spend-advisory.js +64 -0
- package/dist/src/tui/spend-advisory.js.map +1 -0
- package/dist/src/tui/status-format.d.ts +120 -0
- package/dist/src/tui/status-format.js +192 -0
- package/dist/src/tui/status-format.js.map +1 -0
- package/dist/src/tui/subagent-format.d.ts +49 -0
- package/dist/src/tui/subagent-format.js +146 -0
- package/dist/src/tui/subagent-format.js.map +1 -0
- package/dist/src/tui/task-format.d.ts +29 -0
- package/dist/src/tui/task-format.js +87 -0
- package/dist/src/tui/task-format.js.map +1 -0
- package/dist/src/tui/terminal-bell.d.ts +20 -0
- package/dist/src/tui/terminal-bell.js +33 -0
- package/dist/src/tui/terminal-bell.js.map +1 -0
- package/dist/src/tui/tool-detail-presentation.d.ts +60 -0
- package/dist/src/tui/tool-detail-presentation.js +206 -0
- package/dist/src/tui/tool-detail-presentation.js.map +1 -0
- package/dist/src/tui/turn-state.d.ts +195 -0
- package/dist/src/tui/turn-state.js +548 -0
- package/dist/src/tui/turn-state.js.map +1 -0
- package/dist/src/tui/visual-language.d.ts +45 -0
- package/dist/src/tui/visual-language.js +57 -0
- package/dist/src/tui/visual-language.js.map +1 -0
- package/dist/src/version.d.ts +7 -0
- package/dist/src/version.js +38 -0
- package/dist/src/version.js.map +1 -0
- package/package.json +60 -0
|
@@ -0,0 +1,1443 @@
|
|
|
1
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/conversation-manager/compression/context-compression.js b/node_modules/@strands-agents/sdk/dist/src/conversation-manager/compression/context-compression.js
|
|
2
|
+
index 84e3d1bb0bcd499d3dd2cd07c08baa79807ca79c..7e1c407bb04714309226c40b5daa00827799f477 100644
|
|
3
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/conversation-manager/compression/context-compression.js
|
|
4
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/conversation-manager/compression/context-compression.js
|
|
5
|
+
@@ -126,9 +126,16 @@ export async function generateSummary(messagesToSummarize, model, systemPrompt)
|
|
6
|
+
if (!result?.done || !result.value) {
|
|
7
|
+
throw new Error('Failed to generate summary: no response from model');
|
|
8
|
+
}
|
|
9
|
+
+ // Thinking models include reasoning blocks in the summary response; a
|
|
10
|
+
+ // user-role message must never carry reasoning content (providers reject
|
|
11
|
+
+ // the request), so keep only the non-reasoning blocks.
|
|
12
|
+
+ const summaryContent = result.value.message.content.filter((block) => block.type !== 'reasoningBlock');
|
|
13
|
+
+ if (summaryContent.length === 0) {
|
|
14
|
+
+ throw new Error('Failed to generate summary: response contained no non-reasoning content');
|
|
15
|
+
+ }
|
|
16
|
+
return new Message({
|
|
17
|
+
role: 'user',
|
|
18
|
+
- content: result.value.message.content,
|
|
19
|
+
+ content: summaryContent,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/index.d.ts b/node_modules/@strands-agents/sdk/dist/src/index.d.ts
|
|
24
|
+
index 89047d0b24999df274f256d25b4cca8624ce7ac6..ca746d6e27aa644eaf5186c79185263fa3d1fc53 100644
|
|
25
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/index.d.ts
|
|
26
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/index.d.ts
|
|
27
|
+
@@ -56,6 +56,7 @@ export { ConversationManager, type ProactiveCompressionConfig, type Conversation
|
|
28
|
+
export { NullConversationManager } from './conversation-manager/null-conversation-manager.js';
|
|
29
|
+
export { SlidingWindowConversationManager, type SlidingWindowConversationManagerConfig, } from './conversation-manager/sliding-window-conversation-manager.js';
|
|
30
|
+
export { SummarizingConversationManager, type SummarizingConversationManagerConfig, } from './conversation-manager/summarizing-conversation-manager.js';
|
|
31
|
+
+export { DEFAULT_SUMMARIZATION_PROMPT } from './conversation-manager/compression/context-compression.js';
|
|
32
|
+
export { configureLogging } from './logging/logger.js';
|
|
33
|
+
export type { Logger } from './logging/types.js';
|
|
34
|
+
export { type McpClientOptions, type McpListToolsOptions, type McpToolFilterCallback, type McpToolFilters, type McpToolMatcher, type McpClientConfig, type McpClientCredentials, type McpTransport, type McpCallToolOptions, type TasksConfig, type McpConnectionState, type McpServerConfig, type SerializableMcpToolFilters, McpClient, } from './mcp/index.js';
|
|
35
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/index.js b/node_modules/@strands-agents/sdk/dist/src/index.js
|
|
36
|
+
index 3cb62b859eba690822bbd8fb1c2c9388cd151394..4a1febbd5752dc4bb0cbba24b0695c5ce40143e9 100644
|
|
37
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/index.js
|
|
38
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/index.js
|
|
39
|
+
@@ -52,6 +52,7 @@ export { ConversationManager, } from './conversation-manager/conversation-manage
|
|
40
|
+
export { NullConversationManager } from './conversation-manager/null-conversation-manager.js';
|
|
41
|
+
export { SlidingWindowConversationManager, } from './conversation-manager/sliding-window-conversation-manager.js';
|
|
42
|
+
export { SummarizingConversationManager, } from './conversation-manager/summarizing-conversation-manager.js';
|
|
43
|
+
+export { DEFAULT_SUMMARIZATION_PROMPT } from './conversation-manager/compression/context-compression.js';
|
|
44
|
+
// Logging
|
|
45
|
+
export { configureLogging } from './logging/logger.js';
|
|
46
|
+
// MCP Client types and implementations
|
|
47
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/models/openai/errors.js b/node_modules/@strands-agents/sdk/dist/src/models/openai/errors.js
|
|
48
|
+
index 17a473fe3bcdcc02e17cd95283c832d9021634c1..6e5cda23f672684b3926450322459279e2355066 100644
|
|
49
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/models/openai/errors.js
|
|
50
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/models/openai/errors.js
|
|
51
|
+
@@ -20,6 +20,7 @@ const CONTEXT_WINDOW_OVERFLOW_PATTERNS = [
|
|
52
|
+
'input length and `max_tokens` exceed context limit',
|
|
53
|
+
'too many total text bytes',
|
|
54
|
+
'exceed customer model maximum',
|
|
55
|
+
+ 'exceed model maximum',
|
|
56
|
+
];
|
|
57
|
+
/**
|
|
58
|
+
* Error patterns that indicate rate limiting.
|
|
59
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.d.ts b/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.d.ts
|
|
60
|
+
index e17f00ac284c1e3357d55205c57b431061141b55..a7b4edd12a5ac33277a5ad2c4bcea4c4d8c1ea7d 100644
|
|
61
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.d.ts
|
|
62
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.d.ts
|
|
63
|
+
@@ -52,6 +52,7 @@ export interface ResponsesStreamState {
|
|
64
|
+
outputTokens: number;
|
|
65
|
+
totalTokens: number;
|
|
66
|
+
cacheReadInputTokens?: number;
|
|
67
|
+
+ cacheWriteInputTokens?: number;
|
|
68
|
+
} | null;
|
|
69
|
+
stopReason: StopReason;
|
|
70
|
+
}
|
|
71
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.js b/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.js
|
|
72
|
+
index 25091ff4351eaa61dc370382a251285ed6f3a629..8d342dc7be28c63b7f609bd3c9cca00f3877b664 100644
|
|
73
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.js
|
|
74
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/models/openai/responses-adapter.js
|
|
75
|
+
@@ -328,9 +328,13 @@ function mapResponsesUsage(usage) {
|
|
76
|
+
totalTokens: usage.total_tokens,
|
|
77
|
+
};
|
|
78
|
+
const cached = usage.input_tokens_details?.cached_tokens;
|
|
79
|
+
- if (typeof cached === 'number' && cached > 0) {
|
|
80
|
+
+ if (typeof cached === 'number' && cached >= 0) {
|
|
81
|
+
mapped.cacheReadInputTokens = cached;
|
|
82
|
+
}
|
|
83
|
+
+ const cacheWrite = usage.input_tokens_details?.cache_write_tokens;
|
|
84
|
+
+ if (typeof cacheWrite === 'number' && cacheWrite >= 0) {
|
|
85
|
+
+ mapped.cacheWriteInputTokens = cacheWrite;
|
|
86
|
+
+ }
|
|
87
|
+
return mapped;
|
|
88
|
+
}
|
|
89
|
+
function createResponsesStreamError(message, code) {
|
|
90
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.d.ts b/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.d.ts
|
|
91
|
+
index b0223555c1f0410441546be860dbae824ac9857c..92ab47f4c8c1f5225c13dfd8a5e37324846bdfc2 100644
|
|
92
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.d.ts
|
|
93
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.d.ts
|
|
94
|
+
@@ -34,6 +34,8 @@ export interface ContextOffloaderConfig {
|
|
95
|
+
* Defaults to 20. Set to `null` to disable eviction.
|
|
96
|
+
*/
|
|
97
|
+
evictAfterCycles?: number | null;
|
|
98
|
+
+ /** Tool names whose results are never offloaded (kept whole in context). Defaults to none. */
|
|
99
|
+
+ excludeTools?: readonly string[];
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Plugin that offloads oversized tool results to reduce context consumption.
|
|
103
|
+
@@ -69,7 +71,9 @@ export declare class ContextOffloader implements Plugin {
|
|
104
|
+
private readonly _previewTokens;
|
|
105
|
+
private readonly _includeRetrievalTool;
|
|
106
|
+
private readonly _evictAfterCycles;
|
|
107
|
+
+ private readonly _excludeTools;
|
|
108
|
+
private readonly _storageByAgent;
|
|
109
|
+
+ private readonly _scannedAgents;
|
|
110
|
+
private readonly _keyStoredAt;
|
|
111
|
+
private _retrievalTool;
|
|
112
|
+
constructor(config: ContextOffloaderConfig);
|
|
113
|
+
@@ -82,6 +86,9 @@ export declare class ContextOffloader implements Plugin {
|
|
114
|
+
private _createRetrievalTool;
|
|
115
|
+
private _storeBlock;
|
|
116
|
+
private _buildPreviewText;
|
|
117
|
+
+ private _isStoredOffloadPlaceholder;
|
|
118
|
+
+ private _repairRestoredToolResults;
|
|
119
|
+
+ private _offloadToolResult;
|
|
120
|
+
private _handleToolResult;
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=plugin.d.ts.map
|
|
123
|
+
|
|
124
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.js b/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.js
|
|
125
|
+
index 69b6549df8bf55b39e34aaf2940cac2a7fbf0714..440965bdc2879f7c2755ace3cda9ab70b17c53e6 100644
|
|
126
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.js
|
|
127
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-plugins/context-offloader/plugin.js
|
|
128
|
+
@@ -1,5 +1,5 @@
|
|
129
|
+
import { AfterToolCallEvent, BeforeModelCallEvent } from '../../hooks/events.js';
|
|
130
|
+
-import { TextBlock, JsonBlock, ToolResultBlock, Message } from '../../types/messages.js';
|
|
131
|
+
+import { TextBlock, JsonBlock, ToolUseBlock, ToolResultBlock, Message } from '../../types/messages.js';
|
|
132
|
+
import { ImageBlock, VideoBlock, DocumentBlock } from '../../types/media.js';
|
|
133
|
+
import { tool } from '../../tools/tool-factory.js';
|
|
134
|
+
import { z } from 'zod';
|
|
135
|
+
@@ -48,6 +48,21 @@ const CHARS_PER_TOKEN = 4;
|
|
136
|
+
const DEFAULT_MAX_RESULT_TOKENS = 2_500;
|
|
137
|
+
const DEFAULT_PREVIEW_TOKENS = 1_000;
|
|
138
|
+
const RETRIEVAL_TOOL_NAME = 'retrieve_offloaded_content';
|
|
139
|
+
+function offloadGuidance(includeRetrievalTool) {
|
|
140
|
+
+ let guidance = 'Tool result was offloaded to external storage due to size.\n' +
|
|
141
|
+
+ 'Use the preview below if it answers your question.\n';
|
|
142
|
+
+ if (includeRetrievalTool) {
|
|
143
|
+
+ guidance +=
|
|
144
|
+
+ 'If you need more detail, use retrieve_offloaded_content with a reference and:\n' +
|
|
145
|
+
+ ' - pattern: regex or keyword to find matching lines with context\n' +
|
|
146
|
+
+ ' - line_range: { start, end } to read a specific span of lines\n' +
|
|
147
|
+
+ 'Retrieve full content (omit pattern/line_range) as a last resort.';
|
|
148
|
+
+ }
|
|
149
|
+
+ else {
|
|
150
|
+
+ guidance += 'If you need more detail, use your available tools to access specific data.';
|
|
151
|
+
+ }
|
|
152
|
+
+ return guidance;
|
|
153
|
+
+}
|
|
154
|
+
const retrievalInputSchema = z.object({
|
|
155
|
+
reference: z.string().describe('The reference string from the offload placeholder (e.g. "mem_1_tool-123_0").'),
|
|
156
|
+
pattern: z
|
|
157
|
+
@@ -129,6 +144,70 @@ function decodeStoredContent(content, contentType, reference) {
|
|
158
|
+
}
|
|
159
|
+
return new TextDecoder('utf-8', { fatal: false }).decode(content);
|
|
160
|
+
}
|
|
161
|
+
+/**
|
|
162
|
+
+ * Line-addressable projection of stored JSON for pattern/line_range retrieval.
|
|
163
|
+
+ *
|
|
164
|
+
+ * Stored `application/json` blocks are `JSON.stringify(json, null, 2)`, so a string
|
|
165
|
+
+ * field holding a 300-line command output is one escaped line and grep-style search
|
|
166
|
+
+ * sees a handful of lines. Searching runs over this projection instead. It is built
|
|
167
|
+
+ * per call from the stored bytes and never persisted; stored bytes, preview and full
|
|
168
|
+
+ * retrieval are untouched. Rendering rule (deterministic, so line numbers from one
|
|
169
|
+
+ * call stay valid in the next):
|
|
170
|
+
+ * - Objects, arrays, numbers, booleans, null and strings without "\n" render exactly
|
|
171
|
+
+ * as pretty JSON: 2-space indent, stored key order, commas between members.
|
|
172
|
+
+ * - A string containing "\n" is expanded: an object member renders `<indent>"key":`
|
|
173
|
+
+ * (an array item `<indent>[index]:`, a top-level string no header) on its own line,
|
|
174
|
+
+ * followed by the string's lines split on "\n" verbatim, each on a real line at
|
|
175
|
+
+ * column 0 — no quotes, no escaping, no trailing comma — so `^`-anchored patterns
|
|
176
|
+
+ * written for the command's own output match as grep would.
|
|
177
|
+
+ * Returns undefined when the bytes are not JSON; the caller then searches the raw text.
|
|
178
|
+
+ */
|
|
179
|
+
+function projectJsonForSearch(text) {
|
|
180
|
+
+ let value;
|
|
181
|
+
+ try {
|
|
182
|
+
+ value = JSON.parse(text);
|
|
183
|
+
+ }
|
|
184
|
+
+ catch {
|
|
185
|
+
+ return undefined;
|
|
186
|
+
+ }
|
|
187
|
+
+ const out = [];
|
|
188
|
+
+ const emit = (node, indent, memberKey, positionLabel, comma) => {
|
|
189
|
+
+ if (typeof node === 'string' && node.includes('\n')) {
|
|
190
|
+
+ if (positionLabel !== undefined)
|
|
191
|
+
+ out.push(`${indent}${positionLabel}:`);
|
|
192
|
+
+ out.push(...node.split('\n'));
|
|
193
|
+
+ return;
|
|
194
|
+
+ }
|
|
195
|
+
+ const lead = memberKey === undefined ? indent : `${indent}${memberKey}: `;
|
|
196
|
+
+ if (Array.isArray(node)) {
|
|
197
|
+
+ if (node.length === 0) {
|
|
198
|
+
+ out.push(`${lead}[]${comma}`);
|
|
199
|
+
+ return;
|
|
200
|
+
+ }
|
|
201
|
+
+ out.push(`${lead}[`);
|
|
202
|
+
+ node.forEach((item, index) => emit(item, `${indent} `, undefined, `[${index}]`, index < node.length - 1 ? ',' : ''));
|
|
203
|
+
+ out.push(`${indent}]${comma}`);
|
|
204
|
+
+ return;
|
|
205
|
+
+ }
|
|
206
|
+
+ if (node !== null && typeof node === 'object') {
|
|
207
|
+
+ const keys = Object.keys(node);
|
|
208
|
+
+ if (keys.length === 0) {
|
|
209
|
+
+ out.push(`${lead}{}${comma}`);
|
|
210
|
+
+ return;
|
|
211
|
+
+ }
|
|
212
|
+
+ out.push(`${lead}{`);
|
|
213
|
+
+ keys.forEach((key, index) => {
|
|
214
|
+
+ const quoted = JSON.stringify(key);
|
|
215
|
+
+ emit(node[key], `${indent} `, quoted, quoted, index < keys.length - 1 ? ',' : '');
|
|
216
|
+
+ });
|
|
217
|
+
+ out.push(`${indent}}${comma}`);
|
|
218
|
+
+ return;
|
|
219
|
+
+ }
|
|
220
|
+
+ out.push(`${lead}${JSON.stringify(node)}${comma}`);
|
|
221
|
+
+ };
|
|
222
|
+
+ emit(value, '', undefined, undefined, '');
|
|
223
|
+
+ return out.join('\n');
|
|
224
|
+
+}
|
|
225
|
+
/**
|
|
226
|
+
* Plugin that offloads oversized tool results to reduce context consumption.
|
|
227
|
+
*
|
|
228
|
+
@@ -163,7 +242,9 @@ export class ContextOffloader {
|
|
229
|
+
_previewTokens;
|
|
230
|
+
_includeRetrievalTool;
|
|
231
|
+
_evictAfterCycles;
|
|
232
|
+
+ _excludeTools;
|
|
233
|
+
_storageByAgent = new WeakMap();
|
|
234
|
+
+ _scannedAgents = new WeakSet();
|
|
235
|
+
_keyStoredAt = new Map();
|
|
236
|
+
_retrievalTool;
|
|
237
|
+
constructor(config) {
|
|
238
|
+
@@ -179,6 +260,10 @@ export class ContextOffloader {
|
|
239
|
+
if (evictAfterCycles !== null && (!Number.isInteger(evictAfterCycles) || evictAfterCycles < 1)) {
|
|
240
|
+
throw new Error('evictAfterCycles must be a positive integer');
|
|
241
|
+
}
|
|
242
|
+
+ const excludeTools = config.excludeTools ?? [];
|
|
243
|
+
+ if (!Array.isArray(excludeTools) || excludeTools.some((name) => typeof name !== 'string' || name.length === 0)) {
|
|
244
|
+
+ throw new Error('excludeTools must be an array of non-empty tool names');
|
|
245
|
+
+ }
|
|
246
|
+
if (config.storage) {
|
|
247
|
+
this._resolveAndSetStorage(config.storage);
|
|
248
|
+
}
|
|
249
|
+
@@ -186,6 +271,7 @@ export class ContextOffloader {
|
|
250
|
+
this._previewTokens = previewTokens;
|
|
251
|
+
this._includeRetrievalTool = config.includeRetrievalTool ?? true;
|
|
252
|
+
this._evictAfterCycles = evictAfterCycles;
|
|
253
|
+
+ this._excludeTools = new Set(excludeTools);
|
|
254
|
+
}
|
|
255
|
+
_resolveAndSetStorage(storage) {
|
|
256
|
+
if (isOffloaderStorage(storage)) {
|
|
257
|
+
@@ -208,7 +294,8 @@ export class ContextOffloader {
|
|
258
|
+
}
|
|
259
|
+
this._storageForAgent(agent);
|
|
260
|
+
agent.addHook(AfterToolCallEvent, (event) => this._handleToolResult(event));
|
|
261
|
+
- agent.addHook(BeforeModelCallEvent, () => {
|
|
262
|
+
+ agent.addHook(BeforeModelCallEvent, async (event) => {
|
|
263
|
+
+ await this._repairRestoredToolResults(event.agent);
|
|
264
|
+
const cycleCount = agent.metrics.cycleCount;
|
|
265
|
+
if (this._storage instanceof LegacyInMemoryStorage) {
|
|
266
|
+
this._storage._evict(cycleCount);
|
|
267
|
+
@@ -277,6 +364,7 @@ export class ContextOffloader {
|
|
268
|
+
' - Without pattern/line_range: the full original content (use sparingly — re-injects all tokens)\n\n' +
|
|
269
|
+
'Constraints:\n' +
|
|
270
|
+
' - pattern/line_range/context_lines only work on text content. For binary content, omit them.\n' +
|
|
271
|
+
+ ' - For json content, line-based search operates on a readable projection in which multi-line string fields (e.g. a command\'s output) are expanded onto real lines.\n' +
|
|
272
|
+
' - Line numbers in results are 1-indexed and can be used in follow-up line_range calls.\n\n' +
|
|
273
|
+
'Examples:\n' +
|
|
274
|
+
' { reference: "ref_1", pattern: "error" } → lines containing "error" with 5 lines context\n' +
|
|
275
|
+
@@ -294,7 +382,12 @@ export class ContextOffloader {
|
|
276
|
+
if (!isSearchableContent(result.contentType)) {
|
|
277
|
+
return `Error: cannot search binary content (${result.contentType}). Omit pattern/line_range/context_lines to retrieve the full content.`;
|
|
278
|
+
}
|
|
279
|
+
- const text = new TextDecoder().decode(result.content);
|
|
280
|
+
+ const rawText = new TextDecoder().decode(result.content);
|
|
281
|
+
+ // Stored json is one escaped line per string field; search its readable
|
|
282
|
+
+ // projection instead (see projectJsonForSearch). Non-JSON bytes keep the raw text.
|
|
283
|
+
+ const text = result.contentType === 'application/json'
|
|
284
|
+
+ ? (projectJsonForSearch(rawText) ?? rawText)
|
|
285
|
+
+ : rawText;
|
|
286
|
+
const contextLines = input.context_lines ?? 5;
|
|
287
|
+
const lineRange = input.line_range ?? (!input.pattern ? { start: 1, end: Math.max(1, contextLines) } : undefined);
|
|
288
|
+
return searchContent(text, { pattern: input.pattern, line_range: lineRange, context_lines: contextLines }, maxChars);
|
|
289
|
+
@@ -339,40 +432,135 @@ export class ContextOffloader {
|
|
290
|
+
.filter((r) => r.ref)
|
|
291
|
+
.map((r) => ` ${r.ref} (${r.description})`)
|
|
292
|
+
.join('\n');
|
|
293
|
+
- let guidance = 'Tool result was offloaded to external storage due to size.\n' +
|
|
294
|
+
- 'Use the preview below if it answers your question.\n';
|
|
295
|
+
- if (this._includeRetrievalTool) {
|
|
296
|
+
- guidance +=
|
|
297
|
+
- 'If you need more detail, use retrieve_offloaded_content with a reference and:\n' +
|
|
298
|
+
- ' - pattern: regex or keyword to find matching lines with context\n' +
|
|
299
|
+
- ' - line_range: { start, end } to read a specific span of lines\n' +
|
|
300
|
+
- 'Retrieve full content (omit pattern/line_range) as a last resort.';
|
|
301
|
+
- }
|
|
302
|
+
- else {
|
|
303
|
+
- guidance += 'If you need more detail, use your available tools to access specific data.';
|
|
304
|
+
- }
|
|
305
|
+
+ const guidance = offloadGuidance(this._includeRetrievalTool);
|
|
306
|
+
return (`[Offloaded: ${content.length} blocks, ~${tokenCount.toLocaleString()} tokens]\n` +
|
|
307
|
+
`${guidance}\n\n` +
|
|
308
|
+
`${preview}\n\n` +
|
|
309
|
+
`[Stored references:]\n${refLines}`);
|
|
310
|
+
}
|
|
311
|
+
- async _handleToolResult(event) {
|
|
312
|
+
- if (event.result.status === 'error')
|
|
313
|
+
- return;
|
|
314
|
+
- // Skip delegation tool results — their content is the final delegated answer
|
|
315
|
+
- // and must not be truncated/offloaded. The delegation plugin transforms this
|
|
316
|
+
- // result into the AgentResult.lastMessage, so offloading would replace the
|
|
317
|
+
- // final answer with an unrecoverable placeholder.
|
|
318
|
+
- if (event.tool instanceof AgentAsTool && event.tool.delegate)
|
|
319
|
+
- return;
|
|
320
|
+
- // Skip results from the retrieval tool to prevent circular offloading
|
|
321
|
+
- if (this._includeRetrievalTool && event.toolUse.name === RETRIEVAL_TOOL_NAME)
|
|
322
|
+
+ async _isStoredOffloadPlaceholder(agent, result) {
|
|
323
|
+
+ const first = result.content[0];
|
|
324
|
+
+ if (!(first instanceof TextBlock))
|
|
325
|
+
+ return false;
|
|
326
|
+
+ const marker = first.text.match(/^\[Offloaded: (\d+) blocks, ~[\d,]+ tokens\]\n/);
|
|
327
|
+
+ if (!marker)
|
|
328
|
+
+ return false;
|
|
329
|
+
+ const guidancePrefix = `${marker[0]}${offloadGuidance(this._includeRetrievalTool)}\n\n`;
|
|
330
|
+
+ const referencesMarker = '\n\n[Stored references:]\n';
|
|
331
|
+
+ const referencesAt = first.text.lastIndexOf(referencesMarker);
|
|
332
|
+
+ if (!first.text.startsWith(guidancePrefix) || referencesAt < guidancePrefix.length)
|
|
333
|
+
+ return false;
|
|
334
|
+
+ // A tool can return marker-like text. Even when it names a real stored key,
|
|
335
|
+
+ // never trust a purported preview larger than this plugin could have built: a
|
|
336
|
+
+ // forged oversized preview would otherwise bypass restored-history repair.
|
|
337
|
+
+ const preview = first.text.slice(guidancePrefix.length, referencesAt);
|
|
338
|
+
+ if (preview.length > this._previewTokens * CHARS_PER_TOKEN)
|
|
339
|
+
+ return false;
|
|
340
|
+
+ const referencesText = first.text.slice(referencesAt + referencesMarker.length);
|
|
341
|
+
+ if (referencesText === '' || referencesText.endsWith('\n'))
|
|
342
|
+
+ return false;
|
|
343
|
+
+ const referenceLines = referencesText.split('\n');
|
|
344
|
+
+ const parsedReferences = referenceLines.map((line) => line.match(/^ (\S+) \([^\r\n]+\)$/));
|
|
345
|
+
+ if (parsedReferences.some((match) => match === null))
|
|
346
|
+
+ return false;
|
|
347
|
+
+ const originalBlockCount = Number(marker[1]);
|
|
348
|
+
+ const references = parsedReferences.map((match) => match[1]);
|
|
349
|
+
+ const supplementalReferences = [];
|
|
350
|
+
+ for (const supplemental of result.content.slice(1)) {
|
|
351
|
+
+ if (!(supplemental instanceof TextBlock))
|
|
352
|
+
+ return false;
|
|
353
|
+
+ const media = supplemental.text.match(/^\[(?:image|video|document): .+, \d+ bytes(?: \| ref: (\S+))?\]$/);
|
|
354
|
+
+ if (!media)
|
|
355
|
+
+ return false;
|
|
356
|
+
+ if (media[1])
|
|
357
|
+
+ supplementalReferences.push(media[1]);
|
|
358
|
+
+ }
|
|
359
|
+
+ if (supplementalReferences.some((reference) => !references.includes(reference)))
|
|
360
|
+
+ return false;
|
|
361
|
+
+ const referenceIndexes = references.map((reference) => {
|
|
362
|
+
+ const directPrefix = `${result.toolUseId}_`;
|
|
363
|
+
+ const nestedPrefix = `_${directPrefix}`;
|
|
364
|
+
+ const suffix = reference.startsWith(directPrefix)
|
|
365
|
+
+ ? reference.slice(directPrefix.length)
|
|
366
|
+
+ : reference.includes(nestedPrefix)
|
|
367
|
+
+ ? reference.slice(reference.lastIndexOf(nestedPrefix) + nestedPrefix.length)
|
|
368
|
+
+ : '';
|
|
369
|
+
+ return /^\d+$/.test(suffix) ? Number(suffix) : -1;
|
|
370
|
+
+ });
|
|
371
|
+
+ const uniqueIndexes = new Set(referenceIndexes);
|
|
372
|
+
+ if (originalBlockCount < 1 || references.length > originalBlockCount ||
|
|
373
|
+
+ referenceIndexes.some((index) => index < 0 || index >= originalBlockCount) ||
|
|
374
|
+
+ uniqueIndexes.size !== referenceIndexes.length)
|
|
375
|
+
+ return false;
|
|
376
|
+
+ try {
|
|
377
|
+
+ const storage = this._storageForAgent(agent);
|
|
378
|
+
+ for (const reference of references) {
|
|
379
|
+
+ const stored = await retrieveContent(storage, reference);
|
|
380
|
+
+ if (stored.content.length === 0 || stored.contentType === '')
|
|
381
|
+
+ return false;
|
|
382
|
+
+ }
|
|
383
|
+
+ return true;
|
|
384
|
+
+ }
|
|
385
|
+
+ catch {
|
|
386
|
+
+ return false;
|
|
387
|
+
+ }
|
|
388
|
+
+ }
|
|
389
|
+
+
|
|
390
|
+
+ async _repairRestoredToolResults(agent) {
|
|
391
|
+
+ if (this._scannedAgents.has(agent))
|
|
392
|
+
return;
|
|
393
|
+
- const content = event.result.content;
|
|
394
|
+
- const toolUseId = event.result.toolUseId;
|
|
395
|
+
- const tokenCount = await event.agent.model.countTokens([new Message({ role: 'user', content: [event.result] })]);
|
|
396
|
+
+ // Mark before awaiting count/storage so a failure cannot turn the scan into a
|
|
397
|
+
+ // per-cycle retry loop. Session restore has already run during initialize(),
|
|
398
|
+
+ // while request assembly clones messages only after this hook completes.
|
|
399
|
+
+ this._scannedAgents.add(agent);
|
|
400
|
+
+ const delegationToolUseIds = new Set();
|
|
401
|
+
+ const retrievalToolUseIds = new Set();
|
|
402
|
+
+ const excludedToolUseIds = new Set();
|
|
403
|
+
+ for (const message of agent.messages) {
|
|
404
|
+
+ for (const block of message.content) {
|
|
405
|
+
+ if (!(block instanceof ToolUseBlock))
|
|
406
|
+
+ continue;
|
|
407
|
+
+ const tool = agent.toolRegistry.get(block.name);
|
|
408
|
+
+ if (tool instanceof AgentAsTool && tool.delegate) {
|
|
409
|
+
+ delegationToolUseIds.add(block.toolUseId);
|
|
410
|
+
+ }
|
|
411
|
+
+ if (this._includeRetrievalTool && block.name === RETRIEVAL_TOOL_NAME) {
|
|
412
|
+
+ retrievalToolUseIds.add(block.toolUseId);
|
|
413
|
+
+ }
|
|
414
|
+
+ if (this._excludeTools.has(block.name)) {
|
|
415
|
+
+ excludedToolUseIds.add(block.toolUseId);
|
|
416
|
+
+ }
|
|
417
|
+
+ }
|
|
418
|
+
+ }
|
|
419
|
+
+ for (const message of agent.messages) {
|
|
420
|
+
+ for (let index = 0; index < message.content.length; index += 1) {
|
|
421
|
+
+ const block = message.content[index];
|
|
422
|
+
+ if (!(block instanceof ToolResultBlock) || block.status !== 'success' ||
|
|
423
|
+
+ delegationToolUseIds.has(block.toolUseId) || retrievalToolUseIds.has(block.toolUseId) ||
|
|
424
|
+
+ excludedToolUseIds.has(block.toolUseId))
|
|
425
|
+
+ continue;
|
|
426
|
+
+ try {
|
|
427
|
+
+ if (await this._isStoredOffloadPlaceholder(agent, block))
|
|
428
|
+
+ continue;
|
|
429
|
+
+ const replacement = await this._offloadToolResult(agent, block);
|
|
430
|
+
+ if (replacement) {
|
|
431
|
+
+ // Replace only the content block. The Message object (and therefore
|
|
432
|
+
+ // its trackingId/metadata/position) and the matching toolUseId stay intact.
|
|
433
|
+
+ message.content[index] = replacement;
|
|
434
|
+
+ }
|
|
435
|
+
+ }
|
|
436
|
+
+ catch (err) {
|
|
437
|
+
+ logger.warn(`tool_use_id=<${block.toolUseId}> | failed to inspect restored tool result, keeping original`, err);
|
|
438
|
+
+ }
|
|
439
|
+
+ }
|
|
440
|
+
+ }
|
|
441
|
+
+ }
|
|
442
|
+
+ async _offloadToolResult(agent, result) {
|
|
443
|
+
+ const content = result.content;
|
|
444
|
+
+ const toolUseId = result.toolUseId;
|
|
445
|
+
+ const tokenCount = await agent.model.countTokens([new Message({ role: 'user', content: [result] })]);
|
|
446
|
+
if (tokenCount <= this._maxResultTokens)
|
|
447
|
+
- return;
|
|
448
|
+
+ return undefined;
|
|
449
|
+
// Extract text preview from text/JSON blocks
|
|
450
|
+
const textParts = [];
|
|
451
|
+
for (const block of content) {
|
|
452
|
+
@@ -382,22 +570,28 @@ export class ContextOffloader {
|
|
453
|
+
textParts.push(JSON.stringify(block.json, null, 2));
|
|
454
|
+
}
|
|
455
|
+
const fullText = textParts.join('\n');
|
|
456
|
+
- // Store each content block to the storage backend
|
|
457
|
+
+ // Store each content block to the storage backend. Only publish references
|
|
458
|
+
+ // after every write succeeds; a failure leaves the caller's result untouched.
|
|
459
|
+
let references;
|
|
460
|
+
- try {
|
|
461
|
+
- const storage = this._storageForAgent(event.agent);
|
|
462
|
+
- references = await Promise.all(content.map((block, i) => this._storeBlock(storage, block, `${toolUseId}_${i}`)));
|
|
463
|
+
+ const storage = this._storageForAgent(agent);
|
|
464
|
+
+ const settled = await Promise.allSettled(content.map((block, i) => this._storeBlock(storage, block, `${toolUseId}_${i}`)));
|
|
465
|
+
+ const failed = settled.find((entry) => entry.status === 'rejected');
|
|
466
|
+
+ if (failed) {
|
|
467
|
+
if (!isOffloaderStorage(storage)) {
|
|
468
|
+
- const storedAt = event.agent.metrics.cycleCount;
|
|
469
|
+
- for (const entry of references) {
|
|
470
|
+
- if (entry.ref)
|
|
471
|
+
- this._keyStoredAt.set(entry.ref, storedAt);
|
|
472
|
+
- }
|
|
473
|
+
+ await Promise.allSettled(settled.flatMap((entry) => entry.status === 'fulfilled' && entry.value.ref
|
|
474
|
+
+ ? [storage.delete(entry.value.ref)]
|
|
475
|
+
+ : []));
|
|
476
|
+
}
|
|
477
|
+
+ logger.warn(`tool_use_id=<${toolUseId}> | failed to offload tool result, keeping original`, failed.reason);
|
|
478
|
+
+ return undefined;
|
|
479
|
+
}
|
|
480
|
+
- catch (err) {
|
|
481
|
+
- logger.warn(`tool_use_id=<${toolUseId}> | failed to offload tool result, keeping original`, err);
|
|
482
|
+
- return;
|
|
483
|
+
+ references = settled.map((entry) => entry.value);
|
|
484
|
+
+ if (!isOffloaderStorage(storage)) {
|
|
485
|
+
+ const storedAt = agent.metrics.cycleCount;
|
|
486
|
+
+ for (const entry of references) {
|
|
487
|
+
+ if (entry.ref)
|
|
488
|
+
+ this._keyStoredAt.set(entry.ref, storedAt);
|
|
489
|
+
+ }
|
|
490
|
+
}
|
|
491
|
+
logger.debug(`tool_use_id=<${toolUseId}>, blocks=<${references.length}>, tokens=<${tokenCount}> | tool result offloaded`);
|
|
492
|
+
// Build replacement content: preview text + media placeholders
|
|
493
|
+
@@ -422,11 +616,32 @@ export class ContextOffloader {
|
|
494
|
+
newContent.push(new TextBlock(`[${label}, ${size} bytes${ref ? ` | ref: ${ref}` : ''}]`));
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
- event.result = new ToolResultBlock({
|
|
498
|
+
- toolUseId: event.result.toolUseId,
|
|
499
|
+
- status: event.result.status,
|
|
500
|
+
+ return new ToolResultBlock({
|
|
501
|
+
+ toolUseId: result.toolUseId,
|
|
502
|
+
+ status: result.status,
|
|
503
|
+
content: newContent,
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
+ async _handleToolResult(event) {
|
|
507
|
+
+ if (event.result.status === 'error')
|
|
508
|
+
+ return;
|
|
509
|
+
+ // Skip delegation tool results — their content is the final delegated answer
|
|
510
|
+
+ // and must not be truncated/offloaded. The delegation plugin transforms this
|
|
511
|
+
+ // result into the AgentResult.lastMessage, so offloading would replace the
|
|
512
|
+
+ // final answer with an unrecoverable placeholder.
|
|
513
|
+
+ if (event.tool instanceof AgentAsTool && event.tool.delegate)
|
|
514
|
+
+ return;
|
|
515
|
+
+ // Skip results from the retrieval tool to prevent circular offloading
|
|
516
|
+
+ if (this._includeRetrievalTool && event.toolUse.name === RETRIEVAL_TOOL_NAME)
|
|
517
|
+
+ return;
|
|
518
|
+
+ // Skip tools excluded by name: their results must reach the model whole
|
|
519
|
+
+ // (a preview is not the content), so they are never stored or replaced.
|
|
520
|
+
+ if (this._excludeTools.has(event.toolUse.name))
|
|
521
|
+
+ return;
|
|
522
|
+
+ const replacement = await this._offloadToolResult(event.agent, event.result);
|
|
523
|
+
+ if (replacement)
|
|
524
|
+
+ event.result = replacement;
|
|
525
|
+
+ }
|
|
526
|
+
+
|
|
527
|
+
}
|
|
528
|
+
//# sourceMappingURL=plugin.js.map
|
|
529
|
+
|
|
530
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.d.ts b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.d.ts
|
|
531
|
+
index a0a5b0e40e22e6108df5d832e9b1ba051e2f99cd..8907d109ce2866e376df312ebc0bae1a68acec3d 100644
|
|
532
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.d.ts
|
|
533
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.d.ts
|
|
534
|
+
@@ -1,12 +1,19 @@
|
|
535
|
+
-import type { BashOutput } from './types.js';
|
|
536
|
+
+import type { InvokableTool } from '../../index.js';
|
|
537
|
+
+import type { BashInput, BashOutput } from './types.js';
|
|
538
|
+
+export interface CreateBashOptions {
|
|
539
|
+
+ /** Initial cwd for every new persistent shell owned by this tool. */
|
|
540
|
+
+ cwd?: string;
|
|
541
|
+
+ /** Session project root used only for conservative wrong-root path preflight. */
|
|
542
|
+
+ projectRoot?: string;
|
|
543
|
+
+}
|
|
544
|
+
+/**
|
|
545
|
+
+ * Create a host-only bash tool with configured persistent-shell path context.
|
|
546
|
+
+ */
|
|
547
|
+
+export declare function createBash(options?: CreateBashOptions): InvokableTool<BashInput, BashOutput | string>;
|
|
548
|
+
/**
|
|
549
|
+
* Host-only bash tool with a persistent session across calls.
|
|
550
|
+
* State (variables, working directory) persists within the session.
|
|
551
|
+
* Node.js only.
|
|
552
|
+
*/
|
|
553
|
+
-export declare const bash: import("../../index.js").InvokableTool<{
|
|
554
|
+
- mode: "execute" | "restart";
|
|
555
|
+
- command?: string | undefined;
|
|
556
|
+
- timeout?: number | undefined;
|
|
557
|
+
-}, BashOutput | "Bash session restarted">;
|
|
558
|
+
+export declare const bash: InvokableTool<BashInput, BashOutput | string>;
|
|
559
|
+
//# sourceMappingURL=bash.d.ts.map
|
|
560
|
+
|
|
561
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.js b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.js
|
|
562
|
+
index 44fb775853169dab0fde7aee5e7cc275a060de9c..b8b3a1f3f9541de7d671e0a5df9261fac7a100e9 100644
|
|
563
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.js
|
|
564
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/bash.js
|
|
565
|
+
@@ -1,8 +1,64 @@
|
|
566
|
+
import { tool } from '../../tools/tool-factory.js';
|
|
567
|
+
import { z } from 'zod';
|
|
568
|
+
import { spawn } from 'child_process';
|
|
569
|
+
+import { existsSync, statSync } from 'fs';
|
|
570
|
+
+import path from 'path';
|
|
571
|
+
import { Buffer } from 'buffer';
|
|
572
|
+
import { BashTimeoutError, BashSessionError } from './types.js';
|
|
573
|
+
+const SHELL_RESTART_NOTICE = 'Notice: Persistent bash shell exited with code 0; it will restart before the next command.';
|
|
574
|
+
+/**
|
|
575
|
+
+ * Byte cap on each captured-stream tail carried by a timeout result. Deliberately
|
|
576
|
+
+ * the same 64 KiB figure as Darwin's background `output`/`wait` projection
|
|
577
|
+
+ * (`OUTPUT_LIMIT` in `src/tools/background-bash.ts`), which also owns the
|
|
578
|
+
+ * `hasMore` vocabulary used below; do not introduce a second cap.
|
|
579
|
+
+ */
|
|
580
|
+
+const TIMEOUT_TAIL_LIMIT = 64 * 1024;
|
|
581
|
+
+/**
|
|
582
|
+
+ * Grace between SIGTERM and SIGKILL when `stop()` takes down the shell's process
|
|
583
|
+
+ * group. Deliberately the same 500 ms as Darwin's background manager
|
|
584
|
+
+ * (`TERM_GRACE_MS` in `src/tools/background-bash.ts`), so a timed-out foreground
|
|
585
|
+
+ * child and a stopped background job share one TERM→KILL shape; keep them equal.
|
|
586
|
+
+ */
|
|
587
|
+
+const FOREGROUND_TERM_GRACE_MS = 500;
|
|
588
|
+
+/**
|
|
589
|
+
+ * Signal a whole process group. A group that is already gone (ESRCH) or refuses
|
|
590
|
+
+ * the signal (EPERM) is not an error; nothing here may throw, because the KILL
|
|
591
|
+
+ * leg runs from an unref'd timer where a throw would be an uncaught exception.
|
|
592
|
+
+ */
|
|
593
|
+
+function signalProcessGroup(pid, signal) {
|
|
594
|
+
+ try {
|
|
595
|
+
+ process.kill(-pid, signal);
|
|
596
|
+
+ }
|
|
597
|
+
+ catch {
|
|
598
|
+
+ // ESRCH / EPERM: the group is gone or not ours any more.
|
|
599
|
+
+ }
|
|
600
|
+
+}
|
|
601
|
+
+/**
|
|
602
|
+
+ * Keep at most `limit` trailing UTF-8 bytes of `text`, never starting inside a
|
|
603
|
+
+ * multi-byte sequence, and report how much there was.
|
|
604
|
+
+ */
|
|
605
|
+
+function boundedTail(text, limit) {
|
|
606
|
+
+ const bytes = Buffer.from(text, 'utf-8');
|
|
607
|
+
+ if (bytes.length <= limit) {
|
|
608
|
+
+ return { text, total: bytes.length, kept: bytes.length };
|
|
609
|
+
+ }
|
|
610
|
+
+ let start = bytes.length - limit;
|
|
611
|
+
+ while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) {
|
|
612
|
+
+ start += 1;
|
|
613
|
+
+ }
|
|
614
|
+
+ return { text: bytes.subarray(start).toString('utf-8'), total: bytes.length, kept: bytes.length - start };
|
|
615
|
+
+}
|
|
616
|
+
+function describeTail(label, tail) {
|
|
617
|
+
+ if (tail.total === 0) {
|
|
618
|
+
+ return `${label}: (none)`;
|
|
619
|
+
+ }
|
|
620
|
+
+ const bound = tail.kept === tail.total
|
|
621
|
+
+ ? `${tail.total} bytes`
|
|
622
|
+
+ : `last ${tail.kept} of ${tail.total} bytes; hasMore: true`;
|
|
623
|
+
+ return `${label} (${bound}):\n${tail.text}`;
|
|
624
|
+
+}
|
|
625
|
+
+const UNSAFE_PREFLIGHT_SYNTAX = /[\n\r'"\\;&|<>$`(){}\[\]*?!]/;
|
|
626
|
+
+const PLAIN_RELATIVE_PATH = /^(?:\.\/)?[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+\/?$/;
|
|
627
|
+
const bashInputSchema = z.object({
|
|
628
|
+
mode: z
|
|
629
|
+
.enum(['execute', 'restart'])
|
|
630
|
+
@@ -10,6 +66,57 @@ const bashInputSchema = z.object({
|
|
631
|
+
command: z.string().optional().describe('The bash command to execute (required when mode is "execute")'),
|
|
632
|
+
timeout: z.number().positive().optional().describe('Timeout in seconds (default: 120, applies only to execute mode)'),
|
|
633
|
+
});
|
|
634
|
+
+/**
|
|
635
|
+
+ * Recognize only the simple path shapes observed in SRF-014. General shell
|
|
636
|
+
+ * syntax deliberately fails open rather than being tokenized or rewritten.
|
|
637
|
+
+ */
|
|
638
|
+
+function preflightPath(command) {
|
|
639
|
+
+ const trimmed = command.trim();
|
|
640
|
+
+ if (!trimmed || UNSAFE_PREFLIGHT_SYNTAX.test(trimmed)) {
|
|
641
|
+
+ return null;
|
|
642
|
+
+ }
|
|
643
|
+
+ const words = trimmed.split(/[ \t]+/);
|
|
644
|
+
+ if (words[0] === 'cd') {
|
|
645
|
+
+ if (words.length !== 2 || words[1].startsWith('-') || path.isAbsolute(words[1])) {
|
|
646
|
+
+ return null;
|
|
647
|
+
+ }
|
|
648
|
+
+ return { value: words[1], requireDirectory: true };
|
|
649
|
+
+ }
|
|
650
|
+
+ const candidate = words[0];
|
|
651
|
+
+ if (!PLAIN_RELATIVE_PATH.test(candidate) || candidate.startsWith('-') || path.isAbsolute(candidate)) {
|
|
652
|
+
+ return null;
|
|
653
|
+
+ }
|
|
654
|
+
+ return { value: candidate, requireDirectory: false };
|
|
655
|
+
+}
|
|
656
|
+
+function pathExists(candidate, requireDirectory) {
|
|
657
|
+
+ try {
|
|
658
|
+
+ return existsSync(candidate) && (!requireDirectory || statSync(candidate).isDirectory());
|
|
659
|
+
+ }
|
|
660
|
+
+ catch {
|
|
661
|
+
+ return false;
|
|
662
|
+
+ }
|
|
663
|
+
+}
|
|
664
|
+
+function wrongRootDiagnostic(command, cwd, projectRoot) {
|
|
665
|
+
+ const candidate = preflightPath(command);
|
|
666
|
+
+ if (candidate === null) {
|
|
667
|
+
+ return null;
|
|
668
|
+
+ }
|
|
669
|
+
+ const cwdPath = path.resolve(cwd, candidate.value);
|
|
670
|
+
+ const projectPath = path.resolve(projectRoot, candidate.value);
|
|
671
|
+
+ if (cwdPath === projectPath || pathExists(cwdPath, candidate.requireDirectory) || !pathExists(projectPath, candidate.requireDirectory)) {
|
|
672
|
+
+ return null;
|
|
673
|
+
+ }
|
|
674
|
+
+ return {
|
|
675
|
+
+ output: '',
|
|
676
|
+
+ error: `Command not run: relative path "${candidate.value}" does not exist from the persistent shell cwd, but it does exist from the session project root.\n` +
|
|
677
|
+
+ `cwd: ${cwd}\n` +
|
|
678
|
+
+ `cwd path: ${cwdPath}\n` +
|
|
679
|
+
+ `project-root path: ${projectPath}\n` +
|
|
680
|
+
+ `Return to the project root with "cd ${projectRoot}" or use "${projectPath}".`,
|
|
681
|
+
+ cwd,
|
|
682
|
+
+ };
|
|
683
|
+
+}
|
|
684
|
+
+
|
|
685
|
+
/**
|
|
686
|
+
* Internal class for managing a bash session.
|
|
687
|
+
*/
|
|
688
|
+
@@ -18,9 +125,21 @@ class BashSession {
|
|
689
|
+
_started = false;
|
|
690
|
+
_timeout;
|
|
691
|
+
_sentinel;
|
|
692
|
+
- constructor(timeout = 120) {
|
|
693
|
+
+ _stderrSentinel;
|
|
694
|
+
+ _exitCodeSentinel;
|
|
695
|
+
+ _cwdSentinel;
|
|
696
|
+
+ _initialCwd;
|
|
697
|
+
+ _projectRoot;
|
|
698
|
+
+ _cwd;
|
|
699
|
+
+ constructor(timeout = 120, initialCwd = process.cwd(), projectRoot = null) {
|
|
700
|
+
this._timeout = timeout;
|
|
701
|
+
this._sentinel = `__BASH_DONE_${Date.now()}_${Math.random().toString(36).slice(2)}__`;
|
|
702
|
+
+ this._stderrSentinel = `${this._sentinel}_STDERR`;
|
|
703
|
+
+ this._exitCodeSentinel = `${this._sentinel}_EXIT`;
|
|
704
|
+
+ this._cwdSentinel = `${this._sentinel}_CWD`;
|
|
705
|
+
+ this._initialCwd = path.resolve(initialCwd);
|
|
706
|
+
+ this._projectRoot = projectRoot === null ? null : path.resolve(projectRoot);
|
|
707
|
+
+ this._cwd = this._initialCwd;
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Starts the bash process if not already started.
|
|
711
|
+
@@ -30,17 +149,28 @@ class BashSession {
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
try {
|
|
715
|
+
+ // detached: the shell leads its own process group so stop() can take a
|
|
716
|
+
+ // timed-out foreground child down with it instead of orphaning it to pid 1.
|
|
717
|
+
this._process = spawn('bash', [], {
|
|
718
|
+
- cwd: process.cwd(),
|
|
719
|
+
+ cwd: this._initialCwd,
|
|
720
|
+
env: { ...process.env, PS1: '', PS2: '' },
|
|
721
|
+
+ detached: true,
|
|
722
|
+
});
|
|
723
|
+
if (!this._process.stdin || !this._process.stdout || !this._process.stderr) {
|
|
724
|
+
throw new BashSessionError('Failed to create bash process streams');
|
|
725
|
+
}
|
|
726
|
+
this._started = true;
|
|
727
|
+
activeSessions.add(this);
|
|
728
|
+
- // Handle unexpected process exits
|
|
729
|
+
- this._process.on('close', () => {
|
|
730
|
+
+ // Handle unexpected process exits. The handler is bound to the shell it
|
|
731
|
+
+ // was installed for: after stop() the next queued call may already have
|
|
732
|
+
+ // started a replacement before the killed shell's `close` arrives (the
|
|
733
|
+
+ // group kill makes that prompt), and a bare reset here would drop the
|
|
734
|
+
+ // replacement's reference — an unstopped shell that outlives the session.
|
|
735
|
+
+ const started = this._process;
|
|
736
|
+
+ started.on('close', () => {
|
|
737
|
+
+ if (this._process !== started) {
|
|
738
|
+
+ return;
|
|
739
|
+
+ }
|
|
740
|
+
this._process = null;
|
|
741
|
+
this._started = false;
|
|
742
|
+
});
|
|
743
|
+
@@ -54,16 +184,43 @@ class BashSession {
|
|
744
|
+
*/
|
|
745
|
+
stop() {
|
|
746
|
+
if (this._process) {
|
|
747
|
+
- this._process.kill();
|
|
748
|
+
+ // Signal the shell's whole process group (it was spawned detached), so a
|
|
749
|
+
+ // foreground child the shell is waiting on dies with it instead of being
|
|
750
|
+
+ // reparented to pid 1. TERM first, then one bounded KILL after
|
|
751
|
+
+ // FOREGROUND_TERM_GRACE_MS; the timer is unref'd and never awaited, so
|
|
752
|
+
+ // retire()/shutdown do not get slower.
|
|
753
|
+
+ const pid = this._process.pid;
|
|
754
|
+
+ if (typeof pid === 'number') {
|
|
755
|
+
+ signalProcessGroup(pid, 'SIGTERM');
|
|
756
|
+
+ setTimeout(() => signalProcessGroup(pid, 'SIGKILL'), FOREGROUND_TERM_GRACE_MS).unref();
|
|
757
|
+
+ }
|
|
758
|
+
this._process = null;
|
|
759
|
+
this._started = false;
|
|
760
|
+
+ // The replacement shell spawns at the initial cwd; keep the preflight truthful.
|
|
761
|
+
+ this._cwd = this._initialCwd;
|
|
762
|
+
}
|
|
763
|
+
activeSessions.delete(this);
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
- * Runs a command in the bash session.
|
|
767
|
+
+ * Runs a command in the bash session. The per-Agent foreground queue ensures
|
|
768
|
+
+ * this method has exclusive ownership of the persistent process and streams.
|
|
769
|
+
+ * `cancelSignal` is the tool call's `ToolContext.cancelSignal`: an abort takes
|
|
770
|
+
+ * the shell's process group down (TERM→KILL, like the timeout) and rejects at
|
|
771
|
+
+ * once; an already-aborted signal rejects before anything is spawned or written.
|
|
772
|
+
*/
|
|
773
|
+
- async run(command, timeout) {
|
|
774
|
+
+ async run(command, timeout, cancelSignal) {
|
|
775
|
+
+ const diagnostic = this._projectRoot === null ? null : wrongRootDiagnostic(command, this._cwd, this._projectRoot);
|
|
776
|
+
+ if (diagnostic !== null) {
|
|
777
|
+
+ return diagnostic;
|
|
778
|
+
+ }
|
|
779
|
+
+ if (cancelSignal?.aborted) {
|
|
780
|
+
+ const failure = new BashSessionError('Command was cancelled before it started; nothing ran.');
|
|
781
|
+
+ failure.output = '';
|
|
782
|
+
+ failure.error = '';
|
|
783
|
+
+ failure.cwd = this._cwd;
|
|
784
|
+
+ failure.cancelled = true;
|
|
785
|
+
+ throw failure;
|
|
786
|
+
+ }
|
|
787
|
+
this.start();
|
|
788
|
+
if (!this._process || !this._process.stdin || !this._process.stdout || !this._process.stderr) {
|
|
789
|
+
throw new BashSessionError('Bash session not properly initialized');
|
|
790
|
+
@@ -72,33 +229,90 @@ class BashSession {
|
|
791
|
+
let stdoutData = '';
|
|
792
|
+
let stderrData = '';
|
|
793
|
+
let timeoutHandle = null;
|
|
794
|
+
- let isTimedOut = false;
|
|
795
|
+
+ // Set once the timeout or an abort has already settled this call with a
|
|
796
|
+
+ // group kill; the killed shell's later `close` must not settle it again.
|
|
797
|
+
+ let isKilled = false;
|
|
798
|
+
+ let stdoutDone = false;
|
|
799
|
+
+ let stderrDone = false;
|
|
800
|
+
return new Promise((resolve, reject) => {
|
|
801
|
+
const stdout = this._process.stdout;
|
|
802
|
+
const stderr = this._process.stderr;
|
|
803
|
+
const stdin = this._process.stdin;
|
|
804
|
+
// Handlers for stdout
|
|
805
|
+
+ const maybeResolve = () => {
|
|
806
|
+
+ if (!stdoutDone || !stderrDone) {
|
|
807
|
+
+ return;
|
|
808
|
+
+ }
|
|
809
|
+
+ cleanup();
|
|
810
|
+
+ const cwdStart = stdoutData.lastIndexOf(this._cwdSentinel);
|
|
811
|
+
+ const cwdEnd = cwdStart < 0 ? -1 : stdoutData.indexOf('\0', cwdStart);
|
|
812
|
+
+ if (cwdStart < 0 || cwdEnd < 0) {
|
|
813
|
+
+ reject(new BashSessionError('Bash session did not report its effective cwd'));
|
|
814
|
+
+ return;
|
|
815
|
+
+ }
|
|
816
|
+
+ const reportedCwd = stdoutData.slice(cwdStart + this._cwdSentinel.length, cwdEnd).replace(/\n$/, '');
|
|
817
|
+
+ if (path.isAbsolute(reportedCwd)) {
|
|
818
|
+
+ this._cwd = reportedCwd;
|
|
819
|
+
+ }
|
|
820
|
+
+ const afterCwd = stdoutData[cwdEnd + 1] === '\n' ? cwdEnd + 2 : cwdEnd + 1;
|
|
821
|
+
+ const withoutCwd = `${stdoutData.slice(0, cwdStart)}${stdoutData.slice(afterCwd)}`;
|
|
822
|
+
+ const exitStart = withoutCwd.lastIndexOf(this._exitCodeSentinel);
|
|
823
|
+
+ const exitEnd = exitStart < 0 ? -1 : withoutCwd.indexOf('\n', exitStart);
|
|
824
|
+
+ if (exitStart < 0 || exitEnd < 0) {
|
|
825
|
+
+ reject(new BashSessionError('Bash session did not report the command exit code'));
|
|
826
|
+
+ return;
|
|
827
|
+
+ }
|
|
828
|
+
+ const exitCode = Number(withoutCwd.slice(exitStart + this._exitCodeSentinel.length, exitEnd));
|
|
829
|
+
+ if (!Number.isInteger(exitCode)) {
|
|
830
|
+
+ reject(new BashSessionError('Bash session reported an invalid command exit code'));
|
|
831
|
+
+ return;
|
|
832
|
+
+ }
|
|
833
|
+
+ const output = `${withoutCwd.slice(0, exitStart)}${withoutCwd.slice(exitEnd + 1)}`.replace(this._sentinel, '').trim();
|
|
834
|
+
+ const error = stderrData.replace(this._stderrSentinel, '').trim();
|
|
835
|
+
+ resolve({ output, error, cwd: this._cwd, exitCode });
|
|
836
|
+
+ };
|
|
837
|
+
const onStdoutData = (chunk) => {
|
|
838
|
+
const data = Buffer.from(chunk).toString('utf-8');
|
|
839
|
+
stdoutData += data;
|
|
840
|
+
// Check for sentinel
|
|
841
|
+
if (stdoutData.includes(this._sentinel)) {
|
|
842
|
+
- cleanup();
|
|
843
|
+
- // Remove sentinel from output
|
|
844
|
+
- const output = stdoutData.replace(this._sentinel, '').trim();
|
|
845
|
+
- const error = stderrData.trim();
|
|
846
|
+
- resolve({ output, error });
|
|
847
|
+
+ stdoutDone = true;
|
|
848
|
+
+ maybeResolve();
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
// Handlers for stderr
|
|
852
|
+
const onStderrData = (chunk) => {
|
|
853
|
+
stderrData += Buffer.from(chunk).toString('utf-8');
|
|
854
|
+
+ if (stderrData.includes(this._stderrSentinel)) {
|
|
855
|
+
+ stderrDone = true;
|
|
856
|
+
+ maybeResolve();
|
|
857
|
+
+ }
|
|
858
|
+
};
|
|
859
|
+
- // Handler for process close
|
|
860
|
+
- const onClose = (code) => {
|
|
861
|
+
- if (!isTimedOut) {
|
|
862
|
+
+ // Handler for process close. Node emits close only after stdio has closed,
|
|
863
|
+
+ // so the buffers contain everything this invocation produced.
|
|
864
|
+
+ const onClose = (code, signal) => {
|
|
865
|
+
+ if (!isKilled) {
|
|
866
|
+
cleanup();
|
|
867
|
+
- reject(new BashSessionError(`Bash process exited unexpectedly with code ${code ?? 'unknown'}`));
|
|
868
|
+
+ const output = stdoutData.trim();
|
|
869
|
+
+ const error = stderrData.trim();
|
|
870
|
+
+ if (code === 0 && signal === null) {
|
|
871
|
+
+ resolve({
|
|
872
|
+
+ output,
|
|
873
|
+
+ error: error ? `${error}\n${SHELL_RESTART_NOTICE}` : SHELL_RESTART_NOTICE,
|
|
874
|
+
+ cwd: this._cwd,
|
|
875
|
+
+ });
|
|
876
|
+
+ return;
|
|
877
|
+
+ }
|
|
878
|
+
+ const metadata = signal === null
|
|
879
|
+
+ ? `code ${code ?? 'unknown'}`
|
|
880
|
+
+ : `signal ${signal}${code === null ? '' : ` (code ${code})`}`;
|
|
881
|
+
+ const failure = new BashSessionError(`Bash process exited unexpectedly with ${metadata}`);
|
|
882
|
+
+ failure.exitCode = code;
|
|
883
|
+
+ failure.signal = signal;
|
|
884
|
+
+ failure.output = output;
|
|
885
|
+
+ failure.error = error;
|
|
886
|
+
+ failure.cwd = this._cwd;
|
|
887
|
+
+ reject(failure);
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
// Handler for process errors
|
|
891
|
+
@@ -107,13 +321,14 @@ class BashSession {
|
|
892
|
+
this.stop();
|
|
893
|
+
reject(new BashSessionError(`Bash process error: ${err.message}`));
|
|
894
|
+
};
|
|
895
|
+
- // Cleanup function - removes per-command listeners and timeout.
|
|
896
|
+
- // Does NOT stop the process, preserving session state between calls.
|
|
897
|
+
+ // Cleanup function - removes per-command listeners, timeout and the abort
|
|
898
|
+
+ // listener. Does NOT stop the process, preserving session state between calls.
|
|
899
|
+
const cleanup = () => {
|
|
900
|
+
if (timeoutHandle !== null) {
|
|
901
|
+
clearTimeout(timeoutHandle);
|
|
902
|
+
timeoutHandle = null;
|
|
903
|
+
}
|
|
904
|
+
+ cancelSignal?.removeEventListener('abort', onAbort);
|
|
905
|
+
stdout.off('data', onStdoutData);
|
|
906
|
+
stderr.off('data', onStderrData);
|
|
907
|
+
// Check if process still exists before removing listeners
|
|
908
|
+
@@ -122,27 +337,77 @@ class BashSession {
|
|
909
|
+
this._process.off('error', onError);
|
|
910
|
+
}
|
|
911
|
+
};
|
|
912
|
+
+ // Cancellation: mirrors the timeout branch — group kill, captured tails as
|
|
913
|
+
+ // evidence, reject at once without waiting for the shell's `close` (the KILL
|
|
914
|
+
+ // leg finishes on stop()'s unref'd timer).
|
|
915
|
+
+ const onAbort = () => {
|
|
916
|
+
+ if (isKilled) {
|
|
917
|
+
+ return;
|
|
918
|
+
+ }
|
|
919
|
+
+ isKilled = true;
|
|
920
|
+
+ cleanup();
|
|
921
|
+
+ this.stop();
|
|
922
|
+
+ const stdoutTail = boundedTail(stdoutData.trim(), TIMEOUT_TAIL_LIMIT);
|
|
923
|
+
+ const stderrTail = boundedTail(stderrData.trim(), TIMEOUT_TAIL_LIMIT);
|
|
924
|
+
+ const failure = new BashSessionError(`Command was cancelled and its process group was killed (SIGTERM, then SIGKILL after ${FOREGROUND_TERM_GRACE_MS} ms).\n` +
|
|
925
|
+
+ `${describeTail('stdout captured before cancellation', stdoutTail)}\n` +
|
|
926
|
+
+ `${describeTail('stderr captured before cancellation', stderrTail)}\n` +
|
|
927
|
+
+ `Persistent bash shell was killed with the command; it will restart before the next command with cwd: ${this._initialCwd} (shell variables and cd from before the cancellation are gone).`);
|
|
928
|
+
+ failure.output = stdoutTail.text;
|
|
929
|
+
+ failure.error = stderrTail.text;
|
|
930
|
+
+ failure.cwd = this._initialCwd;
|
|
931
|
+
+ failure.cancelled = true;
|
|
932
|
+
+ reject(failure);
|
|
933
|
+
+ };
|
|
934
|
+
// Set up timeout
|
|
935
|
+
timeoutHandle = setTimeout(() => {
|
|
936
|
+
- isTimedOut = true;
|
|
937
|
+
+ if (isKilled) {
|
|
938
|
+
+ return;
|
|
939
|
+
+ }
|
|
940
|
+
+ isKilled = true;
|
|
941
|
+
cleanup();
|
|
942
|
+
this.stop();
|
|
943
|
+
- reject(new BashTimeoutError(`Command timed out after ${effectiveTimeout} seconds`));
|
|
944
|
+
+ // The persistent shell cannot detach a running command, so the kill
|
|
945
|
+
+ // stands; what it printed so far is evidence and travels with the error.
|
|
946
|
+
+ const stdoutTail = boundedTail(stdoutData.trim(), TIMEOUT_TAIL_LIMIT);
|
|
947
|
+
+ const stderrTail = boundedTail(stderrData.trim(), TIMEOUT_TAIL_LIMIT);
|
|
948
|
+
+ const failure = new BashTimeoutError(`Command did not complete within ${effectiveTimeout} seconds and was killed.\n` +
|
|
949
|
+
+ `${describeTail('stdout captured before the timeout', stdoutTail)}\n` +
|
|
950
|
+
+ `${describeTail('stderr captured before the timeout', stderrTail)}\n` +
|
|
951
|
+
+ `Persistent bash shell was killed with the command; it will restart before the next command with cwd: ${this._initialCwd} (shell variables and cd from before the timeout are gone).\n` +
|
|
952
|
+
+ 'For work that may run longer than the timeout, use mode "start" and then "wait" with the returned taskId instead of raising the timeout.');
|
|
953
|
+
+ failure.output = stdoutTail.text;
|
|
954
|
+
+ failure.error = stderrTail.text;
|
|
955
|
+
+ failure.cwd = this._initialCwd;
|
|
956
|
+
+ failure.timeoutSeconds = effectiveTimeout;
|
|
957
|
+
+ reject(failure);
|
|
958
|
+
}, effectiveTimeout * 1000);
|
|
959
|
+
// Attach listeners
|
|
960
|
+
stdout.on('data', onStdoutData);
|
|
961
|
+
stderr.on('data', onStderrData);
|
|
962
|
+
this._process.on('close', onClose);
|
|
963
|
+
this._process.on('error', onError);
|
|
964
|
+
- // Send command with sentinel
|
|
965
|
+
+ // Send command with sentinel. The command runs inside a brace group whose
|
|
966
|
+
+ // stdin is /dev/null: it is not a subshell (cd/variables persist), but a
|
|
967
|
+
+ // command that reads stdin gets EOF at once instead of waiting on the tool's
|
|
968
|
+
+ // command socket — or eating the sentinel lines below and wedging the shell.
|
|
969
|
+
+ // The leading `:` keeps the group non-empty, so a comment-only or blank
|
|
970
|
+
+ // command stays the no-op it always was instead of a syntax error that ends
|
|
971
|
+
+ // the shell (`$?` is untouched: `:` runs before the command, never after).
|
|
972
|
+
+ // The closing brace sits on its own line, after a blank one, so neither a
|
|
973
|
+
+ // trailing `# comment` nor a trailing `\` line continuation can swallow it.
|
|
974
|
+
try {
|
|
975
|
+
- stdin.write(`${command}\necho "${this._sentinel}"\n`);
|
|
976
|
+
+ stdin.write(`{\n:\n${command}\n\n} </dev/null\n__darwin_exit_code=$?\ncommand printf '${this._exitCodeSentinel}%s\\n' "$__darwin_exit_code"\ncommand printf '${this._cwdSentinel}%s\\0\\n' "$(command pwd -P)"\necho "${this._sentinel}"\necho "${this._stderrSentinel}" >&2\n`);
|
|
977
|
+
}
|
|
978
|
+
catch (err) {
|
|
979
|
+
cleanup();
|
|
980
|
+
this.stop();
|
|
981
|
+
reject(new BashSessionError(`Failed to write command: ${err.message}`));
|
|
982
|
+
+ return;
|
|
983
|
+
}
|
|
984
|
+
+ // The abort listener joins only once the command is really running, so
|
|
985
|
+
+ // cleanup() (which removes it) is the single owner of every per-call hook.
|
|
986
|
+
+ cancelSignal?.addEventListener('abort', onAbort, { once: true });
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
@@ -151,6 +416,16 @@ class BashSession {
|
|
991
|
+
*/
|
|
992
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
993
|
+
const sessions = new WeakMap();
|
|
994
|
+
+/**
|
|
995
|
+
+ * Serialize all foreground operations for one Agent, including explicit restart.
|
|
996
|
+
+ */
|
|
997
|
+
+const foregroundTails = new WeakMap();
|
|
998
|
+
+function enqueueForeground(agent, operation) {
|
|
999
|
+
+ const previous = foregroundTails.get(agent) ?? Promise.resolve();
|
|
1000
|
+
+ const result = previous.then(operation, operation);
|
|
1001
|
+
+ foregroundTails.set(agent, result.then(() => undefined, () => undefined));
|
|
1002
|
+
+ return result;
|
|
1003
|
+
+}
|
|
1004
|
+
/**
|
|
1005
|
+
* Track all active sessions for cleanup on process exit.
|
|
1006
|
+
*/
|
|
1007
|
+
@@ -221,42 +496,50 @@ const DEFAULT_DESCRIPTION = 'Executes bash shell commands in a persistent sessio
|
|
1008
|
+
* State (variables, working directory) persists within the session.
|
|
1009
|
+
* Node.js only.
|
|
1010
|
+
*/
|
|
1011
|
+
-export const bash = tool({
|
|
1012
|
+
- name: 'bash',
|
|
1013
|
+
- description: DEFAULT_DESCRIPTION,
|
|
1014
|
+
- inputSchema: bashInputSchema,
|
|
1015
|
+
- callback: async (input, context) => {
|
|
1016
|
+
- if (!context) {
|
|
1017
|
+
- throw new Error('Tool context is required for bash operations');
|
|
1018
|
+
- }
|
|
1019
|
+
- const agent = context.agent;
|
|
1020
|
+
- // Validate execute mode has command
|
|
1021
|
+
- if (input.mode === 'execute' && !input.command) {
|
|
1022
|
+
- throw new Error('command is required when mode is "execute"');
|
|
1023
|
+
- }
|
|
1024
|
+
- // Handle restart mode
|
|
1025
|
+
- if (input.mode === 'restart') {
|
|
1026
|
+
- const existingSession = sessions.get(agent);
|
|
1027
|
+
- if (existingSession) {
|
|
1028
|
+
- existingSession.stop();
|
|
1029
|
+
- sessions.delete(agent);
|
|
1030
|
+
+export function createBash(options = {}) {
|
|
1031
|
+
+ const initialCwd = path.resolve(options.cwd ?? process.cwd());
|
|
1032
|
+
+ const projectRoot = options.projectRoot === undefined ? null : path.resolve(options.projectRoot);
|
|
1033
|
+
+ const reportRestartCwd = options.cwd !== undefined || options.projectRoot !== undefined;
|
|
1034
|
+
+ return tool({
|
|
1035
|
+
+ name: 'bash',
|
|
1036
|
+
+ description: DEFAULT_DESCRIPTION,
|
|
1037
|
+
+ inputSchema: bashInputSchema,
|
|
1038
|
+
+ callback: async (input, context) => {
|
|
1039
|
+
+ if (!context) {
|
|
1040
|
+
+ throw new Error('Tool context is required for bash operations');
|
|
1041
|
+
}
|
|
1042
|
+
- // Create new session (will be added to activeSessions when started)
|
|
1043
|
+
- const newSession = new BashSession(120);
|
|
1044
|
+
- sessions.set(agent, newSession);
|
|
1045
|
+
- sessionFinalizer.register(agent, newSession);
|
|
1046
|
+
- return 'Bash session restarted';
|
|
1047
|
+
- }
|
|
1048
|
+
- // Handle execute mode
|
|
1049
|
+
- // Get or create session
|
|
1050
|
+
- let session = sessions.get(agent);
|
|
1051
|
+
- if (!session) {
|
|
1052
|
+
- session = new BashSession(input.timeout ?? 120);
|
|
1053
|
+
- sessions.set(agent, session);
|
|
1054
|
+
- sessionFinalizer.register(agent, session);
|
|
1055
|
+
- }
|
|
1056
|
+
- // Execute command
|
|
1057
|
+
- return session.run(input.command, input.timeout);
|
|
1058
|
+
- },
|
|
1059
|
+
-});
|
|
1060
|
+
+ const agent = context.agent;
|
|
1061
|
+
+ // Validate execute mode has command
|
|
1062
|
+
+ if (input.mode === 'execute' && !input.command) {
|
|
1063
|
+
+ throw new Error('command is required when mode is "execute"');
|
|
1064
|
+
+ }
|
|
1065
|
+
+ return enqueueForeground(agent, async () => {
|
|
1066
|
+
+ // Handle restart mode
|
|
1067
|
+
+ if (input.mode === 'restart') {
|
|
1068
|
+
+ const existingSession = sessions.get(agent);
|
|
1069
|
+
+ if (existingSession) {
|
|
1070
|
+
+ existingSession.stop();
|
|
1071
|
+
+ sessions.delete(agent);
|
|
1072
|
+
+ }
|
|
1073
|
+
+ // Create new session (will be added to activeSessions when started)
|
|
1074
|
+
+ const newSession = new BashSession(120, initialCwd, projectRoot);
|
|
1075
|
+
+ sessions.set(agent, newSession);
|
|
1076
|
+
+ sessionFinalizer.register(agent, newSession);
|
|
1077
|
+
+ return reportRestartCwd ? `Bash session restarted\ncwd: ${initialCwd}` : 'Bash session restarted';
|
|
1078
|
+
+ }
|
|
1079
|
+
+ // Handle execute mode
|
|
1080
|
+
+ // Get or create session
|
|
1081
|
+
+ let session = sessions.get(agent);
|
|
1082
|
+
+ if (!session) {
|
|
1083
|
+
+ session = new BashSession(input.timeout ?? 120, initialCwd, projectRoot);
|
|
1084
|
+
+ sessions.set(agent, session);
|
|
1085
|
+
+ sessionFinalizer.register(agent, session);
|
|
1086
|
+
+ }
|
|
1087
|
+
+ // Execute command; the call's cancelSignal lets an abort reach the running child.
|
|
1088
|
+
+ return session.run(input.command, input.timeout, context.cancelSignal);
|
|
1089
|
+
+ });
|
|
1090
|
+
+ },
|
|
1091
|
+
+ });
|
|
1092
|
+
+}
|
|
1093
|
+
+export const bash = createBash();
|
|
1094
|
+
//# sourceMappingURL=bash.js.map
|
|
1095
|
+
|
|
1096
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.d.ts b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.d.ts
|
|
1097
|
+
index 9dec5cf05c98402657b1637e745532b9a4e13c03..55d91ba45478088cde57bb27e1d3048d919c7228 100644
|
|
1098
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.d.ts
|
|
1099
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.d.ts
|
|
1100
|
+
@@ -6,7 +6,7 @@
|
|
1101
|
+
* names are re-exported here so pre-rename imports through this path keep
|
|
1102
|
+
* working until v2.0.0.
|
|
1103
|
+
*/
|
|
1104
|
+
-export { bash } from './bash.js';
|
|
1105
|
+
+export { bash, createBash } from './bash.js';
|
|
1106
|
+
export { BashTimeoutError, BashSessionError } from './types.js';
|
|
1107
|
+
export type { BashInput, BashOutput, ExecuteInput, RestartInput } from './types.js';
|
|
1108
|
+
export { makeShell, makeBash } from '../shell/make-shell.js';
|
|
1109
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.js b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.js
|
|
1110
|
+
index c6bdcac15ef1c7c99cb6cee08e8422548c1d5b95..35527ffe4386aaac0d982f145945737dcb4419e1 100644
|
|
1111
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.js
|
|
1112
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/index.js
|
|
1113
|
+
@@ -7,7 +7,7 @@
|
|
1114
|
+
* working until v2.0.0.
|
|
1115
|
+
*/
|
|
1116
|
+
import { SANDBOX_SHELL_DESCRIPTION } from '../shell/types.js';
|
|
1117
|
+
-export { bash } from './bash.js';
|
|
1118
|
+
+export { bash, createBash } from './bash.js';
|
|
1119
|
+
export { BashTimeoutError, BashSessionError } from './types.js';
|
|
1120
|
+
export { makeShell, makeBash } from '../shell/make-shell.js';
|
|
1121
|
+
export { SANDBOX_SHELL_DESCRIPTION, ShellTimeoutError, ShellExecutionError } from '../shell/types.js';
|
|
1122
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/types.d.ts b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/types.d.ts
|
|
1123
|
+
index 1be553288395c19e1251d86ef7c4d798c1917ace..6eeccf95f2a8666b0c8daaefaeac6ce5698e282b 100644
|
|
1124
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/types.d.ts
|
|
1125
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-tools/bash/types.d.ts
|
|
1126
|
+
@@ -48,21 +48,45 @@ export interface BashOutput {
|
|
1127
|
+
* Empty string if no errors occurred.
|
|
1128
|
+
*/
|
|
1129
|
+
error: string;
|
|
1130
|
+
+ /**
|
|
1131
|
+
+ * Effective persistent-shell cwd after the command.
|
|
1132
|
+
+ */
|
|
1133
|
+
+ cwd: string;
|
|
1134
|
+
+ /** Exit status of the foreground command, before Darwin's shell sentinels. */
|
|
1135
|
+
+ exitCode: number;
|
|
1136
|
+
/**
|
|
1137
|
+
* Allow indexing with string keys for JSONValue compatibility.
|
|
1138
|
+
*/
|
|
1139
|
+
- [key: string]: string;
|
|
1140
|
+
+ [key: string]: string | number;
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Error thrown when a bash command exceeds its timeout.
|
|
1144
|
+
*/
|
|
1145
|
+
export declare class BashTimeoutError extends Error {
|
|
1146
|
+
+ /** Bounded tails of what the command printed before the timeout killed it. */
|
|
1147
|
+
+ output?: string;
|
|
1148
|
+
+ error?: string;
|
|
1149
|
+
+ /** Cwd the replacement persistent shell starts in. */
|
|
1150
|
+
+ cwd?: string;
|
|
1151
|
+
+ /** Effective timeout in seconds. */
|
|
1152
|
+
+ timeoutSeconds?: number;
|
|
1153
|
+
constructor(message: string);
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Error thrown when a bash session encounters an error.
|
|
1157
|
+
*/
|
|
1158
|
+
export declare class BashSessionError extends Error {
|
|
1159
|
+
+ /** Exit metadata is present when a running persistent shell closes. */
|
|
1160
|
+
+ exitCode?: number | null;
|
|
1161
|
+
+ signal?: NodeJS.Signals | null;
|
|
1162
|
+
+ output?: string;
|
|
1163
|
+
+ error?: string;
|
|
1164
|
+
+ cwd?: string;
|
|
1165
|
+
+ /**
|
|
1166
|
+
+ * True when the call's `ToolContext.cancelSignal` aborted it: the shell's
|
|
1167
|
+
+ * process group was killed (or, if already aborted, nothing was started).
|
|
1168
|
+
+ */
|
|
1169
|
+
+ cancelled?: boolean;
|
|
1170
|
+
constructor(message: string);
|
|
1171
|
+
}
|
|
1172
|
+
//# sourceMappingURL=types.d.ts.map
|
|
1173
|
+
|
|
1174
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/file-editor.js b/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/file-editor.js
|
|
1175
|
+
index c8f38b7acac37a781e1467a655e88834aa97b4ef..06cc4454899669805633df0ff0228b26b04532df 100644
|
|
1176
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/file-editor.js
|
|
1177
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/file-editor.js
|
|
1178
|
+
@@ -7,6 +7,11 @@ import * as path from 'path';
|
|
1179
|
+
const SNIPPET_LINES = 4;
|
|
1180
|
+
const DEFAULT_MAX_FILE_SIZE = 1048576; // 1MB
|
|
1181
|
+
const MAX_DIRECTORY_DEPTH = 2;
|
|
1182
|
+
+const MISS_CONTEXT_LINES = 2;
|
|
1183
|
+
+const MISS_CONTEXT_LINE_CODE_POINTS = 240;
|
|
1184
|
+
+const MISS_QUERY_CODE_POINTS = 8192;
|
|
1185
|
+
+const MISS_MAX_SEEDS = 64;
|
|
1186
|
+
+const MISS_MAX_SEED_OCCURRENCES = 16;
|
|
1187
|
+
/**
|
|
1188
|
+
* Zod schema for file editor input validation.
|
|
1189
|
+
*/
|
|
1190
|
+
@@ -26,6 +31,10 @@ const fileEditorInputSchema = z.object({
|
|
1191
|
+
.number()
|
|
1192
|
+
.optional()
|
|
1193
|
+
.describe('Line number where text should be inserted (0-indexed, required for insert command).'),
|
|
1194
|
+
+ replace_all: z
|
|
1195
|
+
+ .boolean()
|
|
1196
|
+
+ .optional()
|
|
1197
|
+
+ .describe('For str_replace only: replace every non-overlapping occurrence of old_str in one write instead of requiring it to be unique (default false). Other commands ignore it.'),
|
|
1198
|
+
});
|
|
1199
|
+
/**
|
|
1200
|
+
* File editor tool for viewing, creating, and editing files programmatically.
|
|
1201
|
+
@@ -67,7 +76,7 @@ export function makeFileEditor(sandboxOrOptions, maybeOptions) {
|
|
1202
|
+
case 'create':
|
|
1203
|
+
return handleCreate(sandbox, filePath, input.file_text);
|
|
1204
|
+
case 'str_replace':
|
|
1205
|
+
- return handleStrReplace(sandbox, filePath, input.old_str, input.new_str);
|
|
1206
|
+
+ return handleStrReplace(sandbox, filePath, input.old_str, input.new_str, input.replace_all === true);
|
|
1207
|
+
case 'insert':
|
|
1208
|
+
return handleInsert(sandbox, filePath, input.insert_line, input.new_str);
|
|
1209
|
+
default:
|
|
1210
|
+
@@ -110,35 +119,178 @@ function applyViewRange(fileContent, viewRange) {
|
|
1211
|
+
if (start < 1 || start > nLines) {
|
|
1212
|
+
throw new Error(`Invalid \`view_range\`: [${start}, ${end}]. Its first element \`${start}\` should be within the range of lines of the file: [1, ${nLines}]`);
|
|
1213
|
+
}
|
|
1214
|
+
- if (end !== -1 && end > nLines) {
|
|
1215
|
+
+ const shouldClampEnd = fileContent.length > 0 && end > nLines;
|
|
1216
|
+
+ const effectiveEnd = shouldClampEnd ? nLines : end;
|
|
1217
|
+
+ if (end !== -1 && end > nLines && !shouldClampEnd) {
|
|
1218
|
+
throw new Error(`Invalid \`view_range\`: [${start}, ${end}]. Its second element \`${end}\` should be smaller than the number of lines in the file: \`${nLines}\``);
|
|
1219
|
+
}
|
|
1220
|
+
- if (end !== -1 && end < start) {
|
|
1221
|
+
+ if (end !== -1 && effectiveEnd < start) {
|
|
1222
|
+
throw new Error(`Invalid \`view_range\`: [${start}, ${end}]. Its second element \`${end}\` should be larger or equal than its first \`${start}\``);
|
|
1223
|
+
}
|
|
1224
|
+
- const content = end === -1 ? lines.slice(start - 1).join('\n') : lines.slice(start - 1, end).join('\n');
|
|
1225
|
+
+ const content = end === -1 ? lines.slice(start - 1).join('\n') : lines.slice(start - 1, effectiveEnd).join('\n');
|
|
1226
|
+
return { content, initLine: start };
|
|
1227
|
+
}
|
|
1228
|
+
+function formatOldStrForError(oldStr) {
|
|
1229
|
+
+ const limit = 240;
|
|
1230
|
+
+ if (oldStr.length <= limit * 2) {
|
|
1231
|
+
+ const codePoints = Array.from(oldStr);
|
|
1232
|
+
+ if (codePoints.length <= limit)
|
|
1233
|
+
+ return oldStr;
|
|
1234
|
+
+ return `${codePoints.slice(0, limit).join('')}… [old_str truncated]`;
|
|
1235
|
+
+ }
|
|
1236
|
+
+ return `${Array.from(oldStr.slice(0, limit * 2)).slice(0, limit).join('')}… [old_str truncated]`;
|
|
1237
|
+
+}
|
|
1238
|
+
+
|
|
1239
|
+
+function findMissContextOffset(fileContent, oldStr) {
|
|
1240
|
+
+ if (oldStr.length === 0) {
|
|
1241
|
+
+ return { reason: 'old_str is empty, so there is no safe useful close match to locate.' };
|
|
1242
|
+
+ }
|
|
1243
|
+
+ if (oldStr.length > MISS_QUERY_CODE_POINTS * 2) {
|
|
1244
|
+
+ return { reason: `old_str exceeds the advisory search cap of ${MISS_QUERY_CODE_POINTS} Unicode code points.` };
|
|
1245
|
+
+ }
|
|
1246
|
+
+ const query = Array.from(oldStr);
|
|
1247
|
+
+ if (query.length > MISS_QUERY_CODE_POINTS) {
|
|
1248
|
+
+ return { reason: `old_str exceeds the advisory search cap of ${MISS_QUERY_CODE_POINTS} Unicode code points.` };
|
|
1249
|
+
+ }
|
|
1250
|
+
+ const currentOffsets = new Int32Array(Array.from(fileContent).length + 1);
|
|
1251
|
+
+ let codePointIndex = 0;
|
|
1252
|
+
+ let utf16Index = 0;
|
|
1253
|
+
+ for (const codePoint of fileContent) {
|
|
1254
|
+
+ currentOffsets[codePointIndex] = utf16Index;
|
|
1255
|
+
+ codePointIndex += 1;
|
|
1256
|
+
+ utf16Index += codePoint.length;
|
|
1257
|
+
+ }
|
|
1258
|
+
+ currentOffsets[codePointIndex] = utf16Index;
|
|
1259
|
+
+ const seedWidth = Math.min(64, Math.max(8, Math.floor(query.length / 4)));
|
|
1260
|
+
+ if (query.length < seedWidth) {
|
|
1261
|
+
+ return { reason: 'No safe useful close textual match was found in the current file.' };
|
|
1262
|
+
+ }
|
|
1263
|
+
+ const seedCount = Math.min(MISS_MAX_SEEDS, Math.floor(query.length / seedWidth));
|
|
1264
|
+
+ const candidates = new Map();
|
|
1265
|
+
+ for (let seedIndex = 0; seedIndex < seedCount; seedIndex += 1) {
|
|
1266
|
+
+ const queryOffset = seedCount === 1
|
|
1267
|
+
+ ? 0
|
|
1268
|
+
+ : Math.floor(seedIndex * (query.length - seedWidth) / (seedCount - 1));
|
|
1269
|
+
+ const seed = query.slice(queryOffset, queryOffset + seedWidth).join('');
|
|
1270
|
+
+ if (seed.trim().length === 0)
|
|
1271
|
+
+ continue;
|
|
1272
|
+
+ let from = 0;
|
|
1273
|
+
+ for (let occurrence = 0; occurrence < MISS_MAX_SEED_OCCURRENCES; occurrence += 1) {
|
|
1274
|
+
+ const utf16Offset = fileContent.indexOf(seed, from);
|
|
1275
|
+
+ if (utf16Offset === -1)
|
|
1276
|
+
+ break;
|
|
1277
|
+
+ let low = 0;
|
|
1278
|
+
+ let high = codePointIndex;
|
|
1279
|
+
+ while (low < high) {
|
|
1280
|
+
+ const middle = Math.floor((low + high) / 2);
|
|
1281
|
+
+ if (currentOffsets[middle] < utf16Offset)
|
|
1282
|
+
+ low = middle + 1;
|
|
1283
|
+
+ else
|
|
1284
|
+
+ high = middle;
|
|
1285
|
+
+ }
|
|
1286
|
+
+ const currentOffset = low;
|
|
1287
|
+
+ const projectedStart = currentOffset - queryOffset;
|
|
1288
|
+
+ if (projectedStart >= 0 && projectedStart < codePointIndex) {
|
|
1289
|
+
+ const candidate = candidates.get(projectedStart) ?? { ranges: [], firstOffset: currentOffset };
|
|
1290
|
+
+ candidate.ranges.push([queryOffset, queryOffset + seedWidth]);
|
|
1291
|
+
+ candidate.firstOffset = Math.min(candidate.firstOffset, currentOffset);
|
|
1292
|
+
+ candidates.set(projectedStart, candidate);
|
|
1293
|
+
+ }
|
|
1294
|
+
+ from = utf16Offset + seed.length;
|
|
1295
|
+
+ }
|
|
1296
|
+
+ }
|
|
1297
|
+
+ let best;
|
|
1298
|
+
+ for (const [projectedStart, candidate] of candidates) {
|
|
1299
|
+
+ const ranges = candidate.ranges.sort((left, right) => left[0] - right[0]);
|
|
1300
|
+
+ let covered = 0;
|
|
1301
|
+
+ let rangeEnd = -1;
|
|
1302
|
+
+ for (const [start, end] of ranges) {
|
|
1303
|
+
+ if (end <= rangeEnd)
|
|
1304
|
+
+ continue;
|
|
1305
|
+
+ covered += end - Math.max(start, rangeEnd);
|
|
1306
|
+
+ rangeEnd = end;
|
|
1307
|
+
+ }
|
|
1308
|
+
+ const threshold = Math.max(12, Math.min(128, Math.ceil(query.length / 3)));
|
|
1309
|
+
+ if (covered < threshold)
|
|
1310
|
+
+ continue;
|
|
1311
|
+
+ const ranked = { projectedStart, offset: candidate.firstOffset, covered, seeds: ranges.length };
|
|
1312
|
+
+ if (!best
|
|
1313
|
+
+ || ranked.covered > best.covered
|
|
1314
|
+
+ || (ranked.covered === best.covered && ranked.seeds > best.seeds)
|
|
1315
|
+
+ || (ranked.covered === best.covered && ranked.seeds === best.seeds && ranked.offset < best.offset)) {
|
|
1316
|
+
+ best = ranked;
|
|
1317
|
+
+ }
|
|
1318
|
+
+ }
|
|
1319
|
+
+ return best ? { offset: best.offset } : { reason: 'No safe useful close textual match was found in the current file.' };
|
|
1320
|
+
+}
|
|
1321
|
+
+function formatMissContext(fileContent, oldStr) {
|
|
1322
|
+
+ const match = findMissContextOffset(fileContent, oldStr);
|
|
1323
|
+
+ const heading = 'Advisory context only; no fuzzy replacement was attempted.';
|
|
1324
|
+
+ if (match.offset === undefined) {
|
|
1325
|
+
+ return `${heading}\n${match.reason}`;
|
|
1326
|
+
+ }
|
|
1327
|
+
+ const beforeMatch = Array.from(fileContent).slice(0, match.offset).join('');
|
|
1328
|
+
+ const matchLine = beforeMatch.split('\n').length - 1;
|
|
1329
|
+
+ const lines = fileContent.split('\n');
|
|
1330
|
+
+ const startLine = Math.max(0, matchLine - MISS_CONTEXT_LINES);
|
|
1331
|
+
+ const endLine = Math.min(lines.length, matchLine + MISS_CONTEXT_LINES + 1);
|
|
1332
|
+
+ const numbered = lines.slice(startLine, endLine).map((line, index) => {
|
|
1333
|
+
+ const codePoints = Array.from(line);
|
|
1334
|
+
+ const shown = codePoints.length > MISS_CONTEXT_LINE_CODE_POINTS
|
|
1335
|
+
+ ? `${codePoints.slice(0, MISS_CONTEXT_LINE_CODE_POINTS).join('')}… [line truncated]`
|
|
1336
|
+
+ : line;
|
|
1337
|
+
+ return `${String(startLine + index + 1).padStart(6)} ${shown}`;
|
|
1338
|
+
+ });
|
|
1339
|
+
+ const omissions = [];
|
|
1340
|
+
+ if (startLine > 0)
|
|
1341
|
+
+ omissions.push(`${startLine} earlier line${startLine === 1 ? '' : 's'} omitted`);
|
|
1342
|
+
+ if (endLine < lines.length) {
|
|
1343
|
+
+ const later = lines.length - endLine;
|
|
1344
|
+
+ omissions.push(`${later} later line${later === 1 ? '' : 's'} omitted`);
|
|
1345
|
+
+ }
|
|
1346
|
+
+ const omissionNotice = omissions.length > 0 ? `\n[Excerpt truncated: ${omissions.join('; ')}.]` : '';
|
|
1347
|
+
+ return `${heading}\nClosest current context (lines ${startLine + 1}-${endLine}):\n${numbered.join('\n')}${omissionNotice}`;
|
|
1348
|
+
+}
|
|
1349
|
+
+
|
|
1350
|
+
/**
|
|
1351
|
+
- * Performs a unique str_replace transformation on file content. Validates that
|
|
1352
|
+
- * `oldStr` appears exactly once. Returns the new content plus a snippet around
|
|
1353
|
+
- * the change site (with 0-indexed `startLine`).
|
|
1354
|
+
+ * Performs a str_replace transformation on file content. Without `replaceAll`,
|
|
1355
|
+
+ * validates that `oldStr` appears exactly once; with it, every non-overlapping
|
|
1356
|
+
+ * occurrence is replaced in one pass. Returns the new content plus a snippet
|
|
1357
|
+
+ * around the (first) change site (with 0-indexed `startLine`), and the 1-based
|
|
1358
|
+
+ * line numbers of the replaced occurrences as counted before the edit.
|
|
1359
|
+
*/
|
|
1360
|
+
-function buildStrReplaceResult(originalContent, oldStr, newStr, filePath) {
|
|
1361
|
+
+function buildStrReplaceResult(originalContent, oldStr, newStr, filePath, replaceAll = false) {
|
|
1362
|
+
if (oldStr.length === 0) {
|
|
1363
|
+
throw new Error(`No replacement was performed, old_str must not be empty.`);
|
|
1364
|
+
}
|
|
1365
|
+
const replacement = newStr ?? '';
|
|
1366
|
+
const occurrences = findOccurrences(originalContent, oldStr);
|
|
1367
|
+
if (occurrences.length === 0) {
|
|
1368
|
+
- throw new Error(`No replacement was performed, old_str \`${oldStr}\` did not appear verbatim in ${filePath}.`);
|
|
1369
|
+
+ const advisory = formatMissContext(originalContent, oldStr);
|
|
1370
|
+
+ const displayedOldStr = formatOldStrForError(oldStr);
|
|
1371
|
+
+ throw new Error(`No replacement was performed, old_str \`${displayedOldStr}\` did not appear verbatim in ${filePath}.\n\n${advisory}`);
|
|
1372
|
+
}
|
|
1373
|
+
- if (occurrences.length > 1) {
|
|
1374
|
+
+ if (!replaceAll && occurrences.length > 1) {
|
|
1375
|
+
const lineNumbers = occurrences.map((occurrence) => occurrence.line);
|
|
1376
|
+
throw new Error(`No replacement was performed. Multiple occurrences of old_str \`${oldStr}\` in lines ${JSON.stringify(lineNumbers)}. Please ensure it is unique`);
|
|
1377
|
+
}
|
|
1378
|
+
const matchIndex = occurrences[0].offset;
|
|
1379
|
+
- const newContent = originalContent.slice(0, matchIndex) + replacement + originalContent.slice(matchIndex + oldStr.length);
|
|
1380
|
+
+ let newContent;
|
|
1381
|
+
+ if (replaceAll) {
|
|
1382
|
+
+ // Occurrences are ascending and non-overlapping, so the pieces between them
|
|
1383
|
+
+ // are copied once each and the first replacement lands at `matchIndex`.
|
|
1384
|
+
+ const pieces = [];
|
|
1385
|
+
+ let cursor = 0;
|
|
1386
|
+
+ for (const occurrence of occurrences) {
|
|
1387
|
+
+ pieces.push(originalContent.slice(cursor, occurrence.offset), replacement);
|
|
1388
|
+
+ cursor = occurrence.offset + oldStr.length;
|
|
1389
|
+
+ }
|
|
1390
|
+
+ pieces.push(originalContent.slice(cursor));
|
|
1391
|
+
+ newContent = pieces.join('');
|
|
1392
|
+
+ }
|
|
1393
|
+
+ else {
|
|
1394
|
+
+ newContent = originalContent.slice(0, matchIndex) + replacement + originalContent.slice(matchIndex + oldStr.length);
|
|
1395
|
+
+ }
|
|
1396
|
+
const replacementLine = originalContent.substring(0, matchIndex).split('\n').length - 1;
|
|
1397
|
+
const insertedLines = replacement.split('\n').length;
|
|
1398
|
+
const originalLines = oldStr.split('\n').length;
|
|
1399
|
+
@@ -147,7 +299,7 @@ function buildStrReplaceResult(originalContent, oldStr, newStr, filePath) {
|
|
1400
|
+
const startLine = Math.max(0, replacementLine - SNIPPET_LINES);
|
|
1401
|
+
const endLine = Math.min(newLines.length, replacementLine + SNIPPET_LINES + lineDifference + 1);
|
|
1402
|
+
const snippet = newLines.slice(startLine, endLine).join('\n');
|
|
1403
|
+
- return { newContent, snippet, startLine };
|
|
1404
|
+
+ return { newContent, snippet, startLine, replacedLines: occurrences.map((occurrence) => occurrence.line) };
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Inserts text at a 0-indexed line in file content. Validates the insertion
|
|
1408
|
+
@@ -289,7 +441,7 @@ async function handleCreate(sandbox, filePath, fileText) {
|
|
1409
|
+
await sandbox.writeText(filePath, fileText);
|
|
1410
|
+
return `File created successfully at: ${filePath}`;
|
|
1411
|
+
}
|
|
1412
|
+
-async function handleStrReplace(sandbox, filePath, oldStr, newStr) {
|
|
1413
|
+
+async function handleStrReplace(sandbox, filePath, oldStr, newStr, replaceAll = false) {
|
|
1414
|
+
if (oldStr === undefined) {
|
|
1415
|
+
throw new Error('Parameter `old_str` is required for command: str_replace');
|
|
1416
|
+
}
|
|
1417
|
+
@@ -303,8 +455,12 @@ async function handleStrReplace(sandbox, filePath, oldStr, newStr) {
|
|
1418
|
+
}
|
|
1419
|
+
const fileContent = await sandbox.readText(filePath);
|
|
1420
|
+
assertWithinSizeLimit(fileContent);
|
|
1421
|
+
- const { newContent, snippet, startLine } = buildStrReplaceResult(fileContent, oldStr, newStr, filePath);
|
|
1422
|
+
+ const { newContent, snippet, startLine, replacedLines } = buildStrReplaceResult(fileContent, oldStr, newStr, filePath, replaceAll);
|
|
1423
|
+
await sandbox.writeText(filePath, newContent);
|
|
1424
|
+
+ if (replaceAll) {
|
|
1425
|
+
+ const count = replacedLines.length;
|
|
1426
|
+
+ return `The file ${filePath} has been edited: replace_all replaced ${count} occurrence${count === 1 ? '' : 's'} of old_str at line${count === 1 ? '' : 's'} ${JSON.stringify(replacedLines)} (line numbers before the edit). ${makeOutput(snippet, `a snippet of ${filePath} around the first replacement`, startLine + 1)}Review the changes and make sure they are as expected. Edit the file again if necessary.`;
|
|
1427
|
+
+ }
|
|
1428
|
+
return `The file ${filePath} has been edited. ${makeOutput(snippet, `a snippet of ${filePath}`, startLine + 1)}Review the changes and make sure they are as expected. Edit the file again if necessary.`;
|
|
1429
|
+
}
|
|
1430
|
+
async function handleInsert(sandbox, filePath, insertLine, newStr) {
|
|
1431
|
+
diff --git a/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/types.d.ts b/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/types.d.ts
|
|
1432
|
+
index a673d4adbfc1bb9792ab744b67f4010325c66eb8..a63cfc42445cbff56ce8da62b9fee22e42ca275f 100644
|
|
1433
|
+
--- a/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/types.d.ts
|
|
1434
|
+
+++ b/node_modules/@strands-agents/sdk/dist/src/vended-tools/file-editor/types.d.ts
|
|
1435
|
+
@@ -31,6 +31,8 @@ export interface StrReplaceInput {
|
|
1436
|
+
path: string;
|
|
1437
|
+
old_str: string;
|
|
1438
|
+
new_str?: string;
|
|
1439
|
+
+ /** Replace every non-overlapping occurrence of `old_str` instead of requiring it to be unique (default false). */
|
|
1440
|
+
+ replace_all?: boolean;
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* Input parameters for insert operation.
|