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 ProductReadOnly,
69 ProductConfig,
74 GitMetadataBaseline,
79 PermissionReview,
81 DurableMemory,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct PathAccessRule {
91 path: PathBuf,
92 access: PathAccess,
93 source: PathAccessRuleSource,
94 review_required: bool,
95}
96
97impl PathAccessRule {
98 #[must_use]
100 pub fn new(path: impl Into<PathBuf>, access: PathAccess, source: PathAccessRuleSource) -> Self {
101 Self {
102 path: path.into(),
103 access,
104 source,
105 review_required: false,
106 }
107 }
108
109 #[must_use]
113 pub const fn with_review_required(mut self) -> Self {
114 self.review_required = true;
115 self
116 }
117
118 #[must_use]
120 pub const fn review_required(&self) -> bool {
121 self.review_required
122 }
123
124 #[must_use]
126 pub fn path(&self) -> &Path {
127 &self.path
128 }
129
130 #[must_use]
132 pub const fn access(&self) -> PathAccess {
133 self.access
134 }
135
136 #[must_use]
138 pub const fn source(&self) -> PathAccessRuleSource {
139 self.source
140 }
141}
142
143#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct RuntimeCapabilities {
150 network_allowed: bool,
151 path_rules: Vec<PathAccessRule>,
152}
153
154impl RuntimeCapabilities {
155 #[must_use]
159 pub fn new() -> Self {
160 Self {
161 network_allowed: false,
162 path_rules: Vec::new(),
163 }
164 }
165
166 #[must_use]
168 pub fn allow_network(mut self) -> Self {
169 self.network_allowed = true;
170 self
171 }
172
173 #[must_use]
175 pub fn deny_network(mut self) -> Self {
176 self.network_allowed = false;
177 self
178 }
179
180 #[must_use]
182 pub fn with_path_rule(mut self, rule: PathAccessRule) -> Self {
183 self.path_rules.push(rule);
184 self
185 }
186
187 #[must_use]
189 pub fn with_path_rules(mut self, rules: Vec<PathAccessRule>) -> Self {
190 self.path_rules = rules;
191 self
192 }
193
194 #[must_use]
196 pub fn network_allowed(&self) -> bool {
197 self.network_allowed
198 }
199
200 #[must_use]
202 pub fn path_rules(&self) -> &[PathAccessRule] {
203 &self.path_rules
204 }
205}
206
207impl Default for RuntimeCapabilities {
208 fn default() -> Self {
209 Self::new()
210 }
211}
212
213#[derive(Debug, Error, Clone, PartialEq, Eq)]
215pub enum RuntimeProfileError {
216 #[error("tool {name} is already registered in runtime profile")]
218 DuplicateToolRegistration {
219 name: ToolName,
221 },
222 #[error("tool {name} is reserved by the runtime")]
224 ReservedToolName {
225 name: ToolName,
227 },
228}
229
230#[derive(Clone)]
232pub struct AcceptedLocalWorkspaceProcessRunnerProfile {
233 admission: AcceptedLocalWorkspaceProcessAdmission,
234 runner: Arc<dyn ProcessRunner>,
235}
236
237impl AcceptedLocalWorkspaceProcessRunnerProfile {
238 #[must_use]
240 pub fn new(
241 admission: AcceptedLocalWorkspaceProcessAdmission,
242 runner: Arc<dyn ProcessRunner>,
243 ) -> Self {
244 Self { admission, runner }
245 }
246
247 #[must_use]
249 pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
250 self.admission
251 }
252
253 #[must_use]
255 pub fn runner(&self) -> Arc<dyn ProcessRunner> {
256 Arc::clone(&self.runner)
257 }
258}
259
260#[derive(Clone)]
262pub struct RuntimeProfile {
263 capabilities: RuntimeCapabilities,
264 model_retry_policy: Option<ModelRetryPolicy>,
265 prompt_profile: PromptProfile,
266 progress_commentary: bool,
267 initial_context_summaries: BTreeMap<String, String>,
268 registered_tools: Vec<RegisteredTool>,
269 allow_bridge_tools: bool,
270 allow_low_risk_apply_patches: bool,
271 low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
272 read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
273 accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
274 runtime_trust_level: Option<RuntimeTrustLevel>,
275 permission_review_mode: Option<PermissionReviewMode>,
276 permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
277 permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
278 background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
279 skill_catalog: Option<SkillCatalog>,
280 project_rules: Option<ProjectRules>,
281 task_anchor: Option<TaskAnchor>,
282 subagent_manager: Option<SubagentManager>,
283}
284
285impl RuntimeProfile {
286 #[must_use]
288 pub fn builder() -> RuntimeProfileBuilder {
289 RuntimeProfileBuilder::new()
290 }
291
292 #[must_use]
294 pub const fn capabilities(&self) -> &RuntimeCapabilities {
295 &self.capabilities
296 }
297
298 #[must_use]
300 pub const fn model_retry_policy(&self) -> Option<ModelRetryPolicy> {
301 self.model_retry_policy
302 }
303
304 #[must_use]
306 pub const fn prompt_profile(&self) -> &PromptProfile {
307 &self.prompt_profile
308 }
309
310 #[must_use]
312 pub const fn progress_commentary(&self) -> bool {
313 self.progress_commentary
314 }
315
316 #[must_use]
318 pub fn initial_context_summaries(&self) -> &BTreeMap<String, String> {
319 &self.initial_context_summaries
320 }
321
322 #[must_use]
324 pub fn registered_tools(&self) -> &[RegisteredTool] {
325 &self.registered_tools
326 }
327
328 #[must_use]
330 pub fn into_registered_tools(self) -> Vec<RegisteredTool> {
331 self.registered_tools
332 }
333
334 #[must_use]
336 pub const fn allow_bridge_tools(&self) -> bool {
337 self.allow_bridge_tools
338 }
339
340 #[must_use]
342 pub const fn allow_low_risk_apply_patches(&self) -> bool {
343 self.allow_low_risk_apply_patches
344 }
345
346 #[must_use]
348 pub fn low_risk_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
349 self.low_risk_process_runner.as_ref().map(Arc::clone)
350 }
351
352 #[must_use]
354 pub fn read_only_shell_process_runner(&self) -> Option<Arc<dyn ProcessRunner>> {
355 self.read_only_shell_process_runner.as_ref().map(Arc::clone)
356 }
357
358 #[must_use]
360 pub fn accepted_local_workspace_process_runner(
361 &self,
362 ) -> Option<&AcceptedLocalWorkspaceProcessRunnerProfile> {
363 self.accepted_local_workspace_process_runner.as_ref()
364 }
365
366 #[must_use]
368 pub const fn runtime_trust_level(&self) -> Option<RuntimeTrustLevel> {
369 self.runtime_trust_level
370 }
371
372 #[must_use]
374 pub const fn permission_review_mode(&self) -> Option<PermissionReviewMode> {
375 self.permission_review_mode
376 }
377
378 #[must_use]
380 pub fn permission_admission_source(&self) -> Option<Arc<dyn PermissionAdmissionSource>> {
381 self.permission_admission_source.as_ref().map(Arc::clone)
382 }
383
384 #[must_use]
386 pub fn permissioned_process_runner_factory(
387 &self,
388 ) -> Option<Arc<dyn PermissionedProcessRunnerFactory>> {
389 self.permissioned_process_runner_factory
390 .as_ref()
391 .map(Arc::clone)
392 }
393
394 #[must_use]
396 pub const fn skill_catalog(&self) -> Option<&SkillCatalog> {
397 self.skill_catalog.as_ref()
398 }
399
400 #[must_use]
402 pub const fn project_rules(&self) -> Option<&ProjectRules> {
403 self.project_rules.as_ref()
404 }
405
406 #[must_use]
408 pub const fn task_anchor(&self) -> Option<&TaskAnchor> {
409 self.task_anchor.as_ref()
410 }
411
412 #[must_use]
414 pub const fn subagent_manager(&self) -> Option<&SubagentManager> {
415 self.subagent_manager.as_ref()
416 }
417
418 pub(crate) fn into_parts(self) -> RuntimeProfileParts {
419 RuntimeProfileParts {
420 capabilities: self.capabilities,
421 model_retry_policy: self.model_retry_policy,
422 prompt_profile: self.prompt_profile,
423 progress_commentary: self.progress_commentary,
424 initial_context_summaries: self.initial_context_summaries,
425 registered_tools: self.registered_tools,
426 allow_bridge_tools: self.allow_bridge_tools,
427 allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
428 low_risk_process_runner: self.low_risk_process_runner,
429 read_only_shell_process_runner: self.read_only_shell_process_runner,
430 accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
431 runtime_trust_level: self.runtime_trust_level,
432 permission_review_mode: self.permission_review_mode,
433 permission_admission_source: self.permission_admission_source,
434 permissioned_process_runner_factory: self.permissioned_process_runner_factory,
435 background_process_control: self.background_process_control,
436 skill_catalog: self.skill_catalog,
437 project_rules: self.project_rules,
438 task_anchor: self.task_anchor,
439 subagent_manager: self.subagent_manager,
440 }
441 }
442}
443
444pub(crate) struct RuntimeProfileParts {
445 pub(crate) capabilities: RuntimeCapabilities,
446 pub(crate) model_retry_policy: Option<ModelRetryPolicy>,
447 pub(crate) prompt_profile: PromptProfile,
448 pub(crate) progress_commentary: bool,
449 pub(crate) initial_context_summaries: BTreeMap<String, String>,
450 pub(crate) registered_tools: Vec<RegisteredTool>,
451 pub(crate) allow_bridge_tools: bool,
452 pub(crate) allow_low_risk_apply_patches: bool,
453 pub(crate) low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
454 pub(crate) read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
455 pub(crate) accepted_local_workspace_process_runner:
456 Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
457 pub(crate) runtime_trust_level: Option<RuntimeTrustLevel>,
458 pub(crate) permission_review_mode: Option<PermissionReviewMode>,
459 pub(crate) permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
460 pub(crate) permissioned_process_runner_factory:
461 Option<Arc<dyn PermissionedProcessRunnerFactory>>,
462 pub(crate) background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
463 pub(crate) skill_catalog: Option<SkillCatalog>,
464 pub(crate) project_rules: Option<ProjectRules>,
465 pub(crate) task_anchor: Option<TaskAnchor>,
466 pub(crate) subagent_manager: Option<SubagentManager>,
467}
468
469pub struct RuntimeProfileBuilder {
471 capabilities: RuntimeCapabilities,
472 model_retry_policy: Option<ModelRetryPolicy>,
473 prompt_profile: PromptProfile,
474 progress_commentary: bool,
475 initial_context_summaries: BTreeMap<String, String>,
476 registered_tools: Vec<RegisteredTool>,
477 allow_bridge_tools: bool,
478 allow_low_risk_apply_patches: bool,
479 low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
480 read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
481 accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunnerProfile>,
482 runtime_trust_level: Option<RuntimeTrustLevel>,
483 permission_review_mode: Option<PermissionReviewMode>,
484 permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
485 permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
486 background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
487 skill_catalog: Option<SkillCatalog>,
488 project_rules: Option<ProjectRules>,
489 task_anchor: Option<TaskAnchor>,
490 subagent_manager: Option<SubagentManager>,
491}
492
493impl RuntimeProfileBuilder {
494 #[must_use]
496 pub fn new() -> Self {
497 Self {
498 capabilities: RuntimeCapabilities::default(),
499 model_retry_policy: None,
500 prompt_profile: PromptProfile::default(),
501 progress_commentary: false,
502 initial_context_summaries: BTreeMap::new(),
503 registered_tools: Vec::new(),
504 allow_bridge_tools: false,
505 allow_low_risk_apply_patches: false,
506 low_risk_process_runner: None,
507 read_only_shell_process_runner: None,
508 accepted_local_workspace_process_runner: None,
509 runtime_trust_level: None,
510 permission_review_mode: None,
511 permission_admission_source: None,
512 permissioned_process_runner_factory: None,
513 background_process_control: None,
514 skill_catalog: None,
515 project_rules: None,
516 task_anchor: None,
517 subagent_manager: None,
518 }
519 }
520
521 #[must_use]
523 pub fn capabilities(mut self, capabilities: RuntimeCapabilities) -> Self {
524 self.capabilities = capabilities;
525 self
526 }
527
528 #[must_use]
530 pub fn model_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
531 self.model_retry_policy = Some(policy);
532 self
533 }
534
535 #[must_use]
537 pub fn prompt_profile(mut self, profile: PromptProfile) -> Self {
538 self.prompt_profile = profile;
539 self
540 }
541
542 #[must_use]
548 pub fn progress_commentary(mut self, enabled: bool) -> Self {
549 self.progress_commentary = enabled;
550 self
551 }
552
553 #[must_use]
555 pub fn initial_context_summary(mut self, id: &str, text: &str) -> Self {
556 self.initial_context_summaries
557 .insert(id.to_owned(), text.to_owned());
558 self
559 }
560
561 #[must_use]
563 pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
564 self.registered_tools.push(tool);
565 self
566 }
567
568 #[must_use]
570 pub fn allow_bridge_tools(mut self) -> Self {
571 self.allow_bridge_tools = true;
572 self
573 }
574
575 #[must_use]
577 pub fn allow_low_risk_apply_patches(mut self) -> Self {
578 self.allow_low_risk_apply_patches = true;
579 self
580 }
581
582 #[must_use]
584 pub fn allow_low_risk_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
585 self.low_risk_process_runner = Some(runner);
586 self
587 }
588
589 #[must_use]
591 pub fn allow_read_only_shell_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
592 self.read_only_shell_process_runner = Some(runner);
593 self
594 }
595
596 #[must_use]
598 pub fn allow_accepted_local_workspace_process_actions(
599 mut self,
600 admission: AcceptedLocalWorkspaceProcessAdmission,
601 runner: Arc<dyn ProcessRunner>,
602 ) -> Self {
603 self.accepted_local_workspace_process_runner = Some(
604 AcceptedLocalWorkspaceProcessRunnerProfile::new(admission, runner),
605 );
606 self
607 }
608
609 #[must_use]
611 pub fn runtime_trust_level(mut self, trust_level: RuntimeTrustLevel) -> Self {
612 self.runtime_trust_level = Some(trust_level);
613 self
614 }
615
616 #[must_use]
618 pub fn permission_review_mode(mut self, mode: PermissionReviewMode) -> Self {
619 self.permission_review_mode = Some(mode);
620 self
621 }
622
623 #[must_use]
625 pub fn permission_admission_source(
626 mut self,
627 source: Arc<dyn PermissionAdmissionSource>,
628 ) -> Self {
629 self.permission_admission_source = Some(source);
630 self
631 }
632
633 #[must_use]
635 pub fn background_process_control(
636 mut self,
637 control: Arc<dyn BackgroundProcessControl>,
638 ) -> Self {
639 self.background_process_control = Some(control);
640 self
641 }
642
643 #[must_use]
645 pub fn permissioned_process_runner_factory(
646 mut self,
647 factory: Arc<dyn PermissionedProcessRunnerFactory>,
648 ) -> Self {
649 self.permissioned_process_runner_factory = Some(factory);
650 self
651 }
652
653 #[must_use]
655 pub fn skill_catalog(mut self, catalog: SkillCatalog) -> Self {
656 self.skill_catalog = Some(catalog);
657 self
658 }
659
660 #[must_use]
662 pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
663 self.project_rules = Some(project_rules);
664 self
665 }
666
667 #[must_use]
669 pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
670 self.task_anchor = Some(task_anchor);
671 self
672 }
673
674 #[must_use]
676 pub fn subagent_manager(mut self, manager: SubagentManager) -> Self {
677 self.subagent_manager = Some(manager);
678 self
679 }
680
681 pub fn build(self) -> Result<RuntimeProfile, RuntimeProfileError> {
683 let mut names = BTreeSet::new();
684 for tool in &self.registered_tools {
685 let name = tool.spec().name().clone();
686 if name.as_str() == crate::FINAL_OUTPUT_TOOL_NAME {
687 return Err(RuntimeProfileError::ReservedToolName { name });
688 }
689 if !names.insert(name.clone()) {
690 return Err(RuntimeProfileError::DuplicateToolRegistration { name });
691 }
692 }
693
694 Ok(RuntimeProfile {
695 capabilities: self.capabilities,
696 model_retry_policy: self.model_retry_policy,
697 prompt_profile: self.prompt_profile,
698 progress_commentary: self.progress_commentary,
699 initial_context_summaries: self.initial_context_summaries,
700 registered_tools: self.registered_tools,
701 allow_bridge_tools: self.allow_bridge_tools,
702 allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
703 low_risk_process_runner: self.low_risk_process_runner,
704 read_only_shell_process_runner: self.read_only_shell_process_runner,
705 accepted_local_workspace_process_runner: self.accepted_local_workspace_process_runner,
706 runtime_trust_level: self.runtime_trust_level,
707 permission_review_mode: self.permission_review_mode,
708 permission_admission_source: self.permission_admission_source,
709 permissioned_process_runner_factory: self.permissioned_process_runner_factory,
710 background_process_control: self.background_process_control,
711 skill_catalog: self.skill_catalog,
712 project_rules: self.project_rules,
713 task_anchor: self.task_anchor,
714 subagent_manager: self.subagent_manager,
715 })
716 }
717}
718
719impl Default for RuntimeProfileBuilder {
720 fn default() -> Self {
721 Self::new()
722 }
723}
724
725#[cfg(test)]
726mod tests {
727 use super::{PathAccess, PathAccessRule, PathAccessRuleSource, RuntimeCapabilities};
728 use std::path::Path;
729
730 #[test]
731 fn runtime_capabilities_control_network_without_tool_network_field() {
732 let capabilities = RuntimeCapabilities::default().allow_network();
733
734 assert!(capabilities.network_allowed());
735 }
736
737 #[test]
738 fn runtime_capabilities_deny_network_by_default() {
739 let capabilities = RuntimeCapabilities::default();
740
741 assert!(!capabilities.network_allowed());
742 }
743
744 #[test]
745 fn runtime_capabilities_carry_platform_neutral_path_rules() {
746 let rule = PathAccessRule::new(
747 "/var/log/foo",
748 PathAccess::ReadOnly,
749 PathAccessRuleSource::TrustedGlobalConfig,
750 );
751 let capabilities = RuntimeCapabilities::default().with_path_rule(rule);
752
753 assert_eq!(capabilities.path_rules().len(), 1);
754 assert_eq!(
755 capabilities.path_rules()[0].path(),
756 Path::new("/var/log/foo")
757 );
758 assert_eq!(capabilities.path_rules()[0].access(), PathAccess::ReadOnly);
759 assert_eq!(
760 capabilities.path_rules()[0].source(),
761 PathAccessRuleSource::TrustedGlobalConfig
762 );
763 }
764
765 #[test]
766 fn path_access_has_stable_config_spelling() {
767 assert_eq!(PathAccess::ReadOnly.as_str(), "ro");
768 assert_eq!(PathAccess::ReadWrite.as_str(), "rw");
769 assert_eq!(PathAccess::Deny.as_str(), "deny");
770 }
771
772 #[test]
773 fn path_access_coverage_keeps_read_only_and_read_write_distinct() {
774 assert!(PathAccess::ReadWrite.covers(PathAccess::ReadOnly));
775 assert!(PathAccess::ReadWrite.covers(PathAccess::ReadWrite));
776 assert!(PathAccess::ReadOnly.covers(PathAccess::ReadOnly));
777 assert!(!PathAccess::ReadOnly.covers(PathAccess::ReadWrite));
778 assert!(!PathAccess::Deny.covers(PathAccess::ReadOnly));
779 assert!(!PathAccess::Deny.covers(PathAccess::ReadWrite));
780 }
781}