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::{BrowserProcessLauncher, 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_guidance: merry_runtime::SessionReviewGuidance,
114    workspace_review_notes: merry_runtime::WorkspaceReviewNotes,
115    permission_review_workspace_root: Option<PathBuf>,
116}
117
118impl CodingRuntimePolicy {
119    pub(crate) fn try_new(
120        model_roles: Vec<CodingModelRoleConfig>,
121        permission: CodingPermissionPolicy,
122    ) -> Result<Self, CodingRuntimeBuildError> {
123        let mut configured_roles = BTreeSet::new();
124        for role in &model_roles {
125            if !configured_roles.insert(role.role()) {
126                return Err(CodingRuntimeBuildError::DuplicateModelRole { role: role.role() });
127            }
128        }
129        Ok(Self {
130            model_roles,
131            permission,
132            permission_review_rules: PermissionReviewRules::default(),
133            permission_review_guidance: merry_runtime::SessionReviewGuidance::new(),
134            workspace_review_notes: merry_runtime::WorkspaceReviewNotes::new(),
135            permission_review_workspace_root: None,
136        })
137    }
138
139    pub(crate) fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
140        self.permission_review_rules = rules;
141        self
142    }
143
144    pub(crate) fn with_workspace_review_notes(mut self, notes: Vec<String>) -> Self {
145        self.workspace_review_notes = merry_runtime::WorkspaceReviewNotes::from_notes(notes);
146        self
147    }
148
149    pub(crate) fn with_permission_review_workspace_root(
150        mut self,
151        root: impl Into<PathBuf>,
152    ) -> Self {
153        self.permission_review_workspace_root = Some(root.into());
154        self
155    }
156
157    pub(crate) fn apply_to(&self, mut builder: RuntimeBuilder) -> RuntimeBuilder {
158        for role in &self.model_roles {
159            builder = builder.model_provider_for_role_with_reasoning(
160                role.role(),
161                role.provider(),
162                role.model().clone(),
163                role.reasoning_effort().cloned(),
164            );
165        }
166        if !self.permission_review_rules.is_empty() {
167            builder = builder.permission_review_rules(self.permission_review_rules.clone());
168        }
169        builder = builder
170            .session_review_guidance(self.permission_review_guidance.clone())
171            .workspace_review_notes(self.workspace_review_notes.clone());
172        if let Some(root) = &self.permission_review_workspace_root {
173            builder = builder.permission_review_workspace_root(root.clone());
174        }
175        self.permission.apply_to(builder)
176    }
177}
178
179/// Typed subagent composition policy for a parent coding runtime.
180#[derive(Clone, Default)]
181pub struct CodingSubagentsConfig {
182    installed: bool,
183    enabled: bool,
184    limits: SubagentConfig,
185    role_catalog: SubagentRoleCatalog,
186}
187
188impl CodingSubagentsConfig {
189    /// Installs and enables subagent tools with the supplied runtime limits.
190    #[must_use]
191    pub fn enabled(limits: SubagentConfig) -> Self {
192        Self {
193            installed: true,
194            enabled: true,
195            limits,
196            role_catalog: SubagentRoleCatalog::builtin(),
197        }
198    }
199
200    /// Installs subagent tools while leaving their runtime admission controlled
201    /// by `enabled`.
202    #[must_use]
203    pub fn runtime_controlled(enabled: bool, limits: SubagentConfig) -> Self {
204        Self {
205            installed: true,
206            enabled,
207            limits,
208            role_catalog: SubagentRoleCatalog::builtin(),
209        }
210    }
211
212    /// Attaches a customized role catalog (built-in + `.merry/roles/*.toml` +
213    /// `[subagents.roles.*]` + `[subagents.default]` + `[subagents.toggle]`).
214    #[must_use]
215    pub fn with_role_catalog(mut self, role_catalog: SubagentRoleCatalog) -> Self {
216        self.role_catalog = role_catalog;
217        self
218    }
219
220    /// Returns whether the parent should advertise subagent tools.
221    #[must_use]
222    pub const fn is_installed(&self) -> bool {
223        self.installed
224    }
225
226    /// Returns whether new subagent work is enabled by the parent policy.
227    #[must_use]
228    pub const fn is_enabled(&self) -> bool {
229        self.enabled
230    }
231
232    /// Returns the runtime-owned subagent limits.
233    #[must_use]
234    pub const fn limits(&self) -> SubagentConfig {
235        self.limits
236    }
237
238    /// Returns the configured role catalog.
239    #[must_use]
240    pub fn role_catalog(&self) -> &SubagentRoleCatalog {
241        &self.role_catalog
242    }
243}
244
245/// Typed parent coding-runtime inputs shared by full and read-only variants.
246///
247/// The full constructor requires a [`ProcessBackend`]. The read-only
248/// constructor intentionally has no process backend, making it impossible for
249/// the command-generation variant to install a process session by accident.
250#[derive(Clone)]
251pub struct CodingRuntimeInput {
252    session_id: SessionId,
253    root: PathBuf,
254    provider: Arc<dyn ModelProvider>,
255    model: ModelName,
256    process_backend: Option<Arc<dyn ProcessBackend>>,
257    extra_tools: Vec<RegisteredTool>,
258    automatic_compaction: CompactionConfig,
259    history_retention: HistoryRetention,
260    retry_policy: Option<ModelRetryPolicy>,
261    model_roles: Vec<CodingModelRoleConfig>,
262    skill_roots: Vec<PathBuf>,
263    host_path_policy: HostPathPolicy,
264    subagents: CodingSubagentsConfig,
265    workspace_tool_limits: WorkspaceToolLimits,
266    /// When false, the workspace is read-only: `AGENTS.md` stays unloaded and
267    /// `apply_patch` cannot write.
268    workspace_writable: bool,
269    durable_memory: Option<Arc<DurableMemory>>,
270    browser_process_launcher: Option<Arc<dyn BrowserProcessLauncher>>,
271    permission_review_rules: PermissionReviewRules,
272    workspace_review_notes: Vec<String>,
273    max_parallel_tool_calls: Option<std::num::NonZeroUsize>,
274    context_window_tokens: Option<std::num::NonZeroU64>,
275}
276
277impl CodingRuntimeInput {
278    /// Creates full coding-runtime inputs with a typed process backend.
279    #[must_use]
280    pub fn new(
281        session_id: SessionId,
282        root: impl Into<PathBuf>,
283        provider: Arc<dyn ModelProvider>,
284        model: ModelName,
285        process_backend: Arc<dyn ProcessBackend>,
286    ) -> Self {
287        Self {
288            session_id,
289            root: root.into(),
290            provider,
291            model,
292            process_backend: Some(process_backend),
293            extra_tools: Vec::new(),
294            automatic_compaction: CompactionConfig::default(),
295            history_retention: HistoryRetention::default(),
296            retry_policy: None,
297            model_roles: Vec::new(),
298            skill_roots: Vec::new(),
299            host_path_policy: HostPathPolicy::new(),
300            subagents: CodingSubagentsConfig::default(),
301            workspace_tool_limits: WorkspaceToolLimits::default(),
302            workspace_writable: true,
303            durable_memory: None,
304            browser_process_launcher: None,
305            permission_review_rules: PermissionReviewRules::default(),
306            workspace_review_notes: Vec::new(),
307            max_parallel_tool_calls: None,
308            context_window_tokens: None,
309        }
310    }
311
312    /// Sets whether the workspace is writable (`false` keeps it read-only and
313    /// skips `AGENTS.md`).
314    #[must_use]
315    pub fn read_only_workspace(mut self) -> Self {
316        self.workspace_writable = false;
317        self
318    }
319
320    /// Returns the session identifier owned by this input.
321    #[must_use]
322    pub fn session_id(&self) -> &SessionId {
323        &self.session_id
324    }
325
326    /// Returns the workspace root directory owned by this input.
327    #[must_use]
328    pub fn root(&self) -> &std::path::Path {
329        &self.root
330    }
331
332    /// Creates read-only command-generation inputs without a process backend.
333    #[must_use]
334    pub fn read_only(
335        session_id: SessionId,
336        root: impl Into<PathBuf>,
337        provider: Arc<dyn ModelProvider>,
338        model: ModelName,
339    ) -> Self {
340        Self {
341            session_id,
342            root: root.into(),
343            provider,
344            model,
345            process_backend: None,
346            extra_tools: Vec::new(),
347            automatic_compaction: CompactionConfig::default(),
348            history_retention: HistoryRetention::default(),
349            retry_policy: None,
350            model_roles: Vec::new(),
351            skill_roots: Vec::new(),
352            host_path_policy: HostPathPolicy::new(),
353            subagents: CodingSubagentsConfig::default(),
354            workspace_tool_limits: WorkspaceToolLimits::default(),
355            workspace_writable: true,
356            durable_memory: None,
357            browser_process_launcher: None,
358            permission_review_rules: PermissionReviewRules::default(),
359            workspace_review_notes: Vec::new(),
360            max_parallel_tool_calls: None,
361            context_window_tokens: None,
362        }
363    }
364
365    /// Attaches durable memory for this runtime and the children it spawns.
366    ///
367    /// The parent maintains memory after completed user turns. Children see the
368    /// same store with maintenance disabled.
369    #[must_use]
370    pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
371        self.durable_memory = Some(memory);
372        self
373    }
374
375    /// Overrides the headless browser process launcher used by `browser_tab`
376    /// for this runtime and its spawned subagents (for example in `rootshell`
377    /// hosts that disable local browser launches or supply a custom launcher).
378    #[must_use]
379    pub fn with_browser_process_launcher(
380        mut self,
381        launcher: Arc<dyn BrowserProcessLauncher>,
382    ) -> Self {
383        self.browser_process_launcher = Some(launcher);
384        self
385    }
386
387    /// Adds provider-neutral tools owned by the calling surface or adapter.
388    #[must_use]
389    pub fn with_extra_tools<I>(mut self, tools: I) -> Self
390    where
391        I: IntoIterator<Item = RegisteredTool>,
392    {
393        self.extra_tools.extend(tools);
394        self
395    }
396
397    /// Sets automatic context compaction policy.
398    #[must_use]
399    pub fn with_automatic_compaction(mut self, config: CompactionConfig) -> Self {
400        self.automatic_compaction = config;
401        self
402    }
403
404    /// Sets how compacted history is retained in memory and on disk.
405    #[must_use]
406    pub fn with_history_retention(mut self, retention: HistoryRetention) -> Self {
407        self.history_retention = retention;
408        self
409    }
410
411    /// Sets the model retry/recovery policy shared by parent and child runtimes.
412    #[must_use]
413    pub fn with_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
414        self.retry_policy = Some(policy);
415        self
416    }
417
418    /// Adds one non-primary runtime model role.
419    #[must_use]
420    pub fn with_model_role(mut self, role: CodingModelRoleConfig) -> Self {
421        self.model_roles.push(role);
422        self
423    }
424
425    /// Adds model roles in the supplied deterministic order.
426    #[must_use]
427    pub fn with_model_roles<I>(mut self, roles: I) -> Self
428    where
429        I: IntoIterator<Item = CodingModelRoleConfig>,
430    {
431        self.model_roles.extend(roles);
432        self
433    }
434
435    /// Sets the read-only skill/resource roots.
436    #[must_use]
437    pub fn with_skill_roots<I, P>(mut self, roots: I) -> Self
438    where
439        I: IntoIterator<Item = P>,
440        P: Into<PathBuf>,
441    {
442        self.skill_roots = roots.into_iter().map(Into::into).collect();
443        self
444    }
445
446    /// Sets the shared host path policy so in-process file tools enforce the
447    /// exact same private-path and read-only session-journal boundaries as the
448    /// process sandbox, inherited by parent and child runtimes.
449    #[must_use]
450    pub fn with_host_path_policy(mut self, policy: HostPathPolicy) -> Self {
451        self.host_path_policy = policy;
452        self
453    }
454
455    /// Sets the parent subagent policy.
456    #[must_use]
457    pub fn with_subagents(mut self, subagents: CodingSubagentsConfig) -> Self {
458        self.subagents = subagents;
459        self
460    }
461
462    /// Sets the workspace tool limits for the coding profile.
463    #[must_use]
464    pub fn with_workspace_tool_limits(mut self, limits: WorkspaceToolLimits) -> Self {
465        self.workspace_tool_limits = limits;
466        self
467    }
468
469    /// Sets user-trusted custom rules for AI permission review, inherited by
470    /// both parent and child coding runtimes.
471    #[must_use]
472    pub fn with_permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
473        self.permission_review_rules = rules;
474        self
475    }
476
477    /// Sets saved per-workspace AI review guidance notes inherited live by both
478    /// parent and child coding runtimes.
479    #[must_use]
480    pub fn with_workspace_review_notes(mut self, notes: Vec<String>) -> Self {
481        self.workspace_review_notes = notes;
482        self
483    }
484
485    /// Sets the maximum number of parallel-safe tool calls executed together in
486    /// one model turn for both parent and child runtimes.
487    #[must_use]
488    pub fn with_max_parallel_tool_calls(mut self, limit: std::num::NonZeroUsize) -> Self {
489        self.max_parallel_tool_calls = Some(limit);
490        self
491    }
492
493    /// Sets an explicit context-window override in tokens for budget and
494    /// automatic compaction calculations.
495    #[must_use]
496    pub fn with_context_window_tokens(mut self, tokens: std::num::NonZeroU64) -> Self {
497        self.context_window_tokens = Some(tokens);
498        self
499    }
500}
501
502/// Internal parent coding-runtime variant selected by the surface.
503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
504enum CodingRuntimeVariant {
505    /// Full coding runtime with process, patch, plan, and optional subagent lanes.
506    FullCoding,
507    /// Read-only workspace runtime for command generation.
508    ReadOnlyCommandGeneration,
509}
510
511/// Builder for parent coding runtime composition.
512pub struct CodingRuntimeBuilder {
513    input: CodingRuntimeInput,
514    variant: CodingRuntimeVariant,
515    permission: CodingPermissionPolicy,
516    loaded_session: Option<LoadedSession>,
517    session_store: Option<FileSessionStore>,
518}
519
520impl CodingRuntimeBuilder {
521    /// Creates a full coding-runtime builder.
522    #[must_use]
523    pub fn new(input: CodingRuntimeInput) -> Self {
524        Self {
525            input,
526            variant: CodingRuntimeVariant::FullCoding,
527            permission: CodingPermissionPolicy::default(),
528            loaded_session: None,
529            session_store: None,
530        }
531    }
532
533    /// Creates the explicit read-only command-generation variant.
534    ///
535    /// Full-only inputs such as a process backend and subagent configuration
536    /// are intentionally ignored by this variant. The read-only profile is
537    /// selected by construction so those capabilities cannot be advertised or
538    /// admitted accidentally.
539    #[must_use]
540    pub fn for_command_generation(input: CodingRuntimeInput) -> Self {
541        Self {
542            input,
543            variant: CodingRuntimeVariant::ReadOnlyCommandGeneration,
544            permission: CodingPermissionPolicy::default(),
545            loaded_session: None,
546            session_store: None,
547        }
548    }
549
550    /// Sets the complete permission policy shared by parent and child runtimes.
551    #[must_use]
552    pub fn permission_policy(mut self, policy: CodingPermissionPolicy) -> Self {
553        self.permission = policy;
554        self
555    }
556
557    /// Installs an already loaded session without performing another store read.
558    #[must_use]
559    pub fn with_loaded_session(mut self, loaded: LoadedSession) -> Self {
560        self.loaded_session = Some(loaded);
561        self
562    }
563
564    /// Configures automatic incremental session persistence into `store`.
565    #[must_use]
566    pub fn session_store(mut self, store: FileSessionStore) -> Self {
567        self.session_store = Some(store);
568        self
569    }
570
571    /// Builds a new parent runtime and its stable coding loop policy.
572    pub fn build(self) -> Result<CodingRuntime, CodingRuntimeBuildError> {
573        let mut reservation = None;
574        self.build_with_reservation(&mut reservation)
575    }
576
577    /// Builds a new parent runtime and transfers an already-acquired
578    /// [`merry_runtime::SessionReservation`] into the runtime once validation
579    /// succeeds.
580    pub fn build_with_reservation(
581        self,
582        reservation: &mut Option<merry_runtime::SessionReservation>,
583    ) -> Result<CodingRuntime, CodingRuntimeBuildError> {
584        let (builder, profile) = self.compose()?;
585        let loop_config = profile.loop_config()?;
586        let runtime = builder
587            .build_with_reservation(reservation)
588            .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
589        Ok(CodingRuntime {
590            runtime,
591            profile,
592            loop_config,
593        })
594    }
595
596    /// Resumes a parent runtime without automatic savepoints.
597    pub async fn resume_from_store_without_automatic_savepoints(
598        self,
599        store: FileSessionStore,
600    ) -> Result<CodingRuntime, CodingRuntimeBuildError> {
601        let (builder, profile) = self.compose()?;
602        let loop_config = profile.loop_config()?;
603        let runtime = builder
604            .resume_from_store_without_automatic_savepoints(store)
605            .await
606            .map_err(|source| CodingRuntimeBuildError::RuntimeBuild { source })?;
607        Ok(CodingRuntime {
608            runtime,
609            profile,
610            loop_config,
611        })
612    }
613
614    fn compose(
615        self,
616    ) -> Result<(merry_runtime::RuntimeBuilder, CodingAgentProfile), CodingRuntimeBuildError> {
617        let Self {
618            input,
619            variant,
620            permission,
621            loaded_session,
622            session_store,
623        } = self;
624        let CodingRuntimeInput {
625            session_id,
626            root,
627            provider,
628            model,
629            process_backend,
630            extra_tools,
631            automatic_compaction,
632            history_retention,
633            retry_policy,
634            model_roles,
635            skill_roots,
636            host_path_policy,
637            subagents,
638            workspace_tool_limits,
639            workspace_writable,
640            durable_memory,
641            browser_process_launcher,
642            permission_review_rules,
643            workspace_review_notes,
644            max_parallel_tool_calls,
645            context_window_tokens,
646        } = input;
647
648        let policy = CodingRuntimePolicy::try_new(model_roles, permission)?
649            .with_permission_review_rules(permission_review_rules)
650            .with_workspace_review_notes(workspace_review_notes)
651            .with_permission_review_workspace_root(root.clone());
652
653        let project_rules = if workspace_writable {
654            load_root_project_rules(&root)?
655        } else {
656            None
657        };
658        let skill_catalog = if skill_roots.is_empty() {
659            None
660        } else {
661            Some(SkillCatalog::load_from_roots(skill_roots.clone())?)
662        };
663        if let Some(catalog) = skill_catalog.as_ref() {
664            const MAX_LOGGED_SKILL_NAMES: usize = 64;
665            let skill_names = catalog
666                .skills()
667                .iter()
668                .take(MAX_LOGGED_SKILL_NAMES)
669                .map(|skill| skill.name())
670                .collect::<Vec<_>>();
671            tracing::info!(
672                event = "runtime.skill_catalog.load",
673                session_id = %session_id,
674                configured_root_count = skill_roots.len(),
675                readable_root_count = skill_roots.iter().filter(|root| root.is_dir()).count(),
676                skill_count = catalog.skills().len(),
677                warning_count = catalog.warnings().len(),
678                skill_names = ?skill_names,
679                "runtime skill catalog loaded"
680            );
681        }
682        let mut runtime_builder = Runtime::builder(session_id.clone())
683            .automatic_compaction(automatic_compaction.clone())
684            .history_retention(history_retention)
685            .model_provider(Arc::clone(&provider), model.clone());
686        if let Some(limit) = max_parallel_tool_calls {
687            runtime_builder = runtime_builder.max_parallel_tool_calls(limit);
688        }
689        if let Some(tokens) = context_window_tokens {
690            runtime_builder = runtime_builder.context_window_tokens(tokens);
691        }
692        if matches!(variant, CodingRuntimeVariant::FullCoding) {
693            runtime_builder = runtime_builder.coordinator_plan_tools();
694        }
695
696        let mut profile_builder: CodingAgentProfileBuilder = coding_agent(&root)
697            .readonly_resource_roots(skill_roots.clone())
698            .host_path_policy(host_path_policy)
699            .limits(workspace_tool_limits)
700            .register_tools(extra_tools);
701        if let Some(project_rules) = project_rules {
702            profile_builder = profile_builder.project_rules(project_rules);
703        }
704        if let Some(skill_catalog) = skill_catalog {
705            profile_builder = profile_builder.skill_catalog(skill_catalog);
706        }
707        if let Some(policy) = retry_policy {
708            profile_builder = profile_builder.retry_policy(policy);
709        }
710        if let Some(memory) = durable_memory.clone() {
711            profile_builder = profile_builder.durable_memory(memory);
712        }
713        if let Some(launcher) = browser_process_launcher {
714            profile_builder = profile_builder.browser_process_launcher(launcher);
715        }
716
717        let mut profile_tools = Vec::new();
718        if matches!(variant, CodingRuntimeVariant::FullCoding) {
719            let process_backend =
720                process_backend.ok_or(CodingRuntimeBuildError::MissingProcessBackend)?;
721            let process_session = process_backend.new_session();
722            let parent_process_permissions = process_session.permission_view();
723            profile_builder = profile_builder.patch_tool().web_tools();
724            // For static non-live backends without a live policy handle, keep
725            // `read_only_patch_scope()` enforced when starting read-only; live
726            // backends (`LiveProcessBackend`) govern `workspace_writable`
727            // dynamically via `LivePolicyHandle` so toggling `workspace (ro)
728            // <-> off` unlocks/locks `apply_patch` immediately.
729            if !workspace_writable && !process_session.has_live_policy() {
730                profile_builder = profile_builder.read_only_patch_scope();
731            }
732            let child_profile_builder = profile_builder.clone();
733            profile_builder = profile_builder.accepted_process_session(process_session);
734
735            if subagents.is_installed() {
736                let subagent_config = subagents.limits().with_model_turn_bounds(
737                    MIN_CODING_SUBAGENT_MODEL_TURNS,
738                    subagents.limits().max_model_turns(),
739                )?;
740                tracing::info!(
741                    event = "runtime.subagents.enabled",
742                    session_id = %session_id,
743                    enabled = subagents.is_enabled(),
744                    max_threads = subagent_config.max_threads(),
745                    max_depth = subagent_config.max_depth(),
746                    min_model_turns = subagent_config.min_model_turns(),
747                    max_model_turns = subagent_config.max_model_turns(),
748                    "runtime subagent tools installed"
749                );
750                let role_catalog = subagents.role_catalog().clone();
751                let role_summaries = role_catalog.enabled_role_summaries();
752                let composition = CodingRuntimeComposition {
753                    profile_builder: child_profile_builder,
754                    provider: Arc::clone(&provider),
755                    model: model.clone(),
756                    process_backend,
757                    parent_process_permissions,
758                    parent_workspace_writable: workspace_writable,
759                    subagent_config,
760                    role_catalog,
761                    automatic_compaction,
762                    max_parallel_tool_calls,
763                    policy: policy.clone(),
764                    worktree_manager: crate::WorktreeIsolationManager::new(),
765                };
766                let child_factory: Arc<dyn ChildRuntimeFactory> =
767                    Arc::new(CodingChildRuntimeFactory::from_composition(composition));
768                let manager = SubagentManager::runtime_controlled(
769                    session_id.clone(),
770                    subagent_config,
771                    child_factory,
772                    subagents.is_enabled(),
773                );
774                let [spawn_tool, send_tool, wait_tool, cancel_tool] =
775                    subagent_registered_tools_with_roles(manager.clone(), &role_summaries)?;
776                runtime_builder = runtime_builder.subagent_manager(manager);
777                profile_tools.extend([spawn_tool, send_tool, wait_tool, cancel_tool]);
778            }
779        }
780
781        let profile = profile_builder.register_tools(profile_tools).build()?;
782        runtime_builder = profile
783            .apply_to(runtime_builder)
784            .map_err(|source| CodingRuntimeBuildError::RuntimeProfileApply { source })?;
785        runtime_builder = policy.apply_to(runtime_builder);
786        if let Some(memory) = durable_memory {
787            runtime_builder = runtime_builder.durable_memory(memory, true);
788        }
789        if let Some(loaded_session) = loaded_session {
790            runtime_builder = runtime_builder.with_loaded_session(loaded_session);
791        }
792        if let Some(store) = session_store {
793            runtime_builder = runtime_builder.session_store(store);
794        }
795
796        Ok((runtime_builder, profile))
797    }
798}
799
800/// A built parent coding runtime and the policy that governs its loop.
801pub struct CodingRuntime {
802    runtime: Runtime,
803    profile: CodingAgentProfile,
804    loop_config: AgentLoopConfig,
805}
806
807impl CodingRuntime {
808    /// Borrows the runtime state handle owned by this composition result.
809    #[must_use]
810    pub fn runtime(&self) -> &Runtime {
811        &self.runtime
812    }
813
814    /// Consumes the composition result and returns its runtime handle.
815    #[must_use]
816    pub fn into_runtime(self) -> Runtime {
817        self.runtime
818    }
819
820    /// Borrows the shared coding profile used by this runtime.
821    #[must_use]
822    pub fn profile(&self) -> &CodingAgentProfile {
823        &self.profile
824    }
825
826    /// Clones the loop configuration derived from the shared coding profile.
827    #[must_use]
828    pub fn loop_config(&self) -> AgentLoopConfig {
829        self.loop_config.clone()
830    }
831}
832
833/// Errors raised while composing a parent coding runtime.
834#[derive(Debug, Error)]
835pub enum CodingRuntimeBuildError {
836    /// A full coding runtime was requested without its process backend.
837    #[error("full coding runtime requires a process backend")]
838    MissingProcessBackend,
839    /// A role was configured more than once.
840    #[error("coding model role {role:?} was configured more than once")]
841    DuplicateModelRole { role: RuntimeModelRole },
842    /// A provider-neutral protocol value failed validation.
843    #[error(transparent)]
844    Core(#[from] CoreError),
845    /// Project rules could not be loaded safely.
846    #[error(transparent)]
847    ProjectRules(#[from] ProjectRulesLoadError),
848    /// The skill catalog could not be loaded.
849    #[error(transparent)]
850    SkillCatalog(#[from] SkillError),
851    /// The coding profile was invalid.
852    #[error(transparent)]
853    CodingProfile(#[from] CodingAgentProfileBuildError),
854    /// The profile's coding loop policy was invalid.
855    #[error(transparent)]
856    LoopConfig(#[from] AgentLoopConfigError),
857    /// The coding profile's child-agent model-turn bounds were invalid.
858    #[error(transparent)]
859    SubagentConfig(#[from] SubagentError),
860    /// Applying the profile to the runtime builder failed.
861    #[error("failed to apply coding profile to runtime builder: {source}")]
862    RuntimeProfileApply { source: RuntimeError },
863    /// Runtime construction or resume failed.
864    #[error("failed to build coding runtime: {source}")]
865    RuntimeBuild { source: RuntimeError },
866}