Skip to main content

merry_runtime/runtime/
builder.rs

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