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, 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/// 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    reasoning_effort: Option<ReasoningEffort>,
42}
43
44impl CodingModelRoleConfig {
45    /// Creates a role-specific model configuration.
46    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    /// Sets an optional reasoning-effort override for this runtime model role.
63    #[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    /// Returns the runtime role receiving this provider/model pair.
70    #[must_use]
71    pub const fn role(&self) -> RuntimeModelRole {
72        self.role
73    }
74
75    /// Returns the provider handle for this role.
76    #[must_use]
77    pub fn provider(&self) -> Arc<dyn ModelProvider> {
78        Arc::clone(&self.provider)
79    }
80
81    /// Returns the model name for this role.
82    #[must_use]
83    pub fn model(&self) -> &ModelName {
84        &self.model
85    }
86
87    /// Returns the optional reasoning-effort override for this role.
88    #[must_use]
89    pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
90        self.reasoning_effort.as_ref()
91    }
92}
93
94/// Error returned when a secondary coding role is constructed with the
95/// primary role identifier.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
97pub enum CodingModelRoleConfigError {
98    /// The primary provider/model belongs to [`CodingRuntimeInput::new`].
99    #[error("primary model must be configured as the coding runtime's primary provider")]
100    PrimaryRole,
101}
102
103/// Parent/child policy that must be applied to every coding runtime builder.
104///
105/// The policy contains only validated provider-neutral inputs. Runtime owns the
106/// meaning of model roles and permission admission; this type only forwards the
107/// same values to the parent and child builders.
108#[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/// Typed subagent composition policy for a parent coding runtime.
168#[derive(Clone, Default)]
169pub struct CodingSubagentsConfig {
170    installed: bool,
171    enabled: bool,
172    limits: SubagentConfig,
173    role_catalog: SubagentRoleCatalog,
174}
175
176impl CodingSubagentsConfig {
177    /// Installs and enables subagent tools with the supplied runtime limits.
178    #[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    /// Installs subagent tools while leaving their runtime admission controlled
189    /// by `enabled`.
190    #[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    /// Attaches a customized role catalog (built-in + `.merry/roles/*.toml` +
201    /// `[subagents.roles.*]` + `[subagents.default]` + `[subagents.toggle]`).
202    #[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    /// Returns whether the parent should advertise subagent tools.
209    #[must_use]
210    pub const fn is_installed(&self) -> bool {
211        self.installed
212    }
213
214    /// Returns whether new subagent work is enabled by the parent policy.
215    #[must_use]
216    pub const fn is_enabled(&self) -> bool {
217        self.enabled
218    }
219
220    /// Returns the runtime-owned subagent limits.
221    #[must_use]
222    pub const fn limits(&self) -> SubagentConfig {
223        self.limits
224    }
225
226    /// Returns the configured role catalog.
227    #[must_use]
228    pub fn role_catalog(&self) -> &SubagentRoleCatalog {
229        &self.role_catalog
230    }
231}
232
233/// Typed parent coding-runtime inputs shared by full and read-only variants.
234///
235/// The full constructor requires a [`ProcessBackend`]. The read-only
236/// constructor intentionally has no process backend, making it impossible for
237/// the command-generation variant to install a process session by accident.
238#[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    /// When false, the workspace is read-only: `AGENTS.md` stays unloaded and
255    /// `apply_patch` cannot write.
256    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    /// Creates full coding-runtime inputs with a typed process backend.
265    #[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    /// Sets whether the workspace is writable (`false` keeps it read-only and
297    /// skips `AGENTS.md`).
298    #[must_use]
299    pub fn read_only_workspace(mut self) -> Self {
300        self.workspace_writable = false;
301        self
302    }
303
304    /// Returns the session identifier owned by this input.
305    #[must_use]
306    pub fn session_id(&self) -> &SessionId {
307        &self.session_id
308    }
309
310    /// Returns the workspace root directory owned by this input.
311    #[must_use]
312    pub fn root(&self) -> &std::path::Path {
313        &self.root
314    }
315
316    /// Creates read-only command-generation inputs without a process backend.
317    #[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    /// Attaches durable memory for this runtime and the children it spawns.
348    ///
349    /// The parent maintains memory after completed user turns. Children see the
350    /// same store with maintenance disabled.
351    #[must_use]
352    pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
353        self.durable_memory = Some(memory);
354        self
355    }
356
357    /// Adds provider-neutral tools owned by the calling surface or adapter.
358    #[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    /// Sets automatic context compaction policy.
368    #[must_use]
369    pub fn with_automatic_compaction(mut self, config: CompactionConfig) -> Self {
370        self.automatic_compaction = config;
371        self
372    }
373
374    /// Sets how compacted history is retained in memory and on disk.
375    #[must_use]
376    pub fn with_history_retention(mut self, retention: HistoryRetention) -> Self {
377        self.history_retention = retention;
378        self
379    }
380
381    /// Sets the model retry/recovery policy shared by parent and child runtimes.
382    #[must_use]
383    pub fn with_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
384        self.retry_policy = Some(policy);
385        self
386    }
387
388    /// Adds one non-primary runtime model role.
389    #[must_use]
390    pub fn with_model_role(mut self, role: CodingModelRoleConfig) -> Self {
391        self.model_roles.push(role);
392        self
393    }
394
395    /// Adds model roles in the supplied deterministic order.
396    #[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    /// Sets the read-only skill/resource roots.
406    #[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    /// Sets the shared host path policy so in-process file tools enforce the
417    /// exact same private-path and read-only session-journal boundaries as the
418    /// process sandbox, inherited by parent and child runtimes.
419    #[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    /// Sets the parent subagent policy.
426    #[must_use]
427    pub fn with_subagents(mut self, subagents: CodingSubagentsConfig) -> Self {
428        self.subagents = subagents;
429        self
430    }
431
432    /// Sets the workspace tool limits for the coding profile.
433    #[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    /// Sets user-trusted custom rules for AI permission review, inherited by
440    /// both parent and child coding runtimes.
441    #[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    /// Sets the maximum number of parallel-safe tool calls executed together in
448    /// one model turn for both parent and child runtimes.
449    #[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    /// Sets an explicit context-window override in tokens for budget and
456    /// automatic compaction calculations.
457    #[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/// Internal parent coding-runtime variant selected by the surface.
465#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466enum CodingRuntimeVariant {
467    /// Full coding runtime with process, patch, plan, and optional subagent lanes.
468    FullCoding,
469    /// Read-only workspace runtime for command generation.
470    ReadOnlyCommandGeneration,
471}
472
473/// Builder for parent coding runtime composition.
474pub 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    /// Creates a full coding-runtime builder.
484    #[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    /// Creates the explicit read-only command-generation variant.
496    ///
497    /// Full-only inputs such as a process backend and subagent configuration
498    /// are intentionally ignored by this variant. The read-only profile is
499    /// selected by construction so those capabilities cannot be advertised or
500    /// admitted accidentally.
501    #[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    /// Sets the complete permission policy shared by parent and child runtimes.
513    #[must_use]
514    pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
515        self.permission = policy;
516        self
517    }
518
519    /// Installs an already loaded session without performing another store read.
520    #[must_use]
521    pub fn with_loaded_session(mut self, loaded: LoadedSession) -> Self {
522        self.loaded_session = Some(loaded);
523        self
524    }
525
526    /// Configures automatic incremental session persistence into `store`.
527    #[must_use]
528    pub fn session_store(mut self, store: FileSessionStore) -> Self {
529        self.session_store = Some(store);
530        self
531    }
532
533    /// Builds a new parent runtime and its stable coding loop policy.
534    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    /// Resumes a parent runtime without automatic savepoints.
548    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
741/// A built parent coding runtime and the policy that governs its loop.
742pub struct CodingRuntime {
743    runtime: Runtime,
744    profile: CodingAgentProfile,
745    loop_config: AgentLoopConfig,
746}
747
748impl CodingRuntime {
749    /// Borrows the runtime state handle owned by this composition result.
750    #[must_use]
751    pub fn runtime(&self) -> &Runtime {
752        &self.runtime
753    }
754
755    /// Consumes the composition result and returns its runtime handle.
756    #[must_use]
757    pub fn into_runtime(self) -> Runtime {
758        self.runtime
759    }
760
761    /// Borrows the shared coding profile used by this runtime.
762    #[must_use]
763    pub fn profile(&self) -> &CodingAgentProfile {
764        &self.profile
765    }
766
767    /// Clones the loop configuration derived from the shared coding profile.
768    #[must_use]
769    pub fn loop_config(&self) -> AgentLoopConfig {
770        self.loop_config.clone()
771    }
772}
773
774/// Errors raised while composing a parent coding runtime.
775#[derive(Debug, Error)]
776pub enum CodingRuntimeBuildError {
777    /// A full coding runtime was requested without its process backend.
778    #[error("full coding runtime requires a process backend")]
779    MissingProcessBackend,
780    /// A role was configured more than once.
781    #[error("coding model role {role:?} was configured more than once")]
782    DuplicateModelRole { role: RuntimeModelRole },
783    /// A provider-neutral protocol value failed validation.
784    #[error(transparent)]
785    Core(#[from] CoreError),
786    /// Project rules could not be loaded safely.
787    #[error(transparent)]
788    ProjectRules(#[from] ProjectRulesLoadError),
789    /// The skill catalog could not be loaded.
790    #[error(transparent)]
791    SkillCatalog(#[from] SkillError),
792    /// The coding profile was invalid.
793    #[error(transparent)]
794    CodingProfile(#[from] CodingAgentProfileBuildError),
795    /// The profile's coding loop policy was invalid.
796    #[error(transparent)]
797    LoopConfig(#[from] AgentLoopConfigError),
798    /// The coding profile's child-agent model-turn bounds were invalid.
799    #[error(transparent)]
800    SubagentConfig(#[from] SubagentError),
801    /// Applying the profile to the runtime builder failed.
802    #[error("failed to apply coding profile to runtime builder: {source}")]
803    RuntimeProfileApply { source: RuntimeError },
804    /// Runtime construction or resume failed.
805    #[error("failed to build coding runtime: {source}")]
806    RuntimeBuild { source: RuntimeError },
807}