merry-coding 0.1.3

Coding prompts, project rules, tool catalog, permission policy, and subagent orchestration for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use crate::{
    CODING_LOOP_PROCESS_TOOL, project_capabilities::project_capability_summary_for_root,
    search_tools::SearchToolAvailability,
};
use merry_core::{HostPathPolicy, ToolName};
use merry_llm::ModelRetryPolicy;
use merry_process::{BrowserProcessSpawner, ProcessSession};
use merry_runtime::{
    AcceptedLocalWorkspaceProcessAdmission, DurableMemory, LivePolicyBaseline, LivePolicyHandle,
    MemoryWriteKind, NetworkAccessPolicy, PermissionAdmissionError,
    PermissionedProcessRunnerFactory, ProcessCommandToolError, ProcessRunner,
    ProcessSessionPermissions, RuntimeProfileBuilder, StaticPermissionedProcessRunnerFactory,
    ToolBuildError, WorkspaceAccessPolicy, process_command_tool, read_background_process_tool,
    request_permissions_tool, stop_background_process_tool,
};
use merry_tools::{
    BrowserConfig, BrowserLaunchSpec, BrowserLauncherFuture, BrowserNetworkTool,
    BrowserProcessHandle, BrowserProcessLauncher, BrowserSessionManager, BrowserTabTool,
    ExternalTreePolicy, ExternalWriteKind, WebFetchConfig, WebFetchTool, WorkspaceToolConfigError,
    WorkspaceToolLimits, WorkspaceTools, WorkspaceToolsConfig, child_browser_process_handle,
};
use std::{
    path::{Path, PathBuf},
    sync::Arc,
};
use thiserror::Error;

const PROJECT_CAPABILITY_CONTEXT_ID: &str = "project-capabilities";
const CODING_WORKSPACE_CAPABILITY_SUMMARY: &str = concat!(
    "Coding file capabilities:\n",
    "- `read_file` reads local files (UTF-8 text within configured line/byte limits, images, PDFs, Office docs, and `.ipynb`). A path is relative to the workspace root (also resolving read-only skill/resource roots) or absolute—every spelling including dot-prefixed components is accepted, and an absolute path may name a file outside the workspace where the sandbox decides reachability.\n",
    "- `apply_patch` is the only file-edit tool: one `*** Begin Patch` envelope with `*** Add File:`, `*** Update File:`, or `*** Delete File:` sections, at most one Add or Delete section per file (repeated `*** Update File:` sections for one file merge into a single change), and localized hunks instead of whole-file content. Every hunk must match the current file bytes exactly and uniquely; when one does not, the failure names the closest line and the first difference, so re-read that line before retrying. Runtime admission, write scope, forbidden paths, and current-file preimages are enforced before writes. A section path is relative to the workspace root or absolute: an absolute path inside the workspace root and the matching relative path address the same file, and an absolute path may name a file outside the workspace, where the sandbox decides what is reachable and writable.\n",
    "- `run_process` is the discovery and verification lane when configured. The environment facts below report available search tools.\n",
    "- Process execution runs through Merry runtime policy and the configured sandbox/profile, so filesystem and network access may be intentionally restricted; environment and host IPC access may also be intentionally restricted. Network is withheld from every action that does not request it, so a command that reaches a remote service needs `network: true` in the same call's `permissions`. Paths and host integrations enabled by trusted global configuration are already available to actions. If a command needs access that is still missing, such as network, a reviewed path, or an unconfigured endpoint, put all minimum required capabilities in that same `run_process` call under `permissions`; runtime reviews before executing the exact command through the permissioned backend.\n",
    "- If a capability is discovered only after a sandboxed failure, call `request_permissions` for that exact action before retrying it. Approved paths and host integrations remain available for later actions in this runtime session; network access must be requested again for every action that needs it.\n",
    "- Linux Unix sockets are filesystem paths. If a host resource is not represented by a named integration, request its exact socket/file path through `requested.paths`; the sandbox must already expose the path.\n",
    "- `request_permissions` must name the exact planned action and request only the minimum needed capability; the runtime may approve, deny, or fail the request.",
);

