@punch-bot/cli 1.5.1 → 1.5.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/CHANGELOG.md +162 -1
- package/README.md +6 -8
- package/dist/bundle/chunks/anthropic-messages-WIBS5YKY.js +6 -0
- package/dist/bundle/chunks/azure-openai-responses-GP5GDEGO.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +7 -4
- package/dist/bundle/chunks/chunk-35EHANXE.js +2 -0
- package/dist/bundle/chunks/chunk-3IMHRFLG.js +6 -0
- package/dist/bundle/chunks/chunk-77CRE5SV.js +9 -0
- package/dist/bundle/chunks/chunk-CE33JMCE.js +861 -0
- package/dist/bundle/chunks/{chunk-MYNHUMKE.js → chunk-CXY7BILM.js} +2 -44
- package/dist/bundle/chunks/chunk-EISXNXOQ.js +41 -0
- package/dist/bundle/chunks/chunk-ENMVUQHE.js +26 -0
- package/dist/bundle/chunks/chunk-FFMDRXC4.js +10 -0
- package/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
- package/dist/bundle/chunks/chunk-HQH636GU.js +361 -0
- package/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
- package/dist/bundle/chunks/chunk-JAJLG57O.js +4 -0
- package/dist/bundle/chunks/{chunk-RROECCMX.js → chunk-LOHGXPCL.js} +2 -2
- package/dist/bundle/chunks/{chunk-CRILLKNU.js → chunk-OV2VGRRS.js} +1 -1
- package/dist/bundle/chunks/chunk-P7FPUEYA.js +2 -0
- package/dist/bundle/chunks/chunk-PDENR63J.js +16 -0
- package/dist/bundle/chunks/chunk-RHOWRSGK.js +2 -0
- package/dist/bundle/chunks/{chunk-HMPP4ECW.js → chunk-UZ3LUZDC.js} +1 -1
- package/dist/bundle/chunks/chunk-WN2D4UD4.js +2 -0
- package/dist/bundle/chunks/chunk-X4T5TGM4.js +82 -0
- package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
- package/dist/bundle/chunks/cli-OQNR6ESL.js +53 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-JWAAZATQ.js → cloudflare-workers-ai-system-one-36EDUVVN.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +2 -0
- package/dist/bundle/chunks/{execute-HXULRBCI.js → execute-EHT55MW7.js} +5 -3
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-EHUU7JII.js → google-generative-ai-KA6FZCHM.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-AFMVUS5C.js → google-vertex-DXKQ4IYR.js} +1 -1
- package/dist/bundle/chunks/image-resize-worker.js +1 -1
- package/dist/bundle/chunks/kimi-coding.js +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-YVA2UOJG.js → llama-cpp-classify-676UCBOD.js} +1 -1
- package/dist/bundle/chunks/meta.js +1 -1
- package/dist/bundle/chunks/mistral-conversations-PJ56UMXO.js +5 -0
- package/dist/bundle/chunks/openai-codex-responses-DWVG7MAQ.js +10 -0
- package/dist/bundle/chunks/openai-completions-OKI6KBNP.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-GNOLFL74.js → openai-decisions-SO57QA6O.js} +1 -1
- package/dist/bundle/chunks/openai-responses-3HV234HB.js +4 -0
- package/dist/bundle/chunks/{openrouter-images-ZTNVFSL2.js → openrouter-images-5X6D7HFS.js} +1 -1
- package/dist/bundle/chunks/pi-messages-BS5Z34RE.js +8 -0
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/{runtime-R5GXO4CV.js → runtime-74PFKASL.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-I5AHLF6T.js → typesafe-system-one-IPNULX2M.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-2Y422I6U.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts +0 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +8 -12
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js +26 -2
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/auth-login.d.ts +15 -0
- package/dist/cli/auth-login.d.ts.map +1 -0
- package/dist/cli/auth-login.js +232 -0
- package/dist/cli/auth-login.js.map +1 -0
- package/dist/cli/auth-logout.d.ts +14 -0
- package/dist/cli/auth-logout.d.ts.map +1 -0
- package/dist/cli/auth-logout.js +63 -0
- package/dist/cli/auth-logout.js.map +1 -0
- package/dist/cli/auth-terminal.d.ts +17 -0
- package/dist/cli/auth-terminal.d.ts.map +1 -0
- package/dist/cli/auth-terminal.js +63 -0
- package/dist/cli/auth-terminal.js.map +1 -0
- package/dist/cli/project-trust.js +1 -1
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/config.d.ts +10 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +24 -11
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +5 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +20 -5
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +31 -15
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +158 -71
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +3 -2
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +3 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/cache-warmer.d.ts +4 -37
- package/dist/core/cache-warmer.d.ts.map +1 -1
- package/dist/core/cache-warmer.js +11 -89
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +4 -2
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +16 -4
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +2 -1
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/exec.d.ts +9 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +104 -60
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.js +165 -45
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +10 -13
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
- package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
- package/dist/core/extensions/pi-ai-extension-view.js +22 -0
- package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
- package/dist/core/extensions/runner.d.ts +1 -4
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +0 -14
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +5 -18
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/virtual-modules.js +8 -7
- package/dist/core/extensions/virtual-modules.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +23 -41
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +51 -120
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +1730 -2029
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +2 -3
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +36 -29
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +5 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +11 -4
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/package-manager.d.ts +24 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +210 -51
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +167 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -0
- package/dist/core/pi-ai-schemas.js +21 -0
- package/dist/core/pi-ai-schemas.js.map +1 -0
- package/dist/core/pi-manifest.d.ts +1 -0
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +4 -0
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/preferred-providers.d.ts +17 -0
- package/dist/core/preferred-providers.d.ts.map +1 -0
- package/dist/core/preferred-providers.js +24 -0
- package/dist/core/preferred-providers.js.map +1 -0
- package/dist/core/project-trust.d.ts +1 -1
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +18 -2
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +3 -1
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/provider-matching.d.ts +11 -0
- package/dist/core/provider-matching.d.ts.map +1 -0
- package/dist/core/provider-matching.js +14 -0
- package/dist/core/provider-matching.js.map +1 -0
- package/dist/core/radius-mcp.d.ts +13 -0
- package/dist/core/radius-mcp.d.ts.map +1 -0
- package/dist/core/radius-mcp.js +29 -0
- package/dist/core/radius-mcp.js.map +1 -0
- package/dist/core/radius.d.ts +0 -3
- package/dist/core/radius.d.ts.map +1 -1
- package/dist/core/radius.js +0 -5
- package/dist/core/radius.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +2 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts +4 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +40 -25
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts +8 -0
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js +15 -1
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-cwd.d.ts +0 -1
- package/dist/core/session-cwd.d.ts.map +1 -1
- package/dist/core/session-cwd.js +0 -3
- package/dist/core/session-cwd.js.map +1 -1
- package/dist/core/session-manager.d.ts +7 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +32 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +1 -31
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +1 -31
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -56
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +11 -247
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +4 -54
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +7 -101
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -14
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts +0 -6
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -27
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +9 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +13 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -6
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/telemetry.js +1 -1
- package/dist/core/telemetry.js.map +1 -1
- package/dist/core/theme/theme.d.ts.map +1 -1
- package/dist/core/theme/theme.js +5 -1
- package/dist/core/theme/theme.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +35 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +23 -14
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +182 -41
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +3 -3
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +10 -11
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -2
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +82 -36
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +7 -5
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +87 -75
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts +2 -2
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +2 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/powershell.js +15 -2
- package/dist/core/tools/powershell.js.map +1 -1
- package/dist/core/tools/read.d.ts +10 -2
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +141 -25
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/truncate.d.ts +4 -14
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +23 -29
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts +2 -2
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +14 -8
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +2 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/codemode/execute.js +4 -4
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +2 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +59 -12
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/client.d.ts +2 -0
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +23 -2
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/index.d.ts.map +1 -1
- package/dist/extensions/llama/index.js +1 -1
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts +2 -0
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +83 -22
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +4 -7
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +5 -4
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +11 -49
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +56 -296
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/resources.d.ts +1 -1
- package/dist/extensions/mcp/resources.d.ts.map +1 -1
- package/dist/extensions/mcp/resources.js +4 -3
- package/dist/extensions/mcp/resources.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +4 -3
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +7 -5
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +2 -23
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +6 -58
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/punch/index.d.ts.map +1 -1
- package/dist/extensions/punch/index.js +1 -1
- package/dist/extensions/punch/index.js.map +1 -1
- package/dist/extensions/punch/todos.js +1 -1
- package/dist/extensions/punch/todos.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +278 -129
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +21 -6
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +122 -42
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +106 -14
- package/dist/main.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +19 -10
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +53 -23
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +94 -12
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -2
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/changelog.d.ts +2 -2
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/changelog.js +12 -9
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts.map +1 -1
- package/dist/utils/clipboard-command.js +4 -0
- package/dist/utils/clipboard-command.js.map +1 -1
- package/dist/utils/fuzzy.d.ts.map +1 -1
- package/dist/utils/fuzzy.js +59 -44
- package/dist/utils/fuzzy.js.map +1 -1
- package/dist/utils/git.d.ts +11 -1
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js +44 -0
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -3
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +3 -1
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/open-browser.d.ts.map +1 -1
- package/dist/utils/open-browser.js +4 -1
- package/dist/utils/open-browser.js.map +1 -1
- package/dist/utils/paths.d.ts +17 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +42 -1
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +14 -0
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/terminal-question.d.ts +8 -0
- package/dist/utils/terminal-question.d.ts.map +1 -0
- package/dist/utils/terminal-question.js +24 -0
- package/dist/utils/terminal-question.js.map +1 -0
- package/dist/utils/text.d.ts +2 -0
- package/dist/utils/text.d.ts.map +1 -1
- package/dist/utils/text.js +5 -0
- package/dist/utils/text.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +30 -35
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/web-url.d.ts +12 -0
- package/dist/utils/web-url.d.ts.map +1 -0
- package/dist/utils/web-url.js +20 -0
- package/dist/utils/web-url.js.map +1 -0
- package/docs/cli-integration.md +3 -5
- package/docs/cli.md +45 -26
- package/docs/compaction.md +9 -9
- package/docs/configuration.md +1 -2
- package/docs/containerization.md +16 -14
- package/docs/custom-provider.md +5 -3
- package/docs/docs.json +9 -9
- package/docs/environment-variables.md +5 -12
- package/docs/extensions.md +683 -757
- package/docs/how-pi-works.md +5 -5
- package/docs/index.md +5 -5
- package/docs/llama-cpp.md +41 -39
- package/docs/mcp.md +12 -10
- package/docs/message-types.md +1 -1
- package/docs/models-configuration.md +6 -1
- package/docs/models.md +18 -19
- package/docs/nvidia-rtx-llama-cpp.md +1 -1
- package/docs/packages.md +21 -1
- package/docs/prompt-templates.md +11 -9
- package/docs/providers.md +8 -8
- package/docs/quickstart.md +28 -52
- package/docs/rpc-commands.md +2 -2
- package/docs/rpc-extension-ui.md +5 -7
- package/docs/rpc.md +4 -2
- package/docs/sdk.md +1 -1
- package/docs/security.md +9 -5
- package/docs/session-format.md +7 -9
- package/docs/sessions.md +26 -26
- package/docs/settings.md +36 -67
- package/docs/shell-aliases.md +7 -7
- package/docs/skills.md +4 -4
- package/docs/slash-commands.md +50 -58
- package/docs/termux.md +8 -9
- package/docs/themes.md +21 -41
- package/docs/usage.md +59 -177
- package/docs/virtual-models.md +4 -4
- package/docs/windows.md +8 -10
- package/examples/extensions/README.md +3 -2
- package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +16 -26
- package/examples/extensions/gondolin/package.json +2 -2
- package/examples/extensions/reload-runtime.ts +17 -5
- package/examples/extensions/rpc-demo.ts +2 -2
- package/examples/extensions/subagent/README.md +14 -11
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/tsconfig.json +208 -0
- package/npm-shrinkwrap.json +32 -34
- package/package.json +12 -14
- package/schemas/models.schema.json +65 -36
- package/schemas/settings.schema.json +17 -243
- package/dist/bundle/chunks/anthropic-messages-WAYXCPZL.js +0 -6
- package/dist/bundle/chunks/azure-openai-responses-LUIPKPFC.js +0 -2
- package/dist/bundle/chunks/chunk-275CIYA5.js +0 -16
- package/dist/bundle/chunks/chunk-2W2ATKZM.js +0 -2
- package/dist/bundle/chunks/chunk-3V45WARH.js +0 -7
- package/dist/bundle/chunks/chunk-4LBJE4YM.js +0 -14
- package/dist/bundle/chunks/chunk-4NE64BTO.js +0 -82
- package/dist/bundle/chunks/chunk-7SFLP7ZK.js +0 -1197
- package/dist/bundle/chunks/chunk-BQU3RKDL.js +0 -2
- package/dist/bundle/chunks/chunk-NJK3U3WK.js +0 -8
- package/dist/bundle/chunks/chunk-NQWQE4BR.js +0 -11
- package/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -2
- package/dist/bundle/chunks/chunk-TRN3ET6M.js +0 -2
- package/dist/bundle/chunks/chunk-UE7JCDFW.js +0 -2
- package/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
- package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
- package/dist/bundle/chunks/cli-W5KJM7YB.js +0 -51
- package/dist/bundle/chunks/mistral-conversations-FEBYNTL2.js +0 -5
- package/dist/bundle/chunks/openai-codex-responses-MI7TTP3C.js +0 -10
- package/dist/bundle/chunks/openai-completions-BVORSTAM.js +0 -7
- package/dist/bundle/chunks/openai-responses-TLIV5OQA.js +0 -4
- package/dist/bundle/chunks/pi-messages-4MVQCGGY.js +0 -8
- package/dist/bundle/chunks/virtual-modules-QK7S56IZ.js +0 -2
- package/dist/core/bug-report-upload.d.ts +0 -12
- package/dist/core/bug-report-upload.d.ts.map +0 -1
- package/dist/core/bug-report-upload.js +0 -22
- package/dist/core/bug-report-upload.js.map +0 -1
- package/dist/core/bug-report.d.ts +0 -184
- package/dist/core/bug-report.d.ts.map +0 -1
- package/dist/core/bug-report.js +0 -292
- package/dist/core/bug-report.js.map +0 -1
- package/dist/core/crash-log.d.ts +0 -27
- package/dist/core/crash-log.d.ts.map +0 -1
- package/dist/core/crash-log.js +0 -140
- package/dist/core/crash-log.js.map +0 -1
- package/dist/core/footer-data-provider.d.ts +0 -64
- package/dist/core/footer-data-provider.d.ts.map +0 -1
- package/dist/core/footer-data-provider.js +0 -338
- package/dist/core/footer-data-provider.js.map +0 -1
- package/dist/utils/zip.d.ts +0 -7
- package/dist/utils/zip.d.ts.map +0 -1
- package/dist/utils/zip.js +0 -60
- package/dist/utils/zip.js.map +0 -1
- package/docs/images/interactive-mode.png +0 -0
- package/docs/images/tree-view.png +0 -0
- package/docs/keybindings.md +0 -194
- package/docs/terminal-setup.md +0 -17
- package/docs/tmux.md +0 -55
- package/docs/tui.md +0 -125
- package/examples/extensions/sandbox/index.ts +0 -321
- package/examples/extensions/sandbox/package-lock.json +0 -66
- package/examples/extensions/sandbox/package.json +0 -22
package/dist/core/tools/read.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { constants } from "fs";
|
|
2
|
-
import { access as fsAccess, readFile as fsReadFile } from "fs/promises";
|
|
2
|
+
import { access as fsAccess, open as fsOpen, readFile as fsReadFile } from "fs/promises";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
|
+
import { TextDecoder } from "util";
|
|
4
5
|
import { processImage } from "../../utils/image-process.js";
|
|
5
6
|
import { detectSupportedImageMimeTypeFromFile } from "../../utils/mime.js";
|
|
6
7
|
import { resolveReadPathAsync } from "./path-utils.js";
|
|
@@ -27,9 +28,26 @@ const readOutputSchema = Type.Union([
|
|
|
27
28
|
]);
|
|
28
29
|
const defaultReadOperations = {
|
|
29
30
|
readFile: (path) => fsReadFile(path),
|
|
31
|
+
createReadStream: readLocalFileChunks,
|
|
30
32
|
access: (path) => fsAccess(path, constants.R_OK),
|
|
31
33
|
detectImageMimeType: detectSupportedImageMimeTypeFromFile,
|
|
32
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Stream a local file the way fs.readFile reads it: a regular file up to its size when opened, so text
|
|
37
|
+
* appended during the read is not counted and a growing file still ends; a file reporting size 0 (such
|
|
38
|
+
* as /proc files) and other file types until EOF.
|
|
39
|
+
*/
|
|
40
|
+
async function* readLocalFileChunks(path, { signal }) {
|
|
41
|
+
const handle = await fsOpen(path, "r");
|
|
42
|
+
try {
|
|
43
|
+
const stats = await handle.stat();
|
|
44
|
+
const end = stats.isFile() && stats.size > 0 ? stats.size - 1 : undefined;
|
|
45
|
+
yield* handle.createReadStream({ end, signal, autoClose: false });
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
await handle.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
33
51
|
/** The image block and its note, or the text for text files and images that could not be processed. */
|
|
34
52
|
function toReadOutput(content) {
|
|
35
53
|
const text = content.find((block) => block.type === "text")?.text ?? "";
|
|
@@ -42,6 +60,115 @@ function getNonVisionImageNote(model) {
|
|
|
42
60
|
}
|
|
43
61
|
return "[Current model does not support images. The image will be omitted from this request.]";
|
|
44
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Whether a range can be streamed. Other values (fractional, negative limit) keep the whole-file path,
|
|
65
|
+
* whose array slicing defines what they select, for example limit -1 as all lines but the last.
|
|
66
|
+
*/
|
|
67
|
+
function isStreamableRange(offset, limit) {
|
|
68
|
+
return ((offset === undefined || Number.isInteger(offset)) &&
|
|
69
|
+
(limit === undefined || (Number.isInteger(limit) && limit >= 0)));
|
|
70
|
+
}
|
|
71
|
+
/** Select lines from a whole file in memory: for operations without createReadStream and unusual ranges. */
|
|
72
|
+
function selectLinesFromBuffer(buffer, startLine, limit) {
|
|
73
|
+
const allLines = buffer.toString("utf-8").split("\n");
|
|
74
|
+
const endLine = limit === undefined ? undefined : Math.min(startLine + limit, allLines.length);
|
|
75
|
+
const truncation = truncateHead(allLines.slice(startLine, endLine).join("\n"));
|
|
76
|
+
const firstLineBytes = truncation.firstLineExceedsLimit ? Buffer.byteLength(allLines[startLine], "utf-8") : 0;
|
|
77
|
+
return { totalFileLines: allLines.length, truncation, firstLineBytes };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Select lines from a file read in chunks. Only lines truncateHead can show are stored; the rest are
|
|
81
|
+
* counted, so memory does not grow with the file. Stops reading when the signal aborts.
|
|
82
|
+
*/
|
|
83
|
+
async function selectLinesFromStream(chunks, startLine, limit, signal) {
|
|
84
|
+
const endLine = limit === undefined ? Number.POSITIVE_INFINITY : startLine + limit;
|
|
85
|
+
// Non-fatal UTF-8 that keeps a byte order mark decodes like Buffer.toString("utf-8").
|
|
86
|
+
const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
87
|
+
const storedLines = [];
|
|
88
|
+
let storedBytes = 0;
|
|
89
|
+
let storedPastCaps = false;
|
|
90
|
+
let line = 0;
|
|
91
|
+
let selectedLines = 0;
|
|
92
|
+
let selectedBytes = 0;
|
|
93
|
+
let firstLineBytes = 0;
|
|
94
|
+
let lastLineEmpty = true;
|
|
95
|
+
// The selected line being read: its text, while it is stored, and its size.
|
|
96
|
+
let pieces = [];
|
|
97
|
+
let lineBytes = 0;
|
|
98
|
+
let lineHasText = false;
|
|
99
|
+
const appendToLine = (text, start, end) => {
|
|
100
|
+
lineHasText = true;
|
|
101
|
+
if (!pieces)
|
|
102
|
+
return;
|
|
103
|
+
const piece = text.slice(start, end);
|
|
104
|
+
// A line over the byte cap is never shown, and a first line over it is only measured: never store
|
|
105
|
+
// all of a 1 GB line.
|
|
106
|
+
if (lineBytes <= DEFAULT_MAX_BYTES)
|
|
107
|
+
pieces.push(piece);
|
|
108
|
+
lineBytes += Buffer.byteLength(piece, "utf-8");
|
|
109
|
+
};
|
|
110
|
+
const finishLine = () => {
|
|
111
|
+
if (pieces) {
|
|
112
|
+
if (selectedLines === 0)
|
|
113
|
+
firstLineBytes = lineBytes;
|
|
114
|
+
// Storing continues one line past the caps: truncateHead ignores a trailing empty line, so the
|
|
115
|
+
// line after the cap must be there for it to decide truncation as for the full text.
|
|
116
|
+
if (storedLines.length > DEFAULT_MAX_LINES || storedBytes > DEFAULT_MAX_BYTES)
|
|
117
|
+
storedPastCaps = true;
|
|
118
|
+
const text = pieces.join("");
|
|
119
|
+
storedBytes += Buffer.byteLength(text, "utf-8") + (storedLines.length > 0 ? 1 : 0);
|
|
120
|
+
storedLines.push(text);
|
|
121
|
+
}
|
|
122
|
+
selectedLines++;
|
|
123
|
+
lastLineEmpty = !lineHasText;
|
|
124
|
+
pieces = storedPastCaps ? undefined : [];
|
|
125
|
+
lineBytes = 0;
|
|
126
|
+
lineHasText = false;
|
|
127
|
+
};
|
|
128
|
+
const select = (text) => {
|
|
129
|
+
let position = 0;
|
|
130
|
+
// Start of the selected text in this piece, measured as a whole: the joined lines' size.
|
|
131
|
+
let selectionStart = -1;
|
|
132
|
+
while (true) {
|
|
133
|
+
const selected = line >= startLine && line < endLine;
|
|
134
|
+
if (selected && selectionStart === -1)
|
|
135
|
+
selectionStart = position;
|
|
136
|
+
const newline = text.indexOf("\n", position);
|
|
137
|
+
const end = newline === -1 ? text.length : newline;
|
|
138
|
+
if (selected && end > position)
|
|
139
|
+
appendToLine(text, position, end);
|
|
140
|
+
if (newline === -1)
|
|
141
|
+
break;
|
|
142
|
+
if (selected) {
|
|
143
|
+
finishLine();
|
|
144
|
+
if (line + 1 === endLine) {
|
|
145
|
+
selectedBytes += Buffer.byteLength(text.slice(selectionStart, newline), "utf-8");
|
|
146
|
+
selectionStart = -1;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
line++;
|
|
150
|
+
position = newline + 1;
|
|
151
|
+
}
|
|
152
|
+
if (selectionStart !== -1)
|
|
153
|
+
selectedBytes += Buffer.byteLength(text.slice(selectionStart), "utf-8");
|
|
154
|
+
};
|
|
155
|
+
for await (const chunk of chunks) {
|
|
156
|
+
// Leaving the loop closes the stream.
|
|
157
|
+
if (signal?.aborted)
|
|
158
|
+
throw new Error("Operation aborted");
|
|
159
|
+
select(decoder.decode(chunk, { stream: true }));
|
|
160
|
+
}
|
|
161
|
+
select(decoder.decode());
|
|
162
|
+
if (line >= startLine && line < endLine)
|
|
163
|
+
finishLine();
|
|
164
|
+
const truncation = {
|
|
165
|
+
...truncateHead(storedLines.join("\n")),
|
|
166
|
+
// truncateHead's counts for the joined selected lines, which drop a trailing empty line.
|
|
167
|
+
totalLines: selectedBytes === 0 ? 0 : selectedLines - (lastLineEmpty ? 1 : 0),
|
|
168
|
+
totalBytes: selectedBytes,
|
|
169
|
+
};
|
|
170
|
+
return { totalFileLines: line + 1, truncation, firstLineBytes };
|
|
171
|
+
}
|
|
45
172
|
export function createReadToolDefinition(cwd, options) {
|
|
46
173
|
const autoResizeImages = options?.autoResizeImages ?? true;
|
|
47
174
|
const fallbackResizeOptions = options?.resizeOptions;
|
|
@@ -106,35 +233,24 @@ export function createReadToolDefinition(cwd, options) {
|
|
|
106
233
|
}
|
|
107
234
|
}
|
|
108
235
|
else {
|
|
109
|
-
// Read text content.
|
|
110
|
-
const buffer = await ops.readFile(absolutePath);
|
|
111
|
-
const textContent = buffer.toString("utf-8");
|
|
112
|
-
const allLines = textContent.split("\n");
|
|
113
|
-
const totalFileLines = allLines.length;
|
|
114
|
-
// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.
|
|
236
|
+
// Read text content. Convert offset from 1-indexed input to 0-indexed line access.
|
|
115
237
|
const startLine = offset ? Math.max(0, offset - 1) : 0;
|
|
116
238
|
const startLineDisplay = startLine + 1;
|
|
239
|
+
const { totalFileLines, truncation, firstLineBytes } = ops.createReadStream && isStreamableRange(offset, limit)
|
|
240
|
+
? await selectLinesFromStream(ops.createReadStream(absolutePath, { signal }), startLine, limit, signal)
|
|
241
|
+
: selectLinesFromBuffer(await ops.readFile(absolutePath), startLine, limit);
|
|
242
|
+
if (aborted)
|
|
243
|
+
return;
|
|
117
244
|
// Check if offset is out of bounds.
|
|
118
|
-
if (startLine >=
|
|
119
|
-
throw new Error(`Offset ${offset} is beyond end of file (${
|
|
120
|
-
}
|
|
121
|
-
let selectedContent;
|
|
122
|
-
let userLimitedLines;
|
|
123
|
-
// If limit is specified by the user, honor it first. Otherwise truncateHead decides.
|
|
124
|
-
if (limit !== undefined) {
|
|
125
|
-
const endLine = Math.min(startLine + limit, allLines.length);
|
|
126
|
-
selectedContent = allLines.slice(startLine, endLine).join("\n");
|
|
127
|
-
userLimitedLines = endLine - startLine;
|
|
128
|
-
}
|
|
129
|
-
else {
|
|
130
|
-
selectedContent = allLines.slice(startLine).join("\n");
|
|
245
|
+
if (startLine >= totalFileLines) {
|
|
246
|
+
throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);
|
|
131
247
|
}
|
|
132
|
-
//
|
|
133
|
-
const
|
|
248
|
+
// A user-specified limit is honored before truncation.
|
|
249
|
+
const userLimitedLines = limit === undefined ? undefined : Math.min(startLine + limit, totalFileLines) - startLine;
|
|
134
250
|
let outputText;
|
|
135
251
|
if (truncation.firstLineExceedsLimit) {
|
|
136
252
|
// First line alone exceeds the byte limit. Point the model at a bash fallback.
|
|
137
|
-
const firstLineSize = formatSize(
|
|
253
|
+
const firstLineSize = formatSize(firstLineBytes);
|
|
138
254
|
outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;
|
|
139
255
|
details = { truncation };
|
|
140
256
|
}
|
|
@@ -151,9 +267,9 @@ export function createReadToolDefinition(cwd, options) {
|
|
|
151
267
|
}
|
|
152
268
|
details = { truncation };
|
|
153
269
|
}
|
|
154
|
-
else if (userLimitedLines !== undefined && startLine + userLimitedLines <
|
|
270
|
+
else if (userLimitedLines !== undefined && startLine + userLimitedLines < totalFileLines) {
|
|
155
271
|
// User-specified limit stopped early, but the file still has more content.
|
|
156
|
-
const remaining =
|
|
272
|
+
const remaining = totalFileLines - (startLine + userLimitedLines);
|
|
157
273
|
const nextOffset = startLine + userLimitedLines + 1;
|
|
158
274
|
outputText = `${truncation.content}\n\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;
|
|
159
275
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAE3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,UAAU,EAAyB,YAAY,EAAE,MAAM,eAAe,CAAC;AAEtH,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACrF,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+CAA+C,EAAE,CAAC,CAAC;IACpG,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iCAAiC,EAAE,CAAC,CAAC;CACrF,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,gCAAgC,GAAG;IAC/C,OAAO,EAAE,oBAAoB;IAC7B,UAAU,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C,CACD,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,iBAAiB,EAAE,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;QACtF,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import type { AgentTool } from \"@punch-bot/agent\";\nimport type { Api, ImageContent, Model, ModelImageResizeOptions, TextContent } from \"@punch-bot/ai\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { resolveReadPathAsync } from \"./path-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts: the text for text files, and an image\n * block for images that codemode's `image()` accepts. `note` is the text that goes with the image,\n * such as resize hints. Property descriptions are left out so the type stays on one line in tool\n * descriptions.\n */\nconst readOutputSchema = Type.Union([\n\tType.String(),\n\tType.Object({ type: Type.Literal(\"image\"), data: Type.String(), mimeType: Type.String(), note: Type.String() }),\n]);\n\nexport type ReadToolOutput = Static<typeof readOutputSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Fallback resize profile when the execution context has no model metadata. */\n\tresizeOptions?: ModelImageResizeOptions;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\n/** The image block and its note, or the text for text files and images that could not be processed. */\nfunction toReadOutput(content: (TextContent | ImageContent)[]): ReadToolOutput {\n\tconst text = content.find((block) => block.type === \"text\")?.text ?? \"\";\n\tconst image = content.find((block) => block.type === \"image\");\n\treturn image ? { type: \"image\", data: image.data, mimeType: image.mimeType, note: text } : text;\n}\n\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst fallbackResizeOptions = options?.resizeOptions;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\toutputSchema: readOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, {\n\t\t\t\t\t\t\t\t\tautoResizeImages,\n\t\t\t\t\t\t\t\t\tresizeOptions: ctx?.model?.inputLimits?.images?.resize ?? fallbackResizeOptions,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t).then((result) => ({ ...result, structuredContent: toReadOutput(result.content) }));\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACzF,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAE3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,UAAU,EAAyB,YAAY,EAAE,MAAM,eAAe,CAAC;AAEtH,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACrF,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+CAA+C,EAAE,CAAC,CAAC;IACpG,KAAK,EAAE,IA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C,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;wBAChD,CAAC;wBAED,IAAI,OAAO;4BAAE,OAAO;wBACpB,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;wBAC9C,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;oBAC/B,CAAC;oBAAC,OAAO,KAAU,EAAE,CAAC;wBACrB,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;wBAC9C,IAAI,CAAC,OAAO;4BAAE,MAAM,CAAC,KAAK,CAAC,CAAC;oBAC7B,CAAC;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,CAAC,CACD,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,iBAAiB,EAAE,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;QACtF,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import type { Api, ImageContent, Model, ModelImageResizeOptions, TextContent } from \"@punch-bot/ai\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, open as fsOpen, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { TextDecoder } from \"util\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { resolveReadPathAsync } from \"./path-utils.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts: the text for text files, and an image\n * block for images that codemode's `image()` accepts. `note` is the text that goes with the image,\n * such as resize hints. Property descriptions are left out so the type stays on one line in tool\n * descriptions.\n */\nconst readOutputSchema = Type.Union([\n\tType.String(),\n\tType.Object({ type: Type.Literal(\"image\"), data: Type.String(), mimeType: Type.String(), note: Type.String() }),\n]);\n\nexport type ReadToolOutput = Static<typeof readOutputSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n\t/**\n\t * Stream file contents in chunks. When present, text files are read through it and only the lines\n\t * that will be shown are kept in memory; otherwise readFile loads the whole file. Stop reading when\n\t * the signal aborts; the read tool also stops consuming the stream then.\n\t */\n\tcreateReadStream?: (absolutePath: string, options: { signal?: AbortSignal }) => AsyncIterable<Uint8Array>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\tcreateReadStream: readLocalFileChunks,\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\n/**\n * Stream a local file the way fs.readFile reads it: a regular file up to its size when opened, so text\n * appended during the read is not counted and a growing file still ends; a file reporting size 0 (such\n * as /proc files) and other file types until EOF.\n */\nasync function* readLocalFileChunks(path: string, { signal }: { signal?: AbortSignal }): AsyncIterable<Uint8Array> {\n\tconst handle = await fsOpen(path, \"r\");\n\ttry {\n\t\tconst stats = await handle.stat();\n\t\tconst end = stats.isFile() && stats.size > 0 ? stats.size - 1 : undefined;\n\t\tyield* handle.createReadStream({ end, signal, autoClose: false });\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Fallback resize profile when the execution context has no model metadata. */\n\tresizeOptions?: ModelImageResizeOptions;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\n/** The image block and its note, or the text for text files and images that could not be processed. */\nfunction toReadOutput(content: (TextContent | ImageContent)[]): ReadToolOutput {\n\tconst text = content.find((block) => block.type === \"text\")?.text ?? \"\";\n\tconst image = content.find((block) => block.type === \"image\");\n\treturn image ? { type: \"image\", data: image.data, mimeType: image.mimeType, note: text } : text;\n}\n\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\n/** The lines a read shows, with the file's line count; line counts follow `text.split(\"\\n\")`. */\ninterface SelectedLines {\n\ttotalFileLines: number;\n\ttruncation: TruncationResult;\n\t/** Bytes of the first selected line, for the notice when it alone exceeds the byte limit. */\n\tfirstLineBytes: number;\n}\n\n/**\n * Whether a range can be streamed. Other values (fractional, negative limit) keep the whole-file path,\n * whose array slicing defines what they select, for example limit -1 as all lines but the last.\n */\nfunction isStreamableRange(offset: number | undefined, limit: number | undefined): boolean {\n\treturn (\n\t\t(offset === undefined || Number.isInteger(offset)) &&\n\t\t(limit === undefined || (Number.isInteger(limit) && limit >= 0))\n\t);\n}\n\n/** Select lines from a whole file in memory: for operations without createReadStream and unusual ranges. */\nfunction selectLinesFromBuffer(buffer: Buffer, startLine: number, limit: number | undefined): SelectedLines {\n\tconst allLines = buffer.toString(\"utf-8\").split(\"\\n\");\n\tconst endLine = limit === undefined ? undefined : Math.min(startLine + limit, allLines.length);\n\tconst truncation = truncateHead(allLines.slice(startLine, endLine).join(\"\\n\"));\n\tconst firstLineBytes = truncation.firstLineExceedsLimit ? Buffer.byteLength(allLines[startLine], \"utf-8\") : 0;\n\treturn { totalFileLines: allLines.length, truncation, firstLineBytes };\n}\n\n/**\n * Select lines from a file read in chunks. Only lines truncateHead can show are stored; the rest are\n * counted, so memory does not grow with the file. Stops reading when the signal aborts.\n */\nasync function selectLinesFromStream(\n\tchunks: AsyncIterable<Uint8Array>,\n\tstartLine: number,\n\tlimit: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<SelectedLines> {\n\tconst endLine = limit === undefined ? Number.POSITIVE_INFINITY : startLine + limit;\n\t// Non-fatal UTF-8 that keeps a byte order mark decodes like Buffer.toString(\"utf-8\").\n\tconst decoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\tconst storedLines: string[] = [];\n\tlet storedBytes = 0;\n\tlet storedPastCaps = false;\n\tlet line = 0;\n\tlet selectedLines = 0;\n\tlet selectedBytes = 0;\n\tlet firstLineBytes = 0;\n\tlet lastLineEmpty = true;\n\t// The selected line being read: its text, while it is stored, and its size.\n\tlet pieces: string[] | undefined = [];\n\tlet lineBytes = 0;\n\tlet lineHasText = false;\n\n\tconst appendToLine = (text: string, start: number, end: number) => {\n\t\tlineHasText = true;\n\t\tif (!pieces) return;\n\t\tconst piece = text.slice(start, end);\n\t\t// A line over the byte cap is never shown, and a first line over it is only measured: never store\n\t\t// all of a 1 GB line.\n\t\tif (lineBytes <= DEFAULT_MAX_BYTES) pieces.push(piece);\n\t\tlineBytes += Buffer.byteLength(piece, \"utf-8\");\n\t};\n\tconst finishLine = () => {\n\t\tif (pieces) {\n\t\t\tif (selectedLines === 0) firstLineBytes = lineBytes;\n\t\t\t// Storing continues one line past the caps: truncateHead ignores a trailing empty line, so the\n\t\t\t// line after the cap must be there for it to decide truncation as for the full text.\n\t\t\tif (storedLines.length > DEFAULT_MAX_LINES || storedBytes > DEFAULT_MAX_BYTES) storedPastCaps = true;\n\t\t\tconst text = pieces.join(\"\");\n\t\t\tstoredBytes += Buffer.byteLength(text, \"utf-8\") + (storedLines.length > 0 ? 1 : 0);\n\t\t\tstoredLines.push(text);\n\t\t}\n\t\tselectedLines++;\n\t\tlastLineEmpty = !lineHasText;\n\t\tpieces = storedPastCaps ? undefined : [];\n\t\tlineBytes = 0;\n\t\tlineHasText = false;\n\t};\n\tconst select = (text: string) => {\n\t\tlet position = 0;\n\t\t// Start of the selected text in this piece, measured as a whole: the joined lines' size.\n\t\tlet selectionStart = -1;\n\t\twhile (true) {\n\t\t\tconst selected = line >= startLine && line < endLine;\n\t\t\tif (selected && selectionStart === -1) selectionStart = position;\n\t\t\tconst newline = text.indexOf(\"\\n\", position);\n\t\t\tconst end = newline === -1 ? text.length : newline;\n\t\t\tif (selected && end > position) appendToLine(text, position, end);\n\t\t\tif (newline === -1) break;\n\t\t\tif (selected) {\n\t\t\t\tfinishLine();\n\t\t\t\tif (line + 1 === endLine) {\n\t\t\t\t\tselectedBytes += Buffer.byteLength(text.slice(selectionStart, newline), \"utf-8\");\n\t\t\t\t\tselectionStart = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tline++;\n\t\t\tposition = newline + 1;\n\t\t}\n\t\tif (selectionStart !== -1) selectedBytes += Buffer.byteLength(text.slice(selectionStart), \"utf-8\");\n\t};\n\n\tfor await (const chunk of chunks) {\n\t\t// Leaving the loop closes the stream.\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tselect(decoder.decode(chunk, { stream: true }));\n\t}\n\tselect(decoder.decode());\n\tif (line >= startLine && line < endLine) finishLine();\n\tconst truncation: TruncationResult = {\n\t\t...truncateHead(storedLines.join(\"\\n\")),\n\t\t// truncateHead's counts for the joined selected lines, which drop a trailing empty line.\n\t\ttotalLines: selectedBytes === 0 ? 0 : selectedLines - (lastLineEmpty ? 1 : 0),\n\t\ttotalBytes: selectedBytes,\n\t};\n\treturn { totalFileLines: line + 1, truncation, firstLineBytes };\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst fallbackResizeOptions = options?.resizeOptions;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\toutputSchema: readOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, {\n\t\t\t\t\t\t\t\t\tautoResizeImages,\n\t\t\t\t\t\t\t\t\tresizeOptions: ctx?.model?.inputLimits?.images?.resize ?? fallbackResizeOptions,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content. Convert offset from 1-indexed input to 0-indexed line access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\tconst { totalFileLines, truncation, firstLineBytes } =\n\t\t\t\t\t\t\t\t\tops.createReadStream && isStreamableRange(offset, limit)\n\t\t\t\t\t\t\t\t\t\t? await selectLinesFromStream(\n\t\t\t\t\t\t\t\t\t\t\t\tops.createReadStream(absolutePath, { signal }),\n\t\t\t\t\t\t\t\t\t\t\t\tstartLine,\n\t\t\t\t\t\t\t\t\t\t\t\tlimit,\n\t\t\t\t\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t: selectLinesFromBuffer(await ops.readFile(absolutePath), startLine, limit);\n\t\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= totalFileLines) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// A user-specified limit is honored before truncation.\n\t\t\t\t\t\t\t\tconst userLimitedLines =\n\t\t\t\t\t\t\t\t\tlimit === undefined ? undefined : Math.min(startLine + limit, totalFileLines) - startLine;\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(firstLineBytes);\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < totalFileLines) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = totalFileLines - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t).then((result) => ({ ...result, structuredContent: toReadOutput(result.content) }));\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): TypeBoxAgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
|
|
@@ -1,5 +1,15 @@
|
|
|
1
|
-
import type { AgentTool } from "@punch-bot/agent";
|
|
1
|
+
import type { AgentTool, AgentToolResult, AgentToolUpdateCallback } from "@punch-bot/agent";
|
|
2
|
+
import type { Static, TSchema } from "typebox";
|
|
2
3
|
import type { ExtensionToolContext, ToolDefinition } from "../extensions/types.ts";
|
|
4
|
+
/**
|
|
5
|
+
* An `AgentTool` with a TypeBox parameter schema whose `execute` and `prepareArguments` are typed by TypeBox's
|
|
6
|
+
* `Static`, as the built-in tools are (pi-agent-core types `params` through pi-schema, which maps only the common
|
|
7
|
+
* TypeBox kinds). Spreads into a `ToolDefinition` of the same schema.
|
|
8
|
+
*/
|
|
9
|
+
export type TypeBoxAgentTool<TParams extends TSchema = TSchema, TDetails = any> = Omit<AgentTool<TParams, TDetails>, "prepareArguments" | "execute"> & {
|
|
10
|
+
prepareArguments?: (args: unknown) => Static<TParams>;
|
|
11
|
+
execute: (toolCallId: string, params: Static<TParams>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails>) => Promise<AgentToolResult<TDetails>>;
|
|
12
|
+
};
|
|
3
13
|
/** Creates the context for one tool call. */
|
|
4
14
|
export type ToolContextFactory = (toolCallId: string, signal: AbortSignal | undefined) => ExtensionToolContext;
|
|
5
15
|
/** Wrap a ToolDefinition into an AgentTool for the core runtime. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC5F,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAEnF;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,CAAC,OAAO,SAAS,OAAO,GAAG,OAAO,EAAE,QAAQ,GAAG,GAAG,IAAI,IAAI,CACrF,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,EAC5B,kBAAkB,GAAG,SAAS,CAC9B,GAAG;IACH,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,MAAM,CAAC,OAAO,CAAC,CAAC;IACtD,OAAO,EAAE,CACR,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,uBAAuB,CAAC,QAAQ,CAAC,KACxC,OAAO,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC;CACxC,CAAC;AAEF,6CAA6C;AAC7C,MAAM,MAAM,kBAAkB,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,KAAK,oBAAoB,CAAC;AAE/G,oEAAoE;AACpE,wBAAgB,kBAAkB,CAAC,QAAQ,GAAG,OAAO,EACpD,UAAU,EAAE,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,EACzC,UAAU,CAAC,EAAE,kBAAkB,GAC7B,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAmB1B;AAED,0EAA0E;AAC1E,wBAAgB,mBAAmB,CAClC,WAAW,EAAE,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,EACvC,UAAU,CAAC,EAAE,kBAAkB,GAC7B,SAAS,CAAC,GAAG,CAAC,EAAE,CAElB;AAED;;;;;GAKG;AACH,wBAAgB,iCAAiC,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,GAAG,EAAE,OAAO,CAAC,CAYpG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-definition-wrapper.js","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"tool-definition-wrapper.js","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAyBA,oEAAoE;AACpE,MAAM,UAAU,kBAAkB,CACjC,UAAyC,EACzC,UAA+B;IAE/B,OAAO;QACN,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,KAAK,EAAE,UAAU,CAAC,KAAK;QACvB,WAAW,EAAE,UAAU,CAAC,WAAW;QACnC,UAAU,EAAE,UAAU,CAAC,UAAU;QACjC,YAAY,EAAE,UAAU,CAAC,YAAY;QACrC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;QACnD,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;QAC7C,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,OAAO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAA0B,EAAE,EAAE,CAC7E,UAAU,CAAC,OAAO,CACjB,UAAU,EACV,MAAM,EACN,MAAM,EACN,QAAQ,EACR,GAAG,IAAK,UAAU,EAAE,CAAC,UAAU,EAAE,MAAM,CAA0B,CACjE;KACF,CAAC;AACH,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,mBAAmB,CAClC,WAAuC,EACvC,UAA+B;IAE/B,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,kBAAkB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AACpF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iCAAiC,CAAC,IAAoB;IACrE,OAAO;QACN,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,IAAI,CAAC,UAAiB;QAClC,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;QAC7C,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;KAC3G,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool, AgentToolResult, AgentToolUpdateCallback } from \"@punch-bot/agent\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ExtensionToolContext, ToolDefinition } from \"../extensions/types.ts\";\n\n/**\n * An `AgentTool` with a TypeBox parameter schema whose `execute` and `prepareArguments` are typed by TypeBox's\n * `Static`, as the built-in tools are (pi-agent-core types `params` through pi-schema, which maps only the common\n * TypeBox kinds). Spreads into a `ToolDefinition` of the same schema.\n */\nexport type TypeBoxAgentTool<TParams extends TSchema = TSchema, TDetails = any> = Omit<\n\tAgentTool<TParams, TDetails>,\n\t\"prepareArguments\" | \"execute\"\n> & {\n\tprepareArguments?: (args: unknown) => Static<TParams>;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParams>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n};\n\n/** Creates the context for one tool call. */\nexport type ToolContextFactory = (toolCallId: string, signal: AbortSignal | undefined) => ExtensionToolContext;\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition<TDetails = unknown>(\n\tdefinition: ToolDefinition<any, TDetails>,\n\tctxFactory?: ToolContextFactory,\n): AgentTool<any, TDetails> {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\toutputSchema: definition.outputSchema,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\tprepareArguments: definition.prepareArguments,\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionToolContext) =>\n\t\t\tdefinition.execute(\n\t\t\t\ttoolCallId,\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\tonUpdate,\n\t\t\t\tctx ?? (ctxFactory?.(toolCallId, signal) as ExtensionToolContext),\n\t\t\t),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition<any, any>[],\n\tctxFactory?: ToolContextFactory,\n): AgentTool<any>[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool(tool: AgentTool<any>): ToolDefinition<any, unknown> {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any,\n\t\toutputSchema: tool.outputSchema,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n"]}
|
|
@@ -67,18 +67,8 @@ export declare function truncateLine(line: string, maxChars?: number): {
|
|
|
67
67
|
text: string;
|
|
68
68
|
wasTruncated: boolean;
|
|
69
69
|
};
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
/** Characters left out. */
|
|
75
|
-
removedChars: number;
|
|
76
|
-
totalBytes: number;
|
|
77
|
-
totalLines: number;
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Keep the start and the end of `content`, half of `maxBytes` each, and replace the middle with a
|
|
81
|
-
* `…N chars truncated…` marker, like Codex does for tool output. Cuts only at character boundaries.
|
|
82
|
-
*/
|
|
83
|
-
export declare function truncateMiddle(content: string, maxBytes: number): MiddleTruncationResult;
|
|
70
|
+
/** Returns at most the first `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
|
|
71
|
+
export declare function sliceHead(text: string, maxUnits: number): string;
|
|
72
|
+
/** Returns at most the last `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
|
|
73
|
+
export declare function sliceTail(text: string, maxUnits: number): string;
|
|
84
74
|
//# sourceMappingURL=truncate.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"truncate.d.ts","sourceRoot":"","sources":["../../../src/core/tools/truncate.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,iBAAiB,OAAO,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;;GAGG;AACH,wBAAgB,YAAY,CAC3B,IAAI,EAAE,MAAM,EACZ,QAAQ,GAAE,MAA6B,GACrC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,OAAO,CAAA;CAAE,CAKzC;AAED,4GAA4G;AAC5G,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAMhE;AAED,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAMhE"}
|
|
@@ -210,35 +210,29 @@ export function truncateLine(line, maxChars = GREP_MAX_LINE_LENGTH) {
|
|
|
210
210
|
if (line.length <= maxChars) {
|
|
211
211
|
return { text: line, wasTruncated: false };
|
|
212
212
|
}
|
|
213
|
-
return { text: `${line
|
|
213
|
+
return { text: `${sliceHead(line, maxChars)}... [truncated]`, wasTruncated: true };
|
|
214
214
|
}
|
|
215
|
-
/**
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
return
|
|
237
|
-
content: `${head}…${removedChars} chars truncated…${tail}`,
|
|
238
|
-
truncated: true,
|
|
239
|
-
removedChars,
|
|
240
|
-
totalBytes: buf.length,
|
|
241
|
-
totalLines,
|
|
242
|
-
};
|
|
215
|
+
/** Returns at most the first `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
|
|
216
|
+
export function sliceHead(text, maxUnits) {
|
|
217
|
+
const end = Math.max(0, maxUnits);
|
|
218
|
+
// A lone high surrogate before the cut would be invalid UTF-16; keep the whole character out instead.
|
|
219
|
+
return isHighSurrogate(text.charCodeAt(end - 1)) && isLowSurrogate(text.charCodeAt(end))
|
|
220
|
+
? text.slice(0, end - 1)
|
|
221
|
+
: text.slice(0, end);
|
|
222
|
+
}
|
|
223
|
+
/** Returns at most the last `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */
|
|
224
|
+
export function sliceTail(text, maxUnits) {
|
|
225
|
+
if (maxUnits <= 0)
|
|
226
|
+
return "";
|
|
227
|
+
const start = Math.max(0, text.length - maxUnits);
|
|
228
|
+
return isLowSurrogate(text.charCodeAt(start)) && isHighSurrogate(text.charCodeAt(start - 1))
|
|
229
|
+
? text.slice(start + 1)
|
|
230
|
+
: text.slice(start);
|
|
231
|
+
}
|
|
232
|
+
function isHighSurrogate(code) {
|
|
233
|
+
return code >= 0xd800 && code <= 0xdbff;
|
|
234
|
+
}
|
|
235
|
+
function isLowSurrogate(code) {
|
|
236
|
+
return code >= 0xdc00 && code <= 0xdfff;
|
|
243
237
|
}
|
|
244
238
|
//# sourceMappingURL=truncate.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"truncate.js","sourceRoot":"","sources":["../../../src/core/tools/truncate.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO;AACnD,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC,CAAC,gCAAgC;AAkCzE,SAAS,qBAAqB,CAAC,OAAe;IAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAClC,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5B,KAAK,CAAC,GAAG,EAAE,CAAC;IACb,CAA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,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3F,OAAO;QACN,OAAO,EAAE,GAAG,IAAI,IAAI,YAAY,oBAAoB,IAAI,EAAE;QAC1D,SAAS,EAAE,IAAI;QACf,YAAY;QACZ,UAAU,EAAE,GAAG,CAAC,MAAM;QACtB,UAAU;KACV,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits - whichever is hit first wins:\n * - Line limit (default: 2000 lines)\n * - Byte limit (default: 50KB)\n *\n * Never returns partial lines (except bash tail truncation edge case).\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\nexport const GREP_MAX_LINE_LENGTH = 500; // Max chars per grep match line\n\nexport interface TruncationResult {\n\t/** The truncated content */\n\tcontent: string;\n\t/** Whether truncation occurred */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation edge case) */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation) */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: 2000) */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: 50KB) */\n\tmaxBytes?: number;\n}\n\nfunction splitLinesForCounting(content: string): string[] {\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\tconst lines = content.split(\"\\n\");\n\tif (content.endsWith(\"\\n\")) {\n\t\tlines.pop();\n\t}\n\treturn lines;\n}\n\n/**\n * Format bytes as human-readable size.\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t} else if (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t} else {\n\t\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n\t}\n}\n\n/**\n * Truncate content from the head (keep first N lines/bytes).\n * Suitable for file reads where you want to see the beginning.\n *\n * Never returns partial lines. If first line exceeds byte limit,\n * returns empty content with firstLineExceedsLimit=true.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Check if first line alone exceeds byte limit\n\tconst firstLineBytes = Buffer.byteLength(lines[0], \"utf-8\");\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Collect complete lines that fit\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate content from the tail (keep last N lines/bytes).\n * Suitable for bash output where you want to see the end (errors, final results).\n *\n * May return partial first line if the last line of original content exceeds byte limit.\n */\nexport function truncateTail(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Work backwards from the end\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\tlet lastLinePartial = false;\n\n\tfor (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\t// Edge case: if we haven't added ANY lines yet and this line exceeds maxBytes,\n\t\t\t// take the end of the line (partial)\n\t\t\tif (outputLinesArr.length === 0) {\n\t\t\t\tconst truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);\n\t\t\t\toutputLinesArr.unshift(truncatedLine);\n\t\t\t\toutputBytesCount = Buffer.byteLength(truncatedLine, \"utf-8\");\n\t\t\t\tlastLinePartial = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.unshift(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate a string to fit within a byte limit (from the end).\n * Handles multi-byte UTF-8 characters correctly.\n */\nfunction truncateStringToBytesFromEnd(str: string, maxBytes: number): string {\n\tconst buf = Buffer.from(str, \"utf-8\");\n\tif (buf.length <= maxBytes) {\n\t\treturn str;\n\t}\n\n\t// Start from the end, skip maxBytes back\n\tlet start = buf.length - maxBytes;\n\n\t// Find a valid UTF-8 boundary (start of a character)\n\twhile (start < buf.length && (buf[start] & 0xc0) === 0x80) {\n\t\tstart++;\n\t}\n\n\treturn buf.slice(start).toString(\"utf-8\");\n}\n\n/**\n * Truncate a single line to max characters, adding [truncated] suffix.\n * Used for grep match lines.\n */\nexport function truncateLine(\n\tline: string,\n\tmaxChars: number = GREP_MAX_LINE_LENGTH,\n): { text: string; wasTruncated: boolean } {\n\tif (line.length <= maxChars) {\n\t\treturn { text: line, wasTruncated: false };\n\t}\n\treturn { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };\n}\n\nexport interface MiddleTruncationResult {\n\t/** The start and end of the content with a `…N chars truncated…` marker between them. */\n\tcontent: string;\n\ttruncated: boolean;\n\t/** Characters left out. */\n\tremovedChars: number;\n\ttotalBytes: number;\n\ttotalLines: number;\n}\n\n/**\n * Keep the start and the end of `content`, half of `maxBytes` each, and replace the middle with a\n * `…N chars truncated…` marker, like Codex does for tool output. Cuts only at character boundaries.\n */\nexport function truncateMiddle(content: string, maxBytes: number): MiddleTruncationResult {\n\tconst buf = Buffer.from(content, \"utf-8\");\n\tconst totalLines = splitLinesForCounting(content).length;\n\tif (buf.length <= maxBytes) {\n\t\treturn { content, truncated: false, removedChars: 0, totalBytes: buf.length, totalLines };\n\t}\n\t// Continuation bytes (10xxxxxx) are not character starts.\n\tconst isBoundary = (index: number) => index >= buf.length || (buf[index] & 0xc0) !== 0x80;\n\tlet headEnd = Math.floor(maxBytes / 2);\n\twhile (headEnd > 0 && !isBoundary(headEnd)) headEnd--;\n\tlet tailStart = buf.length - (maxBytes - Math.floor(maxBytes / 2));\n\twhile (tailStart < buf.length && !isBoundary(tailStart)) tailStart++;\n\tconst head = buf.subarray(0, headEnd).toString(\"utf-8\");\n\tconst tail = buf.subarray(tailStart).toString(\"utf-8\");\n\tconst removedChars = Array.from(buf.subarray(headEnd, tailStart).toString(\"utf-8\")).length;\n\treturn {\n\t\tcontent: `${head}…${removedChars} chars truncated…${tail}`,\n\t\ttruncated: true,\n\t\tremovedChars,\n\t\ttotalBytes: buf.length,\n\t\ttotalLines,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"truncate.js","sourceRoot":"","sources":["../../../src/core/tools/truncate.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO;AACnD,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC,CAAC,gCAAgC;AAkCzE,SAAS,qBAAqB,CAAC,OAAe;IAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAClC,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5B,KAAK,CAAC,GAAG,EAAE,CAAC;IACb,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa;IACvC,IAAI,KAAK,GAAG,IAAI,EAAE,CAAC;QAClB,OAAO,GAAG,KAAK,GAAG,CAAC;IACpB,CAAC;SAAM,IAAI,KAAK,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;QAChC,OAAO,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;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C,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACvB,CAAC;AAED,2GAA2G;AAC3G,MAAM,UAAU,SAAS,CAAC,IAAY,EAAE,QAAgB;IACvD,IAAI,QAAQ,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAC7B,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC;IAClD,OAAO,cAAc,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,IAAI,eAAe,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAC3F,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;QACvB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACtB,CAAC;AAED,SAAS,eAAe,CAAC,IAAY;IACpC,OAAO,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC;AACzC,CAAC;AAED,SAAS,cAAc,CAAC,IAAY;IACnC,OAAO,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits - whichever is hit first wins:\n * - Line limit (default: 2000 lines)\n * - Byte limit (default: 50KB)\n *\n * Never returns partial lines (except bash tail truncation edge case).\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\nexport const GREP_MAX_LINE_LENGTH = 500; // Max chars per grep match line\n\nexport interface TruncationResult {\n\t/** The truncated content */\n\tcontent: string;\n\t/** Whether truncation occurred */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation edge case) */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation) */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: 2000) */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: 50KB) */\n\tmaxBytes?: number;\n}\n\nfunction splitLinesForCounting(content: string): string[] {\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\tconst lines = content.split(\"\\n\");\n\tif (content.endsWith(\"\\n\")) {\n\t\tlines.pop();\n\t}\n\treturn lines;\n}\n\n/**\n * Format bytes as human-readable size.\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t} else if (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t} else {\n\t\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n\t}\n}\n\n/**\n * Truncate content from the head (keep first N lines/bytes).\n * Suitable for file reads where you want to see the beginning.\n *\n * Never returns partial lines. If first line exceeds byte limit,\n * returns empty content with firstLineExceedsLimit=true.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Check if first line alone exceeds byte limit\n\tconst firstLineBytes = Buffer.byteLength(lines[0], \"utf-8\");\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Collect complete lines that fit\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate content from the tail (keep last N lines/bytes).\n * Suitable for bash output where you want to see the end (errors, final results).\n *\n * May return partial first line if the last line of original content exceeds byte limit.\n */\nexport function truncateTail(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Work backwards from the end\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\tlet lastLinePartial = false;\n\n\tfor (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\t// Edge case: if we haven't added ANY lines yet and this line exceeds maxBytes,\n\t\t\t// take the end of the line (partial)\n\t\t\tif (outputLinesArr.length === 0) {\n\t\t\t\tconst truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);\n\t\t\t\toutputLinesArr.unshift(truncatedLine);\n\t\t\t\toutputBytesCount = Buffer.byteLength(truncatedLine, \"utf-8\");\n\t\t\t\tlastLinePartial = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.unshift(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate a string to fit within a byte limit (from the end).\n * Handles multi-byte UTF-8 characters correctly.\n */\nfunction truncateStringToBytesFromEnd(str: string, maxBytes: number): string {\n\tconst buf = Buffer.from(str, \"utf-8\");\n\tif (buf.length <= maxBytes) {\n\t\treturn str;\n\t}\n\n\t// Start from the end, skip maxBytes back\n\tlet start = buf.length - maxBytes;\n\n\t// Find a valid UTF-8 boundary (start of a character)\n\twhile (start < buf.length && (buf[start] & 0xc0) === 0x80) {\n\t\tstart++;\n\t}\n\n\treturn buf.slice(start).toString(\"utf-8\");\n}\n\n/**\n * Truncate a single line to max characters, adding [truncated] suffix.\n * Used for grep match lines.\n */\nexport function truncateLine(\n\tline: string,\n\tmaxChars: number = GREP_MAX_LINE_LENGTH,\n): { text: string; wasTruncated: boolean } {\n\tif (line.length <= maxChars) {\n\t\treturn { text: line, wasTruncated: false };\n\t}\n\treturn { text: `${sliceHead(line, maxChars)}... [truncated]`, wasTruncated: true };\n}\n\n/** Returns at most the first `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */\nexport function sliceHead(text: string, maxUnits: number): string {\n\tconst end = Math.max(0, maxUnits);\n\t// A lone high surrogate before the cut would be invalid UTF-16; keep the whole character out instead.\n\treturn isHighSurrogate(text.charCodeAt(end - 1)) && isLowSurrogate(text.charCodeAt(end))\n\t\t? text.slice(0, end - 1)\n\t\t: text.slice(0, end);\n}\n\n/** Returns at most the last `maxUnits` UTF-16 code units of `text`, without splitting a surrogate pair. */\nexport function sliceTail(text: string, maxUnits: number): string {\n\tif (maxUnits <= 0) return \"\";\n\tconst start = Math.max(0, text.length - maxUnits);\n\treturn isLowSurrogate(text.charCodeAt(start)) && isHighSurrogate(text.charCodeAt(start - 1))\n\t\t? text.slice(start + 1)\n\t\t: text.slice(start);\n}\n\nfunction isHighSurrogate(code: number): boolean {\n\treturn code >= 0xd800 && code <= 0xdbff;\n}\n\nfunction isLowSurrogate(code: number): boolean {\n\treturn code >= 0xdc00 && code <= 0xdfff;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type { AgentTool } from "@punch-bot/agent";
|
|
2
1
|
import { type Static, Type } from "typebox";
|
|
3
2
|
import type { ToolDefinition } from "../extensions/types.ts";
|
|
3
|
+
import { type TypeBoxAgentTool } from "./tool-definition-wrapper.ts";
|
|
4
4
|
declare const writeSchema: Type.TObject<{
|
|
5
5
|
path: Type.TString;
|
|
6
6
|
content: Type.TString;
|
|
@@ -25,6 +25,6 @@ export interface WriteToolOptions {
|
|
|
25
25
|
operations?: WriteOperations;
|
|
26
26
|
}
|
|
27
27
|
export declare function createWriteToolDefinition(cwd: string, options?: WriteToolOptions): ToolDefinition<typeof writeSchema, undefined>;
|
|
28
|
-
export declare function createWriteTool(cwd: string, options?: WriteToolOptions):
|
|
28
|
+
export declare function createWriteTool(cwd: string, options?: WriteToolOptions): TypeBoxAgentTool<typeof writeSchema>;
|
|
29
29
|
export {};
|
|
30
30
|
//# sourceMappingURL=write.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAoB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG/E,OAAO,EAAE,KAAK,gBAAgB,EAAsB,MAAM,8BAA8B,CAAC;AAEzF,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,eAAO,MAAM,iCAAiC;aAC7C,OAAO,EAAE,2BAA2B;aACpC,UAAU,YAAG,oDAAoD;CACxD,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC/B,8BAA8B;IAC9B,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,mCAAmC;IACnC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAOD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,UAAU,CAAC,EAAE,eAAe,CAAC;CAC7B;AAED,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gBAAgB,GACxB,cAAc,CAAC,OAAO,WAAW,EAAE,SAAS,CAAC,CA6C/C;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,gBAAgB,CAAC,OAAO,WAAW,CAAC,CAE7G"}
|