merry 0.1.4

Rust SDK facade for the Merry coding agent runtime (CLI available as `merry-cli`).
Documentation
//! Shared configuration validation and construction helpers for foreign bindings.
//!
//! Centralizes validation rules for generation, prompt profile, workspace
//! profile, history retention, compaction, and hook filters so PyO3 and UniFFI
//! bindings stay consistent without duplicating domain checks.

use crate::{
    ArchiveConfig, CompactionConfig, CompactionPrompt, GenerationConfig, HistoryRetention,
    ParallelToolCalls, PromptBlock, PromptProfile, ReasoningEffort, ServiceTier, ToolHookFilter,
    ToolName,
    binding::wire::build_compaction_policy,
    profiles::{
        CodingAgentProfile, CodingAgentProfileBuildError, CodingAgentProfileBuilder,
        WorkspaceToolLimits,
    },
};
use std::{
    collections::BTreeSet,
    num::{NonZeroU64, NonZeroUsize},
    path::PathBuf,
};

/// Errors produced when building a [`CodingAgentProfile`] from binding inputs.
#[derive(Debug)]
pub enum BindingWorkspaceProfileError {
    /// Invalid caller-supplied configuration value.
    Config(String),
    /// Lower-layer profile builder failure.
    Profile(CodingAgentProfileBuildError),
}

/// Provider-neutral workspace tool configuration input shared across bindings.
#[derive(Debug, Clone)]
pub struct WorkspaceProfileInput {
    /// Workspace root directory.
    pub root: String,
    /// Optional additional read-only resource roots.
    pub readonly_resource_roots: Vec<String>,
    /// Whether to enable the workspace `apply_patch` tool.
    pub enable_patch: bool,
    /// Optional patch write scope (only valid when `enable_patch` is true).
    pub patch_write_scope: Option<Vec<String>>,
    /// Relative or absolute forbidden paths inside the workspace.
    pub forbidden_paths: Vec<String>,
    /// Optional override for `max_read_bytes`.
    pub max_read_bytes: Option<usize>,
    /// Optional override for `max_read_lines`.
    pub max_read_lines: Option<usize>,
    /// Optional override for `max_write_bytes`.
    pub max_write_bytes: Option<usize>,
    /// Optional override for `max_patch_bytes`.
    pub max_patch_bytes: Option<usize>,
}

/// Optional compaction prompt overrides shared across bindings.
#[derive(Debug, Clone)]
pub struct CompactionPromptInput {
    /// Custom compaction summary instructions.
    pub instructions: Option<String>,
    /// Optional caller-supplied user context appended to compaction prompts.
    pub user_context: Option<String>,
}

/// Shared automatic compaction configuration fields across JSON and typed FFI.
#[derive(Debug, Clone)]
pub struct CompactionConfigInput {
    /// Whether automatic compaction is enabled.
    pub enabled: bool,
    /// Optional compaction-only reasoning effort override.
    pub reasoning_effort: Option<String>,
    /// Optional maximum recent completed model turns to retain.
    pub retained_model_turns: Option<usize>,
    /// Optional soft summary target output token budget.
    pub target_output_tokens: Option<u64>,
    /// Optional maximum accepted compaction output size in bytes.
    pub max_accepted_output_bytes: Option<usize>,
    /// Optional one-shot fallback tool exchange retention count.
    pub one_shot_retained_tool_exchanges: Option<usize>,
    /// Optional dynamic body budget trigger threshold percent.
    pub trigger_threshold_percent: Option<u8>,
    /// Optional compaction prompt override.
    pub prompt: Option<CompactionPromptInput>,
}

/// Parses and validates a [`GenerationConfig`] from binding scalar fields.
pub fn build_generation_config(
    max_output_tokens: Option<u64>,
    parallel_tool_calls: Option<&str>,
    reasoning_effort: Option<&str>,
    service_tier: Option<&str>,
) -> Result<GenerationConfig, String> {
    let parallel = match parallel_tool_calls {
        None | Some("auto") => ParallelToolCalls::Auto,
        Some("enabled") => ParallelToolCalls::Enabled,
        Some("disabled") => ParallelToolCalls::Disabled,
        Some(other) => {
            return Err(format!("unsupported parallel_tool_calls mode: {other}"));
        }
    };
    let reasoning = reasoning_effort
        .map(ReasoningEffort::new)
        .transpose()
        .map_err(|error| error.to_string())?;
    let tier = service_tier
        .map(ServiceTier::new)
        .transpose()
        .map_err(|error| error.to_string())?;
    Ok(GenerationConfig::new(max_output_tokens, false)
        .map_err(|error| error.to_string())?
        .with_parallel_tool_calls(parallel)
        .with_reasoning_effort(reasoning)
        .with_service_tier(tier))
}

/// Builds a validated [`PromptProfile`] from binding prompt overrides.
pub fn build_prompt_profile(
    base_instructions: Option<String>,
    progress_commentary_instructions: Option<String>,
    stable_blocks: Vec<(String, String)>,
) -> Result<PromptProfile, String> {
    let mut profile = PromptProfile::default();
    if let Some(base) = base_instructions {
        profile = profile
            .with_base_instructions(base)
            .map_err(|error| error.to_string())?;
    }
    if let Some(commentary) = progress_commentary_instructions {
        profile = profile
            .with_progress_commentary_instructions(commentary)
            .map_err(|error| error.to_string())?;
    }
    for (tag, text) in stable_blocks {
        let block = PromptBlock::new(tag, text).map_err(|error| error.to_string())?;
        profile = profile
            .with_stable_block(block)
            .map_err(|error| error.to_string())?;
    }
    Ok(profile)
}

