Skip to main content

tea_coding_tools/bash/
mod.rs

1mod command;
2mod output;
3mod process;
4#[cfg(unix)]
5mod unix;
6#[cfg(windows)]
7mod windows;
8
9#[cfg(unix)]
10use unix as platform;
11#[cfg(windows)]
12use windows as platform;
13
14use std::str::FromStr;
15
16use serde_json::json;
17use tea_control::CancellationScope;
18use tea_protocol::ToolIdempotency;
19use tea_tools::{
20    BoxToolExecutionStream, ToolConcurrency, ToolEffect, ToolExecutionSemantics, ToolExecutor,
21    ToolName, ToolResource, ToolResourceAccess, ToolResourceError, ToolRetrySafety, ToolSpec,
22    ToolSpecError, ToolTimeout, ToolVersion, ValidatedToolInvocation,
23};
24
25pub use command::{BashConfig, BashOutputDirectory, BashShell};
26
27use crate::{FileToolError, FileToolErrorCode, WorkspaceRoot};
28
29/// Workspace-confined bounded shell executor.
30#[derive(Debug, Clone)]
31pub struct BashTool {
32    workspace: WorkspaceRoot,
33    config: BashConfig,
34}
35
36impl BashTool {
37    /// Creates a shell executor from explicit host-owned configuration.
38    #[must_use]
39    pub const fn new(workspace: WorkspaceRoot, config: BashConfig) -> Self {
40        Self { workspace, config }
41    }
42
43    /// Returns the workspace process resource declared by every invocation.
44    ///
45    /// # Errors
46    ///
47    /// Returns an error only if the static resource violates tool bounds.
48    pub fn workspace_resource() -> Result<ToolResource, ToolResourceError> {
49        ToolResource::new("file", "/workspace", ToolResourceAccess::Execute)
50    }
51
52    /// Builds the portable `bash` contract.
53    ///
54    /// # Errors
55    ///
56    /// Returns an error only if the static contract violates tool bounds.
57    pub fn spec() -> Result<ToolSpec, ToolSpecError> {
58        ToolSpec::new(
59            ToolName::from_str("bash").map_err(|_| ToolSpecError::InvalidDescription)?,
60            ToolVersion::from_str("1.0.0").map_err(|_| ToolSpecError::InvalidDescription)?,
61            "Run a command through the configured shell in the workspace.",
62            json!({"type":"object","properties":{"command":{"type":"string","minLength":1,"maxLength":65536}},"required":["command"],"additionalProperties":false}),
63            json!({"type":"object","properties":{"stdout":{"type":"string"},"stderr":{"type":"string"},"exitCode":{"type":["integer","null"]},"success":{"type":"boolean"},"truncated":{"type":"boolean"},"overflowReference":{"type":["string","null"]}},"required":["stdout","stderr","exitCode","success","truncated","overflowReference"],"additionalProperties":false}),
64            [ToolEffect::ProcessSpawn],
65            ToolExecutionSemantics::new(
66                ToolIdempotency::NonIdempotent,
67                ToolRetrySafety::Never,
68                ToolConcurrency::Serial,
69                ToolTimeout::from_millis(120_000)?,
70            )?,
71        )?
72        .with_prompt_hint("Commands run in the workspace through a host-configured shell; cancellation after spawn is uncertain.")
73    }
74}
75
76impl ToolExecutor for BashTool {
77    fn execute(
78        &self,
79        invocation: ValidatedToolInvocation,
80        cancellation: CancellationScope,
81    ) -> BoxToolExecutionStream {
82        let command = invocation
83            .arguments()
84            .get("command")
85            .and_then(serde_json::Value::as_str)
86            .filter(|command| !command.is_empty() && command.len() <= 65_536)
87            .map(str::to_owned);
88        match command {
89            Some(command) => process::execute_process(
90                self.workspace.clone(),
91                self.config.clone(),
92                command,
93                cancellation,
94            ),
95            None => Box::pin(futures_util::stream::iter([
96                tea_tools::ToolExecutionEvent::Failed(
97                    tea_tools::ToolExecutionFailure::execution(
98                        FileToolError::new(FileToolErrorCode::InvalidArguments).message(),
99                    )
100                    .unwrap_or_else(|_| tea_tools::ToolExecutionFailure::internal_contract()),
101                ),
102            ])),
103        }
104    }
105}