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