1use crate::{
4 AcceptedLocalWorkspaceProcessAdmission, BackgroundProcessControl, PermissionAdmissionSource,
5 PermissionReviewMode, PermissionedProcessRunnerFactory, ProcessRunner, ProjectRules,
6 PromptProfile, RegisteredTool, RuntimeTrustLevel, SkillCatalog, SubagentManager, TaskAnchor,
7};
8use merry_core::ToolName;
9use merry_llm::ModelRetryPolicy;
10use std::{
11 collections::{BTreeMap, BTreeSet},
12 path::{Path, PathBuf},
13 sync::Arc,
14};
15use thiserror::Error;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum PathAccess {
20 ReadOnly,
22 ReadWrite,
24 Deny,
26}
27
28impl PathAccess {
29 #[must_use]
31 pub const fn as_str(self) -> &'static str {
32 match self {
33 Self::ReadOnly => "ro",
34 Self::ReadWrite => "rw",
35 Self::Deny => "deny",
36 }
37 }
38
39 #[must_use]
44 pub const fn covers(self, requested: Self) -> bool {
45 matches!(
46 (self, requested),
47 (Self::ReadWrite, Self::ReadOnly | Self::ReadWrite) | (Self::ReadOnly, Self::ReadOnly)
48 )
49 }
50}
51
52#[non_exhaustive]
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
55pub enum PathAccessRuleSource {
56 DefaultDevelopmentBaseline,
58 TrustedGlobalConfig,
63 ProductPrivate,
65 ProductConfig,
70 GitMetadataBaseline,
75 PermissionReview,
77 DurableMemory,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct PathAccessRule {
87 path: PathBuf,
88 access: PathAccess,
89 source: PathAccessRuleSource,
90 review_required: bool,
91}
92
93impl PathAccessRule {
94 #[must_use]
96 pub fn new(path: impl Into<PathBuf>, access: PathAccess, source: PathAccessRuleSource) -> Self {
97 Self {
98 path: path.into(),
99 access,
100 source,
101 review_required: false,
102 }
103 }
104
105 #[must_use]
109 pub const fn with_review_required(mut self) -> Self {
110 self.review_required = true;
111 self
112 }
113
114 #[must_use]
116 pub const fn review_required(&self) -> bool {
117 self.review_required
118 }
119
120 #[must_use]
122 pub fn path(&self) -> &Path {
123 &self.path
124 }
125
126 #[must_use]
128 pub const fn access(&self) -> PathAccess {
129 self.access
130 }
131
132 #[must_use]
134 pub const fn source(&self) -> PathAccessRuleSource {
135 self.source
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct RuntimeCapabilities {
146 network_allowed: bool,
147 path_rules: Vec<PathAccessRule>,
148}
149
150impl RuntimeCapabilities {
151 #[must_use]
155 pub fn new() -> Self {
156 Self {
157 network_allowed: false,
158 path_rules: Vec::new(),
159 }
160 }
161
162 #[must_use]
164 pub fn allow_network(mut self) -> Self {
165 self.network_allowed = true;
166 self
167 }
168
169 #[must_use]
171 pub fn deny_network(mut self) -> Self {
172 self.network_allowed = false;
173 self
174 }
175
176 #[must_use]
178 pub fn with_path_rule(mut self, rule: PathAccessRule) -> Self {
179 self.path_rules.push(rule);
180 self
181 }
182
183 #[must_use]
185 pub fn with_path_rules(mut self, rules: Vec<PathAccessRule>) -> Self {
186 self.path_rules = rules;
187 self
188 }
189
190 #[must_use]
192 pub fn network_allowed(&self) -> bool {
193 self.network_allowed
194 }
195
196 #[must_use]
198 pub fn path_rules(&self) -> &[PathAccessRule] {
199 &self.path_rules
200 }
201}
202
203impl Default for RuntimeCapabilities {
204 fn default() -> Self {
205 Self::new()
206 }
207}
208
209#[derive(Debug, Error, Clone, PartialEq, Eq)]
211pub enum RuntimeProfileError {
212 #[error("tool {name} is already registered in runtime profile")]
214 DuplicateToolRegistration {
215 name: ToolName,
217 },
218 #[error("tool {name} is reserved by the runtime")]
220 ReservedToolName {
221 name: ToolName,
223 },
224}
225
226#[derive(Clone)]
228pub struct AcceptedLocalWorkspaceProcessRunnerProfile {
229 admission: AcceptedLocalWorkspaceProcessAdmission,
230 runner: Arc<dyn ProcessRunner>,
231}
232
233impl AcceptedLocalWorkspaceProcessRunnerProfile {
234 #[must_use]
236 pub fn new(
237 admission: AcceptedLocalWorkspaceProcessAdmission,
238 runner: Arc<dyn ProcessRunner>,
239 ) -> Self {
240 Self { admission, runner }
241 }
242
243 #[must_use]
245 pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
246 self.admission
247 }
248
249 #[must_use]
251 pub fn runner(&self) -> Arc<dyn ProcessRunner> {
252 Arc::clone(&self.runner)
253 }
254}
255
256#[derive(Clone)]
258pub struct RuntimeProfile {
259 capabilities: RuntimeCapabilities,
260 model_retry_policy: Option<ModelRetryPolicy>,
261 prompt_profile: PromptProfile,
262 progress_commentary: bool,
263 initial_context_summaries: BTreeMap<String, String>,
264 registered_tools: Vec<RegisteredTool>,
265 allow_bridge_tools: bool,
266 allow_low_risk_apply_patches: bool,
267 low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
268 read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
269 accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
270 runtime_trust_level: Option<RuntimeTrustLevel>,
271 permission_review_mode: Option<PermissionReviewMode>,
272 permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
273 permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
274 background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
275 skill_catalog: Option<SkillCatalog>,
276 project_rules: Option<ProjectRules>,
277 task_anchor: Option<TaskAnchor>,
278 subagent_manager: Option<SubagentManager>,
279}
280
281impl RuntimeProfile {
282 #[must_use]
284 pub fn builder() -> RuntimeProfileBuilder {
285 RuntimeProfileBuilder::new()
286 }
287
288 #[must_use]
290 pub const fn capabilities(&self) -> &RuntimeCapabilities {
291 &self.capabilities
292 }
293
294 #[must_use]
296 pub const fn model_retry_policy(&self) -> Option<ModelRetryPolicy> {
297 self.model_retry_policy
298 }
299
300 #[must_use]
302 pub const fn prompt_profile(&self) -> &PromptProfile {
303 &self.prompt_profile
304 }
305
306 #[must_use]
308 pub const fn progress_commentary(&self) -> bool {
309 self.progress_commentary
310 }
311
312 #[must_use]
314 pub fn initial_context_summaries(&self) -> &BTreeMap<String, String> {
315 &self.initial_context_summaries
316 }
317
318 #[must_use]
320 pub fn registered_tools(&self) -> &[RegisteredTool] {
321 &self.registered_tools
322 }
323
324 #[must_use]
326 pub fn into_registered_tools(self) -> Vec<RegisteredTool> {
327 self.registered_tools
328 }
329
330 #[must_use]
332 pub const fn allow_bridge_tools(&self) -> bool {
333 self.allow_bridge_tools
334 }
335
336 #[must_use]
338 pub const fn allow_low_risk_apply_patches(&self) -> bool {
339 self.allow_low_risk_apply_patches
340 }
341
342 #[must_use]
344 pub fn low_risk_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
345 self.low_risk_process_runner.as_ref().map(Arc::clone)
346 }
347
348 #[must_use]
350 pub fn read_only_shell_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
351 self.read_only_shell_process_runner.as_ref().map(Arc::clone)
352 }
353
354 #[must_use]
356 pub fn accepted_local_workspace_process_runner(
357 &self,
358 ) -> Option<&AcceptedLocalWorkspaceProcessRunnerProfile> {
359 self.accepted_local_workspace_process_runner.as_ref()
360 }
361
362 #[must_use]
364 pub const fn runtime_trust_level(&self) -> Option<RuntimeTrustLevel> {
365 self.runtime_trust_level
366 }
367
368 #[must_use]
370 pub const fn permission_review_mode(&self) -> Option<PermissionReviewMode> {
371 self.permission_review_mode
372 }
373
374 #[must_use]
376 pub fn permission_admission_source(&self) -> Option<Arc<dyn PermissionAdmissionSource>> {
377 self.permission_admission_source.as_ref().map(Arc::clone)
378 }
379
380 #[must_use]
382 pub fn permissioned_process_runner_factory(
383 &self,
384 ) -> Option<Arc<dyn PermissionedProcessRunnerFactory>> {
385 self.permissioned_process_runner_factory
386 .as_ref()
387 .map(Arc::clone)
388 }
389
390 #[must_use]
392 pub const fn skill_catalog(&self) -> Option<&SkillCatalog> {
393 self.skill_catalog.as_ref()
394 }
395
396 #[must_use]
398 pub const fn project_rules(&self) -> Option<&ProjectRules> {
399 self.project_rules.as_ref()
400 }
401
402 #[must_use]
404 pub const fn task_anchor(&self) -> Option<&TaskAnchor> {
405 self.task_anchor.as_ref()
406 }
407
408 #[must_use]
410 pub const fn subagent_manager(&self) -> Option<&SubagentManager> {
411 self.subagent_manager.as_ref()
412 }
413
414 pub(crate) fn into_parts(self) -> RuntimeProfileParts {
415 RuntimeProfileParts {
416 capabilities: self.capabilities,
417 model_retry_policy: self.model_retry_policy,
418 prompt_profile: self.prompt_profile,
419 progress_commentary: self.progress_commentary,
420 initial_context_summaries: self.initial_context_summaries,
421 registered_tools: self.registered_tools,
422 allow_bridge_tools: self.allow_bridge_tools,
423 allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
424 low_risk_process_runner: self.low_risk_process_runner,
425 read_only_shell_process_runner: self.read_only_shell_process_runner,
426 accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
427 runtime_trust_level: self.runtime_trust_level,
428 permission_review_mode: self.permission_review_mode,
429 permission_admission_source: self.permission_admission_source,
430 permissioned_process_runner_factory: self.permissioned_process_runner_factory,
431 background_process_control: self.background_process_control,
432 skill_catalog: self.skill_catalog,
433 project_rules: self.project_rules,
434 task_anchor: self.task_anchor,
435 subagent_manager: self.subagent_manager,
436 }
437 }
438}
439
440pub(crate) struct RuntimeProfileParts {
441 pub(crate) capabilities: RuntimeCapabilities,
442 pub(crate) model_retry_policy: Option<ModelRetryPolicy>,
443 pub(crate) prompt_profile: PromptProfile,
444 pub(crate) progress_commentary: bool,
445 pub(crate) initial_context_summaries: BTreeMap<String, String>,
446 pub(crate) registered_tools: Vec<RegisteredTool>,
447 pub(crate) allow_bridge_tools: bool,
448 pub(crate) allow_low_risk_apply_patches: bool,
449 pub(crate) low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
450 pub(crate) read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
451 pub(crate) accepted_local_workspace_process_runner:
452 Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
453 pub(crate) runtime_trust_level: Option<RuntimeTrustLevel>,
454 pub(crate) permission_review_mode: Option<PermissionReviewMode>,
455 pub(crate) permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
456 pub(crate) permissioned_process_runner_factory:
457 Option<Arc<dyn PermissionedProcessRunnerFactory>>,
458 pub(crate) background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
459 pub(crate) skill_catalog: Option<SkillCatalog>,
460 pub(crate) project_rules: Option<ProjectRules>,
461 pub(crate) task_anchor: Option<TaskAnchor>,
462 pub(crate) subagent_manager: Option<SubagentManager>,
463}
464
465pub struct RuntimeProfileBuilder {
467 capabilities: RuntimeCapabilities,
468 model_retry_policy: Option<ModelRetryPolicy>,
469 prompt_profile: PromptProfile,
470 progress_commentary: bool,
471 initial_context_summaries: BTreeMap<String, String>,
472 registered_tools: Vec<RegisteredTool>,
473 allow_bridge_tools: bool,
474 allow_low_risk_apply_patches: bool,
475 low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
476 read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
477 accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
478 runtime_trust_level: Option<RuntimeTrustLevel>,
479 permission_review_mode: Option<PermissionReviewMode>,
480 permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
481 permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
482 background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
483 skill_catalog: Option<SkillCatalog>,
484 project_rules: Option<ProjectRules>,
485 task_anchor: Option<TaskAnchor>,
486 subagent_manager: Option<SubagentManager>,
487}
488
489impl RuntimeProfileBuilder {
490 #[must_use]
492 pub fn new() -> Self {
493 Self {
494 capabilities: RuntimeCapabilities::default(),
495 model_retry_policy: None,
496 prompt_profile: PromptProfile::default(),
497 progress_commentary: false,
498 initial_context_summaries: BTreeMap::new(),
499 registered_tools: Vec::new(),
500 allow_bridge_tools: false,
501 allow_low_risk_apply_patches: false,
502 low_risk_process_runner: None,
503 read_only_shell_process_runner: None,
504 accepted_local_workspace_process_runner: None,
505 runtime_trust_level: None,
506 permission_review_mode: None,
507 permission_admission_source: None,
508 permissioned_process_runner_factory: None,
509 background_process_control: None,
510 skill_catalog: None,
511 project_rules: None,
512 task_anchor: None,
513 subagent_manager: None,
514 }
515 }
516
517 #[must_use]
519 pub fn capabilities(mut self, capabilities: RuntimeCapabilities) -> Self {
520 self.capabilities = capabilities;
521 self
522 }
523
524 #[must_use]
526 pub fn model_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
527 self.model_retry_policy = Some(policy);
528 self
529 }
530
531 #[must_use]
533 pub fn prompt_profile(mut self, profile: PromptProfile) -> Self {
534 self.prompt_profile = profile;
535 self
536 }
537
538 #[must_use]
544 pub fn progress_commentary(mut self, enabled: bool) -> Self {
545 self.progress_commentary = enabled;
546 self
547 }
548
549 #[must_use]
551 pub fn initial_context_summary(mut self, id: &str, text: &str) -> Self {
552 self.initial_context_summaries
553 .insert(id.to_owned(), text.to_owned());
554 self
555 }
556
557 #[must_use]
559 pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
560 self.registered_tools.push(tool);
561 self
562 }
563
564 #[must_use]
566 pub fn allow_bridge_tools(mut self) -> Self {
567 self.allow_bridge_tools = true;
568 self
569 }
570
571 #[must_use]
573 pub fn allow_low_risk_apply_patches(mut self) -> Self {
574 self.allow_low_risk_apply_patches = true;
575 self
576 }
577
578 #[must_use]
580 pub fn allow_low_risk_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
581 self.low_risk_process_runner = Some(runner);
582 self
583 }
584
585 #[must_use]
587 pub fn allow_read_only_shell_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
588 self.read_only_shell_process_runner = Some(runner);
589 self
590 }
591
592 #[must_use]
594 pub fn allow_accepted_local_workspace_process_actions(
595 mut self,
596 admission: AcceptedLocalWorkspaceProcessAdmission,
597 runner: Arc<dyn ProcessRunner>,
598 ) -> Self {
599 self.accepted_local_workspace_process_runner = Some(
600 AcceptedLocalWorkspaceProcessRunnerProfile::new(admission, runner),
601 );
602 self
603 }
604
605 #[must_use]
607 pub fn runtime_trust_level(mut self, trust_level: RuntimeTrustLevel) -> Self {
608 self.runtime_trust_level = Some(trust_level);
609 self
610 }
611
612 #[must_use]
614 pub fn permission_review_mode(mut self, mode: PermissionReviewMode) -> Self {
615 self.permission_review_mode = Some(mode);
616 self
617 }
618
619 #[must_use]
621 pub fn permission_admission_source(
622 mut self,
623 source: Arc<dyn PermissionAdmissionSource>,
624 ) -> Self {
625 self.permission_admission_source = Some(source);
626 self
627 }
628
629 #[must_use]
631 pub fn background_process_control(
632 mut self,
633 control: Arc<dyn BackgroundProcessControl>,
634 ) -> Self {
635 self.background_process_control = Some(control);
636 self
637 }
638
639 #[must_use]
641 pub fn permissioned_process_runner_factory(
642 mut self,
643 factory: Arc<dyn PermissionedProcessRunnerFactory>,
644 ) -> Self {
645 self.permissioned_process_runner_factory = Some(factory);
646 self
647 }
648
649 #[must_use]
651 pub fn skill_catalog(mut self, catalog: SkillCatalog) -> Self {
652 self.skill_catalog = Some(catalog);
653 self
654 }
655
656 #[must_use]
658 pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
659 self.project_rules = Some(project_rules);
660 self
661 }
662
663 #[must_use]
665 pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
666 self.task_anchor = Some(task_anchor);
667 self
668 }
669
670 #[must_use]
672 pub fn subagent_manager(mut self, manager: SubagentManager) -> Self {
673 self.subagent_manager = Some(manager);
674 self
675 }
676
677 pub fn build(self) -> Result<RuntimeProfile, RuntimeProfileError> {
679 let mut names = BTreeSet::new();
680 for tool in &self.registered_tools {
681 let name = tool.spec().name().clone();
682 if name.as_str() == crate::FINAL_OUTPUT_TOOL_NAME {
683 return Err(RuntimeProfileError::ReservedToolName { name });
684 }
685 if !names.insert(name.clone()) {
686 return Err(RuntimeProfileError::DuplicateToolRegistration { name });
687 }
688 }
689
690 Ok(RuntimeProfile {
691 capabilities: self.capabilities,
692 model_retry_policy: self.model_retry_policy,
693 prompt_profile: self.prompt_profile,
694 progress_commentary: self.progress_commentary,
695 initial_context_summaries: self.initial_context_summaries,
696 registered_tools: self.registered_tools,
697 allow_bridge_tools: self.allow_bridge_tools,
698 allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
699 low_risk_process_runner: self.low_risk_process_runner,
700 read_only_shell_process_runner: self.read_only_shell_process_runner,
701 accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
702 runtime_trust_level: self.runtime_trust_level,
703 permission_review_mode: self.permission_review_mode,
704 permission_admission_source: self.permission_admission_source,
705 permissioned_process_runner_factory: self.permissioned_process_runner_factory,
706 background_process_control: self.background_process_control,
707 skill_catalog: self.skill_catalog,
708 project_rules: self.project_rules,
709 task_anchor: self.task_anchor,
710 subagent_manager: self.subagent_manager,
711 })
712 }
713}
714
715impl Default for RuntimeProfileBuilder {
716 fn default() -> Self {
717 Self::new()
718 }
719}
720
721#[cfg(test)]
722mod tests {
723 use super::{PathAccess, PathAccessRule, PathAccessRuleSource, RuntimeCapabilities};
724 use std::path::Path;
725
726 #[test]
727 fn runtime_capabilities_control_network_without_tool_network_field() {
728 let capabilities = RuntimeCapabilities::default().allow_network();
729
730 assert!(capabilities.network_allowed());
731 }
732
733 #[test]
734 fn runtime_capabilities_deny_network_by_default() {
735 let capabilities = RuntimeCapabilities::default();
736
737 assert!(!capabilities.network_allowed());
738 }
739
740 #[test]
741 fn runtime_capabilities_carry_platform_neutral_path_rules() {
742 let rule = PathAccessRule::new(
743 "/var/log/foo",
744 PathAccess::ReadOnly,
745 PathAccessRuleSource::TrustedGlobalConfig,
746 );
747 let capabilities = RuntimeCapabilities::default().with_path_rule(rule);
748
749 assert_eq!(capabilities.path_rules().len(), 1);
750 assert_eq!(
751 capabilities.path_rules()[0].path(),
752 Path::new("/var/log/foo")
753 );
754 assert_eq!(capabilities.path_rules()[0].access(), PathAccess::ReadOnly);
755 assert_eq!(
756 capabilities.path_rules()[0].source(),
757 PathAccessRuleSource::TrustedGlobalConfig
758 );
759 }
760
761 #[test]
762 fn path_access_has_stable_config_spelling() {
763 assert_eq!(PathAccess::ReadOnly.as_str(), "ro");
764 assert_eq!(PathAccess::ReadWrite.as_str(), "rw");
765 assert_eq!(PathAccess::Deny.as_str(), "deny");
766 }
767
768 #[test]
769 fn path_access_coverage_keeps_read_only_and_read_write_distinct() {
770 assert!(PathAccess::ReadWrite.covers(PathAccess::ReadOnly));
771 assert!(PathAccess::ReadWrite.covers(PathAccess::ReadWrite));
772 assert!(PathAccess::ReadOnly.covers(PathAccess::ReadOnly));
773 assert!(!PathAccess::ReadOnly.covers(PathAccess::ReadWrite));
774 assert!(!PathAccess::Deny.covers(PathAccess::ReadOnly));
775 assert!(!PathAccess::Deny.covers(PathAccess::ReadWrite));
776 }
777}