Skip to main content

aither_sandbox/builtin/
terminal.rs

1//! The control tools of a shell's jobs: read, input and kill.
2//!
3//! The embedder names and describes each; the texts they return are its
4//! wording's.
5
6use std::borrow::Cow;
7use std::collections::BTreeMap;
8
9use aither_core::llm::ToolContext;
10use aither_core::llm::{Tool, ToolResult};
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14use crate::job_registry::{JobInputError, JobRead, UnchangedRead};
15use crate::jobs::Jobs;
16use crate::wording::{AnyShellWording, CallRefusal, JobInputSent, JobKillAsked, Refused};
17
18/// What an embedder calls one of its tools and how it describes it to the
19/// model; neither has a default.
20#[derive(Debug, Clone)]
21pub struct ToolIdentity {
22    /// The tool's name.
23    pub name: Cow<'static, str>,
24    /// The tool's description, as the model reads it.
25    pub description: Cow<'static, str>,
26    /// What the model reads about each argument the tool takes, by argument
27    /// name. An argument the tool takes and this lacks crashes the tool's
28    /// schema: the arguments carry no descriptions of their own.
29    pub arguments: BTreeMap<&'static str, Cow<'static, str>>,
30}
31
32impl ToolIdentity {
33    /// `schema` with every property described as this identity says.
34    ///
35    /// # Panics
36    /// Panics when a property of the schema has no description here.
37    #[must_use]
38    pub(crate) fn describe(&self, schema: schemars::Schema) -> schemars::Schema {
39        let mut value = schema.to_value();
40        self.describe_properties(&mut value);
41        schemars::Schema::try_from(value).expect("a described schema is a schema")
42    }
43
44    fn describe_properties(&self, value: &mut serde_json::Value) {
45        match value {
46            serde_json::Value::Object(object) => {
47                if let Some(serde_json::Value::Object(properties)) = object.get_mut("properties") {
48                    for (name, property) in properties {
49                        let description = self.arguments.get(name.as_str()).unwrap_or_else(|| {
50                            panic!(
51                                "the identity of the tool `{}` describes no argument `{name}`",
52                                self.name
53                            )
54                        });
55                        if let serde_json::Value::Object(property) = property {
56                            property.insert(
57                                "description".to_owned(),
58                                serde_json::Value::String(description.to_string()),
59                            );
60                        }
61                    }
62                }
63                for child in object.values_mut() {
64                    self.describe_properties(child);
65                }
66            }
67            serde_json::Value::Array(items) => {
68                for item in items {
69                    self.describe_properties(item);
70                }
71            }
72            _ => {}
73        }
74    }
75}
76
77/// The identities of the shell tool and of the three job control tools.
78#[derive(Debug, Clone)]
79pub struct ShellToolSettings {
80    /// The tool that runs a script.
81    pub shell: ToolIdentity,
82    /// The tool that reads a job's output.
83    pub read: ToolIdentity,
84    /// The tool that writes to a job's stdin.
85    pub input: ToolIdentity,
86    /// The tool that kills a job.
87    pub kill: ToolIdentity,
88}
89
90fn task_id<'a>(argument: &'a str, wording: &AnyShellWording) -> aither_core::Result<&'a str> {
91    let task_id = argument.trim();
92    if task_id.is_empty() {
93        return Err(Refused::call(&**wording, CallRefusal::EmptyTaskId));
94    }
95    Ok(task_id)
96}
97
98fn unknown_task(task_id: &str, wording: &AnyShellWording) -> anyhow::Error {
99    Refused::call(
100        &**wording,
101        CallRefusal::UnknownTask {
102            task_id: task_id.to_owned(),
103        },
104    )
105}
106
107/// Tool for killing a job.
108#[derive(Debug, Clone)]
109pub struct JobKillTool {
110    identity: ToolIdentity,
111    jobs: Jobs,
112    wording: AnyShellWording,
113}
114
115impl JobKillTool {
116    /// A kill tool for `jobs`, named and described by `identity`, whose
117    /// reply is `wording`'s.
118    #[must_use]
119    pub const fn new(identity: ToolIdentity, jobs: Jobs, wording: AnyShellWording) -> Self {
120        Self {
121            identity,
122            jobs,
123            wording,
124        }
125    }
126}
127
128// The arguments of the kill tool, described by its `ToolIdentity`.
129#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
130#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
131pub struct JobKillArgs {
132    // The job to kill.
133    pub task_id: String,
134}
135
136impl Tool for JobKillTool {
137    fn name(&self) -> Cow<'static, str> {
138        self.identity.name.clone()
139    }
140
141    fn description(&self) -> Cow<'static, str> {
142        self.identity.description.clone()
143    }
144
145    fn arguments_schema(&self) -> schemars::Schema {
146        self.identity.describe(schemars::schema_for!(JobKillArgs))
147    }
148
149    type Arguments = JobKillArgs;
150    type Res = ToolResult;
151
152    async fn call(
153        &self,
154        args: Self::Arguments,
155        _cx: ToolContext,
156    ) -> aither_core::Result<Self::Res> {
157        let task_id = task_id(&args.task_id, &self.wording)?;
158        let killed = self.jobs.kill(task_id).await;
159        Ok(ToolResult::text(
160            self.wording.job_kill(&JobKillAsked { task_id, killed }),
161        ))
162    }
163}
164
165/// Tool for writing to a job's stdin.
166#[derive(Debug, Clone)]
167pub struct JobInputTool {
168    identity: ToolIdentity,
169    jobs: Jobs,
170    wording: AnyShellWording,
171}
172
173impl JobInputTool {
174    /// An input tool for `jobs`, named and described by `identity`, whose
175    /// reply is `wording`'s.
176    #[must_use]
177    pub const fn new(identity: ToolIdentity, jobs: Jobs, wording: AnyShellWording) -> Self {
178        Self {
179            identity,
180            jobs,
181            wording,
182        }
183    }
184}
185
186// The arguments of the input tool, described by its `ToolIdentity`.
187#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
188#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
189pub struct JobInputArgs {
190    // The job to write to.
191    pub task_id: String,
192    // The text written to the job's stdin.
193    pub input: String,
194    // Whether a trailing newline is appended before writing.
195    #[serde(default = "default_append_newline")]
196    pub append_newline: bool,
197}
198
199const fn default_append_newline() -> bool {
200    true
201}
202
203impl Tool for JobInputTool {
204    fn name(&self) -> Cow<'static, str> {
205        self.identity.name.clone()
206    }
207
208    fn description(&self) -> Cow<'static, str> {
209        self.identity.description.clone()
210    }
211
212    fn arguments_schema(&self) -> schemars::Schema {
213        self.identity.describe(schemars::schema_for!(JobInputArgs))
214    }
215
216    type Arguments = JobInputArgs;
217    type Res = ToolResult;
218
219    async fn call(
220        &self,
221        args: Self::Arguments,
222        _cx: ToolContext,
223    ) -> aither_core::Result<Self::Res> {
224        let task_id = task_id(&args.task_id, &self.wording)?;
225        let job = self
226            .jobs
227            .get(task_id)
228            .await
229            .ok_or_else(|| unknown_task(task_id, &self.wording))?;
230
231        let mut bytes = args.input.into_bytes();
232        if args.append_newline {
233            bytes.push(b'\n');
234        }
235        match job.input(bytes).await {
236            Ok(()) => {}
237            Err(JobInputError::NoStdin { task_id }) => {
238                return Err(Refused::call(
239                    &*self.wording,
240                    CallRefusal::NoStdin { task_id },
241                ));
242            }
243            Err(error) => return Err(error.into()),
244        }
245
246        Ok(ToolResult::text(
247            self.wording.job_input(&JobInputSent { task_id }),
248        ))
249    }
250}
251
252/// Tool for reading a job's output as it grows.
253#[derive(Debug, Clone)]
254pub struct JobReadTool {
255    identity: ToolIdentity,
256    jobs: Jobs,
257    wording: AnyShellWording,
258    output: crate::OutputPolicy,
259}
260
261impl JobReadTool {
262    /// A read tool for `jobs`, named and described by `identity`, whose
263    /// replies are `wording`'s and whose reads default to the `read_bytes`
264    /// of `output`.
265    #[must_use]
266    pub const fn new(
267        identity: ToolIdentity,
268        jobs: Jobs,
269        wording: AnyShellWording,
270        output: crate::OutputPolicy,
271    ) -> Self {
272        Self {
273            identity,
274            jobs,
275            wording,
276            output,
277        }
278    }
279}
280
281// The arguments of the read tool, described by its `ToolIdentity`.
282#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
283#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
284pub struct JobReadArgs {
285    // The job to read.
286    pub task_id: String,
287    // The offset after which output is read.
288    #[serde(default)]
289    pub cursor: usize,
290    // The most bytes returned.
291    #[serde(default)]
292    pub max_bytes: Option<usize>,
293}
294
295impl Tool for JobReadTool {
296    fn name(&self) -> Cow<'static, str> {
297        self.identity.name.clone()
298    }
299
300    fn description(&self) -> Cow<'static, str> {
301        self.identity.description.clone()
302    }
303
304    fn arguments_schema(&self) -> schemars::Schema {
305        self.identity.describe(schemars::schema_for!(JobReadArgs))
306    }
307
308    type Arguments = JobReadArgs;
309    type Res = ToolResult;
310
311    async fn call(
312        &self,
313        args: Self::Arguments,
314        _cx: ToolContext,
315    ) -> aither_core::Result<Self::Res> {
316        let task_id = task_id(&args.task_id, &self.wording)?;
317        let max_bytes = args
318            .max_bytes
319            .unwrap_or_else(|| self.output.get().read_bytes);
320        if max_bytes == 0 {
321            return Err(Refused::call(&*self.wording, CallRefusal::ZeroMaxBytes));
322        }
323        let job = self
324            .jobs
325            .get(task_id)
326            .await
327            .ok_or_else(|| unknown_task(task_id, &self.wording))?;
328        let read = job
329            .read(args.cursor, max_bytes)
330            .await
331            .map_err(anyhow::Error::msg)?;
332        match read {
333            JobRead::Delta(_) => Ok(ToolResult::text(self.wording.job_read(&read))),
334            // A poll is a refusal the loop can tell from a read, worded as
335            // the unchanged read.
336            JobRead::Unchanged { task_id } => {
337                Err(Refused::rendered(UnchangedRead { task_id }, |unchanged| {
338                    self.wording.job_read(&JobRead::Unchanged {
339                        task_id: unchanged.task_id.clone(),
340                    })
341                })
342                .into())
343            }
344        }
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use crate::job_registry::{Delivery, JobDelta, JobRead, JobStatus};
351    use crate::test_wording::TestWording;
352    use crate::wording::ShellWording;
353
354    fn delta(bytes: &str, cursor: usize, total_bytes: usize, status: JobStatus) -> JobRead {
355        JobRead::Delta(JobDelta {
356            task_id: "amber-forest-thunder-pearl".to_string(),
357            bytes: bytes.as_bytes().to_vec(),
358            cursor,
359            total_bytes,
360            status,
361        })
362    }
363
364    #[test]
365    fn a_read_without_more_buffered_states_the_next_cursor() {
366        assert_eq!(
367            TestWording.job_read(&delta("hello", 1005, 1005, JobStatus::Running)),
368            "hello\nTask 'amber-forest-thunder-pearl' is running; read 5 new bytes (1005 buffered in total); next cursor is 1005.\n"
369        );
370    }
371
372    #[test]
373    fn a_read_with_more_buffered_says_how_to_continue() {
374        assert_eq!(
375            TestWording.job_read(&delta(
376                "hello",
377                5,
378                1005,
379                JobStatus::Completed {
380                    exit_code: 0,
381                    delivery: Delivery::Pending,
382                }
383            )),
384            "hello\nTask 'amber-forest-thunder-pearl' completed with exit code 0; read 5 new bytes (1005 buffered in total); next cursor is 5.\nMore output is buffered: call terminal_read with cursor=5.\n"
385        );
386    }
387
388    #[test]
389    fn an_unchanged_read_is_data_the_wording_words() {
390        let text = TestWording.job_read(&JobRead::Unchanged {
391            task_id: "amber-forest-thunder-pearl".to_string(),
392        });
393        assert!(
394            text.contains("'amber-forest-thunder-pearl' produced no new output"),
395            "{text}"
396        );
397    }
398}