Skip to main content

aither_sandbox/
tool_runtime.rs

1use std::ffi::{OsStr, OsString};
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4
5use askama::Template;
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8
9use crate::ContainerPath;
10
11/// Commands guaranteed by a prepared execution environment.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum ManagedTool {
15    /// Contextual multi-file editing.
16    ApplyPatch,
17    /// Parallel text and file search.
18    Ripgrep,
19    /// Syntax-aware code search.
20    AstGrep,
21    /// JSON selection and transformation.
22    Jq,
23}
24
25impl ManagedTool {
26    /// The complete baseline, in stable prompt order.
27    pub const ALL: [Self; 4] = [Self::ApplyPatch, Self::Ripgrep, Self::AstGrep, Self::Jq];
28
29    /// Name used by the model in every execution environment.
30    #[must_use]
31    pub const fn command(self) -> &'static str {
32        match self {
33            Self::ApplyPatch => "apply_patch",
34            Self::Ripgrep => "rg",
35            Self::AstGrep => "ast-grep",
36            Self::Jq => "jq",
37        }
38    }
39
40    fn executable_name(self, target: &ToolTarget) -> String {
41        if target.os == "windows" {
42            let mut name = self.command().to_owned();
43            name.push_str(".exe");
44            name
45        } else {
46            self.command().to_owned()
47        }
48    }
49}
50
51/// Operating system and architecture selected during initialization.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct ToolTarget {
54    os: String,
55    arch: String,
56}
57
58impl ToolTarget {
59    /// Resolves the platform of the harness machine.
60    ///
61    /// # Errors
62    /// Returns an error rather than selecting artifacts for an unsupported target.
63    pub fn native() -> Result<Self, ToolRuntimeError> {
64        Self::from_probe(std::env::consts::OS, std::env::consts::ARCH)
65    }
66
67    /// Normalizes an execution backend's platform probe.
68    ///
69    /// # Errors
70    /// Returns an error for an unsupported operating system or architecture.
71    pub fn from_probe(os: &str, arch: &str) -> Result<Self, ToolRuntimeError> {
72        let normalized_os = match os.trim() {
73            "Linux" | "linux" => "linux",
74            "Darwin" | "macos" => "macos",
75            "Windows_NT" | "windows" => "windows",
76            _ => {
77                return Err(ToolRuntimeError::UnsupportedTarget {
78                    os: os.into(),
79                    arch: arch.into(),
80                });
81            }
82        };
83        let normalized_arch = match arch.trim() {
84            "arm64" | "aarch64" => "aarch64",
85            "amd64" | "x86_64" => "x86_64",
86            _ => {
87                return Err(ToolRuntimeError::UnsupportedTarget {
88                    os: os.into(),
89                    arch: arch.into(),
90                });
91            }
92        };
93        Ok(Self {
94            os: normalized_os.into(),
95            arch: normalized_arch.into(),
96        })
97    }
98
99    /// Normalized operating system name.
100    #[must_use]
101    pub fn os(&self) -> &str {
102        &self.os
103    }
104
105    /// Normalized machine architecture.
106    #[must_use]
107    pub fn arch(&self) -> &str {
108        &self.arch
109    }
110}
111
112/// An executable whose bytes match the distribution's trusted digest.
113#[derive(Debug, Clone)]
114pub struct ToolBinary {
115    pub(crate) tool: ManagedTool,
116    version: semver::Version,
117    pub(crate) sha256: [u8; 32],
118    pub(crate) bytes: Arc<[u8]>,
119}
120
121impl ToolBinary {
122    /// Verifies executable bytes before they can enter a prepared environment.
123    ///
124    /// # Errors
125    /// Rejects an invalid version, oversized artifact or mismatched SHA-256.
126    pub fn verify(
127        tool: ManagedTool,
128        version: &str,
129        expected: &[u8; 32],
130        bytes: Vec<u8>,
131    ) -> Result<Self, ToolRuntimeError> {
132        let version = semver::Version::parse(version)?;
133        if bytes.len() > 64 * 1024 * 1024 {
134            return Err(ToolRuntimeError::ArtifactTooLarge(tool));
135        }
136        if digest(&bytes) != *expected {
137            return Err(ToolRuntimeError::Integrity { tool });
138        }
139        Ok(Self {
140            tool,
141            version,
142            sha256: *expected,
143            bytes: bytes.into(),
144        })
145    }
146}
147
148/// Complete, immutable baseline for one execution platform.
149#[derive(Debug, Clone)]
150pub struct ToolBundle {
151    target: ToolTarget,
152    pub(crate) binaries: Arc<[ToolBinary]>,
153}
154
155impl ToolBundle {
156    /// Constructs a complete baseline from verified binaries.
157    ///
158    /// # Errors
159    /// Rejects missing or duplicate commands; partial bundles cannot become ready.
160    pub fn new(
161        target: ToolTarget,
162        mut binaries: Vec<ToolBinary>,
163    ) -> Result<Self, ToolRuntimeError> {
164        binaries.sort_by_key(|binary| binary.tool);
165        for pair in binaries.windows(2) {
166            if pair[0].tool == pair[1].tool {
167                return Err(ToolRuntimeError::DuplicateTool(pair[0].tool));
168            }
169        }
170        for tool in ManagedTool::ALL {
171            if !binaries.iter().any(|binary| binary.tool == tool) {
172                return Err(ToolRuntimeError::MissingTool(tool));
173            }
174        }
175        Ok(Self {
176            target,
177            binaries: binaries.into(),
178        })
179    }
180
181    /// The target platform; never inferred from the coordinator for a remote backend.
182    #[must_use]
183    pub const fn target(&self) -> &ToolTarget {
184        &self.target
185    }
186
187    /// Stable operational metadata shared by every prepared backend.
188    #[must_use]
189    pub fn catalog(&self) -> ToolCatalog {
190        ToolCatalog {
191            tools: self
192                .binaries
193                .iter()
194                .map(|binary| ToolInfo {
195                    command: binary.tool.command(),
196                    version: binary.version.clone(),
197                })
198                .collect(),
199        }
200    }
201
202    #[cfg(test)]
203    fn binary(&self, tool: ManagedTool) -> &ToolBinary {
204        self.binaries
205            .iter()
206            .find(|binary| binary.tool == tool)
207            .expect("bundle is complete")
208    }
209
210    pub(crate) fn cache_key(&self) -> Result<String, ToolRuntimeError> {
211        #[derive(Serialize)]
212        struct Identity<'a> {
213            target: &'a ToolTarget,
214            tools: Vec<(&'a str, &'a semver::Version, &'a [u8; 32])>,
215        }
216        let identity = Identity {
217            target: &self.target,
218            tools: self
219                .binaries
220                .iter()
221                .map(|binary| (binary.tool.command(), &binary.version, &binary.sha256))
222                .collect(),
223        };
224        Ok(hex::encode(digest(&serde_json::to_vec(&identity)?)))
225    }
226
227    /// Prepares or verifies a content-addressed directory outside agent workspaces.
228    ///
229    /// # Errors
230    /// Returns errors for target mismatch, I/O failure or tampered cached content.
231    pub async fn prepare_local(
232        &self,
233        root: &Path,
234    ) -> Result<PreparedTools<PathBuf>, ToolRuntimeError> {
235        if self.target != ToolTarget::native()? {
236            return Err(ToolRuntimeError::TargetMismatch);
237        }
238        let bundle = self.clone();
239        let root = root.to_path_buf();
240        blocking::unblock(move || bundle.prepare_local_sync(&root)).await
241    }
242
243    #[doc = "Prepares target executables on the coordinator and describes their read-only container mount."]
244    #[doc = "# Errors"]
245    #[doc = "Rejects invalid cached content, failed writes or invalid bundle identity."]
246    #[doc = "# Panics"]
247    #[doc = "Panics if the internal prepared directory lacks its required parent."]
248    pub async fn prepare_container_mount(
249        &self,
250        root: &Path,
251    ) -> Result<(crate::MountSpec, PreparedTools<PathBuf>), ToolRuntimeError> {
252        let bundle = self.clone();
253        let root = root.to_path_buf();
254        let source = blocking::unblock(move || bundle.prepare_local_sync(&root)).await?;
255        let destination = self.container_directory()?;
256        let host_directory = source
257            .bin_dir
258            .parent()
259            .expect("prepared binaries have a parent directory")
260            .to_path_buf();
261        Ok((
262            crate::MountSpec::read_only(host_directory, destination),
263            source,
264        ))
265    }
266
267    /// Where the prepared runtime is mounted inside a container.
268    pub(crate) fn container_directory(&self) -> Result<ContainerPath, ToolRuntimeError> {
269        Ok(ContainerPath::root()
270            .join("opt/aither/tools")
271            .join(self.cache_key()?))
272    }
273
274    /// The executable directory inside a container, which goes on its `PATH`.
275    pub(crate) fn container_bin_dir(&self) -> Result<ContainerPath, ToolRuntimeError> {
276        Ok(self.container_directory()?.join("bin"))
277    }
278
279    /// Returns the verified runtime at `<root>/<cache key>`, staging it when it is
280    /// missing and replacing it when its contents are invalid.
281    ///
282    /// Verifying a valid runtime takes no lock. Creation and replacement run under an
283    /// exclusive lock on `<root>/.<cache key>.lock`, so concurrent preparers never
284    /// discard a runtime another preparer has just activated.
285    fn prepare_local_sync(&self, root: &Path) -> Result<PreparedTools<PathBuf>, ToolRuntimeError> {
286        std::fs::create_dir_all(root)?;
287        let root = std::fs::canonicalize(root)?;
288        let key = self.cache_key()?;
289        let destination = root.join(&key);
290        if let Some(prepared) = self.reusable(&destination)? {
291            return Ok(prepared);
292        }
293        let lock_path = root.join(format!(".{key}.lock"));
294        let mut lock = fd_lock::RwLock::new(
295            std::fs::OpenOptions::new()
296                .create(true)
297                .truncate(false)
298                .write(true)
299                .open(&lock_path)?,
300        );
301        let _guard = lock.write()?;
302        // A preparer holding the lock before us may have activated a valid runtime.
303        if let Some(prepared) = self.reusable(&destination)? {
304            return Ok(prepared);
305        }
306        let stage = self.stage(&root)?;
307        let discarded = if destination.try_exists()? {
308            let discarded = tempfile::Builder::new()
309                .prefix(".invalid-")
310                .tempdir_in(&root)?;
311            std::fs::rename(&destination, discarded.path().join("runtime"))?;
312            Some(discarded)
313        } else {
314            None
315        };
316        match std::fs::rename(stage.path(), &destination) {
317            Ok(()) => {}
318            Err(error) if destination.try_exists()? => {
319                tracing::debug!(%error, "another initializer activated the tool bundle");
320            }
321            Err(error) => return Err(error.into()),
322        }
323        if let Some(discarded) = discarded {
324            discarded.close()?;
325        }
326        self.verify_prepared(&destination)
327    }
328
329    /// Verifies an existing runtime; `None` when it is absent or must be replaced.
330    fn reusable(
331        &self,
332        destination: &Path,
333    ) -> Result<Option<PreparedTools<PathBuf>>, ToolRuntimeError> {
334        if !destination.try_exists()? {
335            return Ok(None);
336        }
337        match self.verify_prepared(destination) {
338            Ok(prepared) => Ok(Some(prepared)),
339            Err(
340                error @ (ToolRuntimeError::InvalidCache(_) | ToolRuntimeError::Integrity { .. }),
341            ) => {
342                tracing::warn!(
343                    path = %destination.display(),
344                    %error,
345                    "prepared tool runtime is invalid and will be replaced"
346                );
347                Ok(None)
348            }
349            Err(error) => Err(error),
350        }
351    }
352
353    /// Writes every executable into a fresh `.initializing-` directory under `root`.
354    fn stage(&self, root: &Path) -> Result<tempfile::TempDir, ToolRuntimeError> {
355        let stage = tempfile::Builder::new()
356            .prefix(".initializing-")
357            .tempdir_in(root)?;
358        let bin = stage.path().join("bin");
359        std::fs::create_dir(&bin)?;
360        for binary in self.binaries.iter() {
361            let path = bin.join(binary.tool.executable_name(&self.target));
362            std::fs::write(&path, &binary.bytes)?;
363            set_executable_readonly(&path)?;
364        }
365        Ok(stage)
366    }
367
368    /// Checks that every executable under `destination` is a regular, read-only
369    /// executable file with the trusted digest.
370    fn verify_prepared(
371        &self,
372        destination: &Path,
373    ) -> Result<PreparedTools<PathBuf>, ToolRuntimeError> {
374        let bin_dir = destination.join("bin");
375        for binary in self.binaries.iter() {
376            let path = bin_dir.join(binary.tool.executable_name(&self.target));
377            let metadata = std::fs::symlink_metadata(&path)
378                .map_err(|error| cache_entry_error(&path, error))?;
379            if !metadata.file_type().is_file() {
380                return Err(ToolRuntimeError::InvalidCache(path));
381            }
382            let bytes = std::fs::read(&path).map_err(|error| cache_entry_error(&path, error))?;
383            if digest(&bytes) != binary.sha256 {
384                return Err(ToolRuntimeError::Integrity { tool: binary.tool });
385            }
386            #[cfg(unix)]
387            {
388                use std::os::unix::fs::PermissionsExt;
389                let mode = metadata.permissions().mode();
390                if mode & 0o222 != 0 || mode & 0o111 == 0 {
391                    return Err(ToolRuntimeError::InvalidCache(path));
392                }
393            }
394            #[cfg(not(unix))]
395            if !metadata.permissions().readonly() {
396                return Err(ToolRuntimeError::InvalidCache(path));
397            }
398        }
399        Ok(PreparedTools {
400            bin_dir,
401            catalog: self.catalog(),
402        })
403    }
404}
405
406/// Computes the SHA-256 digest used to validate artifact bytes.
407pub fn digest(bytes: &[u8]) -> [u8; 32] {
408    Sha256::digest(bytes).into()
409}
410
411/// Names the cache entry when it is missing or its parent is not a directory.
412fn cache_entry_error(path: &Path, error: std::io::Error) -> ToolRuntimeError {
413    match error.kind() {
414        std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory => {
415            ToolRuntimeError::InvalidCache(path.to_path_buf())
416        }
417        _ => ToolRuntimeError::Io(error),
418    }
419}
420
421fn set_executable_readonly(path: &Path) -> Result<(), std::io::Error> {
422    #[cfg(unix)]
423    {
424        use std::os::unix::fs::PermissionsExt;
425        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o555))
426    }
427    #[cfg(not(unix))]
428    {
429        let mut permissions = std::fs::metadata(path)?.permissions();
430        permissions.set_readonly(true);
431        std::fs::set_permissions(path, permissions)
432    }
433}
434
435/// Tool directory available only after successful initialization.
436///
437/// `D` is the path type of the environment the tools run in: a host
438/// [`PathBuf`] for the local sandbox and SSH, a [`ContainerPath`] inside a
439/// container.
440#[derive(Debug, Clone)]
441pub struct PreparedTools<D> {
442    pub(crate) bin_dir: D,
443    pub(crate) catalog: ToolCatalog,
444}
445
446impl<D> PreparedTools<D> {
447    /// Read-only executable directory to expose to the sandbox.
448    #[must_use]
449    pub const fn bin_dir(&self) -> &D {
450        &self.bin_dir
451    }
452
453    /// Verified commands to describe to the model before its first request.
454    #[must_use]
455    pub const fn catalog(&self) -> &ToolCatalog {
456        &self.catalog
457    }
458}
459
460impl PreparedTools<PathBuf> {
461    pub(crate) async fn verify_local_versions<E: executor_core::Executor + Clone + 'static>(
462        &self,
463        executor: E,
464    ) -> Result<(), ToolRuntimeError> {
465        use futures::{StreamExt, TryStreamExt};
466        let scratch = blocking::unblock(tempfile::tempdir).await?;
467        let config = heel::SandboxConfig::builder()
468            .working_dir(scratch.path())
469            .grant(&self.bin_dir, heel::Access::READ | heel::Access::EXEC)
470            .build();
471        let sandbox = std::sync::Arc::new(
472            heel::Sandbox::with_config_and_executor(config, executor)
473                .await
474                .map_err(|error| ToolRuntimeError::SshBootstrap(error.to_string()))?,
475        );
476        let directory = self.bin_dir.clone();
477        futures::stream::iter(self.catalog.tools.clone())
478            .map(|info| {
479                let sandbox = sandbox.clone();
480                let program = directory
481                    .join(info.command)
482                    .with_extension(std::env::consts::EXE_EXTENSION);
483                async move {
484                    let program = program
485                        .to_str()
486                        .ok_or_else(|| ToolRuntimeError::InvalidCache(program.clone()))?;
487                    let command = sandbox.command(program).arg("--version");
488                    let output = futures_lite::future::or(
489                        async {
490                            command
491                                .output()
492                                .await
493                                .map_err(|error| ToolRuntimeError::SshBootstrap(error.to_string()))
494                        },
495                        async {
496                            async_io::Timer::after(std::time::Duration::from_secs(30)).await;
497                            Err(ToolRuntimeError::InitializationTimeout)
498                        },
499                    )
500                    .await?;
501                    if !output.status.success() {
502                        return Err(ToolRuntimeError::VersionMismatch(info.command.into()));
503                    }
504                    info.verify_version(&String::from_utf8(output.stdout)?)
505                }
506            })
507            .buffer_unordered(ManagedTool::ALL.len())
508            .try_collect::<Vec<_>>()
509            .await?;
510        Ok(())
511    }
512
513    #[doc = "Rejects writable host grants that expose the managed executable directory."]
514    #[doc = "# Errors"]
515    #[doc = "Returns path resolution errors or a writable-directory conflict."]
516    pub async fn ensure_readonly<'a>(
517        &self,
518        paths: impl IntoIterator<Item = &'a PathBuf> + Send,
519    ) -> Result<(), ToolRuntimeError> {
520        use futures::{StreamExt, TryStreamExt};
521        let paths = paths.into_iter().cloned().collect::<Vec<_>>();
522        let bin_dir = async_fs::canonicalize(&self.bin_dir).await?;
523        futures::stream::iter(paths)
524            .map(|path| {
525                let bin_dir = &bin_dir;
526                async move {
527                    let canonical = async_fs::canonicalize(path).await?;
528                    if bin_dir.starts_with(&canonical) || canonical.starts_with(bin_dir) {
529                        return Err(ToolRuntimeError::WritableToolDirectory(canonical));
530                    }
531                    Ok(())
532                }
533            })
534            .buffer_unordered(4)
535            .try_collect::<Vec<_>>()
536            .await?;
537        Ok(())
538    }
539
540    /// Prepends the prepared directory while retaining the backend's own PATH.
541    ///
542    /// # Errors
543    /// Returns an error when a path cannot be represented in the platform's PATH format.
544    pub fn prepend_path(&self, existing: Option<&OsStr>) -> Result<OsString, ToolRuntimeError> {
545        let existing = existing.map(std::env::split_paths).into_iter().flatten();
546        Ok(std::env::join_paths(
547            std::iter::once(self.bin_dir.clone()).chain(existing),
548        )?)
549    }
550}
551
552#[derive(Template)]
553#[template(path = "tool_path.sh", escape = "none")]
554struct ToolPathTemplate<'a> {
555    bin_dir: std::borrow::Cow<'a, str>,
556    script: &'a str,
557}
558
559impl PreparedTools<PathBuf> {
560    /// The executable directory as text a shell script can name.
561    pub(crate) fn script_bin_dir(&self) -> Result<&str, ToolRuntimeError> {
562        self.bin_dir
563            .to_str()
564            .ok_or_else(|| ToolRuntimeError::InvalidCache(self.bin_dir.clone()))
565    }
566
567    pub(crate) fn wrap_script(&self, script: &str) -> Result<String, ToolRuntimeError> {
568        render_tool_path(self.script_bin_dir()?, script)
569    }
570}
571
572impl PreparedTools<ContainerPath> {
573    pub(crate) fn wrap_script(&self, script: &str) -> Result<String, ToolRuntimeError> {
574        render_tool_path(self.bin_dir.as_str(), script)
575    }
576}
577
578/// Prepends `bin_dir` to a POSIX shell script's `PATH`.
579fn render_tool_path(bin_dir: &str, script: &str) -> Result<String, ToolRuntimeError> {
580    Ok(ToolPathTemplate {
581        bin_dir: shell_words::quote(bin_dir),
582        script,
583    }
584    .render()?)
585}
586
587/// Prepared command versions, in stable order independent of cache paths.
588#[derive(Debug, Clone, PartialEq, Eq)]
589pub struct ToolCatalog {
590    tools: Vec<ToolInfo>,
591}
592
593#[derive(Debug, Clone, PartialEq, Eq)]
594struct ToolInfo {
595    command: &'static str,
596    version: semver::Version,
597}
598
599impl ToolCatalog {
600    pub(crate) fn verify_versions(&self, output: &str) -> Result<(), ToolRuntimeError> {
601        let reported = output.split_terminator('\0').collect::<Vec<_>>();
602        if reported.len() != self.tools.len() {
603            return Err(ToolRuntimeError::InvalidProbe);
604        }
605        for (info, output) in self.tools.iter().zip(reported) {
606            info.verify_version(output)?;
607        }
608        Ok(())
609    }
610}
611
612impl ToolInfo {
613    fn verify_version(&self, output: &str) -> Result<(), ToolRuntimeError> {
614        let reported = output
615            .lines()
616            .next()
617            .and_then(|line| {
618                line.strip_prefix("jq-")
619                    .or_else(|| line.split_whitespace().nth(1))
620            })
621            .and_then(|version| semver::Version::parse(version).ok());
622        if reported.as_ref() != Some(&self.version) {
623            return Err(ToolRuntimeError::VersionMismatch(self.command.into()));
624        }
625        Ok(())
626    }
627}
628
629#[derive(Template)]
630#[template(path = "prepared_tools.txt", escape = "none")]
631struct ToolCatalogTemplate<'a> {
632    tools: &'a [ToolInfo],
633}
634
635impl ToolCatalog {
636    /// Renders concise operational instructions without a command-discovery phase.
637    ///
638    /// # Errors
639    /// Returns a template rendering error.
640    pub fn render(&self) -> Result<String, ToolRuntimeError> {
641        Ok(ToolCatalogTemplate { tools: &self.tools }.render()?)
642    }
643}
644
645/// A part of a registry's configuration that preparation is bound to.
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
647pub enum PreparedEnvironment {
648    /// The backend that runs commands on this machine or in its container.
649    HomeBackend,
650    /// The container the home tools were mounted into.
651    Container,
652    /// The set of SSH servers and their targets.
653    SshServers,
654}
655
656impl std::fmt::Display for PreparedEnvironment {
657    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
658        formatter.write_str(match self {
659            Self::HomeBackend => "the home execution backend",
660            Self::Container => "the container runtime",
661            Self::SshServers => "the SSH server set",
662        })
663    }
664}
665
666/// Fail-closed errors from tool initialization and shell integration.
667#[derive(Debug, thiserror::Error)]
668pub enum ToolRuntimeError {
669    /// Configured container has no execution transport.
670    #[error("container runtime is not configured")]
671    MissingContainerRuntime,
672    /// Environments resolved different command versions.
673    #[error("prepared tool catalogs differ between environments")]
674    CatalogMismatch,
675    /// SSH runtime bootstrap failed.
676    #[error("SSH runtime initialization failed: {0}")]
677    SshBootstrap(String),
678    /// Installation was not authorized.
679    #[error("managed tool installation denied for {0}")]
680    InstallDenied(String),
681    /// Application authorizer failed.
682    #[error("tool installation authorization failed: {0}")]
683    Authorization(crate::SshAuthorizationError),
684    /// Initialization transport was cancelled.
685    #[error("tool initialization interrupted")]
686    InitializationInterrupted,
687    /// Initialization exceeded its bounded deadline.
688    #[error("tool initialization timed out")]
689    InitializationTimeout,
690    /// Backend platform/path probe was malformed.
691    #[error("invalid tool environment probe output")]
692    InvalidProbe,
693    /// Trusted initialization command failed.
694    #[error("tool initialization command failed ({status:?}): {stderr}")]
695    InitializationCommand {
696        /// Process exit status, if available.
697        status: Option<i32>,
698        /// Backend diagnostic, without artifact contents.
699        stderr: String,
700    },
701    /// Container initialization transport failed.
702    #[error("container tool initialization failed: {0}")]
703    Container(String),
704    /// Backend output is not valid UTF-8.
705    #[error(transparent)]
706    Utf8(#[from] std::string::FromUtf8Error),
707    /// Initialization has not prepared the requested execution environment.
708    #[error("tool runtime is not initialized for {0}")]
709    NotInitialized(String),
710    /// The registry's configuration changed after its environments were prepared.
711    #[error("{0} changed after tool preparation")]
712    EnvironmentChanged(PreparedEnvironment),
713    /// Agent write permissions would expose managed executable contents.
714    #[error("managed tool directory overlaps a writable sandbox path: {0}")]
715    WritableToolDirectory(PathBuf),
716    /// No artifact set supports the probed platform.
717    #[error("unsupported tool target: {os}/{arch}")]
718    UnsupportedTarget {
719        /// Probed operating system.
720        os: String,
721        /// Probed architecture.
722        arch: String,
723    },
724    /// The executable cannot run or does not report the pinned version.
725    #[error("prepared tool failed its version probe: {0}")]
726    VersionMismatch(String),
727    #[doc = "Container mount metadata could not be parsed."]
728    #[error(transparent)]
729    MountInfo(#[from] procfs_core::ProcError),
730    #[doc = "The tools directory is not protected by a read-only container mount."]
731    #[error("managed tools require a read-only container mount: {0}")]
732    MissingReadonlyMount(ContainerPath),
733    /// Required command missing from a bundle.
734    #[error("required tool is missing: {0:?}")]
735    MissingTool(ManagedTool),
736    /// A bundle declares the same command twice.
737    #[error("duplicate managed tool: {0:?}")]
738    DuplicateTool(ManagedTool),
739    /// Bytes do not match the trusted artifact manifest.
740    #[error("tool artifact failed SHA-256 verification: {tool:?}")]
741    Integrity {
742        /// Command whose artifact failed verification.
743        tool: ManagedTool,
744    },
745    /// An artifact exceeds the executable-size limit.
746    #[error("tool artifact exceeds the size limit: {0:?}")]
747    ArtifactTooLarge(ManagedTool),
748    /// A cached command is not a regular read-only executable.
749    #[error("invalid prepared tool cache entry: {0}")]
750    InvalidCache(PathBuf),
751    /// Host installation cannot use another platform's binaries.
752    #[error("tool artifact platform does not match the execution environment")]
753    TargetMismatch,
754    /// Filesystem preparation failed.
755    #[error(transparent)]
756    Io(#[from] std::io::Error),
757    /// Manifest version is not semantic versioning.
758    #[error(transparent)]
759    Version(#[from] semver::Error),
760    /// PATH could not be assembled.
761    #[error(transparent)]
762    Path(#[from] std::env::JoinPathsError),
763    /// Manifest encoding failed.
764    #[error(transparent)]
765    Manifest(#[from] serde_json::Error),
766    /// Artifact source is neither a local file nor credential-free HTTPS.
767    #[error("{0:?} requires a local file or credential-free HTTPS artifact source")]
768    ArtifactSource(ManagedTool),
769    /// Distribution returned a non-success HTTP status.
770    #[error("tool artifact download failed with HTTP status {0}")]
771    DownloadStatus(u16),
772    /// Artifact transfer failed.
773    #[error(transparent)]
774    Download(#[from] zenwave::Error),
775    /// Artifact checksum is not a SHA-256 hexadecimal value.
776    #[error(transparent)]
777    Digest(#[from] hex::FromHexError),
778    /// Executable archive entry is missing, ambiguous, oversized or not regular.
779    #[error("invalid executable archive member")]
780    InvalidArchive,
781    /// ZIP decoding failed.
782    #[error(transparent)]
783    Zip(#[from] zip::result::ZipError),
784    /// Operational prompt rendering failed.
785    #[error(transparent)]
786    Template(#[from] askama::Error),
787}
788
789#[cfg(test)]
790pub mod tests {
791    use super::*;
792    use std::ffi::OsStr;
793
794    #[test]
795    fn artifact_digest_matches_known_sha256_vector() {
796        assert_eq!(
797            hex::encode(digest(b"abc")),
798            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
799        );
800    }
801
802    pub fn bundle() -> ToolBundle {
803        bundle_pinned("1.0.0")
804    }
805
806    /// A bundle pinned to `version` whose commands all report version 1.0.0,
807    /// so any other pin fails the version probe while passing integrity checks.
808    pub fn bundle_pinned(version: &str) -> ToolBundle {
809        let binaries = ManagedTool::ALL
810            .into_iter()
811            .map(|tool| {
812                let bytes =
813                    format!("#!/bin/sh\nprintf '%s\\n' '{} 1.0.0'\n", tool.command()).into_bytes();
814                ToolBinary::verify(tool, version, &digest(&bytes), bytes).unwrap()
815            })
816            .collect();
817        ToolBundle::new(ToolTarget::native().unwrap(), binaries).unwrap()
818    }
819
820    /// Tools as a container sees them once the bundle is mounted read-only.
821    pub fn container_tools(bundle: &ToolBundle) -> PreparedTools<ContainerPath> {
822        PreparedTools {
823            bin_dir: bundle.container_bin_dir().unwrap(),
824            catalog: bundle.catalog(),
825        }
826    }
827
828    // Runs on every host: Windows must still produce POSIX container paths.
829    #[test]
830    fn container_tool_paths_are_posix_on_every_host() {
831        let bundle = bundle();
832        let key = bundle.cache_key().unwrap();
833        assert_eq!(
834            bundle.container_directory().unwrap().as_str(),
835            format!("/opt/aither/tools/{key}")
836        );
837        assert_eq!(
838            bundle.container_bin_dir().unwrap().as_str(),
839            format!("/opt/aither/tools/{key}/bin")
840        );
841        let script = container_tools(&bundle)
842            .wrap_script("rg --version")
843            .unwrap();
844        assert!(
845            script.starts_with(&format!("PATH=/opt/aither/tools/{key}/bin")),
846            "{script}"
847        );
848    }
849
850    #[tokio::test]
851    async fn container_mount_targets_the_posix_tool_directory() {
852        let cache = tempfile::tempdir().unwrap();
853        let bundle = bundle();
854        let (mount, host) = bundle.prepare_container_mount(cache.path()).await.unwrap();
855        assert_eq!(
856            mount.container_path.as_str(),
857            format!("/opt/aither/tools/{}", bundle.cache_key().unwrap())
858        );
859        assert_eq!(Some(mount.host_path.as_path()), host.bin_dir().parent());
860        assert!(mount.access.read_only());
861    }
862
863    #[test]
864    fn missing_baseline_tool_is_an_initialization_error() {
865        let mut binaries = bundle().binaries.to_vec();
866        binaries.pop();
867        assert!(matches!(
868            ToolBundle::new(ToolTarget::native().unwrap(), binaries),
869            Err(ToolRuntimeError::MissingTool(ManagedTool::Jq))
870        ));
871    }
872
873    #[test]
874    fn incorrect_digest_is_rejected_before_installation() {
875        assert!(matches!(
876            ToolBinary::verify(ManagedTool::Ripgrep, "1.0.0", &[0; 32], b"corrupt".to_vec()),
877            Err(ToolRuntimeError::Integrity {
878                tool: ManagedTool::Ripgrep
879            })
880        ));
881    }
882
883    #[tokio::test]
884    async fn initialize_outside_workspace_and_reuse_verified_content() {
885        let cache = tempfile::tempdir().unwrap();
886        let bundle = bundle();
887        let first = bundle.prepare_local(cache.path()).await.unwrap();
888        let second = bundle.prepare_local(cache.path()).await.unwrap();
889        assert_eq!(first.bin_dir(), second.bin_dir());
890        assert_eq!(first.catalog(), second.catalog());
891        for tool in ManagedTool::ALL {
892            let path = first.bin_dir().join(tool.executable_name(&bundle.target));
893            assert_eq!(
894                async_fs::read(path).await.unwrap().as_slice(),
895                bundle.binary(tool).bytes.as_ref()
896            );
897        }
898        let existing = [
899            cache.path().join("system tools"),
900            cache.path().join("project tools"),
901        ];
902        let original_path = std::env::join_paths(&existing).unwrap();
903        let path = first.prepend_path(Some(&original_path)).unwrap();
904        let entries = std::env::split_paths(&path).collect::<Vec<_>>();
905        assert_eq!(entries[0], *first.bin_dir());
906        assert_eq!(entries[1..], existing);
907    }
908
909    #[tokio::test]
910    async fn concurrent_initialization_never_exposes_partial_tools() {
911        let cache = tempfile::tempdir().unwrap();
912        let bundle = bundle();
913        let (left, right) = futures_lite::future::zip(
914            bundle.prepare_local(cache.path()),
915            bundle.prepare_local(cache.path()),
916        )
917        .await;
918        let left = left.unwrap();
919        let right = right.unwrap();
920        assert_eq!(left.bin_dir(), right.bin_dir());
921        for tool in ManagedTool::ALL {
922            assert!(
923                left.bin_dir()
924                    .join(tool.executable_name(&bundle.target))
925                    .is_file()
926            );
927        }
928    }
929
930    #[tokio::test]
931    async fn managed_tools_cannot_overlap_a_writable_grant() {
932        let cache = tempfile::tempdir().unwrap();
933        let workspace = tempfile::tempdir().unwrap();
934        let ready = bundle().prepare_local(cache.path()).await.unwrap();
935        ready
936            .ensure_readonly([&workspace.path().to_path_buf()])
937            .await
938            .unwrap();
939        let result = ready.ensure_readonly([&cache.path().to_path_buf()]).await;
940        assert!(matches!(
941            result,
942            Err(ToolRuntimeError::WritableToolDirectory(_))
943        ));
944    }
945
946    #[tokio::test]
947    async fn writable_grant_to_one_managed_executable_is_rejected() {
948        let cache = tempfile::tempdir().unwrap();
949        let bundle = bundle();
950        let ready = bundle.prepare_local(cache.path()).await.unwrap();
951        let executable = ready
952            .bin_dir()
953            .join(ManagedTool::Ripgrep.executable_name(&bundle.target));
954        assert!(matches!(
955            ready.ensure_readonly([&executable]).await,
956            Err(ToolRuntimeError::WritableToolDirectory(_))
957        ));
958    }
959
960    fn assert_prepared(bundle: &ToolBundle, prepared: &PreparedTools<PathBuf>) {
961        for tool in ManagedTool::ALL {
962            let path = prepared
963                .bin_dir()
964                .join(tool.executable_name(&bundle.target));
965            assert_eq!(
966                std::fs::read(&path).unwrap().as_slice(),
967                bundle.binary(tool).bytes.as_ref(),
968                "{} differs from the bundle",
969                path.display()
970            );
971        }
972        bundle
973            .verify_prepared(prepared.bin_dir().parent().unwrap())
974            .unwrap();
975    }
976
977    /// Entries left in the cache root other than the runtime and its lock file.
978    fn leftovers(root: &Path, bundle: &ToolBundle) -> Vec<OsString> {
979        let key = bundle.cache_key().unwrap();
980        let lock = format!(".{key}.lock");
981        std::fs::read_dir(root)
982            .unwrap()
983            .map(|entry| entry.unwrap().file_name())
984            .filter(|name| *name != *key && *name != *lock)
985            .collect()
986    }
987
988    fn make_writable(path: &Path) {
989        let mut permissions = std::fs::metadata(path).unwrap().permissions();
990        #[cfg(unix)]
991        {
992            use std::os::unix::fs::PermissionsExt;
993            permissions.set_mode(0o755);
994        }
995        #[cfg(not(unix))]
996        permissions.set_readonly(false);
997        std::fs::set_permissions(path, permissions).unwrap();
998    }
999
1000    #[test]
1001    fn missing_executable_is_reported_with_its_path() {
1002        let cache = tempfile::tempdir().unwrap();
1003        let bundle = bundle();
1004        let destination = cache.path().join(bundle.cache_key().unwrap());
1005        std::fs::create_dir_all(destination.join("bin")).unwrap();
1006        let first = destination
1007            .join("bin")
1008            .join(bundle.binaries[0].tool.executable_name(&bundle.target));
1009        assert!(matches!(
1010            bundle.verify_prepared(&destination),
1011            Err(ToolRuntimeError::InvalidCache(path)) if path == first
1012        ));
1013    }
1014
1015    #[tokio::test]
1016    async fn empty_runtime_skeleton_is_replaced() {
1017        let cache = tempfile::tempdir().unwrap();
1018        let bundle = bundle();
1019        std::fs::create_dir_all(cache.path().join(bundle.cache_key().unwrap()).join("bin"))
1020            .unwrap();
1021        let ready = bundle.prepare_local(cache.path()).await.unwrap();
1022        assert_prepared(&bundle, &ready);
1023        assert_eq!(leftovers(cache.path(), &bundle), Vec::<OsString>::new());
1024    }
1025
1026    #[tokio::test]
1027    async fn tampered_executable_is_replaced() {
1028        let cache = tempfile::tempdir().unwrap();
1029        let bundle = bundle();
1030        let ready = bundle.prepare_local(cache.path()).await.unwrap();
1031        let path = ready
1032            .bin_dir()
1033            .join(ManagedTool::Ripgrep.executable_name(&bundle.target));
1034        make_writable(&path);
1035        std::fs::write(&path, b"tampered").unwrap();
1036        assert!(matches!(
1037            bundle.verify_prepared(ready.bin_dir().parent().unwrap()),
1038            Err(ToolRuntimeError::Integrity {
1039                tool: ManagedTool::Ripgrep
1040            })
1041        ));
1042        let repaired = bundle.prepare_local(cache.path()).await.unwrap();
1043        assert_eq!(repaired.bin_dir(), ready.bin_dir());
1044        assert_prepared(&bundle, &repaired);
1045        assert_eq!(leftovers(cache.path(), &bundle), Vec::<OsString>::new());
1046    }
1047
1048    #[tokio::test]
1049    async fn writable_executable_is_replaced() {
1050        let cache = tempfile::tempdir().unwrap();
1051        let bundle = bundle();
1052        let ready = bundle.prepare_local(cache.path()).await.unwrap();
1053        let path = ready
1054            .bin_dir()
1055            .join(ManagedTool::Jq.executable_name(&bundle.target));
1056        make_writable(&path);
1057        assert!(matches!(
1058            bundle.verify_prepared(ready.bin_dir().parent().unwrap()),
1059            Err(ToolRuntimeError::InvalidCache(invalid)) if invalid == path
1060        ));
1061        let repaired = bundle.prepare_local(cache.path()).await.unwrap();
1062        assert_prepared(&bundle, &repaired);
1063    }
1064
1065    #[tokio::test]
1066    async fn valid_runtime_is_reused_untouched() {
1067        let cache = tempfile::tempdir().unwrap();
1068        let bundle = bundle();
1069        let ready = bundle.prepare_local(cache.path()).await.unwrap();
1070        let snapshot = |prepared: &PreparedTools<PathBuf>| {
1071            let mut entries = vec![prepared.bin_dir().parent().unwrap().to_path_buf()];
1072            entries.push(prepared.bin_dir().clone());
1073            entries.extend(ManagedTool::ALL.into_iter().map(|tool| {
1074                prepared
1075                    .bin_dir()
1076                    .join(tool.executable_name(&bundle.target))
1077            }));
1078            entries
1079                .into_iter()
1080                .map(|path| {
1081                    let metadata = std::fs::symlink_metadata(&path).unwrap();
1082                    #[cfg(unix)]
1083                    let inode = std::os::unix::fs::MetadataExt::ino(&metadata);
1084                    #[cfg(not(unix))]
1085                    let inode = 0;
1086                    (path, inode, metadata.modified().unwrap())
1087                })
1088                .collect::<Vec<_>>()
1089        };
1090        let before = snapshot(&ready);
1091        let reused = bundle.prepare_local(cache.path()).await.unwrap();
1092        assert_eq!(before, snapshot(&reused));
1093    }
1094
1095    #[tokio::test]
1096    async fn concurrent_preparers_repair_one_damaged_runtime() {
1097        let cache = tempfile::tempdir().unwrap();
1098        let bundle = bundle();
1099        std::fs::create_dir_all(cache.path().join(bundle.cache_key().unwrap()).join("bin"))
1100            .unwrap();
1101        let results =
1102            futures::future::join_all((0..8).map(|_| bundle.prepare_local(cache.path()))).await;
1103        for result in results {
1104            assert_prepared(&bundle, &result.unwrap());
1105        }
1106        assert_eq!(leftovers(cache.path(), &bundle), Vec::<OsString>::new());
1107    }
1108
1109    #[test]
1110    fn prompt_catalog_is_operational_and_stable() {
1111        let catalog = bundle().catalog();
1112        let first = catalog.render().unwrap();
1113        assert_eq!(first, catalog.render().unwrap());
1114        assert!(first.contains("ast-grep run"));
1115        assert!(first.contains("rg -n"));
1116        assert!(first.contains("*** Begin Patch"));
1117        assert!(first.contains("wait"));
1118        assert!(!first.contains("command -v"));
1119        assert!(!first.contains("which "));
1120    }
1121
1122    struct RuntimeProbe;
1123
1124    #[derive(serde::Deserialize, schemars::JsonSchema)]
1125    struct RuntimeProbeArgs {}
1126
1127    impl heel::IpcCommand for RuntimeProbe {
1128        fn name(&self) -> std::borrow::Cow<'static, str> {
1129            "runtime_probe".into()
1130        }
1131        type Args = RuntimeProbeArgs;
1132        type Response = String;
1133        fn handle(&self, _args: RuntimeProbeArgs) -> impl Future<Output = String> {
1134            std::future::ready("runtime_probe_ok".into())
1135        }
1136    }
1137
1138    #[tokio::test]
1139    async fn prepared_path_retains_heel_ipc_commands() {
1140        let cache = tempfile::tempdir().unwrap();
1141        let workspace = tempfile::tempdir().unwrap();
1142        let ready = bundle().prepare_local(cache.path()).await.unwrap();
1143        let sandbox_path = heel::default_sandbox_path();
1144        let path = ready.prepend_path(Some(OsStr::new(&sandbox_path))).unwrap();
1145        let config = heel::SandboxConfig::builder()
1146            .network(heel::DenyAll)
1147            .working_dir(workspace.path())
1148            .grants([heel::Grant::new(ready.bin_dir(), heel::Access::EXEC)])
1149            .ipc(heel::IpcRouter::new().register(RuntimeProbe))
1150            .security(heel::SecurityConfig::interactive())
1151            .build();
1152        let sandbox =
1153            heel::Sandbox::with_config_and_executor(config, executor_core::tokio::TokioGlobal)
1154                .await
1155                .unwrap();
1156        #[cfg(not(windows))]
1157        let command = sandbox.command("sh").args(["-c", "runtime_probe"]);
1158        #[cfg(windows)]
1159        let command = sandbox
1160            .command("cmd.exe")
1161            .args(["/D", "/S", "/C", "runtime_probe"]);
1162        let output = command
1163            .env("PATH", path.to_str().unwrap())
1164            .output()
1165            .await
1166            .unwrap();
1167        assert!(
1168            output.status.success(),
1169            "prepared PATH removed IPC commands: {}",
1170            String::from_utf8_lossy(&output.stderr)
1171        );
1172        assert!(String::from_utf8_lossy(&output.stdout).contains("runtime_probe_ok"));
1173    }
1174
1175    #[test]
1176    fn unknown_remote_platform_is_not_a_native_fallback() {
1177        assert!(matches!(
1178            ToolTarget::from_probe("FreeBSD", "riscv64"),
1179            Err(ToolRuntimeError::UnsupportedTarget { .. })
1180        ));
1181    }
1182}