1use crate::child_runtime::{CodingChildRuntimeFactory, CodingRuntimeComposition};
9use crate::{
10 CodingAgentProfile, CodingAgentProfileBuildError, CodingAgentProfileBuilder,
11 MIN_CODING_SUBAGENT_MODEL_TURNS, ProjectRulesLoadError, SubagentRoleCatalog, coding_agent,
12 load_root_project_rules,
13};
14use merry_core::{CoreError, HostPathPolicy, SessionId};
15use merry_llm::{ModelName, ModelProvider, ModelRetryPolicy, ReasoningEffort};
16use merry_process::ProcessBackend;
17use merry_runtime::{
18 AgentLoopConfig, AgentLoopConfigError, ChildRuntimeFactory, CompactionConfig, DurableMemory,
19 FileSessionStore, HistoryRetention, LoadedSession, PermissionReviewRules, RegisteredTool,
20 Runtime, RuntimeBuilder, RuntimeError, RuntimeModelRole, SkillCatalog, SkillError,
21 SubagentConfig, SubagentError, SubagentManager, subagent_registered_tools_with_roles,
22};
23use merry_tools::WorkspaceToolLimits;
24pub use permission_policy::{
25 CodingAutoFallback, CodingPermissionMode, CodingPermissionPolicy, CodingPermissionPolicyError,
26};
27use std::{collections::BTreeSet, path::PathBuf, sync::Arc};
28use thiserror::Error;
29
30mod permission_policy;
31
32#[derive(Clone)]
37pub struct CodingModelRoleConfig {
38 role: RuntimeModelRole,
39 provider: Arc<dyn ModelProvider>,
40 model: ModelName,
41 reasoning_effort: Option<ReasoningEffort>,
42}
43
44impl CodingModelRoleConfig {
45 pub fn new(
47 role: RuntimeModelRole,
48 provider: Arc<dyn ModelProvider>,
49 model: ModelName,
50 ) -> Result<Self, CodingModelRoleConfigError> {
51 if role == RuntimeModelRole::Primary {
52 return Err(CodingModelRoleConfigError::PrimaryRole);
53 }
54 Ok(Self {
55 role,
56 provider,
57 model,
58 reasoning_effort: None,
59 })
60 }
61
62 #[must_use]
64 pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
65 self.reasoning_effort = reasoning_effort;
66 self
67 }
68
69 #[must_use]
71 pub const fn role(&self) -> RuntimeModelRole {
72 self.role
73 }
74
75 #[must_use]
77 pub fn provider(&self) -> Arc<dyn ModelProvider> {
78 Arc::clone(&self.provider)
79 }
80
81 #[must_use]
83 pub fn model(&self) -> &ModelName {
84 &self.model
85 }
86
87 #[must_use]
89 pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
90 self.reasoning_effort.as_ref()
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
97pub enum CodingModelRoleConfigError {
98 #[error("primary model must be configured as the coding runtime's primary provider")]
100 PrimaryRole,
101}
102
103#[derive(Clone, Default)]
109pub(crate) struct CodingRuntimePolicy {
110 model_roles: Vec<CodingModelRoleConfig>,
111 permission: CodingPermissionPolicy,
112 permission_review_rules: PermissionReviewRules,
113 permission_review_workspace_root: Option<PathBuf>,
114}
115
116impl CodingRuntimePolicy {
117 pub(crate) fn try_new(
118 model_roles: Vec<CodingModelRoleConfig>,
119 permission: CodingPermissionPolicy,
120 ) -> Result<Self, CodingRuntimeBuildError> {
121 let mut configured_roles = BTreeSet::new();
122 for role in &model_roles {
123 if !configured_roles.insert(role.role()) {
124 return Err(CodingRuntimeBuildError::DuplicateModelRole { role: role.role() });
125 }
126 }
127 Ok(Self {
128 model_roles,
129 permission,
130 permission_review_rules: PermissionReviewRules::default(),
131 permission_review_workspace_root: None,
132 })
133 }
134
135 pub(crate) fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
136 self.permission_review_rules = rules;
137 self
138 }
139
140 pub(crate) fn with_permission_review_workspace_root(
141 mut self,
142 root: impl Into<PathBuf>,
143 ) -> Self {
144 self.permission_review_workspace_root = Some(root.into());
145 self
146 }
147
148 pub(crate) fn apply_to(&self, mut builder: RuntimeBuilder) -> RuntimeBuilder {
149 for role in &self.model_roles {
150 builder = builder.model_provider_for_role_with_reasoning(
151 role.role(),
152 role.provider(),
153 role.model().clone(),
154 role.reasoning_effort().cloned(),
155 );
156 }
157 if !self.permission_review_rules.is_empty() {
158 builder = builder.permission_review_rules(self.permission_review_rules.clone());
159 }
160 if let Some(root) = &self.permission_review_workspace_root {
161 builder = builder.permission_review_workspace_root(root.clone());
162 }
163 self.permission.apply_to(builder)
164 }
165}
166
167#[derive(Clone, Default)]
169pub struct CodingSubagentsConfig {
170 installed: bool,
171 enabled: bool,
172 limits: SubagentConfig,
173 role_catalog: SubagentRoleCatalog,
174}
175
176impl CodingSubagentsConfig {
177 #[must_use]
179 pub fn enabled(limits: SubagentConfig) -> Self {
180 Self {
181 installed: true,
182 enabled: true,
183 limits,
184 role_catalog: SubagentRoleCatalog::builtin(),
185 }
186 }
187
188 #[must_use]
191 pub fn runtime_controlled(enabled: bool, limits: SubagentConfig) -> Self {
192 Self {
193 installed: true,
194 enabled,
195 limits,
196 role_catalog: SubagentRoleCatalog::builtin(),
197 }
198 }
199
200 #[must_use]
203 pub fn with_role_catalog(mut self, role_catalog: SubagentRoleCatalog) -> Self {
204 self.role_catalog = role_catalog;
205 self
206 }
207
208 #[must_use]
210 pub const fn is_installed(&self) -> bool {
211 self.installed
212 }
213
214 #[must_use]
216 pub const fn is_enabled(&self) -> bool {
217 self.enabled
218 }
219
220 #[must_use]
222 pub const fn limits(&self) -> SubagentConfig {
223 self.limits
224 }
225
226 #[must_use]
228 pub fn role_catalog(&self) -> &SubagentRoleCatalog {
229 &self.role_catalog
230 }
231}
232
233#[derive(Clone)]
239pub struct CodingRuntimeInput {
240 session_id: SessionId,
241 root: PathBuf,
242 provider: Arc<dyn ModelProvider>,
243 model: ModelName,
244 process_backend: Option<Arc<dyn ProcessBackend>>,
245 extra_tools: Vec<RegisteredTool>,
246 automatic_compaction: CompactionConfig,
247 history_retention: HistoryRetention,
248 retry_policy: Option<ModelRetryPolicy>,
249 model_roles: Vec<CodingModelRoleConfig>,
250 skill_roots: Vec<PathBuf>,
251 host_path_policy: HostPathPolicy,
252 subagents: CodingSubagentsConfig,
253 workspace_tool_limits: WorkspaceToolLimits,
254 workspace_writable: bool,
257 durable_memory: Option<Arc<DurableMemory>>,
258 permission_review_rules: PermissionReviewRules,
259 max_parallel_tool_calls: Option<std::num::NonZeroUsize>,
260 context_window_tokens: Option<std::num::NonZeroU64>,
261}
262
263impl CodingRuntimeInput {
264 #[must_use]
266 pub fn new(
267 session_id: SessionId,
268 root: impl Into<PathBuf>,
269 provider: Arc<dyn ModelProvider>,
270 model: ModelName,
271 process_backend: Arc<dyn ProcessBackend>,
272 ) -> Self {
273 Self {
274 session_id,
275 root: root.into(),
276 provider,
277 model,
278 process_backend: Some(process_backend),
279 extra_tools: Vec::new(),
280 automatic_compaction: CompactionConfig::default(),
281 history_retention: HistoryRetention::default(),
282 retry_policy: None,
283 model_roles: Vec::new(),
284 skill_roots: Vec::new(),
285 host_path_policy: HostPathPolicy::new(),
286 subagents: CodingSubagentsConfig::default(),
287 workspace_tool_limits: WorkspaceToolLimits::default(),
288 workspace_writable: true,
289 durable_memory: None,
290 permission_review_rules: PermissionReviewRules::default(),
291 max_parallel_tool_calls: None,
292 context_window_tokens: None,
293 }
294 }
295
296 #[must_use]
299 pub fn read_only_workspace(mut self) -> Self {
300 self.workspace_writable = false;
301 self
302 }
303
304 #[must_use]
306 pub fn session_id(&self) -> &SessionId {
307 &self.session_id
308 }
309
310 #[must_use]
312 pub fn root(&self) -> &std::path::Path {
313 &self.root
314 }
315
316 #[must_use]
318 pub fn read_only(
319 session_id: SessionId,
320 root: impl Into<PathBuf>,
321 provider: Arc<dyn ModelProvider>,
322 model: ModelName,
323 ) -> Self {
324 Self {
325 session_id,
326 root: root.into(),
327 provider,
328 model,
329 process_backend: None,
330 extra_tools: Vec::new(),
331 automatic_compaction: CompactionConfig::default(),
332 history_retention: HistoryRetention::default(),
333 retry_policy: None,
334 model_roles: Vec::new(),
335 skill_roots: Vec::new(),
336 host_path_policy: HostPathPolicy::new(),
337 subagents: CodingSubagentsConfig::default(),
338 workspace_tool_limits: WorkspaceToolLimits::default(),
339 workspace_writable: true,
340 durable_memory: None,
341 permission_review_rules: PermissionReviewRules::default(),
342 max_parallel_tool_calls: None,
343 context_window_tokens: None,
344 }
345 }
346
347 #[must_use]
352 pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
353 self.durable_memory = Some(memory);
354 self
355 }
356
357 #[must_use]
359 pub fn with_extra_tools<I>(mut self, tools: I) -> Self
360 where
361 I: IntoIterator<Item = RegisteredTool>,
362 {
363 self.extra_tools.extend(tools);
364 self
365 }
366
367 #[must_use]
369 pub fn with_automatic_compaction(mut self, config: CompactionConfig) -> Self {
370 self.automatic_compaction = config;
371 self
372 }
373
374 #[must_use]
376 pub fn with_history_retention(mut self, retention: HistoryRetention) -> Self {
377 self.history_retention = retention;
378 self
379 }
380
381 #[must_use]
383 pub fn with_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
384 self.retry_policy = Some(policy);
385 self
386 }
387
388 #[must_use]
390 pub fn with_model_role(mut self, role: CodingModelRoleConfig) -> Self {
391 self.model_roles.push(role);
392 self
393 }
394
395 #[must_use]
397 pub fn with_model_roles<I>(mut self, roles: I) -> Self
398 where
399 I: IntoIterator<Item = CodingModelRoleConfig>,
400 {
401 self.model_roles.extend(roles);
402 self
403 }
404
405 #[must_use]
407 pub fn with_skill_roots<I, P>(mut self, roots: I) -> Self
408 where
409 I: IntoIterator<Item = P>,
410 P: Into<PathBuf>,
411 {
412 self.skill_roots = roots.into_iter().map(Into::into).collect();
413 self
414 }
415
416 #[must_use]
420 pub fn with_host_path_policy(mut self, policy: HostPathPolicy) -> Self {
421 self.host_path_policy = policy;
422 self
423 }
424
425 #[must_use]
427 pub fn with_subagents(mut self, subagents: CodingSubagentsConfig) -> Self {
428 self.subagents = subagents;
429 self
430 }
431
432 #[must_use]
434 pub fn with_workspace_tool_limits(mut self, limits: WorkspaceToolLimits) -> Self {
435 self.workspace_tool_limits = limits;
436 self
437 }
438
439 #[must_use]
442 pub fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
443 self.permission_review_rules = rules;
444 self
445 }
446
447 #[must_use]
450 pub fn with_max_parallel_tool_calls(mut self, limit: std::num::NonZeroUsize) -> Self {
451 self.max_parallel_tool_calls = Some(limit);
452 self
453 }
454
455 #[must_use]
458 pub fn with_context_window_tokens(mut self, tokens: std::num::NonZeroU64) -> Self {
459 self.context_window_tokens = Some(tokens);
460 self
461 }
462}
463
464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466enum CodingRuntimeVariant {
467 FullCoding,
469 ReadOnlyCommandGeneration,
471}
472
473pub struct CodingRuntimeBuilder {
475 input: CodingRuntimeInput,
476 variant: CodingRuntimeVariant,
477 permission: CodingPermissionPolicy,
478 loaded_session: Option<LoadedSession>,
479 session_store: Option<FileSessionStore>,
480}
481
482impl CodingRuntimeBuilder {
483 #[must_use]
485 pub fn new(input: CodingRuntimeInput) -> Self {
486 Self {
487 input,
488 variant: CodingRuntimeVariant::FullCoding,
489 permission: CodingPermissionPolicy::default(),
490 loaded_session: None,
491 session_store: None,
492 }
493 }
494
495 #[must_use]
502 pub fn for_command_generation(input: CodingRuntimeInput) -> Self {
503 Self {
504 input,
505 variant: CodingRuntimeVariant::ReadOnlyCommandGeneration,
506 permission: CodingPermissionPolicy::default(),
507 loaded_session: None,
508 session_store: None,
509 }
510 }
511
512 #[must_use]
514 pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
515 self.permission = policy;
516 self
517 }
518
519 #[must_use]
521 pub fn with_loaded_session(mut self, loaded: LoadedSession) -> Self {
522 self.loaded_session = Some(loaded);
523 self
524 }
525
526 #[must_use]
528 pub fn session_store(mut self, store: FileSessionStore) -> Self {
529 self.session_store = Some(store);
530 self
531 }
532
533 pub fn build(self) -> Result<CodingRuntime, CodingRuntimeBuildError> {
535 let (builder, profile) = self.compose()?;
536 let loop_config = profile.loop_config()?;
537 let runtime = builder
538 .build()
539 .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
540 Ok(CodingRuntime {
541 runtime,
542 profile,
543 loop_config,
544 })
545 }
546
547 pub async fn resume_from_store_without_automatic_savepoints(
549 self,
550 store: FileSessionStore,
551 ) -> Result<CodingRuntime, CodingRuntimeBuildError> {
552 let (builder, profile) = self.compose()?;
553 let loop_config = profile.loop_config()?;
554 let runtime = builder
555 .resume_from_store_without_automatic_savepoints(store)
556 .await
557 .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
558 Ok(CodingRuntime {
559 runtime,
560 profile,
561 loop_config,
562 })
563 }
564
565 fn compose(
566 self,
567 ) -> Result<(merry_runtime::RuntimeBuilder, CodingAgentProfile), CodingRuntimeBuildError> {
568 let Self {
569 input,
570 variant,
571 permission,
572 loaded_session,
573 session_store,
574 } = self;
575 let CodingRuntimeInput {
576 session_id,
577 root,
578 provider,
579 model,
580 process_backend,
581 extra_tools,
582 automatic_compaction,
583 history_retention,
584 retry_policy,
585 model_roles,
586 skill_roots,
587 host_path_policy,
588 subagents,
589 workspace_tool_limits,
590 workspace_writable,
591 durable_memory,
592 permission_review_rules,
593 max_parallel_tool_calls,
594 context_window_tokens,
595 } = input;
596
597 let policy = CodingRuntimePolicy::try_new(model_roles, permission)?
598 .with_permission_review_rules(permission_review_rules)
599 .with_permission_review_workspace_root(root.clone());
600
601 let project_rules = if workspace_writable {
602 load_root_project_rules(&root)?
603 } else {
604 None
605 };
606 let skill_catalog = if skill_roots.is_empty() {
607 None
608 } else {
609 Some(SkillCatalog::load_from_roots(skill_roots.clone())?)
610 };
611 if let Some(catalog) = skill_catalog.as_ref() {
612 const MAX_LOGGED_SKILL_NAMES: usize = 64;
613 let skill_names = catalog
614 .skills()
615 .iter()
616 .take(MAX_LOGGED_SKILL_NAMES)
617 .map(|skill| skill.name())
618 .collect::<Vec<_>>();
619 tracing::info!(
620 event = "runtime.skill_catalog.load",
621 session_id = %session_id,
622 configured_root_count = skill_roots.len(),
623 readable_root_count = skill_roots.iter().filter(|root| root.is_dir()).count(),
624 skill_count = catalog.skills().len(),
625 warning_count = catalog.warnings().len(),
626 skill_names = ?skill_names,
627 "runtime skill catalog loaded"
628 );
629 }
630 let mut runtime_builder = Runtime::builder(session_id.clone())
631 .automatic_compaction(automatic_compaction.clone())
632 .history_retention(history_retention)
633 .model_provider(Arc::clone(&provider), model.clone());
634 if let Some(limit) = max_parallel_tool_calls {
635 runtime_builder = runtime_builder.max_parallel_tool_calls(limit);
636 }
637 if let Some(tokens) = context_window_tokens {
638 runtime_builder = runtime_builder.context_window_tokens(tokens);
639 }
640 if matches!(variant, CodingRuntimeVariant::FullCoding) {
641 runtime_builder = runtime_builder.coordinator_plan_tools();
642 }
643
644 let mut profile_builder: CodingAgentProfileBuilder = coding_agent(&root)
645 .readonly_resource_roots(skill_roots.clone())
646 .host_path_policy(host_path_policy)
647 .limits(workspace_tool_limits)
648 .register_tools(extra_tools);
649 if !workspace_writable {
650 profile_builder = profile_builder.read_only_patch_scope();
651 }
652 if let Some(project_rules) = project_rules {
653 profile_builder = profile_builder.project_rules(project_rules);
654 }
655 if let Some(skill_catalog) = skill_catalog {
656 profile_builder = profile_builder.skill_catalog(skill_catalog);
657 }
658 if let Some(policy) = retry_policy {
659 profile_builder = profile_builder.retry_policy(policy);
660 }
661 if let Some(memory) = durable_memory.clone() {
662 profile_builder = profile_builder.durable_memory(memory);
663 }
664
665 let mut profile_tools = Vec::new();
666 if matches!(variant, CodingRuntimeVariant::FullCoding) {
667 let process_backend =
668 process_backend.ok_or(CodingRuntimeBuildError::MissingProcessBackend)?;
669 let process_session = process_backend.new_session();
670 let parent_process_permissions = process_session.permission_view();
671 profile_builder = profile_builder
672 .patch_tool()
673 .web_tools()
674 .accepted_process_session(process_session);
675
676 if subagents.is_installed() {
677 let subagent_config = subagents.limits().with_model_turn_bounds(
678 MIN_CODING_SUBAGENT_MODEL_TURNS,
679 subagents.limits().max_model_turns(),
680 )?;
681 tracing::info!(
682 event = "runtime.subagents.enabled",
683 session_id = %session_id,
684 enabled = subagents.is_enabled(),
685 max_threads = subagent_config.max_threads(),
686 max_depth = subagent_config.max_depth(),
687 min_model_turns = subagent_config.min_model_turns(),
688 max_model_turns = subagent_config.max_model_turns(),
689 "runtime subagent tools installed"
690 );
691 let role_catalog = subagents.role_catalog().clone();
692 let role_summaries = role_catalog.enabled_role_summaries();
693 let composition = CodingRuntimeComposition {
694 profile_builder: profile_builder.clone(),
695 provider: Arc::clone(&provider),
696 model: model.clone(),
697 process_backend,
698 parent_process_permissions,
699 parent_workspace_writable: workspace_writable,
700 subagent_config,
701 role_catalog,
702 automatic_compaction,
703 max_parallel_tool_calls,
704 policy: policy.clone(),
705 worktree_manager: crate::WorktreeIsolationManager::new(),
706 };
707 let child_factory: Arc<dyn ChildRuntimeFactory> =
708 Arc::new(CodingChildRuntimeFactory::from_composition(composition));
709 let manager = SubagentManager::runtime_controlled(
710 session_id.clone(),
711 subagent_config,
712 child_factory,
713 subagents.is_enabled(),
714 );
715 let [spawn_tool, send_tool, wait_tool, cancel_tool] =
716 subagent_registered_tools_with_roles(manager.clone(), &role_summaries)?;
717 runtime_builder = runtime_builder.subagent_manager(manager);
718 profile_tools.extend([spawn_tool, send_tool, wait_tool, cancel_tool]);
719 }
720 }
721
722 let profile = profile_builder.register_tools(profile_tools).build()?;
723 runtime_builder = profile
724 .apply_to(runtime_builder)
725 .map_err(|source| CodingRuntimeBuildError::RuntimeProfileApply { source })?;
726 runtime_builder = policy.apply_to(runtime_builder);
727 if let Some(memory) = durable_memory {
728 runtime_builder = runtime_builder.durable_memory(memory, true);
729 }
730 if let Some(loaded_session) = loaded_session {
731 runtime_builder = runtime_builder.with_loaded_session(loaded_session);
732 }
733 if let Some(store) = session_store {
734 runtime_builder = runtime_builder.session_store(store);
735 }
736
737 Ok((runtime_builder, profile))
738 }
739}
740
741pub struct CodingRuntime {
743 runtime: Runtime,
744 profile: CodingAgentProfile,
745 loop_config: AgentLoopConfig,
746}
747
748impl CodingRuntime {
749 #[must_use]
751 pub fn runtime(&self) -> &Runtime {
752 &self.runtime
753 }
754
755 #[must_use]
757 pub fn into_runtime(self) -> Runtime {
758 self.runtime
759 }
760
761 #[must_use]
763 pub fn profile(&self) -> &CodingAgentProfile {
764 &self.profile
765 }
766
767 #[must_use]
769 pub fn loop_config(&self) -> AgentLoopConfig {
770 self.loop_config.clone()
771 }
772}
773
774#[derive(Debug, Error)]
776pub enum CodingRuntimeBuildError {
777 #[error("full coding runtime requires a process backend")]
779 MissingProcessBackend,
780 #[error("coding model role {role:?} was configured more than once")]
782 DuplicateModelRole { role: RuntimeModelRole },
783 #[error(transparent)]
785 Core(#[from] CoreError),
786 #[error(transparent)]
788 ProjectRules(#[from] ProjectRulesLoadError),
789 #[error(transparent)]
791 SkillCatalog(#[from] SkillError),
792 #[error(transparent)]
794 CodingProfile(#[from] CodingAgentProfileBuildError),
795 #[error(transparent)]
797 LoopConfig(#[from] AgentLoopConfigError),
798 #[error(transparent)]
800 SubagentConfig(#[from] SubagentError),
801 #[error("failed to apply coding profile to runtime builder: {source}")]
803 RuntimeProfileApply { source: RuntimeError },
804 #[error("failed to build coding runtime: {source}")]
806 RuntimeBuild { source: RuntimeError },
807}