const WEB_CAPABILITY_SUMMARY: &str = concat!(
    "Coding web and browser verification capabilities:\n",
    "- `web_fetch` fetches static HTTP/HTTPS pages, JSON endpoints, and docs with SSRF protection and extracts bounded Markdown. An SSRF refusal is final for that URL.\n",
    "- `browser_tab` drives one lazy session-scoped headless Chromium tab (`open` of http(s) or a `data:text/html` / `data:text/plain` document, `click`, `fill`, `press`, `evaluate`, `snapshot` with PNG screenshot, `console`, `resize`, `close`) with SSRF protection. A failed open does not start a session.\n",
    "- `browser_network` inspects HTTP/XHR/fetch requests captured after a successful `browser_tab` open (`list`, `details`).",
);

#[derive(Clone)]
pub(crate) enum WorkspaceProcessRunnerConfig {
    ReadOnly(Arc<dyn ProcessRunner>),
    ReadOnlySession(ProcessSession),
    Accepted(ProcessSession),
}

/// Workspace tool and process-lane inputs used by the coding profile.
#[derive(Clone)]
pub(crate) struct WorkspaceCodingProfileBuilder {
    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) host_path_policy: HostPathPolicy,
    pub(crate) enable_patch_tool: bool,
    pub(crate) enable_web_tools: bool,
    pub(crate) process_runner: Option<WorkspaceProcessRunnerConfig>,
    pub(crate) browser_process_launcher: Option<Arc<dyn BrowserProcessLauncher>>,
    pub(crate) durable_memory: Option<Arc<DurableMemory>>,
}

