Skip to main content

tea_coding_tools/
read.rs

1use std::str::FromStr;
2
3use futures_util::stream;
4use serde_json::json;
5use tea_control::CancellationScope;
6use tea_protocol::ToolIdempotency;
7use tea_tools::{
8    BoxToolExecutionStream, ToolConcurrency, ToolEffect, ToolExecutionEvent,
9    ToolExecutionSemantics, ToolExecutor, ToolName, ToolRetrySafety, ToolSpec, ToolSpecError,
10    ToolTimeout, ToolVersion, ValidatedToolInvocation,
11};
12
13use crate::file::{DEFAULT_READ_LINE_LIMIT, MAX_READ_LINE_LIMIT, read_utf8};
14use crate::output::{failure, success};
15use crate::{FileToolError, FileToolErrorCode, WorkspaceRoot};
16
17/// Workspace-confined bounded UTF-8 text reader.
18#[derive(Debug, Clone)]
19pub struct ReadTool {
20    workspace: WorkspaceRoot,
21}
22
23impl ReadTool {
24    /// Creates a reader bound to one validated workspace capability.
25    #[must_use]
26    pub const fn new(workspace: WorkspaceRoot) -> Self {
27        Self { workspace }
28    }
29
30    /// Builds the portable `read` tool contract.
31    ///
32    /// # Errors
33    ///
34    /// Returns an error only if the static contract violates tool bounds.
35    pub fn spec() -> Result<ToolSpec, ToolSpecError> {
36        ToolSpec::new(
37            ToolName::from_str("read").map_err(|_| ToolSpecError::InvalidDescription)?,
38            ToolVersion::from_str("1.0.0").map_err(|_| ToolSpecError::InvalidDescription)?,
39            "Read bounded UTF-8 text from one workspace file.",
40            json!({
41                "type":"object",
42                "properties":{
43                    "path":{"type":"string","minLength":1,"maxLength":4096},
44                    "offset":{"type":"integer","minimum":1},
45                    "limit":{"type":"integer","minimum":1,"maximum":MAX_READ_LINE_LIMIT}
46                },
47                "required":["path"],
48                "additionalProperties":false
49            }),
50            json!({
51                "type":"object",
52                "properties":{
53                    "path":{"type":"string"},
54                    "content":{"type":"string"},
55                    "startLine":{"type":"integer","minimum":1},
56                    "endLine":{"type":"integer","minimum":0},
57                    "totalLines":{"type":"integer","minimum":0},
58                    "truncated":{"type":"boolean"}
59                },
60                "required":["path","content","startLine","endLine","totalLines","truncated"],
61                "additionalProperties":false
62            }),
63            [ToolEffect::FsRead],
64            ToolExecutionSemantics::new(
65                ToolIdempotency::Idempotent,
66                ToolRetrySafety::Automatic,
67                ToolConcurrency::Parallel,
68                ToolTimeout::from_millis(30_000)?,
69            )?,
70        )?
71        .with_prompt_hint(
72            "Use read with workspace-relative paths; offset and limit are 1-based lines.",
73        )
74    }
75
76    fn run(
77        &self,
78        invocation: &ValidatedToolInvocation,
79    ) -> Result<ToolExecutionEvent, FileToolError> {
80        let path = string_argument(invocation, "path")?;
81        let offset = integer_argument(invocation, "offset")?.unwrap_or(1);
82        let limit = integer_argument(invocation, "limit")?.unwrap_or(DEFAULT_READ_LINE_LIMIT);
83        let target = self.workspace.resolve_existing(path)?;
84        let source = read_utf8(&self.workspace, &target, crate::MAX_READ_BYTES)?;
85        let lines = source.split_inclusive('\n').collect::<Vec<_>>();
86        let start_index = offset.saturating_sub(1).min(lines.len());
87        let end_index = start_index.saturating_add(limit).min(lines.len());
88        let content = lines[start_index..end_index].concat();
89        let end_line = if end_index == start_index {
90            0
91        } else {
92            end_index
93        };
94        let truncated = start_index > 0 || end_index < lines.len();
95        let visible = if content.is_empty() {
96            "(empty text result)".to_owned()
97        } else {
98            content.clone()
99        };
100        Ok(success(
101            visible,
102            json!({
103                "path":target.display_path(),
104                "content":content,
105                "startLine":offset,
106                "endLine":end_line,
107                "totalLines":lines.len(),
108                "truncated":truncated
109            }),
110        ))
111    }
112}
113
114impl ToolExecutor for ReadTool {
115    fn execute(
116        &self,
117        invocation: ValidatedToolInvocation,
118        cancellation: CancellationScope,
119    ) -> BoxToolExecutionStream {
120        let executor = self.clone();
121        Box::pin(stream::once(async move {
122            if cancellation.is_cancelled() {
123                ToolExecutionEvent::Failed(tea_tools::ToolExecutionFailure::cancelled())
124            } else {
125                executor.run(&invocation).unwrap_or_else(failure)
126            }
127        }))
128    }
129}
130
131pub(crate) fn string_argument<'a>(
132    invocation: &'a ValidatedToolInvocation,
133    name: &str,
134) -> Result<&'a str, FileToolError> {
135    invocation
136        .arguments()
137        .get(name)
138        .and_then(serde_json::Value::as_str)
139        .ok_or_else(|| FileToolError::new(FileToolErrorCode::InvalidArguments))
140}
141
142fn integer_argument(
143    invocation: &ValidatedToolInvocation,
144    name: &str,
145) -> Result<Option<usize>, FileToolError> {
146    invocation
147        .arguments()
148        .get(name)
149        .map(|value| {
150            value
151                .as_u64()
152                .and_then(|value| usize::try_from(value).ok())
153                .ok_or_else(|| FileToolError::new(FileToolErrorCode::InvalidArguments))
154        })
155        .transpose()
156}