use crate::child_runtime::{CodingChildRuntimeFactory, CodingRuntimeComposition};
use crate::{
CodingAgentProfile, CodingAgentProfileBuildError, CodingAgentProfileBuilder,
MIN_CODING_SUBAGENT_MODEL_TURNS, ProjectRulesLoadError, SubagentRoleCatalog, coding_agent,
load_root_project_rules,
};
use merry_core::{CoreError, HostPathPolicy, SessionId};
use merry_llm::{ModelName, ModelProvider, ModelRetryPolicy, ReasoningEffort};
use merry_process::ProcessBackend;
use merry_runtime::{
AgentLoopConfig, AgentLoopConfigError, ChildRuntimeFactory, CompactionConfig, DurableMemory,
FileSessionStore, HistoryRetention, LoadedSession, PermissionReviewRules, RegisteredTool,
Runtime, RuntimeBuilder, RuntimeError, RuntimeModelRole, SkillCatalog, SkillError,
SubagentConfig, SubagentError, SubagentManager, subagent_registered_tools_with_roles,
};
use merry_tools::WorkspaceToolLimits;
pub use permission_policy::{
CodingAutoFallback, CodingPermissionMode, CodingPermissionPolicy, CodingPermissionPolicyError,
};
use std::{collections::BTreeSet, path::PathBuf, sync::Arc};
use thiserror::Error;
mod permission_policy;
#[derive(Clone)]
pub struct CodingModelRoleConfig {
role: RuntimeModelRole,
provider: Arc<dyn ModelProvider>,
model: ModelName,
reasoning_effort: Option<ReasoningEffort>,
}
impl CodingModelRoleConfig {
pub fn new(
role: RuntimeModelRole,
provider: Arc<dyn ModelProvider>,
model: ModelName,
) -> Result<Self, CodingModelRoleConfigError> {
if role == RuntimeModelRole::Primary {
return Err(CodingModelRoleConfigError::PrimaryRole);
}
Ok(Self {
role,
provider,
model,
reasoning_effort: None,
})
}
#[must_use]
pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
self.reasoning_effort = reasoning_effort;
self
}
#[must_use]
pub const fn role(&self) -> RuntimeModelRole {
self.role
}
#[must_use]
pub fn provider(&self) -> Arc<dyn ModelProvider> {
Arc::clone(&self.provider)
}
#[must_use]
pub fn model(&self) -> &ModelName {
&self.model
}
#[must_use]
pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
self.reasoning_effort.as_ref()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum CodingModelRoleConfigError {
#[error("primary model must be configured as the coding runtime's primary provider")]
PrimaryRole,
}
#[derive(Clone, Default)]
pub(crate) struct CodingRuntimePolicy {
model_roles: Vec<CodingModelRoleConfig>,
permission: CodingPermissionPolicy,
permission_review_rules: PermissionReviewRules,
permission_review_workspace_root: Option<PathBuf>,
}
impl CodingRuntimePolicy {
pub(crate) fn try_new(
model_roles: Vec<CodingModelRoleConfig>,
permission: CodingPermissionPolicy,
) -> Result<Self, CodingRuntimeBuildError> {
let mut configured_roles = BTreeSet::new();
for role in &model_roles {
if !configured_roles.insert(role.role()) {
return Err(CodingRuntimeBuildError::DuplicateModelRole { role: role.role() });
}
}
Ok(Self {
model_roles,
permission,
permission_review_rules: PermissionReviewRules::default(),
permission_review_workspace_root: None,
})
}
pub(crate) fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
self.permission_review_rules = rules;
self
}
pub(crate) fn with_permission_review_workspace_root(
mut self,
root: impl Into<PathBuf>,
) -> Self {
self.permission_review_workspace_root = Some(root.into());
self
}
pub(crate) fn apply_to(&self, mut builder: RuntimeBuilder) -> RuntimeBuilder {
for role in &self.model_roles {
builder = builder.model_provider_for_role_with_reasoning(
role.role(),
role.provider(),
role.model().clone(),
role.reasoning_effort().cloned(),
);
}
if !self.permission_review_rules.is_empty() {
builder = builder.permission_review_rules(self.permission_review_rules.clone());
}
if let Some(root) = &self.permission_review_workspace_root {
builder = builder.permission_review_workspace_root(root.clone());
}
self.permission.apply_to(builder)
}
}
#[derive(Clone, Default)]
pub struct CodingSubagentsConfig {
installed: bool,
enabled: bool,
limits: SubagentConfig,
role_catalog: SubagentRoleCatalog,
}
impl CodingSubagentsConfig {
#[must_use]
pub fn enabled(limits: SubagentConfig) -> Self {
Self {
installed: true,
enabled: true,
limits,
role_catalog: SubagentRoleCatalog::builtin(),
}
}
#[must_use]
pub fn runtime_controlled(enabled: bool, limits: SubagentConfig) -> Self {
Self {
installed: true,
enabled,
limits,
role_catalog: SubagentRoleCatalog::builtin(),
}
}
#[must_use]
pub fn with_role_catalog(mut self, role_catalog: SubagentRoleCatalog) -> Self {
self.role_catalog = role_catalog;
self
}
#[must_use]
pub const fn is_installed(&self) -> bool {
self.installed
}
#[must_use]
pub const fn is_enabled(&self) -> bool {
self.enabled
}
#[must_use]
pub const fn limits(&self) -> SubagentConfig {
self.limits
}
#[must_use]
pub fn role_catalog(&self) -> &SubagentRoleCatalog {
&self.role_catalog
}
}
#[derive(Clone)]
pub struct CodingRuntimeInput {
session_id: SessionId,
root: PathBuf,
provider: Arc<dyn ModelProvider>,
model: ModelName,
process_backend: Option<Arc<dyn ProcessBackend>>,
extra_tools: Vec<RegisteredTool>,
automatic_compaction: CompactionConfig,
history_retention: HistoryRetention,
retry_policy: Option<ModelRetryPolicy>,
model_roles: Vec<CodingModelRoleConfig>,
skill_roots: Vec<PathBuf>,
host_path_policy: HostPathPolicy,
subagents: CodingSubagentsConfig,
workspace_tool_limits: WorkspaceToolLimits,
workspace_writable: bool,
durable_memory: Option<Arc<DurableMemory>>,
permission_review_rules: PermissionReviewRules,
max_parallel_tool_calls: Option<std::num::NonZeroUsize>,
context_window_tokens: Option<std::num::NonZeroU64>,
}
impl CodingRuntimeInput {
#[must_use]
pub fn new(
session_id: SessionId,
root: impl Into<PathBuf>,
provider: Arc<dyn ModelProvider>,
model: ModelName,
process_backend: Arc<dyn ProcessBackend>,
) -> Self {
Self {
session_id,
root: root.into(),
provider,
model,
process_backend: Some(process_backend),
extra_tools: Vec::new(),
automatic_compaction: CompactionConfig::default(),
history_retention: HistoryRetention::default(),
retry_policy: None,
model_roles: Vec::new(),
skill_roots: Vec::new(),
host_path_policy: HostPathPolicy::new(),
subagents: CodingSubagentsConfig::default(),
workspace_tool_limits: WorkspaceToolLimits::default(),
workspace_writable: true,
durable_memory: None,
permission_review_rules: PermissionReviewRules::default(),
max_parallel_tool_calls: None,
context_window_tokens: None,
}
}
#[must_use]
pub fn read_only_workspace(mut self) -> Self {
self.workspace_writable = false;
self
}
#[must_use]
pub fn session_id(&self) -> &SessionId {
&self.session_id
}
#[must_use]
pub fn root(&self) -> &std::path::Path {
&self.root
}
#[must_use]
pub fn read_only(
session_id: SessionId,
root: impl Into<PathBuf>,
provider: Arc<dyn ModelProvider>,
model: ModelName,
) -> Self {
Self {
session_id,
root: root.into(),
provider,
model,
process_backend: None,
extra_tools: Vec::new(),
automatic_compaction: CompactionConfig::default(),
history_retention: HistoryRetention::default(),
retry_policy: None,
model_roles: Vec::new(),
skill_roots: Vec::new(),
host_path_policy: HostPathPolicy::new(),
subagents: CodingSubagentsConfig::default(),
workspace_tool_limits: WorkspaceToolLimits::default(),
workspace_writable: true,
durable_memory: None,
permission_review_rules: PermissionReviewRules::default(),
max_parallel_tool_calls: None,
context_window_tokens: None,
}
}
#[must_use]
pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
self.durable_memory = Some(memory);
self
}
#[must_use]
pub fn with_extra_tools<I>(mut self, tools: I) -> Self
where
I: IntoIterator<Item = RegisteredTool>,
{
self.extra_tools.extend(tools);
self
}
#[must_use]
pub fn with_automatic_compaction(mut self, config: CompactionConfig) -> Self {
self.automatic_compaction = config;
self
}
#[must_use]
pub fn with_history_retention(mut self, retention: HistoryRetention) -> Self {
self.history_retention = retention;
self
}
#[must_use]
pub fn with_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
self.retry_policy = Some(policy);
self
}
#[must_use]
pub fn with_model_role(mut self, role: CodingModelRoleConfig) -> Self {
self.model_roles.push(role);
self
}
#[must_use]
pub fn with_model_roles<I>(mut self, roles: I) -> Self
where
I: IntoIterator<Item = CodingModelRoleConfig>,
{
self.model_roles.extend(roles);
self
}
#[must_use]
pub fn with_skill_roots<I, P>(mut self, roots: I) -> Self
where
I: IntoIterator<Item = P>,
P: Into<PathBuf>,
{
self.skill_roots = roots.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_host_path_policy(mut self, policy: HostPathPolicy) -> Self {
self.host_path_policy = policy;
self
}
#[must_use]
pub fn with_subagents(mut self, subagents: CodingSubagentsConfig) -> Self {
self.subagents = subagents;
self
}
#[must_use]
pub fn with_workspace_tool_limits(mut self, limits: WorkspaceToolLimits) -> Self {
self.workspace_tool_limits = limits;
self
}
#[must_use]
pub fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
self.permission_review_rules = rules;
self
}
#[must_use]
pub fn with_max_parallel_tool_calls(mut self, limit: std::num::NonZeroUsize) -> Self {
self.max_parallel_tool_calls = Some(limit);
self
}
#[must_use]
pub fn with_context_window_tokens(mut self, tokens: std::num::NonZeroU64) -> Self {
self.context_window_tokens = Some(tokens);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CodingRuntimeVariant {
FullCoding,
ReadOnlyCommandGeneration,
}
pub struct CodingRuntimeBuilder {
input: CodingRuntimeInput,
variant: CodingRuntimeVariant,
permission: CodingPermissionPolicy,
loaded_session: Option<LoadedSession>,
session_store: Option<FileSessionStore>,
}
impl CodingRuntimeBuilder {
#[must_use]
pub fn new(input: CodingRuntimeInput) -> Self {
Self {
input,
variant: CodingRuntimeVariant::FullCoding,
permission: CodingPermissionPolicy::default(),
loaded_session: None,
session_store: None,
}
}
#[must_use]
pub fn for_command_generation(input: CodingRuntimeInput) -> Self {
Self {
input,
variant: CodingRuntimeVariant::ReadOnlyCommandGeneration,
permission: CodingPermissionPolicy::default(),
loaded_session: None,
session_store: None,
}
}
#[must_use]
pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
self.permission = policy;
self
}
#[must_use]
pub fn with_loaded_session(mut self, loaded: LoadedSession) -> Self {
self.loaded_session = Some(loaded);
self
}
#[must_use]
pub fn session_store(mut self, store: FileSessionStore) -> Self {
self.session_store = Some(store);
self
}
pub fn build(self) -> Result<CodingRuntime, CodingRuntimeBuildError> {
let (builder, profile) = self.compose()?;
let loop_config = profile.loop_config()?;
let runtime = builder
.build()
.map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
Ok(CodingRuntime {
runtime,
profile,
loop_config,
})
}
pub async fn resume_from_store_without_automatic_savepoints(
self,
store: FileSessionStore,
) -> Result<CodingRuntime, CodingRuntimeBuildError> {
let (builder, profile) = self.compose()?;
let loop_config = profile.loop_config()?;
let runtime = builder
.resume_from_store_without_automatic_savepoints(store)
.await
.map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
Ok(CodingRuntime {
runtime,
profile,
loop_config,
})
}
fn compose(
self,
) -> Result<(merry_runtime::RuntimeBuilder, CodingAgentProfile), CodingRuntimeBuildError> {
let Self {
input,
variant,
permission,
loaded_session,
session_store,
} = self;
let CodingRuntimeInput {
session_id,
root,
provider,
model,
process_backend,
extra_tools,
automatic_compaction,
history_retention,
retry_policy,
model_roles,
skill_roots,
host_path_policy,
subagents,
workspace_tool_limits,
workspace_writable,
durable_memory,
permission_review_rules,
max_parallel_tool_calls,
context_window_tokens,
} = input;
let policy = CodingRuntimePolicy::try_new(model_roles, permission)?
.with_permission_review_rules(permission_review_rules)
.with_permission_review_workspace_root(root.clone());
let project_rules = if workspace_writable {
load_root_project_rules(&root)?
} else {
None
};
let skill_catalog = if skill_roots.is_empty() {
None
} else {
Some(SkillCatalog::load_from_roots(skill_roots.clone())?)
};
if let Some(catalog) = skill_catalog.as_ref() {
const MAX_LOGGED_SKILL_NAMES: usize = 64;
let skill_names = catalog
.skills()
.iter()
.take(MAX_LOGGED_SKILL_NAMES)
.map(|skill| skill.name())
.collect::<Vec<_>>();
tracing::info!(
event = "runtime.skill_catalog.load",
session_id = %session_id,
configured_root_count = skill_roots.len(),
readable_root_count = skill_roots.iter().filter(|root| root.is_dir()).count(),
skill_count = catalog.skills().len(),
warning_count = catalog.warnings().len(),
skill_names = ?skill_names,
"runtime skill catalog loaded"
);
}
let mut runtime_builder = Runtime::builder(session_id.clone())
.automatic_compaction(automatic_compaction.clone())
.history_retention(history_retention)
.model_provider(Arc::clone(&provider), model.clone());
if let Some(limit) = max_parallel_tool_calls {
runtime_builder = runtime_builder.max_parallel_tool_calls(limit);
}
if let Some(tokens) = context_window_tokens {
runtime_builder = runtime_builder.context_window_tokens(tokens);
}
if matches!(variant, CodingRuntimeVariant::FullCoding) {
runtime_builder = runtime_builder.coordinator_plan_tools();
}
let mut profile_builder: CodingAgentProfileBuilder = coding_agent(&root)
.readonly_resource_roots(skill_roots.clone())
.host_path_policy(host_path_policy)
.limits(workspace_tool_limits)
.register_tools(extra_tools);
if !workspace_writable {
profile_builder = profile_builder.read_only_patch_scope();
}
if let Some(project_rules) = project_rules {
profile_builder = profile_builder.project_rules(project_rules);
}
if let Some(skill_catalog) = skill_catalog {
profile_builder = profile_builder.skill_catalog(skill_catalog);
}
if let Some(policy) = retry_policy {
profile_builder = profile_builder.retry_policy(policy);
}
if let Some(memory) = durable_memory.clone() {
profile_builder = profile_builder.durable_memory(memory);
}
let mut profile_tools = Vec::new();
if matches!(variant, CodingRuntimeVariant::FullCoding) {
let process_backend =
process_backend.ok_or(CodingRuntimeBuildError::MissingProcessBackend)?;
let process_session = process_backend.new_session();
let parent_process_permissions = process_session.permission_view();
profile_builder = profile_builder
.patch_tool()
.web_tools()
.accepted_process_session(process_session);
if subagents.is_installed() {
let subagent_config = subagents.limits().with_model_turn_bounds(
MIN_CODING_SUBAGENT_MODEL_TURNS,
subagents.limits().max_model_turns(),
)?;
tracing::info!(
event = "runtime.subagents.enabled",
session_id = %session_id,
enabled = subagents.is_enabled(),
max_threads = subagent_config.max_threads(),
max_depth = subagent_config.max_depth(),
min_model_turns = subagent_config.min_model_turns(),
max_model_turns = subagent_config.max_model_turns(),
"runtime subagent tools installed"
);
let role_catalog = subagents.role_catalog().clone();
let role_summaries = role_catalog.enabled_role_summaries();
let composition = CodingRuntimeComposition {
profile_builder: profile_builder.clone(),
provider: Arc::clone(&provider),
model: model.clone(),
process_backend,
parent_process_permissions,
parent_workspace_writable: workspace_writable,
subagent_config,
role_catalog,
automatic_compaction,
max_parallel_tool_calls,
policy: policy.clone(),
worktree_manager: crate::WorktreeIsolationManager::new(),
};
let child_factory: Arc<dyn ChildRuntimeFactory> =
Arc::new(CodingChildRuntimeFactory::from_composition(composition));
let manager = SubagentManager::runtime_controlled(
session_id.clone(),
subagent_config,
child_factory,
subagents.is_enabled(),
);
let [spawn_tool, send_tool, wait_tool, cancel_tool] =
subagent_registered_tools_with_roles(manager.clone(), &role_summaries)?;
runtime_builder = runtime_builder.subagent_manager(manager);
profile_tools.extend([spawn_tool, send_tool, wait_tool, cancel_tool]);
}
}
let profile = profile_builder.register_tools(profile_tools).build()?;
runtime_builder = profile
.apply_to(runtime_builder)
.map_err(|source| CodingRuntimeBuildError::RuntimeProfileApply { source })?;
runtime_builder = policy.apply_to(runtime_builder);
if let Some(memory) = durable_memory {
runtime_builder = runtime_builder.durable_memory(memory, true);
}
if let Some(loaded_session) = loaded_session {
runtime_builder = runtime_builder.with_loaded_session(loaded_session);
}
if let Some(store) = session_store {
runtime_builder = runtime_builder.session_store(store);
}
Ok((runtime_builder, profile))
}
}
pub struct CodingRuntime {
runtime: Runtime,
profile: CodingAgentProfile,
loop_config: AgentLoopConfig,
}
impl CodingRuntime {
#[must_use]
pub fn runtime(&self) -> &Runtime {
&self.runtime
}
#[must_use]
pub fn into_runtime(self) -> Runtime {
self.runtime
}
#[must_use]
pub fn profile(&self) -> &CodingAgentProfile {
&self.profile
}
#[must_use]
pub fn loop_config(&self) -> AgentLoopConfig {
self.loop_config.clone()
}
}
#[derive(Debug, Error)]
pub enum CodingRuntimeBuildError {
#[error("full coding runtime requires a process backend")]
MissingProcessBackend,
#[error("coding model role {role:?} was configured more than once")]
DuplicateModelRole { role: RuntimeModelRole },
#[error(transparent)]
Core(#[from] CoreError),
#[error(transparent)]
ProjectRules(#[from] ProjectRulesLoadError),
#[error(transparent)]
SkillCatalog(#[from] SkillError),
#[error(transparent)]
CodingProfile(#[from] CodingAgentProfileBuildError),
#[error(transparent)]
LoopConfig(#[from] AgentLoopConfigError),
#[error(transparent)]
SubagentConfig(#[from] SubagentError),
#[error("failed to apply coding profile to runtime builder: {source}")]
RuntimeProfileApply { source: RuntimeError },
#[error("failed to build coding runtime: {source}")]
RuntimeBuild { source: RuntimeError },
}