Skip to main content

aither_sandbox/
wording.rs

1//! The text the model reads: every refusal, notice, marker and reply the
2//! shell and its tools render.
3//!
4//! The shell raises each as typed data: a [`CallRefusal`], a
5//! [`MonitorStarted`], an [`OutputSaved`] and so on. The embedder's
6//! [`ShellWording`] turns each into the natural language its model reads;
7//! aither ships no implementation, so an embedder words every family itself.
8//! A [`ScriptPolicy`](crate::ScriptPolicy) refusal carries its own text and
9//! has no family here.
10
11use std::fmt;
12use std::sync::Arc;
13
14use crate::MountRootError;
15use crate::job_registry::JobRead;
16use crate::monitor::MonitorRefusal;
17use crate::terminal::{TerminalError, TimeoutKill};
18
19/// A `monitor` call that started watching a task.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct MonitorStarted<'a> {
22    /// The task the monitor watches.
23    pub task_id: &'a str,
24    /// How often its new output is delivered, in seconds.
25    pub interval_secs: u64,
26}
27
28/// A call of the shell's tools refused before it ran.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum CallRefusal {
32    /// The `description` of a `terminal` call is empty.
33    EmptyDescription,
34    /// The call names an interpreter the shell is not configured with.
35    InterpreterNotConfigured {
36        /// The interpreter asked for.
37        interpreter: crate::Interpreter,
38    },
39    /// The `timeout` is zero or above the shell's cap.
40    TimeoutOutOfRange {
41        /// The longest timeout the shell accepts.
42        cap: std::time::Duration,
43    },
44    /// A job control call names no task.
45    EmptyTaskId,
46    /// A job control call names a task the shell does not hold.
47    UnknownTask {
48        /// The task named.
49        task_id: String,
50    },
51    /// A read asks for zero bytes.
52    ZeroMaxBytes,
53    /// An input names a job that reads no input: it was started in the
54    /// foreground, whose stdin is the null device, and a job promoted past
55    /// the foreground window keeps the stdin it started with. Only a job
56    /// started with `background` has a stdin pipe.
57    NoStdin {
58        /// The task named.
59        task_id: String,
60    },
61}
62
63/// Why a foreground command the shell killed was killed.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum CommandKilled<'a> {
66    /// Its `timeout` bound passed.
67    TimedOut(&'a TimeoutKill),
68    /// It was killed before its bound passed, by a kill or a watchdog.
69    BeforeTimeout,
70}
71
72impl<'a> CommandKilled<'a> {
73    /// The reason a kill of `cause` is worded by.
74    #[must_use]
75    pub const fn of(cause: &'a crate::KillCause) -> Self {
76        match cause {
77            crate::KillCause::Timeout(kill) => Self::TimedOut(kill),
78            crate::KillCause::User | crate::KillCause::MemoryRunaway { .. } => Self::BeforeTimeout,
79        }
80    }
81}
82
83/// Bytes written to a job's stdin.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct JobInputSent<'a> {
86    /// The job written to.
87    pub task_id: &'a str,
88}
89
90/// A kill of a job.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct JobKillAsked<'a> {
93    /// The job asked to die.
94    pub task_id: &'a str,
95    /// Whether a running job was found and killed; `false` for an unknown
96    /// one or one that already stopped.
97    pub killed: bool,
98}
99
100/// An output too large for the window, replaced by a preview and the file
101/// that holds all of it.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct OutputSaved<'a> {
104    /// The preview kept in the result, without its trailing newline.
105    pub preview: &'a str,
106    /// Absolute path of the file holding the full output.
107    pub path: &'a str,
108    /// Lines of the full output.
109    pub line_count: usize,
110    /// Bytes of the full output.
111    pub byte_count: usize,
112}
113
114/// A binary part of a result, stored in a file.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct StoredBinaryPart<'a> {
117    /// The part's media type.
118    pub mime: &'a str,
119    /// Its size.
120    pub byte_count: usize,
121    /// The URL the output store names it by.
122    pub url: &'a str,
123    /// Its file.
124    pub path: &'a str,
125}
126
127/// A JSON payload shown as TSV, its original stored in a file.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub struct JsonAsTsv<'a> {
130    /// The TSV, without its trailing newline.
131    pub tsv: &'a str,
132    /// The URL the original is stored under.
133    pub url: &'a str,
134    /// The file holding the original.
135    pub path: &'a str,
136}
137
138/// A run of lines a view of an output leaves out or stands for.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub struct LineRange {
141    /// The first stored line of the range, 1-based.
142    pub first: usize,
143    /// The last stored line of the range.
144    pub last: usize,
145}
146
147/// A block of source code folded into one marker line.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub struct FoldedLines<'a> {
150    /// The indentation matching the line numbers' width.
151    pub indent: &'a str,
152    /// The lines folded.
153    pub count: usize,
154    /// The unfolded lines the marker stands for.
155    pub range: LineRange,
156}
157
158/// The middle of a stored output a preview leaves out.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct OmittedLines {
161    /// The lines left out.
162    pub range: LineRange,
163    /// The lines of the whole output.
164    pub total: usize,
165}
166
167/// A run of identical lines a preview shows once.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct RepeatedLines {
170    /// The lines the run spans.
171    pub range: LineRange,
172    /// The lines in the run.
173    pub count: usize,
174}
175
176/// A call or run that did not get to an end, other than one refused before it
177/// ran: the failure as data, for the embedder to word.
178///
179/// The errors behind it ([`TerminalError`], [`MountRootError`]) carry the
180/// facts a text needs; their `Display` is for logs and is never what the
181/// model reads.
182#[derive(Debug)]
183#[non_exhaustive]
184pub enum RunFailure<'a> {
185    /// The shell's container declares no workspace mount, so a run cannot
186    /// start in a host directory.
187    NoWorkspaceMount,
188    /// The run's directory lies outside the container's workspace mount.
189    OutsideWorkspace(&'a MountRootError),
190    /// Every model-facing id is leased, so the command has no task id.
191    IdsExhausted,
192    /// The shell could not run the script: a target, tool, permission or
193    /// setup failure, or one the execution reported.
194    Terminal(&'a TerminalError),
195    /// The execution failed, with the detail its backend gave
196    /// ([`TerminalError::detail`]).
197    Failed {
198        /// What the backend reported.
199        detail: &'a str,
200    },
201}
202
203/// The text the model reads for each refusal, notice and marker the shell
204/// raises, one method per family.
205///
206/// There is no default for any method and aither ships no implementation.
207pub trait ShellWording: Send + Sync + 'static {
208    /// What a read of a job's output returned: new output, or the fact that
209    /// nothing changed since the job's last read.
210    fn job_read(&self, read: &JobRead) -> String;
211
212    /// A job's stdin was written.
213    fn job_input(&self, sent: &JobInputSent<'_>) -> String;
214
215    /// A kill of a job was asked for.
216    fn job_kill(&self, kill: &JobKillAsked<'_>) -> String;
217
218    /// A call of a tool of the shell refused before it ran.
219    fn call_refused(&self, refusal: &CallRefusal) -> String;
220
221    /// A call or run that failed before or while it ran.
222    fn run_failure(&self, failure: &RunFailure<'_>) -> String;
223
224    /// A `monitor` call refused before anything started.
225    fn monitor_refusal(&self, refusal: &MonitorRefusal) -> String;
226
227    /// The result of a `monitor` call that started watching.
228    fn monitor_started(&self, started: &MonitorStarted<'_>) -> String;
229
230    /// Why a command was killed, appended to its result.
231    fn command_killed(&self, killed: &CommandKilled<'_>) -> String;
232
233    /// A text output replaced by its preview and the file holding all of it.
234    fn output_saved(&self, saved: &OutputSaved<'_>) -> String;
235
236    /// A binary part of a result, stored in a file.
237    fn stored_binary_part(&self, part: &StoredBinaryPart<'_>) -> String;
238
239    /// A JSON payload shown as TSV.
240    fn json_as_tsv(&self, json: &JsonAsTsv<'_>) -> String;
241
242    /// A folded view of source code, without its trailing newline.
243    fn folded_code(&self, folded: &str) -> String;
244
245    /// A run of `count` blank lines collapsed into one marker line.
246    fn blank_lines(&self, count: usize) -> String;
247
248    /// A block of folded lines.
249    fn folded_lines(&self, folded: &FoldedLines<'_>) -> String;
250
251    /// The lines a preview omits.
252    fn omitted_lines(&self, omitted: &OmittedLines) -> String;
253
254    /// A run of identical lines a preview collapses.
255    fn repeated_lines(&self, repeated: &RepeatedLines) -> String;
256}
257
258/// A shared [`ShellWording`], cloned into every shell, store and tool that
259/// renders a text.
260#[derive(Clone)]
261pub struct AnyShellWording(Arc<dyn ShellWording>);
262
263impl AnyShellWording {
264    /// Shares `wording`.
265    #[must_use]
266    pub fn new(wording: impl ShellWording) -> Self {
267        Self(Arc::new(wording))
268    }
269}
270
271/// Shares a value another wrapper already holds, so both render through the
272/// same object.
273impl From<Arc<dyn ShellWording>> for AnyShellWording {
274    fn from(wording: Arc<dyn ShellWording>) -> Self {
275        Self(wording)
276    }
277}
278
279impl std::ops::Deref for AnyShellWording {
280    type Target = dyn ShellWording;
281
282    fn deref(&self) -> &Self::Target {
283        &*self.0
284    }
285}
286
287impl fmt::Debug for AnyShellWording {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        f.debug_struct("AnyShellWording").finish_non_exhaustive()
290    }
291}
292
293/// A call refused before it ran: the typed reason, and the text its
294/// wording rendered for the model.
295///
296/// Tools return it as their error, so an agent loop tells one refusal from
297/// another, and from any other failure, by downcasting to
298/// `Refused<CallRefusal>` and so on.
299#[derive(Debug)]
300pub struct Refused<R> {
301    reason: R,
302    text: String,
303}
304
305impl<R> Refused<R> {
306    /// The refusal of `reason`, read by the model as what `render` returns.
307    pub fn rendered(reason: R, render: impl FnOnce(&R) -> String) -> Self {
308        let text = render(&reason);
309        Self { reason, text }
310    }
311
312    /// Why the call was refused.
313    pub const fn reason(&self) -> &R {
314        &self.reason
315    }
316
317    /// The text the model reads.
318    #[must_use]
319    pub fn text(&self) -> &str {
320        &self.text
321    }
322
323    /// Takes the reason, dropping the text.
324    pub fn into_reason(self) -> R {
325        self.reason
326    }
327}
328
329impl Refused<CallRefusal> {
330    /// The error of a call refused for `refusal`, worded by `wording`.
331    pub(crate) fn call(wording: &dyn ShellWording, refusal: CallRefusal) -> anyhow::Error {
332        Self::rendered(refusal, |refusal| wording.call_refused(refusal)).into()
333    }
334}
335
336impl<R> fmt::Display for Refused<R> {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        f.write_str(&self.text)
339    }
340}
341
342impl<R: fmt::Debug> std::error::Error for Refused<R> {}