/// Builds a validated [`CodingAgentProfile`] from binding workspace inputs.
pub fn build_workspace_profile(
    input: WorkspaceProfileInput,
) -> Result<CodingAgentProfile, BindingWorkspaceProfileError> {
    if input.root.is_empty() {
        return Err(BindingWorkspaceProfileError::Config(
            "workspace requires a root".to_owned(),
        ));
    }
    let defaults = WorkspaceToolLimits::default();
    let mut builder = CodingAgentProfileBuilder::new(PathBuf::from(input.root))
        .readonly_resource_roots(input.readonly_resource_roots.into_iter().map(PathBuf::from))
        .limits(WorkspaceToolLimits {
            max_read_bytes: input.max_read_bytes.unwrap_or(defaults.max_read_bytes),
            max_read_lines: input.max_read_lines.unwrap_or(defaults.max_read_lines),
            max_write_bytes: input.max_write_bytes.unwrap_or(defaults.max_write_bytes),
            max_patch_bytes: input.max_patch_bytes.unwrap_or(defaults.max_patch_bytes),
        })
        .forbidden_paths(input.forbidden_paths.into_iter().map(PathBuf::from));
    if input.enable_patch {
        builder = builder.patch_tool();
        if let Some(scope) = input.patch_write_scope {
            builder = builder.patch_write_scope(scope.into_iter().map(PathBuf::from));
        }
    } else if input.patch_write_scope.is_some() {
        return Err(BindingWorkspaceProfileError::Config(
            "patch_write_scope requires enable_patch=true".to_owned(),
        ));
    }
    builder
        .build()
        .map_err(BindingWorkspaceProfileError::Profile)
}

/// Parses and validates a [`HistoryRetention`] policy from binding inputs.
pub fn build_history_retention(
    mode: &str,
    max_segments: Option<usize>,
    max_bytes: Option<u64>,
    export_markdown: Option<bool>,
) -> Result<HistoryRetention, String> {
    match mode {
        "archive" => {
            let max_segments = max_segments
                .map(|value| {
                    NonZeroUsize::new(value)
                        .ok_or_else(|| "max_segments must be greater than zero".to_owned())
                })
                .transpose()?;
            let max_bytes = max_bytes
                .map(|value| {
                    NonZeroU64::new(value)
                        .ok_or_else(|| "max_bytes must be greater than zero".to_owned())
                })
                .transpose()?;
            let config = ArchiveConfig::new()
                .with_max_segments(max_segments)
                .with_max_bytes(max_bytes)
                .with_export_markdown(export_markdown.unwrap_or(true));
            Ok(HistoryRetention::Archive(config))
        }
        "context_only" => {
            if max_segments.is_some() || max_bytes.is_some() || export_markdown == Some(true) {
                return Err(
                    "max_segments, max_bytes, and export_markdown are only valid for archive retention"
                        .to_owned(),
                );
            }
            Ok(HistoryRetention::ContextOnly)
        }
        other => Err(format!("unsupported history_retention mode: {other}")),
    }
}

/// Builds a validated [`CompactionConfig`] from binding inputs.
pub fn build_compaction_config(input: CompactionConfigInput) -> Result<CompactionConfig, String> {
    let policy = build_compaction_policy(
        input.retained_model_turns,
        input.target_output_tokens,
        input.max_accepted_output_bytes,
        input.one_shot_retained_tool_exchanges,
    )?;
    let reasoning = input
        .reasoning_effort
        .as_deref()
        .map(ReasoningEffort::new)
        .transpose()
        .map_err(|error| error.to_string())?;
    let mut config = if input.enabled {
        CompactionConfig::enabled(policy)
    } else {
        CompactionConfig::disabled().with_policy(policy)
    }
    .with_reasoning_effort(reasoning);
    if let Some(percent) = input.trigger_threshold_percent {
        config = config
            .with_trigger_threshold_percent(percent)
            .map_err(|error| error.to_string())?;
    }
    if let Some(prompt_input) = input.prompt {
        let mut prompt = match prompt_input.instructions {
            Some(instructions) => {
                CompactionPrompt::custom(instructions).map_err(|error| error.to_string())?
            }
            None => CompactionPrompt::default(),
        };
        if let Some(user_context) = prompt_input.user_context {
            prompt = prompt
                .with_user_context(user_context)
                .map_err(|error| error.to_string())?;
        }
        config = config.with_prompt(prompt);
    }
    Ok(config)
}

/// Builds a [`ToolHookFilter::Only`] (collapsing empty lists to `None`) from tool names.
pub fn build_tool_hook_filter_only(tools: &[String]) -> Result<ToolHookFilter, String> {
    let mut set = BTreeSet::new();
    for name in tools {
        let parsed = ToolName::new(name)
            .map_err(|error| format!("hook tool filter name is invalid: {error}"))?;
        set.insert(parsed);
    }
    Ok(if set.is_empty() {
        ToolHookFilter::None
    } else {
        ToolHookFilter::Only(set)
    })
}