impl WorkspaceCodingProfileBuilder {
    /// Creates a profile builder with one workspace root.
    #[must_use]
    pub(crate) 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(),
            host_path_policy: HostPathPolicy::new(),
            enable_patch_tool: false,
            enable_web_tools: false,
            process_runner: None,
            browser_process_launcher: None,
            durable_memory: None,
        }
    }

    pub(crate) fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
        self.durable_memory = Some(memory);
        self
    }

    /// Replaces the workspace root.
    pub(crate) fn root(mut self, root: impl Into<PathBuf>) -> Self {
        self.root = root.into();
        self
    }

    pub(crate) fn readonly_resource_roots<I, P>(mut self, roots: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.readonly_resource_roots = roots.into_iter().map(Into::into).collect();
        self
    }

    pub(crate) fn limits(mut self, limits: WorkspaceToolLimits) -> Self {
        self.limits = limits;
        self
    }

    pub(crate) fn patch_tool(mut self) -> Self {
        self.enable_patch_tool = true;
        self
    }

    pub(crate) fn web_tools(mut self) -> Self {
        self.enable_web_tools = true;
        self
    }

    pub(crate) fn read_scope<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.read_scope = Some(paths.into_iter().map(Into::into).collect());
        self
    }

    pub(crate) fn patch_write_scope<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.patch_write_scope = Some(paths.into_iter().map(Into::into).collect());
        self
    }

    pub(crate) fn read_only_patch_scope(mut self) -> Self {
        self.patch_write_scope = Some(Vec::new());
        self
    }

    pub(crate) fn forbidden_paths<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.forbidden_paths = paths.into_iter().map(Into::into).collect();
        self
    }

    pub(crate) fn host_path_policy(mut self, policy: HostPathPolicy) -> Self {
        self.host_path_policy = policy;
        self
    }

    pub(crate) fn read_only_process_runner(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
        self.process_runner = Some(WorkspaceProcessRunnerConfig::ReadOnly(runner));
        self
    }

    pub(crate) fn read_only_process_session(mut self, session: ProcessSession) -> Self {
        self.process_runner = Some(WorkspaceProcessRunnerConfig::ReadOnlySession(session));
        self
    }

    pub(crate) fn accepted_process_session(mut self, session: ProcessSession) -> Self {
        self.process_runner = Some(WorkspaceProcessRunnerConfig::Accepted(session));
        self
    }

    pub(crate) fn browser_process_launcher(
        mut self,
        launcher: Arc<dyn BrowserProcessLauncher>,
    ) -> Self {
        self.browser_process_launcher = Some(launcher);
        self
    }

    pub(crate) fn apply_to_runtime_profile(
        self,
        mut builder: RuntimeProfileBuilder,
    ) -> Result<RuntimeProfileBuilder, WorkspaceCodingProfileBuildError> {
        let workspace_writable = self
            .patch_write_scope
            .as_ref()
            .is_none_or(|scope| !scope.is_empty());
        let (live_policy, session_browser_spawner, session_permissions) = match &self.process_runner
        {
            Some(
                WorkspaceProcessRunnerConfig::Accepted(session)
                | WorkspaceProcessRunnerConfig::ReadOnlySession(session),
            ) => {
                let browser_spawner = Some(session.browser_spawner(&self.root));
                if let Some(permissions) = session.session_permissions() {
                    let live_policy = session.live_policy_handle(&self.root, workspace_writable);
                    (live_policy, browser_spawner, permissions)
                } else {
                    let permissions = ProcessSessionPermissions::new();
                    let live_policy = session
                        .live_policy_handle(&self.root, workspace_writable)
                        .with_session_permissions(permissions.view());
                    (live_policy, browser_spawner, permissions)
                }
            }
            _ => {
                let permissions = ProcessSessionPermissions::new();
                let workspace_access = WorkspaceAccessPolicy::new(&self.root, workspace_writable);
                let baseline = LivePolicyBaseline::new(
                    true,
                    Some(workspace_access),
                    Vec::new(),
                    NetworkAccessPolicy::default(),
                );
                let live_policy =
                    LivePolicyHandle::new(baseline).with_session_permissions(permissions.view());
                (live_policy, None, permissions)
            }
        };
        let mut config = WorkspaceToolsConfig::new(self.root.clone())
            .with_readonly_resource_roots(self.readonly_resource_roots)
            .with_limits(self.limits)
            .with_read_scope(self.read_scope)
            .with_patch_write_scope(self.patch_write_scope)
            .with_forbidden_paths(self.forbidden_paths)
            .with_write_forbidden_paths(vec![PathBuf::from(".git")])
            .with_host_path_policy(self.host_path_policy)
            .with_live_access_policy(live_policy.clone());
        if let Some(memory) = self.durable_memory.clone() {
            config = config.with_external_tree_policy(Arc::new(DurableMemoryTreePolicy(memory)));
        }
        builder = builder.session_permissions(session_permissions);
        let project_summary = project_capability_summary_for_root(config.root());
        let workspace_tools = WorkspaceTools::new(config)?;

        // The environment facts name what this host actually provides so the
        // static summary can keep asking for modern search tools without
        // promising a tool the sandbox does not have.
        let search_tools = SearchToolAvailability::probe_action_path();
        tracing::debug!(
            event = "coding.search_tools.probe",
            availability = ?search_tools,
            "coding profile probed action-PATH search tools"
        );
        let environment_facts = search_tools.summary_line();
        let mut summary_sections = vec![CODING_WORKSPACE_CAPABILITY_SUMMARY.to_owned()];
        if self.enable_web_tools {
            summary_sections.push(WEB_CAPABILITY_SUMMARY.to_owned());
        }
        if let Some(project_summary) = project_summary {
            summary_sections.push(project_summary);
        }
        summary_sections.push(environment_facts);
        let capability_summary = summary_sections.join("\n");
        builder = builder
            .model_retry_policy(ModelRetryPolicy::coding_agent_default())
            .progress_commentary(true)
            .initial_context_summary(PROJECT_CAPABILITY_CONTEXT_ID, &capability_summary);

        if self.enable_patch_tool {
            builder = builder.allow_low_risk_apply_patches();
        }

        if let Some(process_runner) = self.process_runner {
            let (runner, accepted_admission, permissioned_factory) = match process_runner {
                WorkspaceProcessRunnerConfig::ReadOnly(runner) => {
                    let permissioned_factory = Arc::new(
                        StaticPermissionedProcessRunnerFactory::new(Arc::clone(&runner)),
                    );
                    (
                        runner,
                        None,
                        permissioned_factory as Arc<dyn PermissionedProcessRunnerFactory>,
                    )
                }
                WorkspaceProcessRunnerConfig::ReadOnlySession(session) => {
                    let runner = session.runner();
                    let permissioned_factory = Arc::new(
                        StaticPermissionedProcessRunnerFactory::new(Arc::clone(&runner)),
                    );
                    (
                        runner,
                        None,
                        permissioned_factory as Arc<dyn PermissionedProcessRunnerFactory>,
                    )
                }
                WorkspaceProcessRunnerConfig::Accepted(session) => {
                    let admission = session.admission();
                    let runner = session.runner();
                    let permissioned_factory = session.permissioned_factory();
                    (runner, Some(admission), permissioned_factory)
                }
            };

            let background_control = runner.background_control();
            builder = builder
                .allow_low_risk_process_actions(Arc::clone(&runner))
                .allow_read_only_shell_process_actions(Arc::clone(&runner))
                .permissioned_process_runner_factory(permissioned_factory);
            if let Some(admission) = accepted_admission {
                builder = builder.allow_accepted_local_workspace_process_actions(admission, runner);
            }

            let process_tool = process_command_tool(
                ToolName::new(CODING_LOOP_PROCESS_TOOL)?,
                "Run one shell command through Merry's configured process runner. Provide command as one JSON string; omit cwd for the current workspace directory, or use null or a workspace-relative directory such as \".\". Do not add a bash field or pass argv. The runtime validates command and cwd byte/control-character limits. Workspace files and directories are writable in the sandbox. Paths and host integrations enabled by trusted global configuration are already available; .git, network, and anything not configured remain restricted and may require a reviewed capability. Network is never granted implicitly: a command that reaches a remote service, such as one that authenticates, installs, downloads, or publishes, must include network in this call's permissions. If the command needs access that is still missing, include the minimum capabilities in permissions and runtime will review before running this exact command. If the need is discovered only after failure, use request_permissions for the exact same action before retrying it. Network access must be requested again for each action that needs it. Linux Unix sockets can be requested as exact filesystem paths when no named integration applies. Set background to true with a short display_name for long-lived processes such as a web API, dev server, daemon, watcher, or GUI that should keep running after this call; Merry retains it until stopped or the session ends. The default waits until the command exits or hits timeout_secs (default 120s, configurable up to 3600s — set a larger timeout_secs for intentionally slow finite commands like full builds or test suites); if timeout_secs elapses while still running, Merry does NOT kill the process and instead retains it in the background with an id and partial output so you can inspect progress with read_background_process or stop it with stop_background_process. Do not use `&`, setsid, nohup, or a systemd unit instead of background. A background result includes an id. read_background_process lists retained commands or reads later output, and stop_background_process stops that process group.",
            )?;
            builder = builder
                .register_tool(process_tool)
                .register_tool(request_permissions_tool()?);
            if let Some(control) = background_control {
                builder = builder.background_process_control(Arc::clone(&control));
                builder = builder
                    .register_tool(read_background_process_tool(Arc::clone(&control))?)
                    .register_tool(stop_background_process_tool(control)?);
            }
        }

        let tools = if self.enable_patch_tool {
            workspace_tools.into_registered_tools_with_patch()
        } else {
            workspace_tools.into_registered_tools()
        };
        for tool in tools {
            builder = builder.register_tool(tool);
        }
        if self.enable_web_tools {
            // Route web and browser tools through the runtime's permissioned
            // network admission lane while keeping headless Chromium private to
            // `BrowserSessionManager` (never registered in the user-visible
            // background process supervisor). On desktop `--sandbox workspace`,
            // `SessionBrowserProcessLauncher` confines Chromium with
            // `BrowserSandboxProfile` (zero workspace / `$HOME` / `providers/`).
            // Hosts such as `rootshell` may still override or disable launching
            // by supplying an explicit `BrowserProcessLauncher`.
            let mut browser_config =
                BrowserConfig::default().with_live_network_policy(live_policy.clone());
            if let Some(launcher) = self.browser_process_launcher {
                browser_config = browser_config.with_process_launcher(launcher);
            } else if let Some(spawner) = session_browser_spawner {
                browser_config = browser_config
                    .with_process_launcher(Arc::new(SessionBrowserProcessLauncher::new(spawner)));
            }
            let browser_manager = Arc::new(BrowserSessionManager::new(browser_config));
            let web_fetch_config = WebFetchConfig::default().with_live_network_policy(live_policy);
            builder = builder
                .allow_permissioned_network_tools()
                .register_tool(WebFetchTool::new(web_fetch_config).into_registered_tool()?)
                .register_tool(
                    BrowserTabTool::new(Arc::clone(&browser_manager)).into_registered_tool()?,
                )
                .register_tool(BrowserNetworkTool::new(browser_manager).into_registered_tool()?);
        }

        Ok(builder)
    }

    pub(crate) fn hash_material(&self) -> Vec<u8> {
        let mut material = Vec::new();
        append_hash_field(
            &mut material,
            "workspace-root",
            &self.root.to_string_lossy(),
        );
        for root in &self.readonly_resource_roots {
            append_hash_field(
                &mut material,
                "readonly-resource-root",
                &root.to_string_lossy(),
            );
        }
        append_hash_field(
            &mut material,
            "patch-tool",
            if self.enable_patch_tool { "on" } else { "off" },
        );
        if self.enable_web_tools {
            append_hash_field(&mut material, "web-tools", "on");
        }
        match self.read_scope.as_ref() {
            None => append_hash_field(&mut material, "read-scope-state", "unrestricted"),
            Some(paths) => {
                append_hash_field(&mut material, "read-scope-state", "restricted");
                for path in paths {
                    append_hash_field(&mut material, "read-scope", &path.to_string_lossy());
                }
            }
        }
        match self.patch_write_scope.as_ref() {
            None => append_hash_field(&mut material, "patch-write-scope-state", "unrestricted"),
            Some(paths) => {
                append_hash_field(&mut material, "patch-write-scope-state", "restricted");
                for path in paths {
                    append_hash_field(&mut material, "patch-write-scope", &path.to_string_lossy());
                }
            }
        }
        for path in &self.forbidden_paths {
            append_hash_field(&mut material, "forbidden-path", &path.to_string_lossy());
        }
        for path in self.host_path_policy.denied() {
            append_hash_field(
                &mut material,
                "denied-absolute-path",
                &path.to_string_lossy(),
            );
        }
        for path in self.host_path_policy.product_readonly() {
            append_hash_field(
                &mut material,
                "readonly-product-path",
                &path.to_string_lossy(),
            );
        }
        for (name, value) in [
            ("max-read-bytes", self.limits.max_read_bytes),
            ("max-read-lines", self.limits.max_read_lines),
            ("max-write-bytes", self.limits.max_write_bytes),
            ("max-patch-bytes", self.limits.max_patch_bytes),
        ] {
            append_hash_field(&mut material, name, &value.to_string());
        }
        let process_runner_label = match &self.process_runner {
            None => "none",
            Some(
                WorkspaceProcessRunnerConfig::ReadOnly(_)
                | WorkspaceProcessRunnerConfig::ReadOnlySession(_),
            ) => "read-only",
            Some(WorkspaceProcessRunnerConfig::Accepted(session)) => {
                let admission = session.admission();
                append_hash_field(
                    &mut material,
                    "process-sandbox",
                    sandbox_profile_label(admission),
                );
                append_hash_field(
                    &mut material,
                    "process-permission-profile",
                    admission.permission_profile_id().as_str(),
                );
                "accepted-process-permissioned"
            }
        };
        append_hash_field(&mut material, "process-runner", process_runner_label);
        material
    }
}

