Skip to main content

merry_runtime/runtime/
builder.rs

1use super::config::{CompactionConfig, HistoryRetention};
2use super::state::AcceptedLocalWorkspaceProcessRunner;
3use super::{Runtime, RuntimeInner};
4use crate::{
5    AcceptedLocalWorkspaceProcessAdmission, CompactedCheckpoint, FileSessionStore, LoadedSession,
6    ProcessRunner, ProjectRules, PromptProfile, RuntimeCapabilities, RuntimeError,
7    RuntimeModelRole, RuntimeProfile, SkillCatalog, TaskAnchor, ToolAdmission,
8    memory::{MemoryActivationSource, StoredMemoryActivationSource},
9    model_config::RuntimeModelConfigs,
10    permission::{
11        PermissionAdmissionSource, PermissionReviewMode, PermissionReviewRules, RuntimeTrustLevel,
12    },
13    plan::tools::coordinator_plan_registered_tools,
14    process::{
15        BackgroundProcessControl, PermissionedProcessRunnerFactory,
16        StaticPermissionedProcessRunnerFactory,
17    },
18    session::SessionState,
19    subagent::{
20        ChildWorkspaceScope, SUBAGENT_WORKSPACE_SCOPE_CONTEXT_ID, SubagentActivityHub,
21        SubagentManager,
22    },
23    todo::todo_registered_tool,
24    tool::{RegisteredTool, ToolRegistry, ToolRegistryError},
25    trajectory::RuntimeObservability,
26};
27use merry_core::{SessionId, ToolName};
28use merry_llm::{ModelName, ModelProvider, ModelRetryPolicy};
29use std::{
30    collections::{BTreeMap, VecDeque},
31    num::NonZeroUsize,
32    path::PathBuf,
33    sync::{
34        Arc,
35        atomic::{AtomicBool, AtomicU64},
36    },
37};
38use tokio::sync::{Mutex, RwLock};
39
40const DEFAULT_EVENT_BUFFER_SIZE: usize = 16;
41const DEFAULT_MAX_PARALLEL_TOOL_CALLS: usize = 8;
42
43/// Builder for a Merry runtime.
44///
45/// The builder wires provider-neutral runtime configuration: event buffering,
46/// one optional model provider, and zero or more runtime-owned tool executors.
47/// Provider integrations stay outside this crate behind [`ModelProvider`].
48pub struct RuntimeBuilder {
49    session_id: SessionId,
50    prompt_cache_key: Option<SessionId>,
51    event_buffer_size: NonZeroUsize,
52    max_parallel_tool_calls: NonZeroUsize,
53    model_configs: RuntimeModelConfigs,
54    model_retry_policy: ModelRetryPolicy,
55    automatic_compaction: CompactionConfig,
56    history_retention: HistoryRetention,
57    capabilities: RuntimeCapabilities,
58    prompt_profile: PromptProfile,
59    progress_commentary: bool,
60    registered_tools: Vec<RegisteredTool>,
61    tool_admission: Option<ToolAdmission>,
62    coordinator_plan_tools: bool,
63    initial_context_summaries: BTreeMap<String, String>,
64    skill_catalog: Option<SkillCatalog>,
65    project_rules: Option<ProjectRules>,
66    task_anchor: Option<TaskAnchor>,
67    compacted_checkpoint: Option<CompactedCheckpoint>,
68    memory_activation_source: Arc<dyn MemoryActivationSource>,
69    allow_bridge_tools: bool,
70    allow_low_risk_apply_patches: bool,
71    low_risk_process_runner: Option<Arc<dyn ProcessRunner>>,
72    read_only_shell_process_runner: Option<Arc<dyn ProcessRunner>>,
73    accepted_local_workspace_process_runner: Option<AcceptedLocalWorkspaceProcessRunner>,
74    runtime_trust_level: RuntimeTrustLevel,
75    permission_review_mode: PermissionReviewMode,
76    permission_review_rules: PermissionReviewRules,
77    permission_review_workspace_root: Option<PathBuf>,
78    permission_actor: crate::PermissionActor,
79    permission_admission_source: Option<Arc<dyn PermissionAdmissionSource>>,
80    permissioned_process_runner_factory: Option<Arc<dyn PermissionedProcessRunnerFactory>>,
81    background_process_control: Option<Arc<dyn BackgroundProcessControl>>,
82    subagent_manager: Option<SubagentManager>,
83    subagent_parent_scope: Option<ChildWorkspaceScope>,
84    activity_hub: Arc<SubagentActivityHub>,
85    session_store: Option<FileSessionStore>,
86    loaded_session: Option<SessionState>,
87    durable_memory: Option<Arc<crate::DurableMemory>>,
88    memory_maintenance: bool,
89}
90
91impl RuntimeBuilder {
92    pub(super) fn new(session_id: SessionId) -> Self {
93        Self {
94            session_id,
95            prompt_cache_key: None,
96            event_buffer_size: NonZeroUsize::new(DEFAULT_EVENT_BUFFER_SIZE)
97                .expect("default event buffer size is non-zero"),
98            max_parallel_tool_calls: NonZeroUsize::new(DEFAULT_MAX_PARALLEL_TOOL_CALLS)
99                .expect("default parallel tool-call limit is non-zero"),
100            model_configs: RuntimeModelConfigs::default(),
101            model_retry_policy: ModelRetryPolicy::default(),
102            automatic_compaction: CompactionConfig::default(),
103            history_retention: HistoryRetention::default(),
104            capabilities: RuntimeCapabilities::default(),
105            prompt_profile: PromptProfile::default(),
106            progress_commentary: false,
107            registered_tools: Vec::new(),
108            tool_admission: None,
109            coordinator_plan_tools: false,
110            initial_context_summaries: BTreeMap::new(),
111            skill_catalog: None,
112            project_rules: None,
113            task_anchor: None,
114            compacted_checkpoint: None,
115            memory_activation_source: Arc::new(StoredMemoryActivationSource),
116            allow_bridge_tools: false,
117            allow_low_risk_apply_patches: false,
118            low_risk_process_runner: None,
119            read_only_shell_process_runner: None,
120            accepted_local_workspace_process_runner: None,
121            runtime_trust_level: RuntimeTrustLevel::Agent,
122            permission_review_mode: PermissionReviewMode::DefaultForTrust,
123            permission_review_rules: PermissionReviewRules::default(),
124            permission_review_workspace_root: None,
125            permission_actor: crate::PermissionActor::MainAgent,
126            permission_admission_source: None,
127            permissioned_process_runner_factory: None,
128            background_process_control: None,
129            subagent_manager: None,
130            subagent_parent_scope: None,
131            activity_hub: Arc::new(SubagentActivityHub::new()),
132            session_store: None,
133            loaded_session: None,
134            durable_memory: None,
135            memory_maintenance: false,
136        }
137    }
138
139    /// Sets the actor identity attached to outgoing host permission review requests.
140    #[must_use]
141    pub fn permission_actor(mut self, actor: crate::PermissionActor) -> Self {
142        self.permission_actor = actor;
143        self
144    }
145
146    /// Sets the bounded event channel buffer size.
147    ///
148    /// Runtime event production uses a bounded channel. Capacity counts
149    /// internal emission batches rather than individual public events, so one
150    /// slot may carry consecutive events whose state must be committed and
151    /// enqueued together. Backpressure is part of the state-before-event
152    /// contract: producers reserve a batch slot before mutating durable session
153    /// state for the corresponding events.
154    #[must_use]
155    pub fn event_buffer_size(mut self, event_buffer_size: NonZeroUsize) -> Self {
156        self.event_buffer_size = event_buffer_size;
157        self
158    }
159
160    /// Sets the maximum number of adjacent parallel-safe calls executed together.
161    #[must_use]
162    pub fn max_parallel_tool_calls(mut self, limit: NonZeroUsize) -> Self {
163        self.max_parallel_tool_calls = limit;
164        self
165    }
166
167    /// Overrides the deterministic provider prompt-cache key used for model
168    /// requests in this runtime.
169    ///
170    /// When omitted, model requests default to this runtime's own `session_id`.
171    /// Child runtimes use this to share a deterministic cache partition across
172    /// sibling subagents running the same role under one parent session.
173    #[must_use]
174    pub fn prompt_cache_key(mut self, prompt_cache_key: SessionId) -> Self {
175        self.prompt_cache_key = Some(prompt_cache_key);
176        self
177    }
178
179    /// Sets the provider and model used by runtime steps.
180    ///
181    /// The provider receives normalized model requests and returns normalized
182    /// model events from `merry-llm`. Provider response formats are not stored
183    /// in runtime state.
184    #[must_use]
185    pub fn model_provider(mut self, provider: Arc<dyn ModelProvider>, model: ModelName) -> Self {
186        self.model_configs.insert(
187            RuntimeModelRole::Primary,
188            provider,
189            model,
190            self.model_retry_policy,
191        );
192        self
193    }
194
195    /// Sets the provider and model for a runtime model role.
196    ///
197    /// Only [`RuntimeModelRole::Primary`] is used by normal runtime steps today.
198    /// Non-primary roles are stored as runtime-owned configuration for future
199    /// review gates and do not alter provider request compilation.
200    #[must_use]
201    pub fn model_provider_for_role(
202        mut self,
203        role: RuntimeModelRole,
204        provider: Arc<dyn ModelProvider>,
205        model: ModelName,
206    ) -> Self {
207        self.model_configs
208            .insert(role, provider, model, self.model_retry_policy);
209        self
210    }
211
212    /// Sets the provider, model, and retry policy for a runtime model role.
213    ///
214    /// This is useful for higher-level construction layers that treat provider
215    /// config as a component. Unlike [`RuntimeBuilder::model_retry_policy`],
216    /// this method does not alter already configured providers.
217    #[must_use]
218    pub fn model_provider_for_role_with_retry(
219        mut self,
220        role: RuntimeModelRole,
221        provider: Arc<dyn ModelProvider>,
222        model: ModelName,
223        retry_policy: ModelRetryPolicy,
224    ) -> Self {
225        self.model_configs
226            .insert(role, provider, model, retry_policy);
227        self
228    }
229
230    /// Sets the retry policy applied to configured and subsequently configured
231    /// model providers.
232    #[must_use]
233    pub fn model_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
234        self.model_retry_policy = policy;
235        self.model_configs.set_retry_policy(policy);
236        self
237    }
238
239    /// Sets the runtime policy for automatic compaction.
240    ///
241    /// Automatic compaction runs only when a compiled provider request crosses
242    /// the compaction threshold. The current step input is still outside the
243    /// compaction input and is projected raw after any installed checkpoint.
244    #[must_use]
245    pub fn automatic_compaction(mut self, config: CompactionConfig) -> Self {
246        self.automatic_compaction = config;
247        self
248    }
249
250    /// Sets the stable prompt composition used by runtime request compilation.
251    #[must_use]
252    pub fn prompt_profile(mut self, profile: PromptProfile) -> Self {
253        self.prompt_profile = profile;
254        self
255    }
256
257    /// Controls whether the runtime asks the model to emit brief tool-progress commentary.
258    #[must_use]
259    pub fn progress_commentary(mut self, enabled: bool) -> Self {
260        self.progress_commentary = enabled;
261        self
262    }
263
264    /// Registers a runtime-owned tool executor.
265    ///
266    /// Registering a tool makes its spec available to provider requests and
267    /// lets [`Runtime::execute_tool_call`] resolve matching pending calls. It
268    /// does not start an automatic tool loop.
269    #[must_use]
270    pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
271        self.registered_tools.push(tool);
272        self
273    }
274
275    /// Installs runtime admission for tool execution without changing the
276    /// provider-visible tool catalog.
277    #[must_use]
278    pub fn tool_admission(mut self, admission: ToolAdmission) -> Self {
279        self.tool_admission = Some(admission);
280        self
281    }
282
283    /// Installs the stable coordinator Plan Mode and Todo tool surface.
284    #[must_use]
285    pub fn coordinator_plan_tools(mut self) -> Self {
286        self.coordinator_plan_tools = true;
287        self
288    }
289
290    /// Applies a complete runtime profile while keeping this builder as the
291    /// construction owner.
292    pub fn with_profile(mut self, profile: RuntimeProfile) -> Result<Self, RuntimeError> {
293        let parts = profile.into_parts();
294        self.capabilities = parts.capabilities;
295        self.prompt_profile = parts.prompt_profile;
296        if let Some(policy) = parts.model_retry_policy {
297            self = self.model_retry_policy(policy);
298        }
299        self.progress_commentary = parts.progress_commentary;
300        for (id, text) in parts.initial_context_summaries {
301            self = self.initial_context_summary(&id, &text);
302        }
303        for tool in parts.registered_tools {
304            self = self.register_tool(tool);
305        }
306        if parts.allow_bridge_tools {
307            self = self.allow_bridge_tools();
308        }
309        if parts.allow_low_risk_apply_patches {
310            self = self.allow_low_risk_apply_patches();
311        }
312        if let Some(runner) = parts.low_risk_process_runner {
313            self = self.allow_low_risk_process_actions(runner);
314        }
315        if let Some(runner) = parts.read_only_shell_process_runner {
316            self = self.allow_read_only_shell_process_actions(runner);
317        }
318        if let Some(accepted) = parts.accepted_local_workspace_process_runner {
319            self = self.allow_accepted_local_workspace_process_actions(
320                accepted.admission(),
321                accepted.runner(),
322            );
323        }
324        if let Some(trust_level) = parts.runtime_trust_level {
325            self = self.runtime_trust_level(trust_level);
326        }
327        if let Some(mode) = parts.permission_review_mode {
328            self = self.permission_review_mode(mode);
329        }
330        if let Some(source) = parts.permission_admission_source {
331            self = self.permission_admission_source(source);
332        }
333        if let Some(factory) = parts.permissioned_process_runner_factory {
334            self = self.permissioned_process_runner_factory(factory);
335        }
336        if let Some(control) = parts.background_process_control {
337            self = self.background_process_control(control);
338        }
339        if let Some(catalog) = parts.skill_catalog {
340            self = self.skill_catalog(catalog);
341        }
342        if let Some(project_rules) = parts.project_rules {
343            self = self.project_rules(project_rules);
344        }
345        if let Some(task_anchor) = parts.task_anchor {
346            self = self.task_anchor(task_anchor);
347        }
348        if let Some(manager) = parts.subagent_manager {
349            self = self.subagent_manager(manager);
350        }
351        Ok(self)
352    }
353
354    /// Allows bridge tools to be registered for this runtime.
355    ///
356    /// Bridge handlers run in host code outside Merry-managed sandboxing. This
357    /// opt-in is separate from [`RuntimeCapabilities`] policy.
358    #[must_use]
359    pub fn allow_bridge_tools(mut self) -> Self {
360        self.allow_bridge_tools = true;
361        self
362    }
363
364    /// Reconciles deterministic runtime context without emitting observable events.
365    ///
366    /// This is for startup-owned facts such as a compact project capability
367    /// summary. The supplied id becomes the current construction-owned seed on
368    /// both new and resumed sessions; construction seeds omitted from this
369    /// builder are left untouched. It is not a substitute for runtime artifacts
370    /// produced during a step, and repeated builder ids are replaced before
371    /// build-time validation.
372    #[must_use]
373    pub fn initial_context_summary(mut self, id: &str, text: &str) -> Self {
374        self.initial_context_summaries
375            .insert(id.to_owned(), text.to_owned());
376        self
377    }
378
379    /// Adds explicit project rules to the cacheable stable request prefix.
380    ///
381    /// This is a construction-time projection for durable project instructions
382    /// such as `AGENTS.md`. It does not scan the filesystem and is separate
383    /// from context summaries, ledger facts, and artifact payloads.
384    #[must_use]
385    pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
386        self.project_rules = Some(project_rules);
387        self
388    }
389
390    /// Adds available skill metadata to the cacheable stable request prefix.
391    ///
392    /// This projects only `SKILL.md` frontmatter metadata. Full skill bodies
393    /// remain on disk and must be read through registered workspace file tools.
394    #[must_use]
395    pub fn skill_catalog(mut self, skill_catalog: SkillCatalog) -> Self {
396        self.skill_catalog = Some(skill_catalog);
397        self
398    }
399
400    /// Sets the current task objective control-plane anchor.
401    ///
402    /// This reserves the runtime context slot for future `/task` commands. It
403    /// is rendered as dynamic request context, not as project rules, ledger
404    /// projection, or ordered transcript history.
405    #[must_use]
406    pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
407        self.task_anchor = Some(task_anchor);
408        self
409    }
410
411    /// Sets compacted checkpoint context for dynamic provider requests.
412    ///
413    /// This is selected by a checkpoint/compaction boundary. It does not
414    /// project ordinary ledger facts, artifact payloads, or tool-result
415    /// observations. The checkpoint is prose. Resume a real runtime checkpoint
416    /// with [`RuntimeBuilder::resume_from_store`] so its transcript and archived
417    /// tool refs are restored together.
418    #[must_use]
419    pub fn compacted_checkpoint(mut self, checkpoint: CompactedCheckpoint) -> Self {
420        self.compacted_checkpoint = Some(checkpoint);
421        self
422    }
423
424    /// Opts in to executing validated low-risk workspace patch proposals.
425    ///
426    /// This keeps the default policy conservative: workspace writes remain
427    /// denied unless the tool provides valid workspace patch proposal evidence
428    /// and runtime construction explicitly enables this lane.
429    #[must_use]
430    pub fn allow_low_risk_apply_patches(mut self) -> Self {
431        self.allow_low_risk_apply_patches = true;
432        self
433    }
434
435    /// Opts in to executing validated low-risk process action proposals.
436    ///
437    /// The default policy remains deny. This lane is available only for command
438    /// execution proposals with provider-neutral process evidence, an injected
439    /// runtime runner, and the narrow SP2 low-risk predicate.
440    #[must_use]
441    pub fn allow_low_risk_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
442        self.low_risk_process_runner = Some(runner);
443        self
444    }
445
446    /// Opts in to executing validated read-only shell wrapper proposals.
447    ///
448    /// This lane is intentionally separate from the structured low-risk argv
449    /// lane. It accepts only a narrow `bash`/`sh`/`zsh -c|-lc` plain command
450    /// sequence classifier and requires an injected runner selected for the
451    /// shell read-only profile. It does not authorize arbitrary shell syntax.
452    #[must_use]
453    pub fn allow_read_only_shell_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
454        self.read_only_shell_process_runner = Some(runner);
455        self
456    }
457
458    /// Opts in to executing validated local workspace effect process proposals.
459    ///
460    /// Runner injection alone is not a sandbox or an authorization source. This
461    /// lane requires explicit runtime construction-time admission that declares
462    /// the sandbox profile and accepted local workspace process risk for the
463    /// narrow classified process intent.
464    #[must_use]
465    pub fn allow_accepted_local_workspace_process_actions(
466        mut self,
467        admission: AcceptedLocalWorkspaceProcessAdmission,
468        runner: Arc<dyn ProcessRunner>,
469    ) -> Self {
470        self.accepted_local_workspace_process_runner =
471            Some(AcceptedLocalWorkspaceProcessRunner { admission, runner });
472        self
473    }
474
475    /// Sets the trust level used by permission request admission defaults.
476    ///
477    /// Agentic/coding-agent runtimes require review by default. Trusted SDK
478    /// hosts may explicitly choose host-only admission for business workflows
479    /// where the host already owns the action policy.
480    #[must_use]
481    pub fn runtime_trust_level(mut self, trust_level: RuntimeTrustLevel) -> Self {
482        self.runtime_trust_level = trust_level;
483        self
484    }
485
486    /// Sets how permission requests are reviewed before execution.
487    #[must_use]
488    pub fn permission_review_mode(mut self, mode: PermissionReviewMode) -> Self {
489        self.permission_review_mode = mode;
490        self
491    }
492
493    /// Sets user-trusted custom rules for AI permission review.
494    #[must_use]
495    pub fn permission_review_rules(mut self, rules: PermissionReviewRules) -> Self {
496        self.permission_review_rules = rules;
497        self
498    }
499
500    /// Sets the workspace root used for read-only harness environment probes
501    /// (such as `git status` cleanliness) during AI permission review.
502    #[must_use]
503    pub fn permission_review_workspace_root(mut self, root: impl Into<PathBuf>) -> Self {
504        self.permission_review_workspace_root = Some(root.into());
505        self
506    }
507
508    /// Explicitly enables fully trusted SDK/host execution for registered
509    /// tools. Runtime schema validation, tool executor boundaries, sandboxing,
510    /// and cancellation remain active. Proposal-based commit lifecycle checks
511    /// are intentionally bypassed at this explicit trust boundary.
512    #[must_use]
513    pub fn fully_trusted_tools(self) -> Self {
514        self.permission_review_mode(PermissionReviewMode::FullyTrusted)
515    }
516
517    /// Installs a host-owned permission admission source.
518    ///
519    /// This is used for trusted SDK hosts or tests. Agentic runtimes should
520    /// normally use the model-backed review selected from
521    /// [`RuntimeModelRole::ApprovalReview`] with primary fallback.
522    #[must_use]
523    pub fn permission_admission_source(
524        mut self,
525        source: Arc<dyn PermissionAdmissionSource>,
526    ) -> Self {
527        self.permission_admission_source = Some(source);
528        self
529    }
530
531    /// Opts in to executing process actions approved by `request_permissions`.
532    ///
533    /// The runner should represent the backend/profile used for approved
534    /// permission requests. Runtime admission approves only the exact planned
535    /// action, while a concrete backend may retain the approved capabilities
536    /// for later actions in the same runtime session.
537    #[must_use]
538    pub fn allow_permissioned_process_actions(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
539        self.permissioned_process_runner_factory = Some(Arc::new(
540            StaticPermissionedProcessRunnerFactory::new(runner),
541        ));
542        self
543    }
544
545    /// Opts in to constructing a process runner per approved permission request.
546    ///
547    /// This is the preferred path when approved capabilities must be
548    /// materialized into each new action while remaining active for the
549    /// current runtime session.
550    #[must_use]
551    pub fn permissioned_process_runner_factory(
552        mut self,
553        factory: Arc<dyn PermissionedProcessRunnerFactory>,
554    ) -> Self {
555        self.permissioned_process_runner_factory = Some(factory);
556        self
557    }
558
559    /// Installs the board that lists, reads, and stops background processes.
560    #[must_use]
561    pub fn background_process_control(
562        mut self,
563        control: Arc<dyn BackgroundProcessControl>,
564    ) -> Self {
565        self.background_process_control = Some(control);
566        self
567    }
568
569    /// Installs a runtime-owned subagent manager for future subagent tools.
570    #[must_use]
571    pub fn subagent_manager(mut self, manager: SubagentManager) -> Self {
572        self.subagent_manager = Some(manager);
573        self
574    }
575
576    /// Reuses a runtime-owned activity hub for this runtime and its children.
577    #[must_use]
578    pub fn subagent_activity_hub(mut self, hub: Arc<SubagentActivityHub>) -> Self {
579        self.activity_hub = hub;
580        self
581    }
582
583    /// Sets the effective workspace scope inherited by nested subagent tasks.
584    #[must_use]
585    pub fn subagent_parent_scope(mut self, scope: ChildWorkspaceScope) -> Self {
586        self.subagent_parent_scope = Some(scope);
587        self
588    }
589
590    /// Installs the filesystem store used by explicit and automatic session savepoints.
591    #[must_use]
592    pub fn session_store(mut self, store: FileSessionStore) -> Self {
593        self.session_store = Some(store);
594        self
595    }
596
597    /// Configures how compacted session history is retained in memory and on disk.
598    #[must_use]
599    pub fn history_retention(mut self, retention: HistoryRetention) -> Self {
600        self.history_retention = retention;
601        self
602    }
603
604    /// Installs a session that was already loaded by the runtime boundary.
605    #[must_use]
606    pub fn with_loaded_session(mut self, loaded: LoadedSession) -> Self {
607        self.loaded_session = Some(loaded.into_state());
608        self
609    }
610
611    /// Loads persisted session state from an injected filesystem store, then builds a runtime.
612    pub async fn resume_from_store(
613        mut self,
614        store: FileSessionStore,
615    ) -> Result<Runtime, RuntimeError> {
616        let session = SessionState::load_from(&store, &self.session_id).await?;
617        self.session_store = Some(store);
618        self.loaded_session = Some(session);
619        let runtime = self.build()?;
620        Ok(runtime)
621    }
622
623    /// Loads persisted state without replaying or restarting Plan execution.
624    pub async fn resume_from_store_without_automatic_savepoints(
625        mut self,
626        store: FileSessionStore,
627    ) -> Result<Runtime, RuntimeError> {
628        self.loaded_session = Some(SessionState::load_from(&store, &self.session_id).await?);
629        let runtime = self.build()?;
630        Ok(runtime)
631    }
632
633    /// Loads persisted session state without enabling automatic savepoints.
634    pub async fn load_session_from_store(
635        mut self,
636        store: FileSessionStore,
637    ) -> Result<Self, RuntimeError> {
638        self.loaded_session = Some(SessionState::load_from(&store, &self.session_id).await?);
639        Ok(self)
640    }
641
642    /// Attaches durable memory and freezes its index for this runtime.
643    ///
644    /// `maintain` schedules capture and one-shot dream after a completed parent
645    /// turn. Child runtimes keep the same store with maintenance disabled.
646    #[must_use]
647    pub fn durable_memory(mut self, memory: Arc<crate::DurableMemory>, maintain: bool) -> Self {
648        self.durable_memory = Some(memory);
649        self.memory_maintenance = maintain;
650        self
651    }
652
653    /// Builds the runtime.
654    ///
655    /// Duplicate tool names are rejected before the runtime is constructed.
656    pub fn build(self) -> Result<Runtime, RuntimeError> {
657        let mut registered_tools = self.registered_tools;
658        if self.coordinator_plan_tools {
659            registered_tools
660                .extend(coordinator_plan_registered_tools().map_err(RuntimeError::from)?);
661            registered_tools.push(todo_registered_tool().map_err(RuntimeError::from)?);
662        }
663        let tool_registry =
664            ToolRegistry::from_registered(registered_tools).map_err(|error| match error {
665                ToolRegistryError::DuplicateName { name } => {
666                    RuntimeError::DuplicateToolRegistration { name }
667                }
668                ToolRegistryError::ReservedName { name } => RuntimeError::ReservedToolName { name },
669                ToolRegistryError::InvalidToolInputSchema { name, message } => {
670                    RuntimeError::InvalidToolInputSchema { name, message }
671                }
672            })?;
673        if !self.allow_bridge_tools
674            && let Some(name) = tool_registry.first_bridge_tool_name()
675        {
676            return Err(RuntimeError::BridgeToolsNotAllowed { name: name.clone() });
677        }
678
679        let effective_subagent_scope = self.subagent_manager.as_ref().map(|_| {
680            self.subagent_parent_scope
681                .clone()
682                .unwrap_or_else(ChildWorkspaceScope::workspace_root)
683        });
684
685        let external_tool_catalog = tool_registry.external_tool_catalog()?;
686        let mut session = match self.loaded_session {
687            Some(mut session) => {
688                session.set_external_tool_catalog(external_tool_catalog);
689                session
690            }
691            None => {
692                let mut session = SessionState::with_external_tool_catalog(
693                    self.session_id.clone(),
694                    external_tool_catalog,
695                );
696                if let Some(checkpoint) = self.compacted_checkpoint {
697                    session.set_compacted_checkpoint(checkpoint);
698                }
699                session
700            }
701        };
702        if let Some(store) = self.session_store.as_ref() {
703            session.set_tracked_store_dir(store.sessions_dir().to_path_buf());
704        }
705        if session.session_id() != &self.session_id {
706            return Err(RuntimeError::SessionStore {
707                source: crate::SessionStoreError::SessionIdMismatch {
708                    requested: self.session_id.clone(),
709                    actual: session.session_id().clone(),
710                },
711            });
712        }
713        // Scope is runtime/session-specific dynamic context; keep it out of
714        // the stable provider prefix and out of the user task text.
715        if let Some(scope) = effective_subagent_scope.as_ref() {
716            let scope_text = scope.prompt_declaration();
717            session.reconcile_construction_context_seed(
718                SUBAGENT_WORKSPACE_SCOPE_CONTEXT_ID,
719                &scope_text,
720            )?;
721        }
722        for (id, text) in self.initial_context_summaries {
723            session.reconcile_construction_context_seed(&id, &text)?;
724        }
725        let trajectory =
726            RuntimeObservability::new(self.session_id.clone(), tool_registry.tool_specs());
727        trajectory.seed_prompt_profile(
728            &self.prompt_profile,
729            self.progress_commentary,
730            self.skill_catalog.as_ref(),
731            self.project_rules.as_ref(),
732        );
733        if let Some(project_rules) = self.project_rules {
734            session.set_project_rules(project_rules);
735        }
736        if let Some(skill_catalog) = self.skill_catalog {
737            session.set_skill_catalog(skill_catalog);
738        }
739        if let Some(task_anchor) = self.task_anchor {
740            session.set_task_anchor(task_anchor);
741        }
742
743        trajectory.seed_from_session(&session);
744
745        let memory_context = match &self.durable_memory {
746            Some(memory) => match memory.render_context() {
747                Ok(text) => Some(Arc::<str>::from(text)),
748                Err(error) => {
749                    tracing::warn!(
750                        error = %error,
751                        "durable memory context was not injected"
752                    );
753                    None
754                }
755            },
756            None => None,
757        };
758        let persisted_subagents = session.persisted_subagents().to_vec();
759        let session = Arc::new(Mutex::new(session));
760        let subagent_event_sink = crate::subagent::SubagentEventSink::new(
761            Arc::clone(&session),
762            self.session_store.clone(),
763            Arc::clone(&trajectory),
764            self.event_buffer_size.get().max(64),
765        );
766        let activity_hub = self.activity_hub;
767        let subagent_manager = self.subagent_manager;
768        if let Some(manager) = subagent_manager.as_ref() {
769            let allowed_tools = tool_registry
770                .tool_specs()
771                .into_iter()
772                .map(|spec| spec.name().clone())
773                .collect::<Vec<ToolName>>();
774            let parent_scope = effective_subagent_scope
775                .as_ref()
776                .expect("effective scope exists when a subagent manager is present")
777                .clone();
778            manager.attach_parent_capabilities(allowed_tools, parent_scope);
779            manager.attach_activity_hub(Arc::clone(&activity_hub));
780            manager.attach_event_sink(subagent_event_sink.clone());
781            if let Some(store) = self.session_store.as_ref() {
782                manager.attach_child_session_store(store.subagents_store(&self.session_id));
783            }
784            if !persisted_subagents.is_empty() {
785                manager.hydrate_persisted(persisted_subagents);
786            }
787            if let Some(primary) = self.model_configs.get(RuntimeModelRole::Primary) {
788                manager.update_parent_primary_model(crate::ParentPrimaryModel {
789                    provider: primary.provider(),
790                    model: primary.model().clone(),
791                    retry_policy: primary.retry_policy(),
792                });
793            }
794        }
795        Ok(Runtime {
796            inner: Arc::new(RuntimeInner {
797                session_id: self.session_id.clone(),
798                prompt_cache_key: self
799                    .prompt_cache_key
800                    .unwrap_or_else(|| self.session_id.clone()),
801                session,
802                active_step: Arc::new(AtomicBool::new(false)),
803                memory_projection_epoch: AtomicU64::new(0),
804                event_buffer_size: self.event_buffer_size,
805                max_parallel_tool_calls: std::sync::atomic::AtomicUsize::new(
806                    self.max_parallel_tool_calls.get(),
807                ),
808                model_configs: self.model_configs,
809                role_model_overrides: RwLock::new(std::collections::BTreeMap::new()),
810                automatic_compaction: RwLock::new(self.automatic_compaction),
811                history_retention: self.history_retention,
812                context_window_tokens: RwLock::new(None),
813                capabilities: self.capabilities,
814                prompt_profile: self.prompt_profile,
815                progress_commentary: self.progress_commentary,
816                tool_registry,
817                tool_admission: self.tool_admission,
818                memory_activation_source: self.memory_activation_source,
819                allow_low_risk_apply_patches: self.allow_low_risk_apply_patches,
820                low_risk_process_runner: self.low_risk_process_runner,
821                read_only_shell_process_runner: self.read_only_shell_process_runner,
822                accepted_local_workspace_process_runner: self
823                    .accepted_local_workspace_process_runner,
824                runtime_trust_level: self.runtime_trust_level,
825                permission_review_mode: RwLock::new(self.permission_review_mode),
826                permission_review_rules: self.permission_review_rules,
827                permission_review_workspace_root: self.permission_review_workspace_root,
828                permission_actor: self.permission_actor,
829                recorded_permission_decisions: RwLock::new(VecDeque::new()),
830                permission_admission_source: RwLock::new(self.permission_admission_source),
831                permissioned_process_runner_factory: self.permissioned_process_runner_factory,
832                background_process_control: self.background_process_control,
833                subagent_manager,
834                coordinator_plan_tools: self.coordinator_plan_tools,
835                session_store: self.session_store,
836                tool_batch_active: AtomicBool::new(false),
837                activity_hub,
838                subagent_event_sink,
839                trajectory,
840                durable_memory: self.durable_memory,
841                memory_maintenance: self.memory_maintenance,
842                memory_context,
843            }),
844        })
845    }
846}