Skip to main content

merry_coding/
runtime.rs

1//! Parent coding-runtime composition.
2//!
3//! This module owns the typed assembly boundary between a coding surface and
4//! the provider-neutral runtime. It constructs runtime state through
5//! [`merry_runtime::RuntimeBuilder`], but it does not own that state after the
6//! builder returns a [`CodingRuntime`].
7
8use 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, SessionId};
15use merry_llm::{ModelName, ModelProvider, ModelRetryPolicy};
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/// A provider-neutral model/provider pair for one non-primary runtime role.
33///
34/// Provider adapters are represented by the Merry-owned [`ModelProvider`] trait;
35/// provider wire request and response types never cross this contract.
36#[derive(Clone)]
37pub struct CodingModelRoleConfig {
38    role: RuntimeModelRole,
39    provider: Arc<dyn ModelProvider>,
40    model: ModelName,
41}
42
43impl CodingModelRoleConfig {
44    /// Creates a role-specific model configuration.
45    pub fn new(
46        role: RuntimeModelRole,
47        provider: Arc<dyn ModelProvider>,
48        model: ModelName,
49    ) -> Result<Self, CodingModelRoleConfigError> {
50        if role == RuntimeModelRole::Primary {
51            return Err(CodingModelRoleConfigError::PrimaryRole);
52        }
53        Ok(Self {
54            role,
55            provider,
56            model,
57        })
58    }
59
60    /// Returns the runtime role receiving this provider/model pair.
61    #[must_use]
62    pub const fn role(&self) -> RuntimeModelRole {
63        self.role
64    }
65
66    /// Returns the provider handle for this role.
67    #[must_use]
68    pub fn provider(&self) -> Arc<dyn ModelProvider> {
69        Arc::clone(&self.provider)
70    }
71
72    /// Returns the model name for this role.
73    #[must_use]
74    pub fn model(&self) -> &ModelName {
75        &self.model
76    }
77}
78
79/// Error returned when a secondary coding role is constructed with the
80/// primary role identifier.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
82pub enum CodingModelRoleConfigError {
83    /// The primary provider/model belongs to [`CodingRuntimeInput::new`].
84    #[error("primary model must be configured as the coding runtime's primary provider")]
85    PrimaryRole,
86}
87
88/// Parent/child policy that must be applied to every coding runtime builder.
89///
90/// The policy contains only validated provider-neutral inputs. Runtime owns the
91/// meaning of model roles and permission admission; this type only forwards the
92/// same values to the parent and child builders.
93#[derive(Clone, Default)]
94pub(crate) struct CodingRuntimePolicy {
95    model_roles: Vec<CodingModelRoleConfig>,
96    permission: CodingPermissionPolicy,
97    permission_review_rules: PermissionReviewRules,
98    permission_review_workspace_root: Option<PathBuf>,
99}
100
101impl CodingRuntimePolicy {
102    pub(crate) fn try_new(
103        model_roles: Vec<CodingModelRoleConfig>,
104        permission: CodingPermissionPolicy,
105    ) -> Result<Self, CodingRuntimeBuildError> {
106        let mut configured_roles = BTreeSet::new();
107        for role in &model_roles {
108            if !configured_roles.insert(role.role()) {
109                return Err(CodingRuntimeBuildError::DuplicateModelRole { role: role.role() });
110            }
111        }
112        Ok(Self {
113            model_roles,
114            permission,
115            permission_review_rules: PermissionReviewRules::default(),
116            permission_review_workspace_root: None,
117        })
118    }
119
120    pub(crate) fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
121        self.permission_review_rules = rules;
122        self
123    }
124
125    pub(crate) fn with_permission_review_workspace_root(
126        mut self,
127        root: impl Into<PathBuf>,
128    ) -> Self {
129        self.permission_review_workspace_root = Some(root.into());
130        self
131    }
132
133    pub(crate) fn apply_to(&self, mut builder: RuntimeBuilder) -> RuntimeBuilder {
134        for role in &self.model_roles {
135            builder =
136                builder.model_provider_for_role(role.role(), role.provider(), role.model().clone());
137        }
138        if !self.permission_review_rules.is_empty() {
139            builder = builder.permission_review_rules(self.permission_review_rules.clone());
140        }
141        if let Some(root) = &self.permission_review_workspace_root {
142            builder = builder.permission_review_workspace_root(root.clone());
143        }
144        self.permission.apply_to(builder)
145    }
146}
147
148/// Typed subagent composition policy for a parent coding runtime.
149#[derive(Clone, Default)]
150pub struct CodingSubagentsConfig {
151    installed: bool,
152    enabled: bool,
153    limits: SubagentConfig,
154    role_catalog: SubagentRoleCatalog,
155}
156
157impl CodingSubagentsConfig {
158    /// Installs and enables subagent tools with the supplied runtime limits.
159    #[must_use]
160    pub fn enabled(limits: SubagentConfig) -> Self {
161        Self {
162            installed: true,
163            enabled: true,
164            limits,
165            role_catalog: SubagentRoleCatalog::builtin(),
166        }
167    }
168
169    /// Installs subagent tools while leaving their runtime admission controlled
170    /// by `enabled`.
171    #[must_use]
172    pub fn runtime_controlled(enabled: bool, limits: SubagentConfig) -> Self {
173        Self {
174            installed: true,
175            enabled,
176            limits,
177            role_catalog: SubagentRoleCatalog::builtin(),
178        }
179    }
180
181    /// Attaches a customized role catalog (built-in + `.merry/roles/*.toml` +
182    /// `[subagents.roles.*]` + `[subagents.default]` + `[subagents.toggle]`).
183    #[must_use]
184    pub fn with_role_catalog(mut self, role_catalog: SubagentRoleCatalog) -> Self {
185        self.role_catalog = role_catalog;
186        self
187    }
188
189    /// Returns whether the parent should advertise subagent tools.
190    #[must_use]
191    pub const fn is_installed(&self) -> bool {
192        self.installed
193    }
194
195    /// Returns whether new subagent work is enabled by the parent policy.
196    #[must_use]
197    pub const fn is_enabled(&self) -> bool {
198        self.enabled
199    }
200
201    /// Returns the runtime-owned subagent limits.
202    #[must_use]
203    pub const fn limits(&self) -> SubagentConfig {
204        self.limits
205    }
206
207    /// Returns the configured role catalog.
208    #[must_use]
209    pub fn role_catalog(&self) -> &SubagentRoleCatalog {
210        &self.role_catalog
211    }
212}
213
214/// Typed parent coding-runtime inputs shared by full and read-only variants.
215///
216/// The full constructor requires a [`ProcessBackend`]. The read-only
217/// constructor intentionally has no process backend, making it impossible for
218/// the command-generation variant to install a process session by accident.
219#[derive(Clone)]
220pub struct CodingRuntimeInput {
221    session_id: SessionId,
222    root: PathBuf,
223    provider: Arc<dyn ModelProvider>,
224    model: ModelName,
225    process_backend: Option<Arc<dyn ProcessBackend>>,
226    extra_tools: Vec<RegisteredTool>,
227    automatic_compaction: CompactionConfig,
228    history_retention: HistoryRetention,
229    retry_policy: Option<ModelRetryPolicy>,
230    model_roles: Vec<CodingModelRoleConfig>,
231    skill_roots: Vec<PathBuf>,
232    denied_absolute_paths: Vec<PathBuf>,
233    subagents: CodingSubagentsConfig,
234    workspace_tool_limits: WorkspaceToolLimits,
235    /// When false, the workspace is read-only: `AGENTS.md` stays unloaded and
236    /// `apply_patch` cannot write.
237    workspace_writable: bool,
238    durable_memory: Option<Arc<DurableMemory>>,
239    permission_review_rules: PermissionReviewRules,
240    max_parallel_tool_calls: Option<std::num::NonZeroUsize>,
241}
242
243impl CodingRuntimeInput {
244    /// Creates full coding-runtime inputs with a typed process backend.
245    #[must_use]
246    pub fn new(
247        session_id: SessionId,
248        root: impl Into<PathBuf>,
249        provider: Arc<dyn ModelProvider>,
250        model: ModelName,
251        process_backend: Arc<dyn ProcessBackend>,
252    ) -> Self {
253        Self {
254            session_id,
255            root: root.into(),
256            provider,
257            model,
258            process_backend: Some(process_backend),
259            extra_tools: Vec::new(),
260            automatic_compaction: CompactionConfig::default(),
261            history_retention: HistoryRetention::default(),
262            retry_policy: None,
263            model_roles: Vec::new(),
264            skill_roots: Vec::new(),
265            denied_absolute_paths: Vec::new(),
266            subagents: CodingSubagentsConfig::default(),
267            workspace_tool_limits: WorkspaceToolLimits::default(),
268            workspace_writable: true,
269            durable_memory: None,
270            permission_review_rules: PermissionReviewRules::default(),
271            max_parallel_tool_calls: None,
272        }
273    }
274
275    /// Keeps the workspace read-only and does not load `AGENTS.md`.
276    ///
277    /// Used when the person declined read-write access on first open. The
278    /// sandbox stays in place; this does not switch to host execution.
279    #[must_use]
280    pub fn read_only_workspace(mut self) -> Self {
281        self.workspace_writable = false;
282        self
283    }
284
285    /// Creates read-only command-generation inputs without a process backend.
286    #[must_use]
287    pub fn read_only(
288        session_id: SessionId,
289        root: impl Into<PathBuf>,
290        provider: Arc<dyn ModelProvider>,
291        model: ModelName,
292    ) -> Self {
293        Self {
294            session_id,
295            root: root.into(),
296            provider,
297            model,
298            process_backend: None,
299            extra_tools: Vec::new(),
300            automatic_compaction: CompactionConfig::default(),
301            history_retention: HistoryRetention::default(),
302            retry_policy: None,
303            model_roles: Vec::new(),
304            skill_roots: Vec::new(),
305            denied_absolute_paths: Vec::new(),
306            subagents: CodingSubagentsConfig::default(),
307            workspace_tool_limits: WorkspaceToolLimits::default(),
308            workspace_writable: true,
309            durable_memory: None,
310            permission_review_rules: PermissionReviewRules::default(),
311            max_parallel_tool_calls: None,
312        }
313    }
314
315    /// Attaches durable memory for this runtime and the children it spawns.
316    ///
317    /// The parent maintains memory after completed user turns. Children see the
318    /// same store with maintenance disabled.
319    #[must_use]
320    pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
321        self.durable_memory = Some(memory);
322        self
323    }
324
325    /// Adds provider-neutral tools owned by the calling surface or adapter.
326    #[must_use]
327    pub fn with_extra_tools<I>(mut self, tools: I) -> Self
328    where
329        I: IntoIterator<Item = RegisteredTool>,
330    {
331        self.extra_tools.extend(tools);
332        self
333    }
334
335    /// Sets automatic context compaction policy.
336    #[must_use]
337    pub fn with_automatic_compaction(mut self, config: CompactionConfig) -> Self {
338        self.automatic_compaction = config;
339        self
340    }
341
342    /// Sets how compacted history is retained in memory and on disk.
343    #[must_use]
344    pub fn with_history_retention(mut self, retention: HistoryRetention) -> Self {
345        self.history_retention = retention;
346        self
347    }
348
349    /// Sets the model retry/recovery policy shared by parent and child runtimes.
350    #[must_use]
351    pub fn with_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
352        self.retry_policy = Some(policy);
353        self
354    }
355
356    /// Adds one non-primary runtime model role.
357    #[must_use]
358    pub fn with_model_role(mut self, role: CodingModelRoleConfig) -> Self {
359        self.model_roles.push(role);
360        self
361    }
362
363    /// Adds model roles in the supplied deterministic order.
364    #[must_use]
365    pub fn with_model_roles<I>(mut self, roles: I) -> Self
366    where
367        I: IntoIterator<Item = CodingModelRoleConfig>,
368    {
369        self.model_roles.extend(roles);
370        self
371    }
372
373    /// Sets the read-only skill/resource roots.
374    #[must_use]
375    pub fn with_skill_roots<I, P>(mut self, roots: I) -> Self
376    where
377        I: IntoIterator<Item = P>,
378        P: Into<PathBuf>,
379    {
380        self.skill_roots = roots.into_iter().map(Into::into).collect();
381        self
382    }
383
384    /// Sets absolute host paths that in-process file tools (`read_file` and
385    /// `apply_patch`) must never read or modify, inherited by parent and child
386    /// runtimes.
387    #[must_use]
388    pub fn with_denied_absolute_paths<I, P>(mut self, paths: I) -> Self
389    where
390        I: IntoIterator<Item = P>,
391        P: Into<PathBuf>,
392    {
393        self.denied_absolute_paths = paths.into_iter().map(Into::into).collect();
394        self
395    }
396
397    /// Sets the parent subagent policy.
398    #[must_use]
399    pub fn with_subagents(mut self, subagents: CodingSubagentsConfig) -> Self {
400        self.subagents = subagents;
401        self
402    }
403
404    /// Sets the workspace tool limits for the coding profile.
405    #[must_use]
406    pub fn with_workspace_tool_limits(mut self, limits: WorkspaceToolLimits) -> Self {
407        self.workspace_tool_limits = limits;
408        self
409    }
410
411    /// Sets user-trusted custom rules for AI permission review, inherited by
412    /// both parent and child coding runtimes.
413    #[must_use]
414    pub fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
415        self.permission_review_rules = rules;
416        self
417    }
418
419    /// Sets the maximum number of parallel-safe tool calls executed together in
420    /// one model turn for both parent and child runtimes.
421    #[must_use]
422    pub fn with_max_parallel_tool_calls(mut self, limit: std::num::NonZeroUsize) -> Self {
423        self.max_parallel_tool_calls = Some(limit);
424        self
425    }
426}
427
428/// Internal parent coding-runtime variant selected by the surface.
429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
430enum CodingRuntimeVariant {
431    /// Full coding runtime with process, patch, plan, and optional subagent lanes.
432    FullCoding,
433    /// Read-only workspace runtime for command generation.
434    ReadOnlyCommandGeneration,
435}
436
437/// Builder for parent coding runtime composition.
438pub struct CodingRuntimeBuilder {
439    input: CodingRuntimeInput,
440    variant: CodingRuntimeVariant,
441    permission: CodingPermissionPolicy,
442    loaded_session: Option<LoadedSession>,
443    session_store: Option<FileSessionStore>,
444}
445
446impl CodingRuntimeBuilder {
447    /// Creates a full coding-runtime builder.
448    #[must_use]
449    pub fn new(input: CodingRuntimeInput) -> Self {
450        Self {
451            input,
452            variant: CodingRuntimeVariant::FullCoding,
453            permission: CodingPermissionPolicy::default(),
454            loaded_session: None,
455            session_store: None,
456        }
457    }
458
459    /// Creates the explicit read-only command-generation variant.
460    ///
461    /// Full-only inputs such as a process backend and subagent configuration
462    /// are intentionally ignored by this variant. The read-only profile is
463    /// selected by construction so those capabilities cannot be advertised or
464    /// admitted accidentally.
465    #[must_use]
466    pub fn for_command_generation(input: CodingRuntimeInput) -> Self {
467        Self {
468            input,
469            variant: CodingRuntimeVariant::ReadOnlyCommandGeneration,
470            permission: CodingPermissionPolicy::default(),
471            loaded_session: None,
472            session_store: None,
473        }
474    }
475
476    /// Sets the complete permission policy shared by parent and child runtimes.
477    #[must_use]
478    pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
479        self.permission = policy;
480        self
481    }
482
483    /// Installs an already loaded session without performing another store read.
484    #[must_use]
485    pub fn with_loaded_session(mut self, loaded: LoadedSession) -> Self {
486        self.loaded_session = Some(loaded);
487        self
488    }
489
490    /// Configures automatic incremental session persistence into `store`.
491    #[must_use]
492    pub fn session_store(mut self, store: FileSessionStore) -> Self {
493        self.session_store = Some(store);
494        self
495    }
496
497    /// Builds a new parent runtime and its stable coding loop policy.
498    pub fn build(self) -> Result<CodingRuntime, CodingRuntimeBuildError> {
499        let (builder, profile) = self.compose()?;
500        let loop_config = profile.loop_config()?;
501        let runtime = builder
502            .build()
503            .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
504        Ok(CodingRuntime {
505            runtime,
506            profile,
507            loop_config,
508        })
509    }
510
511    /// Resumes a parent runtime without automatic savepoints.
512    pub async fn resume_from_store_without_automatic_savepoints(
513        self,
514        store: FileSessionStore,
515    ) -> Result<CodingRuntime, CodingRuntimeBuildError> {
516        let (builder, profile) = self.compose()?;
517        let loop_config = profile.loop_config()?;
518        let runtime = builder
519            .resume_from_store_without_automatic_savepoints(store)
520            .await
521            .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
522        Ok(CodingRuntime {
523            runtime,
524            profile,
525            loop_config,
526        })
527    }
528
529    fn compose(
530        self,
531    ) -> Result<(merry_runtime::RuntimeBuilder, CodingAgentProfile), CodingRuntimeBuildError> {
532        let Self {
533            input,
534            variant,
535            permission,
536            loaded_session,
537            session_store,
538        } = self;
539        let CodingRuntimeInput {
540            session_id,
541            root,
542            provider,
543            model,
544            process_backend,
545            extra_tools,
546            automatic_compaction,
547            history_retention,
548            retry_policy,
549            model_roles,
550            skill_roots,
551            denied_absolute_paths,
552            subagents,
553            workspace_tool_limits,
554            workspace_writable,
555            durable_memory,
556            permission_review_rules,
557            max_parallel_tool_calls,
558        } = input;
559
560        let policy = CodingRuntimePolicy::try_new(model_roles, permission)?
561            .with_permission_review_rules(permission_review_rules)
562            .with_permission_review_workspace_root(root.clone());
563
564        let project_rules = if workspace_writable {
565            load_root_project_rules(&root)?
566        } else {
567            None
568        };
569        let skill_catalog = if skill_roots.is_empty() {
570            None
571        } else {
572            Some(SkillCatalog::load_from_roots(skill_roots.clone())?)
573        };
574        if let Some(catalog) = skill_catalog.as_ref() {
575            const MAX_LOGGED_SKILL_NAMES: usize = 64;
576            let skill_names = catalog
577                .skills()
578                .iter()
579                .take(MAX_LOGGED_SKILL_NAMES)
580                .map(|skill| skill.name())
581                .collect::<Vec<_>>();
582            tracing::info!(
583                event = "runtime.skill_catalog.load",
584                session_id = %session_id,
585                configured_root_count = skill_roots.len(),
586                readable_root_count = skill_roots.iter().filter(|root| root.is_dir()).count(),
587                skill_count = catalog.skills().len(),
588                warning_count = catalog.warnings().len(),
589                skill_names = ?skill_names,
590                "runtime skill catalog loaded"
591            );
592        }
593        let mut runtime_builder = Runtime::builder(session_id.clone())
594            .automatic_compaction(automatic_compaction.clone())
595            .history_retention(history_retention)
596            .model_provider(Arc::clone(&provider), model.clone());
597        if let Some(limit) = max_parallel_tool_calls {
598            runtime_builder = runtime_builder.max_parallel_tool_calls(limit);
599        }
600        if matches!(variant, CodingRuntimeVariant::FullCoding) {
601            runtime_builder = runtime_builder.coordinator_plan_tools();
602        }
603
604        let mut profile_builder: CodingAgentProfileBuilder = coding_agent(&root)
605            .readonly_resource_roots(skill_roots.clone())
606            .denied_absolute_paths(denied_absolute_paths)
607            .limits(workspace_tool_limits)
608            .register_tools(extra_tools);
609        if !workspace_writable {
610            profile_builder = profile_builder.read_only_patch_scope();
611        }
612        if let Some(project_rules) = project_rules {
613            profile_builder = profile_builder.project_rules(project_rules);
614        }
615        if let Some(skill_catalog) = skill_catalog {
616            profile_builder = profile_builder.skill_catalog(skill_catalog);
617        }
618        if let Some(policy) = retry_policy {
619            profile_builder = profile_builder.retry_policy(policy);
620        }
621        if let Some(memory) = durable_memory.clone() {
622            profile_builder = profile_builder.durable_memory(memory);
623        }
624
625        let mut profile_tools = Vec::new();
626        if matches!(variant, CodingRuntimeVariant::FullCoding) {
627            let process_backend =
628                process_backend.ok_or(CodingRuntimeBuildError::MissingProcessBackend)?;
629            let process_session = process_backend.new_session();
630            let parent_process_permissions = process_session.permission_view();
631            profile_builder = profile_builder
632                .patch_tool()
633                .web_tools()
634                .accepted_process_session(process_session);
635
636            if subagents.is_installed() {
637                let subagent_config = subagents.limits().with_model_turn_bounds(
638                    MIN_CODING_SUBAGENT_MODEL_TURNS,
639                    subagents.limits().max_model_turns(),
640                )?;
641                tracing::info!(
642                    event = "runtime.subagents.enabled",
643                    session_id = %session_id,
644                    enabled = subagents.is_enabled(),
645                    max_threads = subagent_config.max_threads(),
646                    max_depth = subagent_config.max_depth(),
647                    min_model_turns = subagent_config.min_model_turns(),
648                    max_model_turns = subagent_config.max_model_turns(),
649                    "runtime subagent tools installed"
650                );
651                let role_catalog = subagents.role_catalog().clone();
652                let role_summaries = role_catalog.enabled_role_summaries();
653                let composition = CodingRuntimeComposition {
654                    profile_builder: profile_builder.clone(),
655                    provider: Arc::clone(&provider),
656                    model: model.clone(),
657                    process_backend,
658                    parent_process_permissions,
659                    parent_workspace_writable: workspace_writable,
660                    subagent_config,
661                    role_catalog,
662                    automatic_compaction,
663                    max_parallel_tool_calls,
664                    policy: policy.clone(),
665                    worktree_manager: crate::WorktreeIsolationManager::new(),
666                };
667                let child_factory: Arc<dyn ChildRuntimeFactory> =
668                    Arc::new(CodingChildRuntimeFactory::from_composition(composition));
669                let manager = SubagentManager::runtime_controlled(
670                    session_id.clone(),
671                    subagent_config,
672                    child_factory,
673                    subagents.is_enabled(),
674                );
675                let [spawn_tool, send_tool, wait_tool, cancel_tool] =
676                    subagent_registered_tools_with_roles(manager.clone(), &role_summaries)?;
677                runtime_builder = runtime_builder.subagent_manager(manager);
678                profile_tools.extend([spawn_tool, send_tool, wait_tool, cancel_tool]);
679            }
680        }
681
682        let profile = profile_builder.register_tools(profile_tools).build()?;
683        runtime_builder = profile
684            .apply_to(runtime_builder)
685            .map_err(|source| CodingRuntimeBuildError::RuntimeProfileApply { source })?;
686        runtime_builder = policy.apply_to(runtime_builder);
687        if let Some(memory) = durable_memory {
688            runtime_builder = runtime_builder.durable_memory(memory, true);
689        }
690        if let Some(loaded_session) = loaded_session {
691            runtime_builder = runtime_builder.with_loaded_session(loaded_session);
692        }
693        if let Some(store) = session_store {
694            runtime_builder = runtime_builder.session_store(store);
695        }
696
697        Ok((runtime_builder, profile))
698    }
699}
700
701/// A built parent coding runtime and the policy that governs its loop.
702pub struct CodingRuntime {
703    runtime: Runtime,
704    profile: CodingAgentProfile,
705    loop_config: AgentLoopConfig,
706}
707
708impl CodingRuntime {
709    /// Borrows the runtime state handle owned by this composition result.
710    #[must_use]
711    pub fn runtime(&self) -> &Runtime {
712        &self.runtime
713    }
714
715    /// Consumes the composition result and returns its runtime handle.
716    #[must_use]
717    pub fn into_runtime(self) -> Runtime {
718        self.runtime
719    }
720
721    /// Borrows the shared coding profile used by this runtime.
722    #[must_use]
723    pub fn profile(&self) -> &CodingAgentProfile {
724        &self.profile
725    }
726
727    /// Clones the loop configuration derived from the shared coding profile.
728    #[must_use]
729    pub fn loop_config(&self) -> AgentLoopConfig {
730        self.loop_config.clone()
731    }
732}
733
734/// Errors raised while composing a parent coding runtime.
735#[derive(Debug, Error)]
736pub enum CodingRuntimeBuildError {
737    /// A full coding runtime was requested without its process backend.
738    #[error("full coding runtime requires a process backend")]
739    MissingProcessBackend,
740    /// A role was configured more than once.
741    #[error("coding model role {role:?} was configured more than once")]
742    DuplicateModelRole { role: RuntimeModelRole },
743    /// A provider-neutral protocol value failed validation.
744    #[error(transparent)]
745    Core(#[from] CoreError),
746    /// Project rules could not be loaded safely.
747    #[error(transparent)]
748    ProjectRules(#[from] ProjectRulesLoadError),
749    /// The skill catalog could not be loaded.
750    #[error(transparent)]
751    SkillCatalog(#[from] SkillError),
752    /// The coding profile was invalid.
753    #[error(transparent)]
754    CodingProfile(#[from] CodingAgentProfileBuildError),
755    /// The profile's coding loop policy was invalid.
756    #[error(transparent)]
757    LoopConfig(#[from] AgentLoopConfigError),
758    /// The coding profile's child-agent model-turn bounds were invalid.
759    #[error(transparent)]
760    SubagentConfig(#[from] SubagentError),
761    /// Applying the profile to the runtime builder failed.
762    #[error("failed to apply coding profile to runtime builder: {source}")]
763    RuntimeProfileApply { source: RuntimeError },
764    /// Runtime construction or resume failed.
765    #[error("failed to build coding runtime: {source}")]
766    RuntimeBuild { source: RuntimeError },
767}