fn sandbox_profile_label(admission: AcceptedLocalWorkspaceProcessAdmission) -> &'static str {
    admission.sandbox_profile().as_str()
}

fn append_hash_field(material: &mut Vec<u8>, name: &str, value: &str) {
    material.extend_from_slice(name.as_bytes());
    material.push(0);
    material.extend_from_slice(&(value.len() as u64).to_be_bytes());
    material.extend_from_slice(value.as_bytes());
}

#[derive(Debug)]
struct SessionBrowserProcessLauncher {
    spawner: BrowserProcessSpawner,
}

impl SessionBrowserProcessLauncher {
    fn new(spawner: BrowserProcessSpawner) -> Self {
        Self { spawner }
    }
}

impl BrowserProcessLauncher for SessionBrowserProcessLauncher {
    fn launch(
        &self,
        spec: BrowserLaunchSpec,
    ) -> BrowserLauncherFuture<'_, Result<Box<dyn BrowserProcessHandle>, String>> {
        Box::pin(async move {
            let child = self
                .spawner
                .spawn(&spec.executable, &spec.args, spec.profile_dir.as_deref())
                .await
                .map_err(|error| error.to_string())?;
            child_browser_process_handle(child)
        })
    }
}

#[derive(Debug)]
struct DurableMemoryTreePolicy(Arc<DurableMemory>);

