Skip to main content

merry_tools/
config.rs

1use std::{
2    io,
3    path::{Path, PathBuf},
4    sync::Arc,
5};
6
7use merry_runtime::DurableMemory;
8use thiserror::Error;
9
10/// Limits applied by workspace tools.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct WorkspaceToolLimits {
13    /// Maximum bytes returned or scanned by one text `read_file` request.
14    pub max_read_bytes: usize,
15    /// Maximum lines returned by one text `read_file` request, also used when omitted.
16    /// Defaults to 2,000 lines; the independent byte limit still applies.
17    pub max_read_lines: usize,
18    /// Maximum bytes written to one file by `apply_patch`.
19    pub max_write_bytes: usize,
20    /// Maximum bytes accepted in one `apply_patch` patch payload.
21    pub max_patch_bytes: usize,
22}
23
24impl Default for WorkspaceToolLimits {
25    fn default() -> Self {
26        Self {
27            max_read_bytes: 1024 * 1024,
28            max_read_lines: 2_000,
29            max_write_bytes: 1024 * 1024,
30            max_patch_bytes: 128 * 1024,
31        }
32    }
33}
34
35/// Configuration for workspace tools.
36#[derive(Debug, Clone)]
37pub struct WorkspaceToolsConfig {
38    pub(crate) root: PathBuf,
39    pub(crate) readonly_resource_roots: Vec<PathBuf>,
40    pub(crate) limits: WorkspaceToolLimits,
41    pub(crate) read_scope: Option<Vec<PathBuf>>,
42    pub(crate) patch_write_scope: Option<Vec<PathBuf>>,
43    pub(crate) forbidden_paths: Vec<PathBuf>,
44    pub(crate) denied_absolute_paths: Vec<PathBuf>,
45    pub(crate) durable_memory: Option<Arc<DurableMemory>>,
46}
47
48impl WorkspaceToolsConfig {
49    /// Creates a config with one workspace root.
50    ///
51    /// A workspace has exactly one root, so a relative path never has to be
52    /// guessed between candidates. Anything outside that root is named by its
53    /// own absolute path, where the sandbox decides reachability.
54    #[must_use]
55    pub fn new(root: impl Into<PathBuf>) -> Self {
56        Self {
57            root: root.into(),
58            readonly_resource_roots: Vec::new(),
59            limits: WorkspaceToolLimits::default(),
60            read_scope: None,
61            patch_write_scope: None,
62            forbidden_paths: Vec::new(),
63            denied_absolute_paths: Vec::new(),
64            durable_memory: None,
65        }
66    }
67
68    /// Attaches the durable memory store enforced by read and patch tools.
69    #[must_use]
70    pub fn with_durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
71        self.durable_memory = Some(memory);
72        self
73    }
74
75    /// Returns the configured, pre-canonical workspace root.
76    #[must_use]
77    pub fn root(&self) -> &Path {
78        &self.root
79    }
80
81    /// Returns independent read-only resource roots, such as skill directories.
82    /// Resources are addressable by the same relative read APIs but are never
83    /// patch targets.
84    #[must_use]
85    pub fn readonly_resource_roots(&self) -> &[PathBuf] {
86        &self.readonly_resource_roots
87    }
88
89    /// Adds read-only resource roots without treating them as a workspace root.
90    #[must_use]
91    pub fn with_readonly_resource_roots(mut self, roots: Vec<PathBuf>) -> Self {
92        self.readonly_resource_roots = roots;
93        self
94    }
95
96    /// Returns the configured tool limits.
97    #[must_use]
98    pub fn limits(&self) -> &WorkspaceToolLimits {
99        &self.limits
100    }
101
102    /// Returns the optional workspace-relative read scope for `read_file`.
103    #[must_use]
104    pub fn read_scope(&self) -> Option<&[PathBuf]> {
105        self.read_scope.as_deref()
106    }
107
108    /// Returns the optional workspace-relative write scope for `apply_patch`.
109    #[must_use]
110    pub fn patch_write_scope(&self) -> Option<&[PathBuf]> {
111        self.patch_write_scope.as_deref()
112    }
113
114    /// Returns workspace-relative paths forbidden to `apply_patch` and `read_file`.
115    #[must_use]
116    pub fn forbidden_paths(&self) -> &[PathBuf] {
117        &self.forbidden_paths
118    }
119
120    /// Sets workspace tool limits.
121    #[must_use]
122    pub fn with_limits(mut self, limits: WorkspaceToolLimits) -> Self {
123        self.limits = limits;
124        self
125    }
126
127    /// Sets the optional root-relative read scope for `read_file`.
128    ///
129    /// `None` preserves existing unrestricted workspace read behavior.
130    /// `Some([])` denies all workspace file reads (read-only resource roots
131    /// such as skills remain readable).
132    #[must_use]
133    pub fn with_read_scope(mut self, paths: Option<Vec<PathBuf>>) -> Self {
134        self.read_scope = paths;
135        self
136    }
137
138    /// Sets the optional root-relative write scope for `apply_patch`.
139    ///
140    /// `None` preserves existing unrestricted patch behavior. `Some([])` makes
141    /// the patch tool read-only by denying all writes.
142    #[must_use]
143    pub fn with_patch_write_scope(mut self, paths: Option<Vec<PathBuf>>) -> Self {
144        self.patch_write_scope = paths;
145        self
146    }
147
148    /// Sets root-relative paths forbidden to `apply_patch`.
149    #[must_use]
150    pub fn with_forbidden_paths(mut self, paths: Vec<PathBuf>) -> Self {
151        self.forbidden_paths = paths;
152        self
153    }
154
155    /// Returns absolute host paths denied to both `read_file` and `apply_patch`
156    /// (for example Merry's private state and credential directories).
157    #[must_use]
158    pub fn denied_absolute_paths(&self) -> &[PathBuf] {
159        &self.denied_absolute_paths
160    }
161
162    /// Sets absolute host paths denied to both `read_file` and `apply_patch`.
163    #[must_use]
164    pub fn with_denied_absolute_paths(mut self, paths: Vec<PathBuf>) -> Self {
165        self.denied_absolute_paths = paths;
166        self
167    }
168}
169
170/// Errors raised while validating workspace tool configuration.
171#[derive(Debug, Error)]
172pub enum WorkspaceToolConfigError {
173    /// A built-in tool declaration could not be validated.
174    #[error("invalid built-in tool definition: {0}")]
175    ToolDefinition(#[from] merry_runtime::ToolBuildError),
176    /// A configured root does not exist.
177    #[error("workspace root does not exist: {root}")]
178    RootNotFound {
179        /// Configured root path.
180        root: PathBuf,
181    },
182    /// A configured root could not be canonicalized.
183    #[error("could not canonicalize workspace root {root}: {source}")]
184    RootCanonicalize {
185        /// Configured root path.
186        root: PathBuf,
187        /// Source IO error.
188        #[source]
189        source: io::Error,
190    },
191    /// A configured root is not a directory.
192    #[error("workspace root is not a directory: {root}")]
193    RootNotDirectory {
194        /// Configured root path.
195        root: PathBuf,
196    },
197    /// A numeric limit is invalid.
198    #[error("workspace tool limit {name} must be greater than zero")]
199    InvalidLimit {
200        /// Limit name.
201        name: &'static str,
202    },
203    /// A workspace tool scope path was not relative and normalized.
204    #[error("workspace tool scope path must be relative and normalized: {path}")]
205    InvalidScopePath {
206        /// Rejected scope path.
207        path: PathBuf,
208    },
209}