Skip to main content

base/interface/exec/
mod.rs

1//! The execution layer — how a tool touches the machine.
2//!
3//! Four contracts, designed as one because they are entangled: a sandbox
4//! constrains a process, a process needs files and a network, and the network
5//! policy has to reach inside the sandbox. `docs/ARCHITECTURE.md` §5 is
6//! the blueprint; this module is its vocabulary.
7//!
8//! # What is deliberately not here
9//!
10//! An execution layer is the easiest place in an engine for a second kernel to
11//! grow, so the boundary is written down rather than assumed. Retries,
12//! timeouts, caching and metrics belong to [`tool_middleware`]; whether a
13//! provider is healthy belongs to [`health`]; kept time belongs to
14//! [`environment`]; path safety is a policy and stays with `permissions`; and
15//! the sandbox *policy* — what to constrain and whether to constrain at all —
16//! is the kernel's. A provider decides *how* to constrain, never *whether*.
17//!
18//! This machine's own answers to the four contracts are the `platform` crate,
19//! which depends on this one; [`env`] stays here because it is the
20//! `sandbox.env` setting and the engine's credential list, both of
21//! which `base` itself reads.
22//!
23//! [`tool_middleware`]: crate::interface::tool_middleware
24//! [`health`]: crate::interface::health
25//! [`environment`]: crate::interface::environment
26
27pub mod capture;
28pub mod env;
29pub mod filesystem;
30pub mod in_process;
31pub mod network;
32pub mod process;
33pub mod sandbox;
34
35pub use capture::{capture, Captured};
36pub use env::{EnvPlan, EnvScope, SubprocessEnv, SubprocessEnvMode};
37pub use filesystem::{DirEntry, FileSystem, Metadata};
38pub use network::{
39    domains_name_host, is_internal_address, names_loopback, HttpRequest, HttpResponse, HttpStream,
40    Network, Origin, DEFAULT_MAX_REDIRECTS,
41};
42pub use process::{
43    ExitStatus, OutputChunk, OutputStream, Process, ProcessHandle, ProcessSpec,
44    OUTPUT_GRACE_AFTER_EXIT,
45};
46pub use sandbox::{
47    default_deny_read, default_deny_read_in, Confined, ConfinementReport, EgressProxy, Enforcement,
48    NetworkMode, ReadScope, Sandbox, SandboxMode, SandboxPolicy, SandboxSettings,
49};
50
51/// The four providers a tool reaches the machine through.
52///
53/// One field on a [`ToolContext`](crate::interface::tool::ToolContext) rather
54/// than four, because they are swapped as a set: a deployment executing
55/// elsewhere that kept this machine's filesystem would be running commands
56/// against files that are not there.
57#[derive(Clone)]
58pub struct ExecProviders {
59    pub process: std::sync::Arc<dyn Process>,
60    pub filesystem: std::sync::Arc<dyn FileSystem>,
61    pub network: std::sync::Arc<dyn Network>,
62    pub sandbox: std::sync::Arc<dyn Sandbox>,
63}
64
65impl ExecProviders {
66    /// Nothing on the machine: a memory tree, commands decided in advance, no
67    /// network, and a sandbox honest enough to say it constrains nothing.
68    ///
69    /// The provider beside this machine's (`platform::local_providers`).
70    /// Switching is this call.
71    pub fn in_process() -> Self {
72        Self {
73            process: std::sync::Arc::new(in_process::ScriptedProcess::new()),
74            filesystem: std::sync::Arc::new(in_process::InMemoryFileSystem::new()),
75            network: std::sync::Arc::new(in_process::OfflineNetwork::new()),
76            sandbox: std::sync::Arc::new(in_process::NoSandbox),
77        }
78    }
79
80    /// Replace the network without touching the rest — the egress policy is
81    /// per-deployment while the other three are per-machine.
82    pub fn with_network(mut self, n: std::sync::Arc<dyn Network>) -> Self {
83        self.network = n;
84        self
85    }
86}
87
88impl std::fmt::Debug for ExecProviders {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.write_str("ExecProviders")
91    }
92}
93
94/// Why an execution-layer call did not do what was asked.
95///
96/// Three variants because a tool has three different things to say about
97/// them, and collapsing any two would make one of those sentences
98/// unavailable. "The execution environment is unreachable" is the host's
99/// problem; "the policy refused" is something the model should work around;
100/// "the file does not exist" is the model's to interpret.
101#[derive(Debug, Clone, thiserror::Error)]
102#[non_exhaustive]
103pub enum ExecError {
104    /// The provider itself is not usable — a remote that cannot be reached, a
105    /// backend that was never mounted.
106    ///
107    /// A provider that reports this must never have fallen back to executing
108    /// locally instead. A deployment configured to run elsewhere, quietly
109    /// running here when the elsewhere is down, has an isolation promise that
110    /// fails exactly when it is needed.
111    #[error("execution environment unavailable: {0}")]
112    Unavailable(String),
113
114    /// A policy refused: the sandbox, the network egress rules, a path
115    /// outside what may be written.
116    #[error("refused by policy: {0}")]
117    Denied(String),
118
119    /// The target's own failure — no such file, a non-zero exit, an HTTP 500.
120    #[error("{0}")]
121    Failed(String),
122}
123
124impl ExecError {
125    pub fn unavailable(m: impl std::fmt::Display) -> Self {
126        Self::Unavailable(m.to_string())
127    }
128    pub fn denied(m: impl std::fmt::Display) -> Self {
129        Self::Denied(m.to_string())
130    }
131    pub fn failed(m: impl std::fmt::Display) -> Self {
132        Self::Failed(m.to_string())
133    }
134}
135
136/// The three sentences of [`ExecError`], said in the vocabulary a tool result
137/// speaks.
138///
139/// Collapsing them would cost the host the one case it can act on: a
140/// `Denied` is the model's to work around, a `Failed` is the target's own
141/// words, and an `Unavailable` is neither — it keeps its own prefix so that a
142/// deployment whose execution environment is down reads as a broken
143/// environment rather than as a tool the model used wrongly.
144impl From<ExecError> for crate::error::ToolError {
145    fn from(e: ExecError) -> Self {
146        match e {
147            ExecError::Unavailable(_) => Self::exec(e.to_string()),
148            ExecError::Denied(m) => Self::Denied(m),
149            ExecError::Failed(m) => Self::exec(m),
150        }
151    }
152}