merry-tools 0.1.0

Workspace file, search, patch, web fetch, and document tools for the Merry agent runtime.
Documentation
use std::{
    io,
    path::{Path, PathBuf},
    sync::Arc,
};

use merry_runtime::DurableMemory;
use thiserror::Error;

/// Limits applied by workspace tools.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkspaceToolLimits {
    /// Maximum bytes returned or scanned by one text `read_file` request.
    pub max_read_bytes: usize,
    /// Maximum lines returned by one text `read_file` request, also used when omitted.
    /// Defaults to 2,000 lines; the independent byte limit still applies.
    pub max_read_lines: usize,
    /// Maximum bytes written to one file by `apply_patch`.
    pub max_write_bytes: usize,
    /// Maximum bytes accepted in one `apply_patch` patch payload.
    pub max_patch_bytes: usize,
}

impl Default for WorkspaceToolLimits {
    fn default() -> Self {
        Self {
            max_read_bytes: 1024 * 1024,
            max_read_lines: 2_000,
            max_write_bytes: 1024 * 1024,
            max_patch_bytes: 128 * 1024,
        }
    }
}

/// Configuration for workspace tools.
#[derive(Debug, Clone)]
pub struct WorkspaceToolsConfig {
    pub(crate) root: PathBuf,
    pub(crate) readonly_resource_roots: Vec<PathBuf>,
    pub(crate) limits: WorkspaceToolLimits,
    pub(crate) read_scope: Option<Vec<PathBuf>>,
    pub(crate) patch_write_scope: Option<Vec<PathBuf>>,
    pub(crate) forbidden_paths: Vec<PathBuf>,
    pub(crate) denied_absolute_paths: Vec<PathBuf>,
    pub(crate) durable_memory: Option<Arc<DurableMemory>>,
}

impl WorkspaceToolsConfig {
    /// Creates a config with one workspace root.
    ///
    /// A workspace has exactly one root, so a relative path never has to be
    /// guessed between candidates. Anything outside that root is named by its
    /// own absolute path, where the sandbox decides reachability.
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            readonly_resource_roots: Vec::new(),
            limits: WorkspaceToolLimits::default(),
            read_scope: None,
            patch_write_scope: None,
            forbidden_paths: Vec::new(),
            denied_absolute_paths: Vec::new(),
            durable_memory: None,
        }
    }

    /// Attaches the durable memory store enforced by read and patch tools.
    #[must_use]
    pub fn with_durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
        self.durable_memory = Some(memory);
        self
    }

    /// Returns the configured, pre-canonical workspace root.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Returns independent read-only resource roots, such as skill directories.
    /// Resources are addressable by the same relative read APIs but are never
    /// patch targets.
    #[must_use]
    pub fn readonly_resource_roots(&self) -> &[PathBuf] {
        &self.readonly_resource_roots
    }

    /// Adds read-only resource roots without treating them as a workspace root.
    #[must_use]
    pub fn with_readonly_resource_roots(mut self, roots: Vec<PathBuf>) -> Self {
        self.readonly_resource_roots = roots;
        self
    }

    /// Returns the configured tool limits.
    #[must_use]
    pub fn limits(&self) -> &WorkspaceToolLimits {
        &self.limits
    }

    /// Returns the optional workspace-relative read scope for `read_file`.
    #[must_use]
    pub fn read_scope(&self) -> Option<&[PathBuf]> {
        self.read_scope.as_deref()
    }

    /// Returns the optional workspace-relative write scope for `apply_patch`.
    #[must_use]
    pub fn patch_write_scope(&self) -> Option<&[PathBuf]> {
        self.patch_write_scope.as_deref()
    }

    /// Returns workspace-relative paths forbidden to `apply_patch` and `read_file`.
    #[must_use]
    pub fn forbidden_paths(&self) -> &[PathBuf] {
        &self.forbidden_paths
    }

    /// Sets workspace tool limits.
    #[must_use]
    pub fn with_limits(mut self, limits: WorkspaceToolLimits) -> Self {
        self.limits = limits;
        self
    }

    /// Sets the optional root-relative read scope for `read_file`.
    ///
    /// `None` preserves existing unrestricted workspace read behavior.
    /// `Some([])` denies all workspace file reads (read-only resource roots
    /// such as skills remain readable).
    #[must_use]
    pub fn with_read_scope(mut self, paths: Option<Vec<PathBuf>>) -> Self {
        self.read_scope = paths;
        self
    }

    /// Sets the optional root-relative write scope for `apply_patch`.
    ///
    /// `None` preserves existing unrestricted patch behavior. `Some([])` makes
    /// the patch tool read-only by denying all writes.
    #[must_use]
    pub fn with_patch_write_scope(mut self, paths: Option<Vec<PathBuf>>) -> Self {
        self.patch_write_scope = paths;
        self
    }

    /// Sets root-relative paths forbidden to `apply_patch`.
    #[must_use]
    pub fn with_forbidden_paths(mut self, paths: Vec<PathBuf>) -> Self {
        self.forbidden_paths = paths;
        self
    }

    /// Returns absolute host paths denied to both `read_file` and `apply_patch`
    /// (for example Merry's private state and credential directories).
    #[must_use]
    pub fn denied_absolute_paths(&self) -> &[PathBuf] {
        &self.denied_absolute_paths
    }

    /// Sets absolute host paths denied to both `read_file` and `apply_patch`.
    #[must_use]
    pub fn with_denied_absolute_paths(mut self, paths: Vec<PathBuf>) -> Self {
        self.denied_absolute_paths = paths;
        self
    }
}

/// Errors raised while validating workspace tool configuration.
#[derive(Debug, Error)]
pub enum WorkspaceToolConfigError {
    /// A built-in tool declaration could not be validated.
    #[error("invalid built-in tool definition: {0}")]
    ToolDefinition(#[from] merry_runtime::ToolBuildError),
    /// A configured root does not exist.
    #[error("workspace root does not exist: {root}")]
    RootNotFound {
        /// Configured root path.
        root: PathBuf,
    },
    /// A configured root could not be canonicalized.
    #[error("could not canonicalize workspace root {root}: {source}")]
    RootCanonicalize {
        /// Configured root path.
        root: PathBuf,
        /// Source IO error.
        #[source]
        source: io::Error,
    },
    /// A configured root is not a directory.
    #[error("workspace root is not a directory: {root}")]
    RootNotDirectory {
        /// Configured root path.
        root: PathBuf,
    },
    /// A numeric limit is invalid.
    #[error("workspace tool limit {name} must be greater than zero")]
    InvalidLimit {
        /// Limit name.
        name: &'static str,
    },
    /// A workspace tool scope path was not relative and normalized.
    #[error("workspace tool scope path must be relative and normalized: {path}")]
    InvalidScopePath {
        /// Rejected scope path.
        path: PathBuf,
    },
}