Skip to main content

merry_tools/
config.rs

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