merry-coding 0.1.0

Coding prompts, project rules, tool catalog, permission policy, and subagent orchestration for Merry.
Documentation
use crate::{
    CODING_LOOP_PROCESS_TOOL, project_capabilities::project_capability_summary_for_root,
    search_tools::SearchToolAvailability,
};
use merry_core::ToolName;
use merry_llm::ModelRetryPolicy;
use merry_process::ProcessSession;
use merry_runtime::{
    AcceptedLocalWorkspaceProcessAdmission, DurableMemory, PermissionAdmissionError,
    PermissionedProcessRunnerFactory, ProcessCommandToolError, ProcessRunner,
    RuntimeProfileBuilder, StaticPermissionedProcessRunnerFactory, ToolBuildError,
    process_command_tool, read_background_process_tool, request_permissions_tool,
    stop_background_process_tool,
};
use merry_tools::{
    BrowserConfig, BrowserNetworkTool, BrowserSessionManager, BrowserTabTool, WebFetchConfig,
    WebFetchTool, WorkspaceToolConfigError, WorkspaceToolLimits, WorkspaceTools,
    WorkspaceToolsConfig,
};
use std::{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>),
    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) denied_absolute_paths: Vec<PathBuf>,
    pub(crate) enable_patch_tool: bool,
    pub(crate) enable_web_tools: bool,
    pub(crate) process_runner: Option<WorkspaceProcessRunnerConfig>,
    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(),
            denied_absolute_paths: Vec::new(),
            enable_patch_tool: false,
            enable_web_tools: false,
            process_runner: 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 denied_absolute_paths<I, P>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.denied_absolute_paths = paths.into_iter().map(Into::into).collect();
        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 accepted_process_session(mut self, session: ProcessSession) -> Self {
        self.process_runner = Some(WorkspaceProcessRunnerConfig::Accepted(session));
        self
    }

    pub(crate) fn apply_to_runtime_profile(
        self,
        mut builder: RuntimeProfileBuilder,
    ) -> Result<RuntimeProfileBuilder, WorkspaceCodingProfileBuildError> {
        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_denied_absolute_paths(self.denied_absolute_paths);
        if let Some(memory) = self.durable_memory.clone() {
            config = config.with_durable_memory(memory);
        }
        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::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 {
            let browser_manager = Arc::new(BrowserSessionManager::new(BrowserConfig::default()));
            builder = builder
                .register_tool(WebFetchTool::new(WebFetchConfig::default()).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.denied_absolute_paths {
            append_hash_field(
                &mut material,
                "denied-absolute-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(_)) => "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());
}

/// 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),
}