impl ExternalTreePolicy for DurableMemoryTreePolicy {
    fn root(&self) -> &Path {
        self.0.layout().root()
    }

    fn governs_path(&self, path: &Path) -> bool {
        self.0.governs_path(path)
    }

    fn on_text_read(&self, path: &Path) -> Result<(), String> {
        self.0.note_read(path).map_err(|error| error.to_string())
    }

    fn authorize_write(
        &self,
        kind: ExternalWriteKind,
        path: &Path,
        byte_len: usize,
    ) -> Result<(), String> {
        let memory_kind = match kind {
            ExternalWriteKind::Create => MemoryWriteKind::Create,
            ExternalWriteKind::Update => MemoryWriteKind::Update,
            ExternalWriteKind::Delete => MemoryWriteKind::Delete,
        };
        self.0
            .authorize_write(memory_kind, path, byte_len)
            .map_err(|error| error.to_string())
    }

    fn on_writes_committed(&self, paths: &[PathBuf]) -> Result<(), String> {
        self.0
            .refresh_after_writes(paths)
            .map_err(|error| error.to_string())
    }
}

/// Errors raised while composing workspace tools into the coding profile.
#[derive(Debug, Error)]
pub(crate) enum WorkspaceCodingProfileBuildError {
    /// Workspace tool configuration was invalid.
    #[error(transparent)]
    WorkspaceTools(#[from] WorkspaceToolConfigError),
    /// The process command tool could not be constructed.
    #[error(transparent)]
    ProcessTool(#[from] ProcessCommandToolError),
    /// The permission request tool could not be constructed.
    #[error(transparent)]
    PermissionTool(#[from] PermissionAdmissionError),
    /// A static workspace tool name failed validation.
    #[error(transparent)]
    Core(#[from] merry_core::CoreError),
    /// A web or browser tool schema failed construction.
    #[error(transparent)]
    WebToolBuild(#[from] ToolBuildError),
}