Skip to main content

aither_sandbox/terminal/
builder.rs

1//! Building a [`Shell`] on a [`Sandbox`].
2
3use std::sync::Arc;
4
5use executor_core::AnyExecutor;
6
7use super::{Interpreter, Shell, ShellToolSettings, TerminalError};
8use crate::output_treatment::AnyTreatOutput;
9use crate::{
10    AnyIpcProvider, AnyScriptPolicy, AnyShellWording, HostLaunch, IpcProvider, OutputPolicy,
11    Sandbox, ScriptPolicy, ShellEvents, ShellLimits, ShellWording, TreatOutput,
12};
13
14/// A value the builder has not been given yet.
15#[derive(Debug, Clone, Copy)]
16pub struct Missing;
17
18/// A value the builder was given.
19#[derive(Debug, Clone)]
20pub struct Given<T>(T);
21
22/// What a shell is built from besides its sandbox.
23pub struct ShellParts {
24    pub(crate) interpreters: Vec<Interpreter>,
25    pub(crate) limits: ShellLimits,
26    pub(crate) output: OutputPolicy,
27    pub(crate) wording: AnyShellWording,
28    pub(crate) tools: ShellToolSettings,
29    pub(crate) events: Option<ShellEvents>,
30    pub(crate) policies: Vec<AnyScriptPolicy>,
31    pub(crate) ipc: Option<AnyIpcProvider>,
32    pub(crate) treat_output: Option<AnyTreatOutput>,
33    pub(crate) host_shell: Option<HostLaunch>,
34}
35
36/// Builds a [`Shell`] on the [`Sandbox`] its scripts run in.
37///
38/// The interpreters, limits, output policy, wording and tool identities have
39/// no defaults: [`build`](Self::build) exists once every one is given.
40#[derive(Debug)]
41pub struct ShellBuilder<I, L, O, W, T> {
42    sandbox: Sandbox,
43    interpreters: I,
44    limits: L,
45    output: O,
46    wording: W,
47    tools: T,
48    events: Option<ShellEvents>,
49    policies: Vec<AnyScriptPolicy>,
50    ipc: Option<AnyIpcProvider>,
51    treat_output: Option<AnyTreatOutput>,
52    host_shell: Option<HostLaunch>,
53}
54
55impl Shell<Arc<AnyExecutor>> {
56    /// Starts a shell whose scripts run in `sandbox`, a sandbox on a
57    /// container: its working directory, live grants, environment source,
58    /// network policy, priority and backend are the shell's, and the shell
59    /// is the one the container's launch names. A sandbox on the host takes
60    /// [`builder_on_host`](Self::builder_on_host).
61    #[must_use]
62    pub const fn builder(
63        sandbox: Sandbox,
64    ) -> ShellBuilder<Missing, Missing, Missing, Missing, Missing> {
65        ShellBuilder {
66            sandbox,
67            interpreters: Missing,
68            limits: Missing,
69            output: Missing,
70            wording: Missing,
71            tools: Missing,
72            events: None,
73            policies: Vec::new(),
74            ipc: None,
75            treat_output: None,
76            host_shell: None,
77        }
78    }
79
80    /// Starts a shell whose scripts run in `sandbox`, a sandbox on the host,
81    /// under the shell `host_shell` names. A host sandbox spawns programs and
82    /// names no shell of its own, so the shell is an input of the shell that
83    /// needs one.
84    #[must_use]
85    pub const fn builder_on_host(
86        sandbox: Sandbox,
87        host_shell: HostLaunch,
88    ) -> ShellBuilder<Missing, Missing, Missing, Missing, Missing> {
89        ShellBuilder {
90            sandbox,
91            interpreters: Missing,
92            limits: Missing,
93            output: Missing,
94            wording: Missing,
95            tools: Missing,
96            events: None,
97            policies: Vec::new(),
98            ipc: None,
99            treat_output: None,
100            host_shell: Some(host_shell),
101        }
102    }
103}
104
105impl<I, L, O, W, T> ShellBuilder<I, L, O, W, T> {
106    /// Lets every script of the shell, and of the subagent shells it
107    /// launches, call the commands `provider` serves back on the host. The
108    /// provider is asked once per process the shell starts on the host or in
109    /// a container. A process on an SSH server has no way back to this
110    /// machine, so the shell asks for none there. Without a provider no
111    /// script reaches a command of the embedder.
112    #[must_use]
113    pub fn ipc(mut self, provider: impl IpcProvider) -> Self {
114        self.ipc = Some(AnyIpcProvider::new(provider));
115        self
116    }
117
118    /// Puts every script to `policy`, after the policies given before it.
119    /// Each agent's shell gets state of its own from the policy's
120    /// definition, see [`ScriptPolicies::for_agent`](crate::ScriptPolicies).
121    #[must_use]
122    pub fn policy(mut self, policy: impl ScriptPolicy) -> Self {
123        self.policies.push(AnyScriptPolicy::new(policy));
124        self
125    }
126
127    /// Lets `treat` choose, before each script of the shell and of the
128    /// subagent shells it launches runs, whether its output reaches the model
129    /// verbatim or cleaned as command output; it replaces one given before.
130    /// Without it every script's output is cleaned as command output, see
131    /// [`OutputTreatment`](crate::OutputTreatment).
132    #[must_use]
133    pub fn treat_output(mut self, treat: impl TreatOutput) -> Self {
134        self.treat_output = Some(AnyTreatOutput::new(treat));
135        self
136    }
137
138    /// Raises the shell's events, and those of the subagent shells it
139    /// launches, on `events`, which other shells may share. Without it the
140    /// shell has a handle of its own, read with [`Shell::events`].
141    #[must_use]
142    pub fn events(mut self, events: ShellEvents) -> Self {
143        self.events = Some(events);
144        self
145    }
146
147    /// The interpreters a script may run under, and the ones the model's
148    /// `interpreter` argument lists.
149    #[must_use]
150    pub fn interpreters(
151        self,
152        interpreters: impl IntoIterator<Item = Interpreter>,
153    ) -> ShellBuilder<Given<Vec<Interpreter>>, L, O, W, T> {
154        ShellBuilder {
155            sandbox: self.sandbox,
156            interpreters: Given(interpreters.into_iter().collect()),
157            limits: self.limits,
158            output: self.output,
159            wording: self.wording,
160            tools: self.tools,
161            events: self.events,
162            policies: self.policies,
163            ipc: self.ipc,
164            treat_output: self.treat_output,
165            host_shell: self.host_shell,
166        }
167    }
168
169    /// The time bounds of every script.
170    #[must_use]
171    pub fn limits(self, limits: ShellLimits) -> ShellBuilder<I, Given<ShellLimits>, O, W, T> {
172        ShellBuilder {
173            sandbox: self.sandbox,
174            interpreters: self.interpreters,
175            limits: Given(limits),
176            output: self.output,
177            wording: self.wording,
178            tools: self.tools,
179            events: self.events,
180            policies: self.policies,
181            ipc: self.ipc,
182            treat_output: self.treat_output,
183            host_shell: self.host_shell,
184        }
185    }
186
187    /// The budgets of what a script's output returns inline.
188    #[must_use]
189    pub fn output(self, output: OutputPolicy) -> ShellBuilder<I, L, Given<OutputPolicy>, W, T> {
190        ShellBuilder {
191            sandbox: self.sandbox,
192            interpreters: self.interpreters,
193            limits: self.limits,
194            output: Given(output),
195            wording: self.wording,
196            tools: self.tools,
197            events: self.events,
198            policies: self.policies,
199            ipc: self.ipc,
200            treat_output: self.treat_output,
201            host_shell: self.host_shell,
202        }
203    }
204
205    /// What words every text the model reads.
206    #[must_use]
207    pub fn wording(
208        self,
209        wording: impl ShellWording,
210    ) -> ShellBuilder<I, L, O, Given<AnyShellWording>, T> {
211        ShellBuilder {
212            sandbox: self.sandbox,
213            interpreters: self.interpreters,
214            limits: self.limits,
215            output: self.output,
216            wording: Given(AnyShellWording::new(wording)),
217            tools: self.tools,
218            events: self.events,
219            policies: self.policies,
220            ipc: self.ipc,
221            treat_output: self.treat_output,
222            host_shell: self.host_shell,
223        }
224    }
225
226    /// What the shell tool and the job control tools are named and
227    /// described as.
228    #[must_use]
229    pub fn tools(
230        self,
231        tools: ShellToolSettings,
232    ) -> ShellBuilder<I, L, O, W, Given<ShellToolSettings>> {
233        ShellBuilder {
234            sandbox: self.sandbox,
235            interpreters: self.interpreters,
236            limits: self.limits,
237            output: self.output,
238            wording: self.wording,
239            tools: Given(tools),
240            events: self.events,
241            policies: self.policies,
242            ipc: self.ipc,
243            treat_output: self.treat_output,
244            host_shell: self.host_shell,
245        }
246    }
247}
248
249impl
250    ShellBuilder<
251        Given<Vec<Interpreter>>,
252        Given<ShellLimits>,
253        Given<OutputPolicy>,
254        Given<AnyShellWording>,
255        Given<ShellToolSettings>,
256    >
257{
258    /// Builds the shell.
259    ///
260    /// # Errors
261    /// Returns an error when the working directory or the output store cannot
262    /// be created, when the sandbox runs its processes on an SSH server (a
263    /// server is a location a script names, not a shell's home), or when the
264    /// constructor does not fit the sandbox's backend: a host sandbox built
265    /// with [`Shell::builder`], or a container sandbox built with
266    /// [`Shell::builder_on_host`].
267    pub async fn build(self) -> Result<Shell<Arc<AnyExecutor>>, TerminalError> {
268        let Self {
269            sandbox,
270            interpreters: Given(interpreters),
271            limits: Given(limits),
272            output: Given(output),
273            wording: Given(wording),
274            tools: Given(tools),
275            events,
276            policies,
277            ipc,
278            treat_output,
279            host_shell,
280        } = self;
281        let executor = sandbox.executor();
282        Shell::from_parts(
283            sandbox,
284            executor,
285            ShellParts {
286                interpreters,
287                limits,
288                output,
289                wording,
290                tools,
291                events,
292                policies,
293                ipc,
294                treat_output,
295                host_shell,
296            },
297        )
298        .await
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use aither_core::llm::Tool;
305
306    use super::*;
307    use crate::spawn::Grants;
308    use crate::{Backend, test_budgets, test_wording};
309
310    async fn shell(
311        directory: &std::path::Path,
312        grants: Grants,
313        interpreters: &[Interpreter],
314    ) -> Shell<Arc<AnyExecutor>> {
315        let heel = crate::test_heel::binary().await.expect("a heel for tests");
316        let sandbox = Sandbox::new(
317            Backend::Host { heel },
318            executor_core::tokio::TokioGlobal,
319            directory,
320        )
321        .with_grants(grants);
322        Shell::builder_on_host(sandbox, HostLaunch::new("/bin/bash"))
323            .interpreters(interpreters.iter().copied())
324            .limits(test_budgets::limits())
325            .output(test_budgets::output_policy())
326            .wording(test_wording::TestWording)
327            .tools(test_wording::job_tools())
328            .build()
329            .await
330            .expect("the shell builds")
331    }
332
333    async fn ipc_shell(
334        directory: &std::path::Path,
335        provider: crate::spawn::ipc_fixture::Recording,
336    ) -> Shell<Arc<AnyExecutor>> {
337        let heel = crate::test_heel::binary().await.expect("a heel for tests");
338        let sandbox = Sandbox::new(
339            Backend::Host { heel },
340            executor_core::tokio::TokioGlobal,
341            directory,
342        );
343        Shell::builder_on_host(sandbox, HostLaunch::new("/bin/bash"))
344            .interpreters([Interpreter::Shell])
345            .limits(test_budgets::limits())
346            .output(test_budgets::output_policy())
347            .wording(test_wording::TestWording)
348            .tools(test_wording::job_tools())
349            .ipc(provider)
350            .build()
351            .await
352            .expect("the shell builds")
353    }
354
355    /// Keeps the output of a script that reads a file with `cat` verbatim.
356    struct CatIsVerbatim;
357
358    impl TreatOutput for CatIsVerbatim {
359        fn treatment(&self, script: &crate::ScriptCheck<'_>) -> crate::OutputTreatment {
360            if script.script.starts_with("cat ") {
361                crate::OutputTreatment::Verbatim
362            } else {
363                crate::OutputTreatment::Command
364            }
365        }
366    }
367
368    async fn treated_shell(
369        directory: &std::path::Path,
370        treat: Option<CatIsVerbatim>,
371    ) -> Shell<Arc<AnyExecutor>> {
372        let heel = crate::test_heel::binary().await.expect("a heel for tests");
373        let sandbox = Sandbox::new(
374            Backend::Host { heel },
375            executor_core::tokio::TokioGlobal,
376            directory,
377        );
378        let builder = Shell::builder_on_host(sandbox, HostLaunch::new("/bin/bash"))
379            .interpreters([Interpreter::Shell])
380            .limits(test_budgets::limits())
381            .output(test_budgets::output_policy())
382            .wording(test_wording::TestWording)
383            .tools(test_wording::job_tools());
384        let builder = match treat {
385            Some(treat) => builder.treat_output(treat),
386            None => builder,
387        };
388        builder.build().await.expect("the shell builds")
389    }
390
391    async fn run_in(
392        shell: &Shell<Arc<AnyExecutor>>,
393        dir: &std::path::Path,
394        script: &str,
395    ) -> crate::ScriptResult {
396        let result = shell
397            .run(crate::Script::new(
398                script,
399                dir,
400                std::time::Duration::from_secs(30),
401            ))
402            .await
403            .expect("the script runs");
404        assert!(
405            matches!(result.outcome, crate::RunOutcome::Exited { code: 0 }),
406            "{result:?}"
407        );
408        result
409    }
410
411    /// A file whose blank-line runs command-output cleaning collapses.
412    const NOTES: &str = "# Notes\n\n\n\nfirst\n\n\nsecond\n";
413
414    #[cfg(unix)]
415    #[tokio::test(flavor = "multi_thread")]
416    async fn a_shell_without_a_treatment_cleans_every_output_as_command_output() {
417        let directory = tempfile::tempdir().unwrap();
418        let start = directory.path().canonicalize().unwrap();
419        std::fs::write(start.join("notes.md"), NOTES).unwrap();
420        let shell = treated_shell(&start, None).await;
421        let read = run_in(&shell, &start, "cat notes.md").await;
422        assert_ne!(stdout_of(&read), NOTES, "the blank runs collapse");
423        assert!(
424            stdout_of(&read).contains("blank lines collapsed"),
425            "{read:?}"
426        );
427    }
428
429    #[cfg(unix)]
430    #[tokio::test(flavor = "multi_thread")]
431    async fn the_treatment_keeps_a_read_verbatim_and_cleans_command_output() {
432        let directory = tempfile::tempdir().unwrap();
433        let start = directory.path().canonicalize().unwrap();
434        std::fs::write(start.join("notes.md"), NOTES).unwrap();
435        let shell = treated_shell(&start, Some(CatIsVerbatim)).await;
436
437        let read = run_in(&shell, &start, "cat notes.md").await;
438        assert_eq!(
439            stdout_of(&read),
440            NOTES,
441            "the file reaches the model as it is"
442        );
443
444        let command = run_in(&shell, &start, "printf '# Notes\\n\\n\\n\\nfirst\\n'").await;
445        assert!(
446            stdout_of(&command).contains("blank lines collapsed"),
447            "{command:?}"
448        );
449    }
450
451    #[cfg(unix)]
452    #[tokio::test(flavor = "multi_thread")]
453    async fn a_verbatim_output_over_the_budget_stores_the_whole_text() {
454        let directory = tempfile::tempdir().unwrap();
455        let start = directory.path().canonicalize().unwrap();
456        let lines = test_budgets::output_policy().lines(None) * 2;
457        let long = (0..lines)
458            .map(|line| line.to_string())
459            .collect::<Vec<_>>()
460            .join("\n\n\n");
461        std::fs::write(start.join("long.md"), &long).unwrap();
462        let shell = treated_shell(&start, Some(CatIsVerbatim)).await;
463
464        let read = run_in(&shell, &start, "cat long.md").await;
465        let aither_core::llm::CommandStream::Stored { file, preview, .. } = &read.stdout else {
466            panic!("output over the line budget is stored: {read:?}");
467        };
468        assert!(!preview.is_empty(), "the model reads a preview");
469        assert_eq!(
470            std::fs::read_to_string(&file.path).unwrap(),
471            long,
472            "the stored file holds the whole text, blank runs included"
473        );
474    }
475
476    fn stdout_of(result: &crate::ScriptResult) -> &str {
477        match &result.stdout {
478            aither_core::llm::CommandStream::Inline { text } => text,
479            other => panic!("a short answer is inline: {other:?}"),
480        }
481    }
482
483    #[cfg(unix)]
484    #[tokio::test(flavor = "multi_thread")]
485    async fn a_script_calls_the_command_the_providers_router_serves() {
486        let directory = tempfile::tempdir().unwrap();
487        let start = directory.path().canonicalize().unwrap();
488        let provider = crate::spawn::ipc_fixture::Recording::default();
489        let shell = ipc_shell(&start, provider.clone()).await;
490        let result = shell
491            .run(crate::Script::new(
492                "probe",
493                &start,
494                std::time::Duration::from_secs(30),
495            ))
496            .await
497            .expect("the script runs");
498        assert_eq!(
499            stdout_of(&result).trim(),
500            crate::spawn::ipc_fixture::ANSWER,
501            "{result:?}"
502        );
503        let launches = provider.launches.lock().unwrap();
504        assert_eq!(launches.len(), 1, "one process, one question");
505        assert!(launches[0].task_id.is_some(), "{:?}", launches[0]);
506        assert_eq!(launches[0].mode, crate::SandboxMode::Sandboxed);
507    }
508
509    #[cfg(unix)]
510    #[tokio::test(flavor = "multi_thread")]
511    async fn a_shell_without_a_provider_serves_no_command() {
512        let directory = tempfile::tempdir().unwrap();
513        let start = directory.path().canonicalize().unwrap();
514        let shell = shell(&start, Grants::new(), &[Interpreter::Shell]).await;
515        // The `;` makes the script one the managed shell runs: a bare
516        // `probe` is a direct command, which Linux's supervisor refuses to
517        // start at all and macOS reports as an exit.
518        let result = shell
519            .run(crate::Script::new(
520                "probe;",
521                &start,
522                std::time::Duration::from_secs(30),
523            ))
524            .await
525            .expect("the script runs");
526        assert!(
527            matches!(result.outcome, crate::RunOutcome::Exited { code: 127 }),
528            "the shell finds no `probe`: {result:?}"
529        );
530    }
531
532    #[tokio::test]
533    async fn the_shell_is_built_on_the_sandboxs_directory_and_live_grants() {
534        let directory = tempfile::tempdir().unwrap();
535        let grants = Grants::new();
536        let shell = shell(directory.path(), grants.clone(), &[Interpreter::Shell]).await;
537        assert_eq!(
538            shell.working_dir,
539            dunce::simplified(&directory.path().canonicalize().unwrap())
540        );
541        let granted = directory.path().join("granted");
542        grants.add_writable(&granted);
543        assert_eq!(
544            shell.sandbox.grants().snapshot().writable,
545            grants.snapshot().writable,
546            "the shell sees the grants the sandbox's handle changes"
547        );
548    }
549
550    #[tokio::test]
551    async fn the_tool_schema_lists_exactly_the_configured_interpreters() {
552        let directory = tempfile::tempdir().unwrap();
553        for (configured, listed) in [
554            (vec![Interpreter::Shell], serde_json::json!(["shell"])),
555            (
556                vec![Interpreter::Shell, Interpreter::Python],
557                serde_json::json!(["shell", "python"]),
558            ),
559        ] {
560            let shell = shell(directory.path(), Grants::new(), &configured).await;
561            let tool = shell.tool();
562            assert_eq!(tool.name(), "terminal");
563            let schema = tool.arguments_schema().to_value();
564            assert_eq!(schema["$defs"]["Interpreter"]["enum"], listed);
565        }
566    }
567
568    #[tokio::test]
569    async fn every_argument_is_described_by_the_identity_alone() {
570        let directory = tempfile::tempdir().unwrap();
571        let shell = shell(directory.path(), Grants::new(), &[Interpreter::Shell]).await;
572        let schema = shell.tool().arguments_schema().to_value();
573        let described = test_wording::argument_descriptions();
574        let properties = schema["properties"].as_object().expect("an object schema");
575        assert!(!properties.is_empty());
576        for (name, property) in properties {
577            assert_eq!(
578                property["description"].as_str(),
579                Some(&*described[name.as_str()]),
580                "{name}"
581            );
582        }
583        assert!(schema.get("description").is_none(), "{schema}");
584        assert!(
585            schema["$defs"]["Interpreter"].get("description").is_none(),
586            "{schema}"
587        );
588    }
589
590    #[tokio::test]
591    async fn a_script_in_an_interpreter_the_shell_lacks_is_refused() {
592        let directory = tempfile::tempdir().unwrap();
593        let shell = shell(directory.path(), Grants::new(), &[Interpreter::Shell]).await;
594        let arguments: super::super::ShellArgs = serde_json::from_value(serde_json::json!({
595            "description": "print",
596            "script": "print(1)",
597            "interpreter": "python",
598            "timeout": 5
599        }))
600        .unwrap();
601        let error = shell
602            .tool()
603            .call(arguments, aither_core::llm::ToolContext::new())
604            .await
605            .expect_err("python is not configured");
606        assert!(error.to_string().contains("not configured"), "{error}");
607    }
608
609    #[tokio::test]
610    async fn a_host_sandbox_built_without_its_host_shell_is_refused() {
611        let directory = tempfile::tempdir().unwrap();
612        let heel = crate::test_heel::binary().await.expect("a heel for tests");
613        let sandbox = Sandbox::new(
614            Backend::Host { heel },
615            executor_core::tokio::TokioGlobal,
616            directory.path(),
617        );
618        let error = Shell::builder(sandbox)
619            .interpreters([Interpreter::Shell])
620            .limits(test_budgets::limits())
621            .output(test_budgets::output_policy())
622            .wording(test_wording::TestWording)
623            .tools(test_wording::job_tools())
624            .build()
625            .await
626            .expect_err("a host shell needs its program");
627        assert!(error.to_string().contains("host shell"), "{error}");
628    }
629
630    #[cfg(unix)]
631    #[tokio::test(flavor = "multi_thread")]
632    async fn the_shells_sandbox_spawns_a_program_in_the_shells_directory() {
633        let directory = tempfile::tempdir().unwrap();
634        let shell = shell(directory.path(), Grants::new(), &[Interpreter::Shell]).await;
635        let mut child = shell
636            .sandbox()
637            .spawn(crate::SpawnSpec::new("/bin/pwd"))
638            .await
639            .expect("the process starts");
640        let stdout = child.take_stdout().expect("stdout is piped");
641        let mut printed = Vec::new();
642        while let Ok(chunk) = stdout.recv().await {
643            printed.extend(chunk);
644        }
645        child.wait().await;
646        let printed = String::from_utf8(printed).unwrap();
647        assert_eq!(
648            std::path::Path::new(printed.trim()),
649            shell.sandbox().working_dir()
650        );
651    }
652}