Skip to main content

merry_tools/
config.rs

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