@maxmo74/pi-coding-agent 1.5.0-max.8 → 1.6.0-max.16
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 +214 -0
- package/README.md +1 -1
- package/dist/bundle/chunks/anthropic-messages-WAFIHSF7.js +6 -0
- package/dist/bundle/chunks/{azure-openai-responses-FSC6BAW3.js → azure-openai-responses-EB4MRIM4.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +3 -3
- package/dist/bundle/chunks/chunk-E6LJTZYC.js +82 -0
- package/dist/bundle/chunks/chunk-EEBRZED2.js +44 -0
- package/dist/bundle/chunks/chunk-EVSO24NP.js +2 -0
- package/dist/bundle/chunks/chunk-EXXWEFU5.js +1247 -0
- package/dist/bundle/chunks/{chunk-EOO47QGR.js → chunk-F7LEMV2T.js} +1 -1
- package/dist/bundle/chunks/chunk-I6HYYNH6.js +8 -0
- package/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
- package/dist/bundle/chunks/{chunk-V6KH5QG4.js → chunk-ILDLA2JW.js} +1 -1
- package/dist/bundle/chunks/chunk-INODY4DR.js +2 -0
- package/dist/bundle/chunks/{chunk-MSIQUO5T.js → chunk-KREOSXD7.js} +1 -1
- package/dist/bundle/chunks/chunk-LWG2CUTI.js +31 -0
- package/dist/bundle/chunks/{chunk-3TGLJEWK.js → chunk-NRLRGOCX.js} +1 -1
- package/dist/bundle/chunks/chunk-NRY4NBZW.js +4 -0
- package/dist/bundle/chunks/chunk-NV3NPOPF.js +20 -0
- package/dist/bundle/chunks/{chunk-C2WU32PX.js → chunk-RCNEHRMW.js} +1 -1
- package/dist/bundle/chunks/{chunk-4EYXVSA5.js → chunk-X26YOAEH.js} +15 -14
- package/dist/bundle/chunks/chunk-X6RQRO3L.js +16 -0
- package/dist/bundle/chunks/chunk-XGGZYFNG.js +55 -0
- package/dist/bundle/chunks/chunk-XJ2YV77J.js +30 -0
- package/dist/bundle/chunks/{chunk-YZKQS34S.js → chunk-Y55SJART.js} +5 -1
- package/dist/bundle/chunks/chunk-YOWSKVK7.js +2 -0
- package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
- package/dist/bundle/chunks/{cli-MCOUW5WS.js → cli-QMJEURSM.js} +7 -7
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-WLAFJSP6.js → cloudflare-workers-ai-system-one-AMCR7QEI.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +2 -0
- package/dist/bundle/chunks/{easter-egg-3d-WMBNSJ4M.js → easter-egg-3d-7CBVPJQ3.js} +1 -1
- package/dist/bundle/chunks/{execute-4CEBORGZ.js → execute-XDNPBEMU.js} +5 -3
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/google-generative-ai-43M4N5LK.js +2 -0
- package/dist/bundle/chunks/google-vertex-2B3PASK2.js +2 -0
- package/dist/bundle/chunks/{llama-cpp-classify-V5U3QKXI.js → llama-cpp-classify-XXZYF3RR.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-S4OWXIXQ.js → mistral-conversations-E3D5ZQKB.js} +2 -2
- package/dist/bundle/chunks/{openai-codex-responses-QAWLOQSN.js → openai-codex-responses-MSQDSDUR.js} +2 -2
- package/dist/bundle/chunks/openai-completions-4IC6AGTR.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-IXI34BYG.js → openai-decisions-LZ2RLVRX.js} +1 -1
- package/dist/bundle/chunks/openai-responses-MCO3BHCC.js +4 -0
- package/dist/bundle/chunks/{openrouter-images-PISKSFMS.js → openrouter-images-SHUJ3VSG.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-NORUKF4E.js → pi-messages-NIKOQ4O7.js} +1 -1
- package/dist/bundle/chunks/{runtime-FQB7RU7U.js → runtime-F3SXQONS.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-CHVC2UUI.js → typesafe-system-one-R2CDUWNO.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-2WYTGPJ3.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.map +1 -1
- package/dist/cli/args.js +5 -3
- 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 +57 -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/config-selector.d.ts.map +1 -1
- package/dist/cli/config-selector.js +12 -7
- package/dist/cli/config-selector.js.map +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js +9 -6
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +4 -0
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +16 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +40 -3
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +31 -9
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +160 -63
- 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/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 +1 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +4 -1
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/ansi-to-html.d.ts +6 -1
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js +57 -20
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/template.js +1 -1
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +2 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- 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 +28 -6
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +1 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +14 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +33 -6
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +2 -2
- package/dist/core/keybindings.js +1 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +12 -37
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +42 -121
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +52 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-resolver.d.ts +0 -8
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +22 -85
- 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 +26 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +95 -7
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +4 -0
- package/dist/core/pi-ai-schemas.d.ts.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/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 +6 -0
- package/dist/core/provider-matching.d.ts.map +1 -0
- package/dist/core/provider-matching.js +8 -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/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +9 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts +5 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +2 -0
- 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/session-cwd.d.ts +7 -0
- package/dist/core/session-cwd.d.ts.map +1 -1
- package/dist/core/session-cwd.js +9 -1
- package/dist/core/session-cwd.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +45 -36
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-ownership.js +15 -1
- package/dist/core/session-ownership.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +1 -1
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +1 -1
- package/dist/core/settings-defaults.js.map +1 -1
- 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.map +1 -1
- package/dist/core/tools/edit.js +8 -7
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +96 -39
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +5 -3
- 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.map +1 -1
- package/dist/core/tools/ls.js +2 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +4 -1
- package/dist/core/tools/output-accumulator.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 +13 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +146 -35
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/renderers/read.d.ts.map +1 -1
- package/dist/core/tools/renderers/read.js +6 -2
- package/dist/core/tools/renderers/read.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/extensions/codemode/execute.js +4 -4
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +34 -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/provider.d.ts +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +6 -4
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +15 -3
- package/dist/extensions/llama/ui.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 +49 -14
- 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 +7 -9
- 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 -319
- 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/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +18 -6
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +98 -27
- package/dist/main.js.map +1 -1
- package/dist/modes/diagnostics-stderr.d.ts +4 -0
- package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
- package/dist/modes/diagnostics-stderr.js +11 -0
- package/dist/modes/diagnostics-stderr.js.map +1 -0
- package/dist/modes/interactive/components/assistant-message.d.ts +2 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +9 -3
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.js +12 -4
- package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts +5 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.js +12 -4
- package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +5 -2
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts +5 -2
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +10 -3
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.js +11 -5
- package/dist/modes/interactive/components/diff.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +9 -1
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +1 -18
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts +2 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +25 -20
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +19 -8
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +10 -3
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +39 -8
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/provider-brand.d.ts +14 -0
- package/dist/modes/interactive/components/provider-brand.d.ts.map +1 -0
- package/dist/modes/interactive/components/provider-brand.js +66 -0
- package/dist/modes/interactive/components/provider-brand.js.map +1 -0
- package/dist/modes/interactive/components/radius-login-selector.d.ts +1 -2
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.js +8 -38
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +9 -1
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +8 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +41 -9
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +5 -1
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +12 -4
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/themed-text.d.ts +1 -1
- package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
- package/dist/modes/interactive/components/themed-text.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +5 -1
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +3 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +19 -10
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +2 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +9 -3
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +14 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +232 -127
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/session-share.js +2 -0
- package/dist/modes/interactive/session-share.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +5 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +35 -23
- 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 +67 -45
- 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 +53 -9
- package/dist/package-manager-cli.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 +15 -8
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/flush-stdout.d.ts +8 -0
- package/dist/utils/flush-stdout.d.ts.map +1 -0
- package/dist/utils/flush-stdout.js +23 -0
- package/dist/utils/flush-stdout.js.map +1 -0
- 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/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/version-check.js +1 -1
- package/dist/utils/version-check.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.md +14 -1
- package/docs/extensions.md +31 -11
- package/docs/keybindings.md +1 -1
- package/docs/llama-cpp.md +5 -8
- package/docs/models-configuration.md +9 -3
- package/docs/models.md +2 -1
- package/docs/nvidia-rtx-llama-cpp.md +5 -5
- package/docs/prompt-templates.md +1 -1
- package/docs/providers.md +4 -2
- package/docs/rpc-commands.md +1 -1
- package/docs/rpc.md +4 -2
- package/docs/sessions.md +7 -1
- package/docs/settings.md +1 -1
- package/docs/tui.md +3 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/index.ts +4 -7
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/plan-mode/index.ts +23 -13
- package/examples/extensions/plan-mode/utils.ts +42 -16
- package/examples/extensions/subagent/README.md +14 -11
- package/examples/extensions/subagent/index.ts +392 -171
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/tsconfig.json +63 -35
- package/package.json +11 -11
- package/schemas/models.schema.json +30 -1
- package/schemas/settings.schema.json +1 -1
- package/dist/bundle/chunks/anthropic-messages-BWGCKOF4.js +0 -6
- package/dist/bundle/chunks/chunk-62VOPMLK.js +0 -65
- package/dist/bundle/chunks/chunk-7O7QKK6A.js +0 -2
- package/dist/bundle/chunks/chunk-B46VJEHW.js +0 -44
- package/dist/bundle/chunks/chunk-CF5GWZHW.js +0 -31
- package/dist/bundle/chunks/chunk-CHWNPHIS.js +0 -82
- package/dist/bundle/chunks/chunk-FGCQRPD5.js +0 -1239
- package/dist/bundle/chunks/chunk-GN3QYODH.js +0 -16
- package/dist/bundle/chunks/chunk-NL4X6LBY.js +0 -4
- package/dist/bundle/chunks/chunk-NZY7EIPA.js +0 -4
- package/dist/bundle/chunks/chunk-R2EGYMOO.js +0 -7
- package/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
- package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
- package/dist/bundle/chunks/chunk-VOLAXWGI.js +0 -2
- package/dist/bundle/chunks/google-generative-ai-INGKNW72.js +0 -2
- package/dist/bundle/chunks/google-vertex-IBTX6MBF.js +0 -2
- package/dist/bundle/chunks/openai-completions-EJNYB6IX.js +0 -7
- package/dist/bundle/chunks/openai-responses-MD3562FB.js +0 -4
- package/dist/bundle/chunks/virtual-modules-CLD44EYP.js +0 -2
- package/dist/utils/deprecation.d.ts +0 -4
- package/dist/utils/deprecation.d.ts.map +0 -1
- package/dist/utils/deprecation.js +0 -13
- package/dist/utils/deprecation.js.map +0 -1
|
@@ -240,7 +240,21 @@ function collectLiveOwners() {
|
|
|
240
240
|
removeStaleRecord(join(root, file));
|
|
241
241
|
continue;
|
|
242
242
|
}
|
|
243
|
-
|
|
243
|
+
let raw;
|
|
244
|
+
try {
|
|
245
|
+
raw = readFileSync(join(root, file), "utf8");
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
// The owner removed its record after readdir listed it, which means it exited: the same
|
|
249
|
+
// conclusion the missing-process check above reaches. Concurrent scanners hit this routinely,
|
|
250
|
+
// and without it the scan throws, so every gate that asks who holds a session fails with a
|
|
251
|
+
// filesystem error instead of an answer.
|
|
252
|
+
if (error.code !== "ENOENT")
|
|
253
|
+
throw error;
|
|
254
|
+
removeStaleRecord(join(root, file));
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
const record = JSON.parse(raw);
|
|
244
258
|
if (!record ||
|
|
245
259
|
typeof record !== "object" ||
|
|
246
260
|
!("start" in record) ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-ownership.js","sourceRoot":"","sources":["../../src/core/session-ownership.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OA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AE,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["// Coordinate session users and relocation within one local user account.\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmdirSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { canonicalizePath } from \"../utils/paths.ts\";\n\nconst root = join(tmpdir(), `pi-session-owners-${process.getuid?.() ?? \"user\"}`);\nconst sessions = new Map<string, number>();\nconst gateWait = new Int32Array(new SharedArrayBuffer(4));\nconst gateTimeoutMs = 2000;\nlet holdingGate = false;\n\n/** Serialize registration and moves; an abandoned gate fails closed rather than guessing. */\nexport function withSessionOwnershipGate<T>(operation: () => T): T {\n\tif (holdingGate) throw new Error(\"Session ownership operations cannot acquire the gate recursively.\");\n\tmkdirSync(root, { recursive: true, mode: 0o700 });\n\t// POSIX mode bits are only meaningful where they are reported. On Windows the per-user\n\t// temporary directory is the isolation boundary and lstat reports a fixed mode.\n\tconst info = lstatSync(root);\n\tconst uid = process.getuid?.();\n\tif (!info.isDirectory() || (uid !== undefined && (info.uid !== uid || (info.mode & 0o077) !== 0))) {\n\t\tthrow new Error(`Unsafe session ownership directory: ${root}`);\n\t}\n\tconst gate = join(root, \"gate\");\n\tconst deadline = performance.now() + gateTimeoutMs;\n\tfor (;;) {\n\t\ttry {\n\t\t\tmkdirSync(gate, { mode: 0o700 });\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\t\tconst remaining = deadline - performance.now();\n\t\t\tif (remaining <= 0) {\n\t\t\t\tthrow new Error(`Session ownership is busy. Retry later. If a process crashed, inspect ${gate}.`);\n\t\t\t}\n\t\t\t// SessionManager's API is synchronous. Wait only for other processes, never for work on this event loop.\n\t\t\tAtomics.wait(gateWait, 0, 0, Math.min(25, remaining));\n\t\t}\n\t}\n\tholdingGate = true;\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tholdingGate = false;\n\t\trmdirSync(gate);\n\t}\n}\n\n/** Register a manager's session before reading it, releasing its previous registration. */\nexport function changeSessionOwnership(previous: string | undefined, next: string | undefined): void {\n\tif (previous === next) return;\n\twithSessionOwnershipGate(() => {\n\t\tif (next && !existsSync(next) && existsSync(movedMarker(next)))\n\t\t\tthrow new Error(\"This session has moved. Refresh the session picker.\");\n\t\tconst updated = new Map(sessions);\n\t\tif (previous) {\n\t\t\tconst path = canonicalSessionPath(previous);\n\t\t\tconst count = updated.get(path) ?? 0;\n\t\t\tif (count <= 1) updated.delete(path);\n\t\t\telse updated.set(path, count - 1);\n\t\t}\n\t\tif (next) {\n\t\t\tconst path = canonicalSessionPath(next);\n\t\t\tupdated.set(path, (updated.get(path) ?? 0) + 1);\n\t\t}\n\t\t// A null start means the platform cannot distinguish a PID from a later process that reused it.\n\t\tconst temporary = join(root, `${process.pid}.tmp`);\n\t\twriteFileSync(\n\t\t\ttemporary,\n\t\t\tJSON.stringify({ start: processIdentity(process.pid) ?? null, sessions: [...updated.keys()] }),\n\t\t\t{ mode: 0o600 },\n\t\t);\n\t\trenameSync(temporary, join(root, `${process.pid}.json`));\n\t\tsessions.clear();\n\t\tfor (const [path, count] of updated) sessions.set(path, count);\n\t});\n}\n\n/** Hold a counted session reference during a synchronous read/copy/mutation operation. */\nexport function withSessionFileUsage<T>(path: string, operation: () => T): T {\n\tchangeSessionOwnership(undefined, path);\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tchangeSessionOwnership(path, undefined);\n\t}\n}\n\nfunction canonicalSessionPath(path: string): string {\n\tconst absolute = resolve(path);\n\treturn canonicalizePath(join(canonicalizePath(dirname(absolute)), basename(absolute)));\n}\n\nfunction movedMarker(path: string): string {\n\treturn join(root, `${createHash(\"sha256\").update(canonicalSessionPath(path)).digest(\"hex\")}.moved`);\n}\n\n/** Prevent a concurrent opener from recreating the old path after relocation. */\nexport function markSessionMoved(path: string, destination: string): void {\n\twriteFileSync(movedMarker(path), destination, { mode: 0o600 });\n}\n\n/** Roll back a relocation marker when the source was not removed. */\nexport function unmarkSessionMoved(path: string): void {\n\tunlinkSync(movedMarker(path));\n}\n\n// Linux only: stat field 22 distinguishes a PID from a later process that reused it.\n// comm can contain spaces and parentheses, so fields are read after the last ')'.\nfunction linuxProcessStart(pid: number): string {\n\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\treturn stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n}\n\nconst processIdentity = process.platform === \"linux\" ? linuxProcessStart : () => undefined;\n\n/**\n * Drop a record whose owner is provably gone. This is cleanup only: a failed removal must never\n * affect the safety decision, because Windows can report EPERM or EBUSY for a file another\n * process still has open.\n */\nfunction removeStaleRecord(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {\n\t\t// The next move retries the cleanup. A surviving stale record only ever causes a refusal.\n\t}\n}\n\n/**\n * Report whether a recorded owner process is still running. Anything other than a confirmed\n * absence counts as running, including a permission error, so an uncertain check never allows\n * the operation. On non-Linux platforms a reused PID is indistinguishable and also counts as\n * running, which can refuse an operation that would have been safe.\n */\nfunction processIsLive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n\t}\n}\n\n/** Refuse live users of this file and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */\nexport function assertSessionUnused(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"moving\");\n\t// Relocation splits a session across two paths if any process keeps the old one open, including\n\t// a process that cannot be inspected, so an untracked Pi blocks a move with no override.\n\t// Detecting Pi processes that predate ownership requires scanning the process table, and the\n\t// portable process list is not reliable enough to do so outside Linux. Those platforms only\n\t// enforce ownership registered by cooperating Pi instances.\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership. Close older Pi instances before moving.`,\n\t\t);\n}\n\n/**\n * Refuse a delete where the harm is proven, and allow an override where it is only possible. A live\n * process that registered this file always blocks it, with or without the override: deleting a session\n * out from under its writer is the same loss as forking its history. An untracked Pi cannot be\n * inspected at all, so it blocks too, but `PI_ALLOW_SHARED_SESSION` clears that case. Without the\n * override, one unrelated official Pi on Linux would make session cleanup impossible, and the worst\n * outcome it prevents is a process writing to a removed file rather than lost conversation.\n * Caller must hold the ownership gate.\n */\nexport function assertSessionDeletable(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"deleting\");\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return;\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership, so it may hold this session. Close it, or set PI_ALLOW_SHARED_SESSION to delete anyway.`,\n\t\t);\n}\n\nfunction refuseWhileOpen(owners: LiveOwner[], canonical: string, purpose: string): void {\n\tfor (const owner of owners) {\n\t\tif (owner.sessions.includes(canonical))\n\t\t\tthrow new Error(`Session is open in process ${owner.pid}. Close it before ${purpose}.`);\n\t}\n}\n\n/** First Pi process of this user that runs without an ownership record, if any. Linux only. */\nfunction findUntrackedPiPid(owners: LiveOwner[]): number | undefined {\n\tif (process.platform !== \"linux\") return undefined;\n\tconst registered = new Set(owners.map((owner) => owner.pid));\n\tconst processes = execFileSync(\"ps\", [\"-u\", String(process.getuid!()), \"-o\", \"pid=,comm=,args=\"], {\n\t\tencoding: \"utf8\",\n\t});\n\tfor (const line of processes.split(\"\\n\")) {\n\t\tconst match = line.trim().match(/^(\\d+)\\s+(\\S+)\\s+(.*)$/);\n\t\tif (!match) continue;\n\t\tconst pid = Number(match[1]);\n\t\tif (pid === process.pid || registered.has(pid)) continue;\n\t\tconst isPi =\n\t\t\tmatch[2] === \"pi\" ||\n\t\t\t/(?:^|\\s)\\S*(?:pi-coding-agent\\/(?:dist|src)\\/cli\\.(?:js|ts)|\\/pi\\/packages\\/coding-agent\\/src\\/cli\\.ts)(?:\\s|$)/.test(\n\t\t\t\tmatch[3],\n\t\t\t);\n\t\tif (isPi) return pid;\n\t}\n\treturn undefined;\n}\n\n/**\n * Refuse resuming a session a live Pi already holds. Appends carry the writer's own leaf, so two\n * writers on one file fork its history and a later read follows the branch that appended last,\n * hiding the other one without warning. This process's own registrations never refuse, so\n * re-selecting the current session stays a no-op and unrelated sessions are unaffected. Returns\n * the message instead of throwing so the interactive picker can refuse without ending its session.\n * Set PI_ALLOW_SHARED_SESSION to resume anyway.\n */\nexport function getSessionOpenRefusal(path: string): string | undefined {\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return undefined;\n\tconst canonical = canonicalSessionPath(path);\n\tfor (const owner of collectLiveOwners()) {\n\t\tif (owner.pid === process.pid) continue;\n\t\tif (owner.sessions.includes(canonical))\n\t\t\treturn `This session is open in process ${owner.pid}. Close that Pi first, or set PI_ALLOW_SHARED_SESSION to resume anyway. Two writers on one session fork its history: only the branch written last stays visible.`;\n\t}\n\treturn undefined;\n}\n\ninterface LiveOwner {\n\tpid: number;\n\tsessions: unknown[];\n}\n\n/**\n * Owners that a record claims are running, after records proven stale are dropped. Removal is\n * idempotent and its failure is ignored, so this is safe with and without the ownership gate.\n * Records are written only by Pi in a directory only this user can read.\n */\nfunction collectLiveOwners(): LiveOwner[] {\n\tconst owners: LiveOwner[] = [];\n\tfor (const file of readdirSync(root)) {\n\t\tif (!/^\\d+\\.json$/.test(file)) continue;\n\t\tconst pid = Number(file.split(\".\")[0]);\n\t\tlet start: string | undefined;\n\t\ttry {\n\t\t\tstart = processIdentity(pid);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tconst record: unknown = JSON.parse(readFileSync(join(root, file), \"utf8\"));\n\t\tif (\n\t\t\t!record ||\n\t\t\ttypeof record !== \"object\" ||\n\t\t\t!(\"start\" in record) ||\n\t\t\t!(\"sessions\" in record) ||\n\t\t\t!Array.isArray(record.sessions)\n\t\t) {\n\t\t\tthrow new Error(`Invalid session ownership record: ${file}`);\n\t\t}\n\t\tif (record.start !== null) {\n\t\t\t// Linux records carry a start identity. A mismatch means another process reused the PID,\n\t\t\t// so the record is provably stale.\n\t\t\tif (start === undefined || record.start !== start) {\n\t\t\t\tremoveStaleRecord(join(root, file));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!processIsLive(pid)) {\n\t\t\t// Without a start identity, only a PID the OS confirms is gone proves the owner exited.\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\towners.push({ pid, sessions: record.sessions });\n\t}\n\treturn owners;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-ownership.js","sourceRoot":"","sources":["../../src/core/session-ownership.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,YAAY,EACZ,UAAU,EACV,SAAS,EACT,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM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AAC;IACjD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["// Coordinate session users and relocation within one local user account.\n\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmdirSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { canonicalizePath } from \"../utils/paths.ts\";\n\nconst root = join(tmpdir(), `pi-session-owners-${process.getuid?.() ?? \"user\"}`);\nconst sessions = new Map<string, number>();\nconst gateWait = new Int32Array(new SharedArrayBuffer(4));\nconst gateTimeoutMs = 2000;\nlet holdingGate = false;\n\n/** Serialize registration and moves; an abandoned gate fails closed rather than guessing. */\nexport function withSessionOwnershipGate<T>(operation: () => T): T {\n\tif (holdingGate) throw new Error(\"Session ownership operations cannot acquire the gate recursively.\");\n\tmkdirSync(root, { recursive: true, mode: 0o700 });\n\t// POSIX mode bits are only meaningful where they are reported. On Windows the per-user\n\t// temporary directory is the isolation boundary and lstat reports a fixed mode.\n\tconst info = lstatSync(root);\n\tconst uid = process.getuid?.();\n\tif (!info.isDirectory() || (uid !== undefined && (info.uid !== uid || (info.mode & 0o077) !== 0))) {\n\t\tthrow new Error(`Unsafe session ownership directory: ${root}`);\n\t}\n\tconst gate = join(root, \"gate\");\n\tconst deadline = performance.now() + gateTimeoutMs;\n\tfor (;;) {\n\t\ttry {\n\t\t\tmkdirSync(gate, { mode: 0o700 });\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\t\tconst remaining = deadline - performance.now();\n\t\t\tif (remaining <= 0) {\n\t\t\t\tthrow new Error(`Session ownership is busy. Retry later. If a process crashed, inspect ${gate}.`);\n\t\t\t}\n\t\t\t// SessionManager's API is synchronous. Wait only for other processes, never for work on this event loop.\n\t\t\tAtomics.wait(gateWait, 0, 0, Math.min(25, remaining));\n\t\t}\n\t}\n\tholdingGate = true;\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tholdingGate = false;\n\t\trmdirSync(gate);\n\t}\n}\n\n/** Register a manager's session before reading it, releasing its previous registration. */\nexport function changeSessionOwnership(previous: string | undefined, next: string | undefined): void {\n\tif (previous === next) return;\n\twithSessionOwnershipGate(() => {\n\t\tif (next && !existsSync(next) && existsSync(movedMarker(next)))\n\t\t\tthrow new Error(\"This session has moved. Refresh the session picker.\");\n\t\tconst updated = new Map(sessions);\n\t\tif (previous) {\n\t\t\tconst path = canonicalSessionPath(previous);\n\t\t\tconst count = updated.get(path) ?? 0;\n\t\t\tif (count <= 1) updated.delete(path);\n\t\t\telse updated.set(path, count - 1);\n\t\t}\n\t\tif (next) {\n\t\t\tconst path = canonicalSessionPath(next);\n\t\t\tupdated.set(path, (updated.get(path) ?? 0) + 1);\n\t\t}\n\t\t// A null start means the platform cannot distinguish a PID from a later process that reused it.\n\t\tconst temporary = join(root, `${process.pid}.tmp`);\n\t\twriteFileSync(\n\t\t\ttemporary,\n\t\t\tJSON.stringify({ start: processIdentity(process.pid) ?? null, sessions: [...updated.keys()] }),\n\t\t\t{ mode: 0o600 },\n\t\t);\n\t\trenameSync(temporary, join(root, `${process.pid}.json`));\n\t\tsessions.clear();\n\t\tfor (const [path, count] of updated) sessions.set(path, count);\n\t});\n}\n\n/** Hold a counted session reference during a synchronous read/copy/mutation operation. */\nexport function withSessionFileUsage<T>(path: string, operation: () => T): T {\n\tchangeSessionOwnership(undefined, path);\n\ttry {\n\t\treturn operation();\n\t} finally {\n\t\tchangeSessionOwnership(path, undefined);\n\t}\n}\n\nfunction canonicalSessionPath(path: string): string {\n\tconst absolute = resolve(path);\n\treturn canonicalizePath(join(canonicalizePath(dirname(absolute)), basename(absolute)));\n}\n\nfunction movedMarker(path: string): string {\n\treturn join(root, `${createHash(\"sha256\").update(canonicalSessionPath(path)).digest(\"hex\")}.moved`);\n}\n\n/** Prevent a concurrent opener from recreating the old path after relocation. */\nexport function markSessionMoved(path: string, destination: string): void {\n\twriteFileSync(movedMarker(path), destination, { mode: 0o600 });\n}\n\n/** Roll back a relocation marker when the source was not removed. */\nexport function unmarkSessionMoved(path: string): void {\n\tunlinkSync(movedMarker(path));\n}\n\n// Linux only: stat field 22 distinguishes a PID from a later process that reused it.\n// comm can contain spaces and parentheses, so fields are read after the last ')'.\nfunction linuxProcessStart(pid: number): string {\n\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\treturn stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n}\n\nconst processIdentity = process.platform === \"linux\" ? linuxProcessStart : () => undefined;\n\n/**\n * Drop a record whose owner is provably gone. This is cleanup only: a failed removal must never\n * affect the safety decision, because Windows can report EPERM or EBUSY for a file another\n * process still has open.\n */\nfunction removeStaleRecord(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {\n\t\t// The next move retries the cleanup. A surviving stale record only ever causes a refusal.\n\t}\n}\n\n/**\n * Report whether a recorded owner process is still running. Anything other than a confirmed\n * absence counts as running, including a permission error, so an uncertain check never allows\n * the operation. On non-Linux platforms a reused PID is indistinguishable and also counts as\n * running, which can refuse an operation that would have been safe.\n */\nfunction processIsLive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n\t}\n}\n\n/** Refuse live users of this file and, on Linux, untracked Pi processes. Caller must hold the ownership gate. */\nexport function assertSessionUnused(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"moving\");\n\t// Relocation splits a session across two paths if any process keeps the old one open, including\n\t// a process that cannot be inspected, so an untracked Pi blocks a move with no override.\n\t// Detecting Pi processes that predate ownership requires scanning the process table, and the\n\t// portable process list is not reliable enough to do so outside Linux. Those platforms only\n\t// enforce ownership registered by cooperating Pi instances.\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership. Close older Pi instances before moving.`,\n\t\t);\n}\n\n/**\n * Refuse a delete where the harm is proven, and allow an override where it is only possible. A live\n * process that registered this file always blocks it, with or without the override: deleting a session\n * out from under its writer is the same loss as forking its history. An untracked Pi cannot be\n * inspected at all, so it blocks too, but `PI_ALLOW_SHARED_SESSION` clears that case. Without the\n * override, one unrelated official Pi on Linux would make session cleanup impossible, and the worst\n * outcome it prevents is a process writing to a removed file rather than lost conversation.\n * Caller must hold the ownership gate.\n */\nexport function assertSessionDeletable(path: string): void {\n\tconst canonical = canonicalSessionPath(path);\n\tconst owners = collectLiveOwners();\n\trefuseWhileOpen(owners, canonical, \"deleting\");\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return;\n\tconst untracked = findUntrackedPiPid(owners);\n\tif (untracked !== undefined)\n\t\tthrow new Error(\n\t\t\t`Pi process ${untracked} does not report session ownership, so it may hold this session. Close it, or set PI_ALLOW_SHARED_SESSION to delete anyway.`,\n\t\t);\n}\n\nfunction refuseWhileOpen(owners: LiveOwner[], canonical: string, purpose: string): void {\n\tfor (const owner of owners) {\n\t\tif (owner.sessions.includes(canonical))\n\t\t\tthrow new Error(`Session is open in process ${owner.pid}. Close it before ${purpose}.`);\n\t}\n}\n\n/** First Pi process of this user that runs without an ownership record, if any. Linux only. */\nfunction findUntrackedPiPid(owners: LiveOwner[]): number | undefined {\n\tif (process.platform !== \"linux\") return undefined;\n\tconst registered = new Set(owners.map((owner) => owner.pid));\n\tconst processes = execFileSync(\"ps\", [\"-u\", String(process.getuid!()), \"-o\", \"pid=,comm=,args=\"], {\n\t\tencoding: \"utf8\",\n\t});\n\tfor (const line of processes.split(\"\\n\")) {\n\t\tconst match = line.trim().match(/^(\\d+)\\s+(\\S+)\\s+(.*)$/);\n\t\tif (!match) continue;\n\t\tconst pid = Number(match[1]);\n\t\tif (pid === process.pid || registered.has(pid)) continue;\n\t\tconst isPi =\n\t\t\tmatch[2] === \"pi\" ||\n\t\t\t/(?:^|\\s)\\S*(?:pi-coding-agent\\/(?:dist|src)\\/cli\\.(?:js|ts)|\\/pi\\/packages\\/coding-agent\\/src\\/cli\\.ts)(?:\\s|$)/.test(\n\t\t\t\tmatch[3],\n\t\t\t);\n\t\tif (isPi) return pid;\n\t}\n\treturn undefined;\n}\n\n/**\n * Refuse resuming a session a live Pi already holds. Appends carry the writer's own leaf, so two\n * writers on one file fork its history and a later read follows the branch that appended last,\n * hiding the other one without warning. This process's own registrations never refuse, so\n * re-selecting the current session stays a no-op and unrelated sessions are unaffected. Returns\n * the message instead of throwing so the interactive picker can refuse without ending its session.\n * Set PI_ALLOW_SHARED_SESSION to resume anyway.\n */\nexport function getSessionOpenRefusal(path: string): string | undefined {\n\tif (process.env.PI_ALLOW_SHARED_SESSION) return undefined;\n\tconst canonical = canonicalSessionPath(path);\n\tfor (const owner of collectLiveOwners()) {\n\t\tif (owner.pid === process.pid) continue;\n\t\tif (owner.sessions.includes(canonical))\n\t\t\treturn `This session is open in process ${owner.pid}. Close that Pi first, or set PI_ALLOW_SHARED_SESSION to resume anyway. Two writers on one session fork its history: only the branch written last stays visible.`;\n\t}\n\treturn undefined;\n}\n\ninterface LiveOwner {\n\tpid: number;\n\tsessions: unknown[];\n}\n\n/**\n * Owners that a record claims are running, after records proven stale are dropped. Removal is\n * idempotent and its failure is ignored, so this is safe with and without the ownership gate.\n * Records are written only by Pi in a directory only this user can read.\n */\nfunction collectLiveOwners(): LiveOwner[] {\n\tconst owners: LiveOwner[] = [];\n\tfor (const file of readdirSync(root)) {\n\t\tif (!/^\\d+\\.json$/.test(file)) continue;\n\t\tconst pid = Number(file.split(\".\")[0]);\n\t\tlet start: string | undefined;\n\t\ttry {\n\t\t\tstart = processIdentity(pid);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tlet raw: string;\n\t\ttry {\n\t\t\traw = readFileSync(join(root, file), \"utf8\");\n\t\t} catch (error) {\n\t\t\t// The owner removed its record after readdir listed it, which means it exited: the same\n\t\t\t// conclusion the missing-process check above reaches. Concurrent scanners hit this routinely,\n\t\t\t// and without it the scan throws, so every gate that asks who holds a session fails with a\n\t\t\t// filesystem error instead of an answer.\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\tconst record: unknown = JSON.parse(raw);\n\t\tif (\n\t\t\t!record ||\n\t\t\ttypeof record !== \"object\" ||\n\t\t\t!(\"start\" in record) ||\n\t\t\t!(\"sessions\" in record) ||\n\t\t\t!Array.isArray(record.sessions)\n\t\t) {\n\t\t\tthrow new Error(`Invalid session ownership record: ${file}`);\n\t\t}\n\t\tif (record.start !== null) {\n\t\t\t// Linux records carry a start identity. A mismatch means another process reused the PID,\n\t\t\t// so the record is provably stale.\n\t\t\tif (start === undefined || record.start !== start) {\n\t\t\t\tremoveStaleRecord(join(root, file));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (!processIsLive(pid)) {\n\t\t\t// Without a start identity, only a PID the OS confirms is gone proves the owner exited.\n\t\t\tremoveStaleRecord(join(root, file));\n\t\t\tcontinue;\n\t\t}\n\t\towners.push({ pid, sessions: record.sessions });\n\t}\n\treturn owners;\n}\n"]}
|
|
@@ -56,7 +56,7 @@ export declare const SETTINGS_DEFAULTS: {
|
|
|
56
56
|
readonly mode: "on";
|
|
57
57
|
readonly inlineBudget: 3000;
|
|
58
58
|
};
|
|
59
|
-
readonly cacheWarming: "
|
|
59
|
+
readonly cacheWarming: "idle";
|
|
60
60
|
readonly tuiMode: "fullscreen";
|
|
61
61
|
readonly fullscreenExitOutput: "transcript";
|
|
62
62
|
readonly fullscreenScrollbar: "auto";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-defaults.d.ts","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,mFAAmF;AACnF,eAAO,MAAM,iBAAiB;aAC7B,SAAS,EAAE,MAAM;aACjB,uBAAuB,EAAE,MAAM;aAC/B,YAAY,EAAE,eAAe;aAC7B,YAAY,EAAE,eAAe;aAC7B,UAAU;iBACT,OAAO;iBACP,aAAa,EAAE,KAAK;iBACpB,gBAAgB,EAAE,KAAK;;aAExB,aAAa;iBACZ,aAAa,EAAE,KAAK;iBACpB,UAAU;;aAEX,KAAK;iBACJ,OAAO;iBACP,UAAU,EAAE,CAAC;iBACb,WAAW,EAAE,IAAI;iBACjB,eAAe;iBACf,QAAQ;qBACP,eAAe,EAAE,KAAK;;;aAGxB,iBAAiB;aACjB,oBAAoB;aACpB,YAAY;aACZ,mBAAmB,EAAE,KAAK;aAC1B,iBAAiB;aACjB,sBAAsB;aACtB,eAAe;aACf,mBAAmB;aACnB,QAAQ;iBACP,UAAU;iBACV,eAAe,EAAE,EAAE;iBACnB,aAAa;iBACb,oBAAoB;;aAErB,MAAM;iBACL,UAAU;iBACV,WAAW;;aAEZ,kBAAkB,EAAE,MAAM;aAC1B,cAAc,EAAE,SAAS;aACzB,cAAc,EAAE,CAAC;aACjB,SAAS,EAAE,CAAC;aACZ,sBAAsB,EAAE,CAAC;aACzB,QAAQ;iBACP,eAAe,EAAE,IAAI;iBACrB,OAAO,EAAE,WAAW;;aAErB,QAAQ;iBACP,mBAAmB;;aAEpB,QAAQ;iBACP,IAAI,EAAE,IAAI;iBACV,YAAY,EAAE,IAAI;;aAEnB,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"settings-defaults.d.ts","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,mFAAmF;AACnF,eAAO,MAAM,iBAAiB;aAC7B,SAAS,EAAE,MAAM;aACjB,uBAAuB,EAAE,MAAM;aAC/B,YAAY,EAAE,eAAe;aAC7B,YAAY,EAAE,eAAe;aAC7B,UAAU;iBACT,OAAO;iBACP,aAAa,EAAE,KAAK;iBACpB,gBAAgB,EAAE,KAAK;;aAExB,aAAa;iBACZ,aAAa,EAAE,KAAK;iBACpB,UAAU;;aAEX,KAAK;iBACJ,OAAO;iBACP,UAAU,EAAE,CAAC;iBACb,WAAW,EAAE,IAAI;iBACjB,eAAe;iBACf,QAAQ;qBACP,eAAe,EAAE,KAAK;;;aAGxB,iBAAiB;aACjB,oBAAoB;aACpB,YAAY;aACZ,mBAAmB,EAAE,KAAK;aAC1B,iBAAiB;aACjB,sBAAsB;aACtB,eAAe;aACf,mBAAmB;aACnB,QAAQ;iBACP,UAAU;iBACV,eAAe,EAAE,EAAE;iBACnB,aAAa;iBACb,oBAAoB;;aAErB,MAAM;iBACL,UAAU;iBACV,WAAW;;aAEZ,kBAAkB,EAAE,MAAM;aAC1B,cAAc,EAAE,SAAS;aACzB,cAAc,EAAE,CAAC;aACjB,SAAS,EAAE,CAAC;aACZ,sBAAsB,EAAE,CAAC;aACzB,QAAQ;iBACP,eAAe,EAAE,IAAI;iBACrB,OAAO,EAAE,WAAW;;aAErB,QAAQ;iBACP,mBAAmB;;aAEpB,QAAQ;iBACP,IAAI,EAAE,IAAI;iBACV,YAAY,EAAE,IAAI;;aAEnB,YAAY,EAAE,MAAM;aACpB,OAAO,EAAE,YAAY;aACrB,oBAAoB,EAAE,YAAY;aAClC,mBAAmB,EAAE,MAAM;aAC3B,sBAAsB;aACtB,0BAA0B,EAAE,MAAM;CACzB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-defaults.js","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,mCAAmC,CAAC;AAErF,mFAAmF;AACnF,MAAM,CAAC,MAAM,iBAAiB,GAAG;I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,IAAI,EAAE,IAAI;QACV,YAAY,EAAE,IAAI;KAClB;IACD,YAAY,EAAE,MAAM;IACpB,OAAO,EAAE,YAAY;IACrB,oBAAoB,EAAE,YAAY;IAClC,mBAAmB,EAAE,MAAM;IAC3B,sBAAsB,EAAE,IAAI;IAC5B,0BAA0B,EAAE,MAAM;CACzB,CAAC","sourcesContent":["import { DEFAULT_MAX_AGENT_RETRY_DELAY_MS } from \"@earendil-works/pi-ai/utils/retry\";\n\n/** Runtime defaults shared by settings accessors and the published JSON Schema. */\nexport const SETTINGS_DEFAULTS = {\n\ttransport: \"auto\",\n\tsessionShareDestination: \"auto\",\n\tsteeringMode: \"one-at-a-time\",\n\tfollowUpMode: \"one-at-a-time\",\n\tcompaction: {\n\t\tenabled: true,\n\t\treserveTokens: 16384,\n\t\tkeepRecentTokens: 20000,\n\t},\n\tbranchSummary: {\n\t\treserveTokens: 16384,\n\t\tskipPrompt: false,\n\t},\n\tretry: {\n\t\tenabled: true,\n\t\tmaxRetries: 3,\n\t\tbaseDelayMs: 2000,\n\t\tmaxAgentDelayMs: DEFAULT_MAX_AGENT_RETRY_DELAY_MS,\n\t\tprovider: {\n\t\t\tmaxRetryDelayMs: 60000,\n\t\t},\n\t},\n\thideThinkingBlock: false,\n\tshowCacheMissNotices: false,\n\tquietStartup: false,\n\tdefaultProjectTrust: \"ask\",\n\tcollapseChangelog: false,\n\tenableInstallTelemetry: true,\n\tenableAnalytics: false,\n\tenableSkillCommands: true,\n\tterminal: {\n\t\tshowImages: true,\n\t\timageWidthCells: 60,\n\t\tclearOnShrink: false,\n\t\tshowTerminalProgress: false,\n\t},\n\timages: {\n\t\tautoResize: true,\n\t\tblockImages: false,\n\t},\n\tdoubleEscapeAction: \"tree\",\n\ttreeFilterMode: \"default\",\n\teditorPaddingX: 0,\n\toutputPad: 1,\n\tautocompleteMaxVisible: 5,\n\tmarkdown: {\n\t\tcodeBlockIndent: \" \",\n\t\tmermaid: \"streaming\",\n\t},\n\twarnings: {\n\t\tanthropicExtraUsage: true,\n\t},\n\tcodemode: {\n\t\tmode: \"on\",\n\t\tinlineBudget: 3000,\n\t},\n\tcacheWarming: \"idle\",\n\ttuiMode: \"fullscreen\",\n\tfullscreenExitOutput: \"transcript\",\n\tfullscreenScrollbar: \"auto\",\n\tfullscreenCopyOnSelect: true,\n\tfullscreenWheelScrollLines: \"auto\",\n} as const;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAIN,KAAK,WAAW,EAGhB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAoB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG/E,OAAO,EAAE,KAAK,gBAAgB,EAAsB,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAoBxG,QAAA,MAAM,UAAU;;;EAGd,CAAC;AAEH,eAAO,MAAM,gCAAgC;aAC5C,OAAO,EAAE,8CAA8C;aACvD,UAAU,YAAG,mFAAmF;CACvF,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD;;;GAGG;AACH,QAAA,MAAM,gBAAgB;;;;;;EAMpB,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAE7D,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;;;;OAOG;IACH,IAAI,EAAE,CACL,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;QACR,MAA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AAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,cAAc,EAAE,MAAM,CAAC;CACvB;AAED,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CA8KjF;AAYD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CAEjF;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC,OAAO,UAAU,CAAC,CAQ1G"}
|
package/dist/core/tools/bash.js
CHANGED
|
@@ -44,6 +44,18 @@ const bashOutputSchema = Type.Object({
|
|
|
44
44
|
exit_code: Type.Number(),
|
|
45
45
|
wall_time_seconds: Type.Number(),
|
|
46
46
|
});
|
|
47
|
+
/**
|
|
48
|
+
* Timeout of the local shell backend. Its message keeps the `timeout:<seconds>` form custom operations throw.
|
|
49
|
+
* `shellExit` is set when the shell itself exited before the deadline, so the tool was only still waiting
|
|
50
|
+
* because background processes kept writing to the inherited stdout/stderr pipes (#11613).
|
|
51
|
+
*/
|
|
52
|
+
class ShellTimeoutError extends Error {
|
|
53
|
+
shellExit;
|
|
54
|
+
constructor(timeout, shellExit) {
|
|
55
|
+
super(`timeout:${timeout}`);
|
|
56
|
+
this.shellExit = shellExit;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
47
59
|
/** Shared process execution used by the built-in shell tools. */
|
|
48
60
|
export function createLocalShellOperations(shellName, resolveShellConfig) {
|
|
49
61
|
return {
|
|
@@ -73,7 +85,13 @@ export function createLocalShellOperations(shellName, resolveShellConfig) {
|
|
|
73
85
|
}
|
|
74
86
|
if (child.pid)
|
|
75
87
|
trackDetachedChildPid(child.pid);
|
|
88
|
+
const startedAt = performance.now();
|
|
89
|
+
let shellExitedAfterMs;
|
|
90
|
+
child.once("exit", () => {
|
|
91
|
+
shellExitedAfterMs = performance.now() - startedAt;
|
|
92
|
+
});
|
|
76
93
|
let timedOut = false;
|
|
94
|
+
let exitedBeforeDeadlineAfterMs;
|
|
77
95
|
let timeoutHandle;
|
|
78
96
|
const onAbort = () => {
|
|
79
97
|
if (child.pid)
|
|
@@ -84,6 +102,9 @@ export function createLocalShellOperations(shellName, resolveShellConfig) {
|
|
|
84
102
|
if (timeoutMs !== undefined) {
|
|
85
103
|
timeoutHandle = setTimeout(() => {
|
|
86
104
|
timedOut = true;
|
|
105
|
+
exitedBeforeDeadlineAfterMs = shellExitedAfterMs;
|
|
106
|
+
// Also when the shell already exited: on Unix the group kill still reaches background
|
|
107
|
+
// processes holding the pipes. Windows cannot find them once the shell pid is gone.
|
|
87
108
|
if (child.pid)
|
|
88
109
|
killProcessTree(child.pid);
|
|
89
110
|
}, timeoutMs);
|
|
@@ -104,13 +125,16 @@ export function createLocalShellOperations(shellName, resolveShellConfig) {
|
|
|
104
125
|
if (signal?.aborted) {
|
|
105
126
|
throw new Error("aborted");
|
|
106
127
|
}
|
|
107
|
-
if (timedOut) {
|
|
108
|
-
throw new Error(`timeout:${timeout}`);
|
|
109
|
-
}
|
|
110
128
|
// A signal-killed shell has no exit code. Use the standard shell convention so
|
|
111
129
|
// callers do not mistake the termination for a successful command.
|
|
112
130
|
const signalCode = child.signalCode;
|
|
113
|
-
|
|
131
|
+
const resolvedExitCode = exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1);
|
|
132
|
+
if (timedOut) {
|
|
133
|
+
throw new ShellTimeoutError(timeout, exitedBeforeDeadlineAfterMs !== undefined
|
|
134
|
+
? { exitCode: resolvedExitCode, afterSeconds: Math.round(exitedBeforeDeadlineAfterMs / 100) / 10 }
|
|
135
|
+
: undefined);
|
|
136
|
+
}
|
|
137
|
+
return { exitCode: resolvedExitCode };
|
|
114
138
|
}
|
|
115
139
|
finally {
|
|
116
140
|
if (child.pid)
|
|
@@ -272,7 +296,13 @@ export function createShellToolDefinition(cwd, config, options) {
|
|
|
272
296
|
}
|
|
273
297
|
if (err instanceof Error && err.message.startsWith("timeout:")) {
|
|
274
298
|
const timeoutSecs = err.message.split(":")[1];
|
|
275
|
-
|
|
299
|
+
let status = `Command timed out after ${timeoutSecs} seconds`;
|
|
300
|
+
if (err instanceof ShellTimeoutError && err.shellExit) {
|
|
301
|
+
// Both facts matter: the command's real result, and that its background processes
|
|
302
|
+
// were still writing output when the timeout hit (#11613).
|
|
303
|
+
status += `. The shell exited with code ${err.shellExit.exitCode} after ${err.shellExit.afterSeconds} seconds, but background processes it started kept writing output until the timeout.`;
|
|
304
|
+
}
|
|
305
|
+
throw new Error(appendStatus(text, status));
|
|
276
306
|
}
|
|
277
307
|
throw err;
|
|
278
308
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EAEf,qBAAqB,EACrB,uBAAuB,G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AAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS, createShellRenderers } from \"./renderers/bash.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n/** Output limit of `structuredContent.output`, which programmatic callers such as codemode scripts receive. */\nconst STRUCTURED_OUTPUT_MAX_BYTES = 1024 * 1024;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.\n * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.\n */\nconst bashOutputSchema = Type.Object({\n\toutput: Type.String({ description: \"Combined stdout and stderr, possibly truncated\" }),\n\ttruncated: Type.Boolean(),\n\tfull_output_path: Type.Optional(Type.String({ description: \"Full output, when truncated\" })),\n\texit_code: Type.Number(),\n\twall_time_seconds: Type.Number(),\n});\n\nexport type BashToolOutput = Static<typeof bashOutputSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\treturn { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst startedAt = performance.now();\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode === null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, \"Command terminated without an exit code\"));\n\t\t\t\t}\n\t\t\t\tconst wallTimeSeconds = Math.round((performance.now() - startedAt) / 100) / 10;\n\t\t\t\tconst fullOutput = await output.readFullOutput(STRUCTURED_OUTPUT_MAX_BYTES);\n\t\t\t\tconst structuredContent: BashToolOutput = {\n\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t...(fullOutput.truncated && snapshot.fullOutputPath\n\t\t\t\t\t\t? { full_output_path: snapshot.fullOutputPath }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\twall_time_seconds: wallTimeSeconds,\n\t\t\t\t};\n\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: appendStatus(outputText, `Command exited with code ${exitCode}`) }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t\tstructuredContent,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details, structuredContent };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\t...createShellRenderers(config.prompt),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): TypeBoxAgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EAEf,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACpF,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,UAAU,EAAyB,MAAM,eAAe,CAAC;AAExG,MAAM,cAAc,GAAG,aAAa,CAAC;AACrC,+GAA+G;AAC/G,MAAM,2BAA2B,GAAG,IAAI,GAAG,IAAI,CAAC;AAChD,MAAM,mBAAmB,GAAG,cAAc,GAAG,IAAI,CAAC;AAElD,SAAS,gBAAgB,CAAC,OAA2B;IACpD,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,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ACD,GAAG,oBAAoB,CAAC,MAAM,CAAC,MAAM,CAAC;KACtC,CAAC;AACH,CAAC;AAED,MAAM,cAAc,GAAoB;IACvC,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,MAAM;IACb,SAAS,EAAE,MAAM;IACjB,MAAM,EAAE,GAAG;IACX,aAAa,EAAE,gCAAgC,CAAC,OAAO;IACvD,gBAAgB,EAAE,gCAAgC,CAAC,UAAU;IAC7D,cAAc,EAAE,SAAS;CACzB,CAAC;AAEF,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB;IAEzB,OAAO,yBAAyB,CAAC,GAAG,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,MAAM,UAAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS, createShellRenderers } from \"./renderers/bash.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n/** Output limit of `structuredContent.output`, which programmatic callers such as codemode scripts receive. */\nconst STRUCTURED_OUTPUT_MAX_BYTES = 1024 * 1024;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\n/**\n * Result for programmatic callers such as codemode scripts. A non-zero exit code is an error result for the model, but scripts still resolve to this value.\n * `output` is not limited like the model-facing output: callers decide how much of it reaches the model.\n */\nconst bashOutputSchema = Type.Object({\n\toutput: Type.String({ description: \"Combined stdout and stderr, possibly truncated\" }),\n\ttruncated: Type.Boolean(),\n\tfull_output_path: Type.Optional(Type.String({ description: \"Full output, when truncated\" })),\n\texit_code: Type.Number(),\n\twall_time_seconds: Type.Number(),\n});\n\nexport type BashToolOutput = Static<typeof bashOutputSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/**\n * Timeout of the local shell backend. Its message keeps the `timeout:<seconds>` form custom operations throw.\n * `shellExit` is set when the shell itself exited before the deadline, so the tool was only still waiting\n * because background processes kept writing to the inherited stdout/stderr pipes (#11613).\n */\nclass ShellTimeoutError extends Error {\n\treadonly shellExit: { exitCode: number; afterSeconds: number } | undefined;\n\n\tconstructor(timeout: number | undefined, shellExit: { exitCode: number; afterSeconds: number } | undefined) {\n\t\tsuper(`timeout:${timeout}`);\n\t\tthis.shellExit = shellExit;\n\t}\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tconst startedAt = performance.now();\n\t\t\tlet shellExitedAfterMs: number | undefined;\n\t\t\tchild.once(\"exit\", () => {\n\t\t\t\tshellExitedAfterMs = performance.now() - startedAt;\n\t\t\t});\n\t\t\tlet timedOut = false;\n\t\t\tlet exitedBeforeDeadlineAfterMs: number | undefined;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\texitedBeforeDeadlineAfterMs = shellExitedAfterMs;\n\t\t\t\t\t\t// Also when the shell already exited: on Unix the group kill still reaches background\n\t\t\t\t\t\t// processes holding the pipes. Windows cannot find them once the shell pid is gone.\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\tconst resolvedExitCode = exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1);\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new ShellTimeoutError(\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\texitedBeforeDeadlineAfterMs !== undefined\n\t\t\t\t\t\t\t? { exitCode: resolvedExitCode, afterSeconds: Math.round(exitedBeforeDeadlineAfterMs / 100) / 10 }\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { exitCode: resolvedExitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\t\t\tconst startedAt = performance.now();\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tlet status = `Command timed out after ${timeoutSecs} seconds`;\n\t\t\t\t\t\tif (err instanceof ShellTimeoutError && err.shellExit) {\n\t\t\t\t\t\t\t// Both facts matter: the command's real result, and that its background processes\n\t\t\t\t\t\t\t// were still writing output when the timeout hit (#11613).\n\t\t\t\t\t\t\tstatus += `. The shell exited with code ${err.shellExit.exitCode} after ${err.shellExit.afterSeconds} seconds, but background processes it started kept writing output until the timeout.`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new Error(appendStatus(text, status));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode === null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, \"Command terminated without an exit code\"));\n\t\t\t\t}\n\t\t\t\tconst wallTimeSeconds = Math.round((performance.now() - startedAt) / 100) / 10;\n\t\t\t\tconst fullOutput = await output.readFullOutput(STRUCTURED_OUTPUT_MAX_BYTES);\n\t\t\t\tconst structuredContent: BashToolOutput = {\n\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t...(fullOutput.truncated && snapshot.fullOutputPath\n\t\t\t\t\t\t? { full_output_path: snapshot.fullOutputPath }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\twall_time_seconds: wallTimeSeconds,\n\t\t\t\t};\n\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: appendStatus(outputText, `Command exited with code ${exitCode}`) }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t\tstructuredContent,\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details, structuredContent };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\t...createShellRenderers(config.prompt),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): TypeBoxAgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared diff computation utilities for the edit and similar tools.
|
|
3
3
|
*/
|
|
4
|
-
export declare function detectLineEnding(content: string): "\r\n" | "\n";
|
|
5
4
|
export declare function normalizeToLF(text: string): string;
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Apply replacements matched in `normalizeToLF(originalContent)` to `originalContent` itself.
|
|
7
|
+
* Text outside the replaced ranges keeps its bytes, including its line endings. Line breaks in
|
|
8
|
+
* the new text get the line ending of the line where the replaced range starts. The result,
|
|
9
|
+
* normalized to LF, equals the replacements applied to the normalized content.
|
|
10
|
+
*/
|
|
11
|
+
export declare function applyReplacementsToOriginal(originalContent: string, replacements: TextReplacement[]): string;
|
|
7
12
|
/**
|
|
8
13
|
* Normalize text for fuzzy matching. Applies progressive transformations:
|
|
9
14
|
* - Strip trailing whitespace from each line
|
|
@@ -18,18 +23,8 @@ interface MatchedEdit {
|
|
|
18
23
|
matchLength: number;
|
|
19
24
|
newText: string;
|
|
20
25
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
* Apply replacements matched against `baseContent` to `originalContent` while
|
|
24
|
-
* preserving unchanged line blocks from the original.
|
|
25
|
-
*
|
|
26
|
-
* This is useful when `baseContent` is a normalized view of the original. Each
|
|
27
|
-
* replacement is widened to the lines it actually touches, those touched lines
|
|
28
|
-
* are rewritten from the normalized base, and all other lines are copied back
|
|
29
|
-
* from `originalContent`. The actual replacement ranges drive preservation so
|
|
30
|
-
* duplicate normalized lines cannot be aligned to the wrong occurrence.
|
|
31
|
-
*/
|
|
32
|
-
export declare function applyReplacementsPreservingUnchangedLines(originalContent: string, baseContent: string, replacements: TextReplacement[]): string;
|
|
26
|
+
/** Replacement of `matchLength` characters at `matchIndex` with `newText`. */
|
|
27
|
+
export type TextReplacement = Pick<MatchedEdit, "matchIndex" | "matchLength" | "newText">;
|
|
33
28
|
export interface FuzzyMatchResult {
|
|
34
29
|
/** Whether a match was found */
|
|
35
30
|
found: boolean;
|
|
@@ -52,6 +47,8 @@ export interface Edit {
|
|
|
52
47
|
export interface AppliedEditsResult {
|
|
53
48
|
baseContent: string;
|
|
54
49
|
newContent: string;
|
|
50
|
+
/** Sorted replacements of `baseContent` that turn it into `newContent` */
|
|
51
|
+
replacements: TextReplacement[];
|
|
55
52
|
}
|
|
56
53
|
/**
|
|
57
54
|
* Find oldText in content, trying exact match first, then fuzzy match.
|
|
@@ -80,6 +77,18 @@ export declare function generateDiffString(oldContent: string, newContent: strin
|
|
|
80
77
|
diff: string;
|
|
81
78
|
firstChangedLine: number | undefined;
|
|
82
79
|
};
|
|
80
|
+
/** Display diff and unified patch of an edit, as returned in the edit tool's details. */
|
|
81
|
+
export interface EditDiff {
|
|
82
|
+
diff: string;
|
|
83
|
+
patch: string;
|
|
84
|
+
firstChangedLine: number | undefined;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Diff an edit only around its replacements, so time and memory follow the size of the change instead of
|
|
88
|
+
* the file. The result matches generateDiffString and generateUnifiedPatch over the whole contents, except
|
|
89
|
+
* that jsdiff may align runs of repeated lines differently within a window.
|
|
90
|
+
*/
|
|
91
|
+
export declare function generateEditDiff(path: string, baseContent: string, newContent: string, replacements: TextReplacement[], contextLines?: number): EditDiff;
|
|
83
92
|
export interface EditDiffResult {
|
|
84
93
|
diff: string;
|
|
85
94
|
firstChangedLine: number | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAQH,wBAAgB,
|
|
1
|
+
{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAQH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,eAAe,EAAE,MAAM,EAAE,YAAY,EAAE,eAAe,EAAE,GAAG,MAAM,CAmC5G;AAcD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB3D;AAWD,UAAU,WAAW;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,8EAA8E;AAC9E,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,WAAW,EAAE,YAAY,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC;AAmG1F,MAAM,WAAW,gBAAgB;IAChC,gCAAgC;IAChC,KAAK,EAAE,OAAO,CAAC;IACf,4FAA4F;IAC5F,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IA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