Skip to main content

artifactize_tools/builtin/
fixed.rs

1//! Fixed tool parsing and scoped text execution shared by every caller.
2use super::input::{List, LogicalPath};
3use crate::{
4    Builtin, Content, ToolResult,
5    launch::Launcher,
6    scope::{ArtifactId, Scope},
7};
8use serde::Deserialize;
9use serde_json::Value;
10use std::{
11    ffi::OsString,
12    io::Read,
13    path::{Path, PathBuf},
14};
15use tokio_util::sync::CancellationToken;
16
17mod declaration;
18mod help;
19mod markdown;
20pub use declaration::{fixed_description, fixed_schema, is_url, validate_args, validate_target};
21use help::help;
22use markdown::section;
23/// Fixed text tools contribute at most one 64 KiB block to a review.
24const TEXT_BYTES: usize = 64 * 1024;
25/// Bound Markdown parsing, including a section near the end of the document.
26const DOCUMENT_BYTES: usize = 8 * 1024 * 1024;
27/// Read one byte past the cap to distinguish an exact fit from truncated input.
28const OVERFLOW_PROBE_BYTES: usize = 1;
29
30/// Where a fixed built-in runs: the workspace root, the scope it may read, the Artifact
31/// that declares it, and the launcher that starts a `help` program.
32pub struct Context<'a> {
33    pub root: &'a Path,
34    pub scope: &'a Scope,
35    pub owner: &'a ArtifactId,
36    pub launcher: &'a dyn Launcher,
37}
38
39pub async fn call_fixed(
40    builtin: Builtin,
41    args: &[String],
42    input: Value,
43    context: Context<'_>,
44    cancellation: &CancellationToken,
45) -> ToolResult {
46    if cancellation.is_cancelled() {
47        return ToolResult::error("Tool call was cancelled.");
48    }
49    let input = match FixedInput::parse(builtin, args, input) {
50        Ok(input) => input,
51        Err(error) => return ToolResult::error(error),
52    };
53    execute(input, context, cancellation).await
54}
55
56pub(crate) async fn execute(
57    input: FixedInput,
58    context: Context<'_>,
59    cancellation: &CancellationToken,
60) -> ToolResult {
61    if cancellation.is_cancelled() {
62        return ToolResult::error("Tool call was cancelled.");
63    }
64    let Context {
65        root,
66        scope,
67        owner,
68        launcher,
69    } = context;
70    let input = match input.0 {
71        Invocation::Text(input) => input,
72        Invocation::Help { program, args } => {
73            let cwd = match scope
74                .artifact(owner)
75                .and_then(|artifact| artifact.native_folder(root))
76            {
77                Ok(cwd) => cwd,
78                Err(error) => return ToolResult::error(error.to_string()),
79            };
80            return match help(&program, args, &cwd, launcher, cancellation).await {
81                Ok(text) => text_result(text),
82                Err(error) => ToolResult::error(bounded(&error)),
83            };
84        }
85    };
86    let root = root.to_owned();
87    let scope = Scope {
88        artifacts: scope.artifacts.clone(),
89    };
90    let owner = owner.clone();
91    let cancellation = cancellation.child_token();
92    let _cancel_on_drop = cancellation.clone().drop_guard();
93    tokio::task::spawn_blocking(move || call_text(input, &root, &scope, &owner, &cancellation))
94        .await
95        .unwrap_or_else(|error| {
96            if error.is_panic() {
97                std::panic::resume_unwind(error.into_panic());
98            }
99            ToolResult::error("Built-in tool execution failed.")
100        })
101}
102
103/// The model's input to a fixed `section` tool: the heading, when the declaration leaves
104/// it open.
105#[derive(Deserialize)]
106#[serde(deny_unknown_fields)]
107struct SectionInput {
108    heading: Option<String>,
109}
110
111/// Parsed fixed declarations and model input. Execution cannot index an absent argument
112/// or combine a heading with a tool that does not accept one.
113pub(crate) struct FixedInput(Invocation);
114
115enum Invocation {
116    Text(TextInput),
117    Help {
118        program: PathBuf,
119        args: Vec<OsString>,
120    },
121}
122
123enum TextInput {
124    Read { path: LogicalPath },
125    List(List),
126    Section { path: LogicalPath, heading: String },
127}
128
129impl FixedInput {
130    fn text(input: TextInput) -> Self {
131        Self(Invocation::Text(input))
132    }
133
134    pub(crate) fn read(path: LogicalPath) -> Result<Self, String> {
135        Ok(Self::text(TextInput::Read { path }))
136    }
137
138    pub(crate) fn list(path: LogicalPath) -> Result<Self, String> {
139        Ok(Self::text(TextInput::List(List {
140            path,
141            offset: 0,
142            limit: super::MAX_RESULTS,
143        })))
144    }
145
146    pub(crate) fn section(path: LogicalPath, heading: String) -> Result<Self, String> {
147        declaration::validate_heading(&heading)?;
148        Ok(Self::text(TextInput::Section { path, heading }))
149    }
150
151    fn with_heading(path: String, heading: String) -> Result<Self, String> {
152        Ok(Self::text(TextInput::Section {
153            path: LogicalPath::parse(path)?,
154            heading,
155        }))
156    }
157
158    /// Help for a program and its subcommands as the command line gave them, native strings
159    /// kept: the program is a native path, never shown text to decode.
160    pub(crate) fn native_help(args: Vec<OsString>) -> Result<Self, String> {
161        let mut args = args.into_iter();
162        let program = args
163            .next()
164            .filter(|program| {
165                !program.is_empty()
166                    && !program
167                        .as_encoded_bytes()
168                        .iter()
169                        .all(u8::is_ascii_whitespace)
170            })
171            .ok_or("Invalid fixed args for this builtin/kind.")?;
172        let args: Vec<OsString> = args.collect();
173        if std::iter::once(&program)
174            .chain(&args)
175            .any(|arg| arg.as_encoded_bytes().contains(&0))
176        {
177            return Err("Invalid fixed args for this builtin/kind.".into());
178        }
179        Ok(Self(Invocation::Help {
180            program: PathBuf::from(program),
181            args,
182        }))
183    }
184
185    fn with_help(args: &[String]) -> Result<Self, String> {
186        let (program, args) = args
187            .split_first()
188            .expect("validated help requires a program");
189        // A program given as shown path text (encoded or verbatim) is read back to its native
190        // path before the lookup.
191        let program = crate::files::path_from_text(program).map_err(|error| error.to_string())?;
192        Ok(Self(Invocation::Help {
193            program,
194            args: args.iter().map(OsString::from).collect(),
195        }))
196    }
197
198    fn parse(builtin: Builtin, args: &[String], value: Value) -> Result<Self, String> {
199        validate_args(builtin, Some(args), false)?;
200        let validator = crate::schema::compile(&fixed_schema(builtin, args))?;
201        crate::schema::validate(&validator, &value)?;
202        let path = || {
203            args.first()
204                .expect("validated builtin requires a target")
205                .clone()
206        };
207        match builtin {
208            Builtin::Read => Self::read(LogicalPath::parse(path())?),
209            Builtin::List => Self::list(LogicalPath::parse(path())?),
210            Builtin::Section => {
211                let input: SectionInput = serde_json::from_value(value)
212                    .map_err(|_| "Tool arguments cannot be read as the declared builtin input.")?;
213                let heading = args
214                    .get(1)
215                    .cloned()
216                    .or(input.heading)
217                    .expect("validated section requires a heading");
218                Self::with_heading(path(), heading)
219            }
220            Builtin::Help => Self::with_help(args),
221            _ => Err("This builtin cannot run as a fixed Agent tool.".into()),
222        }
223    }
224}
225
226fn call_text(
227    input: TextInput,
228    root: &Path,
229    scope: &Scope,
230    owner: &ArtifactId,
231    cancellation: &CancellationToken,
232) -> ToolResult {
233    let result = match input {
234        TextInput::Read { path } => read_text(root, scope, owner, &path, ReadKind::Excerpt),
235        TextInput::Section { path, heading } => {
236            read_text(root, scope, owner, &path, ReadKind::Document)
237                .and_then(|text| section(&text, &heading))
238        }
239        TextInput::List(input) => {
240            return super::call(super::Input::List(input), root, scope, owner, cancellation);
241        }
242    };
243    if cancellation.is_cancelled() {
244        return ToolResult::error("Tool call was cancelled.");
245    }
246    match result {
247        Ok(text) => text_result(text),
248        Err(error) => ToolResult::error(error),
249    }
250}
251
252fn text_result(text: String) -> ToolResult {
253    ToolResult::success(Content::Text { text })
254}
255
256#[derive(Clone, Copy)]
257enum ReadKind {
258    Excerpt,
259    Document,
260}
261
262impl ReadKind {
263    fn limit(self) -> usize {
264        match self {
265            Self::Excerpt => TEXT_BYTES,
266            Self::Document => DOCUMENT_BYTES,
267        }
268    }
269}
270
271fn read_text(
272    root: &Path,
273    scope: &Scope,
274    owner: &ArtifactId,
275    path: &LogicalPath,
276    kind: ReadKind,
277) -> Result<String, String> {
278    let path = path.resolve(scope, owner, false)?;
279    let location = scope
280        .locate(owner, path)
281        .map_err(|error| error.to_string())?;
282    let (path, file) = location
283        .open_direct(root)
284        .map_err(|error| error.to_string())?;
285    if !file
286        .metadata()
287        .map_err(|error| error.to_string())?
288        .is_file()
289    {
290        return Err("Reading requires a regular file.".into());
291    }
292    let file = crate::artf::reader(file, path.as_ref()).map_err(|error| error.to_string())?;
293    let mut bytes = Vec::new();
294    file.take((kind.limit() + OVERFLOW_PROBE_BYTES) as u64)
295        .read_to_end(&mut bytes)
296        .map_err(|error| error.to_string())?;
297    text_from_bytes(bytes, kind)
298}
299
300fn text_from_bytes(bytes: Vec<u8>, kind: ReadKind) -> Result<String, String> {
301    if bytes.contains(&0) {
302        return Err("Reading requires UTF-8 text, not binary data.".into());
303    }
304    let overflow = bytes.len() > kind.limit();
305    if overflow && matches!(kind, ReadKind::Document) {
306        return Err("Markdown document exceeds 8 MiB.".into());
307    }
308    let text = match String::from_utf8(bytes) {
309        Ok(text) => text,
310        // Only an incomplete trailing UTF-8 sequence may be omitted at the byte boundary.
311        Err(error) if overflow && error.utf8_error().error_len().is_none() => {
312            let end = error.utf8_error().valid_up_to();
313            let mut bytes = error.into_bytes();
314            bytes.truncate(end);
315            String::from_utf8(bytes).expect("valid UTF-8 prefix")
316        }
317        Err(_) => return Err("Reading requires UTF-8 text.".into()),
318    };
319    Ok(if overflow { truncated(&text) } else { text })
320}
321
322fn bounded(text: &str) -> String {
323    if text.len() <= TEXT_BYTES {
324        return text.to_owned();
325    }
326    truncated(text)
327}
328
329fn truncated(text: &str) -> String {
330    let suffix = "\n[output truncated]";
331    let end = text.floor_char_boundary((TEXT_BYTES - suffix.len()).min(text.len()));
332    format!("{}{suffix}", &text[..end])
333}