Skip to main content

lash/
core.rs

1use crate::support::*;
2use lash_core::runtime::{
3    ProcessCommand, ProcessEffectOutcome, RuntimeEffectCommand, RuntimeEffectEnvelope,
4    RuntimeEffectKind, RuntimeEffectLocalExecutor, RuntimeEffectOutcome, RuntimeInvocation,
5    RuntimeScope,
6};
7
8#[derive(Clone)]
9pub struct LashCore {
10    pub(crate) env: RuntimeEnvironment,
11    pub(crate) policy: SessionPolicy,
12    pub(crate) modes: Arc<BTreeMap<ModeId, ModePreset>>,
13    pub(crate) default_mode: ModeId,
14    pub(crate) store_factory: Option<Arc<dyn SessionStoreFactory>>,
15    pub(crate) plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
16    pub(crate) provider: Option<ProviderHandle>,
17    pub(crate) live_replay_store: Arc<dyn LiveReplayStore>,
18    pub(crate) process_observer: Option<ProcessWorkObserver>,
19    /// Shared resolution of the process work runner. The poke it yields is
20    /// threaded onto every session's host so the process control seam can wake
21    /// the runner after a successful start. Shared across `LashCore` clones so
22    /// the default inline runner is spawned at most once (Decision 3).
23    pub(crate) process_work_runner: Arc<ProcessWorkRunnerSlot>,
24}
25
26/// How a [`LashCore`] resolves its process work runner, decided at `build()`
27/// and shared across clones.
28pub(crate) enum ProcessWorkRunnerSetup {
29    /// No process registry is wired; there is nothing to run and no poke.
30    None,
31    /// Lazily spawn the default inline [`ProcessWorkRunner`] on first
32    /// `session().open()` (Decision 3: the runtime is guaranteed by then, and
33    /// `build()` is sync — some tests call it outside a tokio runtime). A store
34    /// factory is required to build the config (the worker rebuilds a session
35    /// runtime per process); a registry with no store factory is rejected at
36    /// build with [`EmbedError::ProcessRegistryRequiresStoreFactory`].
37    LazyDefault {
38        config: Box<DurableProcessWorkerConfig>,
39    },
40    /// The host wired an external runner (e.g. the Restate ingress-client
41    /// runner) and handed its driver to the core.
42    External { driver: ProcessWorkDriver },
43}
44
45#[derive(Clone, Default)]
46pub(crate) enum ProcessWorkSource {
47    #[default]
48    None,
49    Inline {
50        registry: Arc<dyn ProcessRegistry>,
51    },
52    External(ProcessWorkDriver),
53}
54
55impl ProcessWorkSource {
56    fn process_registry(&self) -> Option<Arc<dyn ProcessRegistry>> {
57        match self {
58            Self::None => None,
59            Self::Inline { registry } => Some(Arc::clone(registry)),
60            Self::External(driver) => Some(driver.process_registry()),
61        }
62    }
63
64    fn has_registry(&self) -> bool {
65        !matches!(self, Self::None)
66    }
67}
68
69/// Shared, lazily-initialized process-work-runner state for a [`LashCore`].
70///
71/// The once-guard ([`tokio::sync::OnceCell`]) makes the default inline runner
72/// spawn exactly once across `LashCore` clones, on the first `session().open()`
73/// that needs it. The resolved [`ProcessWorkPoke`] (if any) is then reused for
74/// every session host.
75pub(crate) struct ProcessWorkRunnerSlot {
76    setup: ProcessWorkRunnerSetup,
77    poke: tokio::sync::OnceCell<Option<ProcessWorkPoke>>,
78}
79
80impl ProcessWorkRunnerSlot {
81    fn new(setup: ProcessWorkRunnerSetup) -> Self {
82        Self {
83            setup,
84            poke: tokio::sync::OnceCell::new(),
85        }
86    }
87
88    /// Resolve the poke for a session host, spawning the default inline runner
89    /// on first use. Idempotent: the once-guard ensures a single spawn.
90    pub(crate) async fn poke(&self) -> Option<ProcessWorkPoke> {
91        self.poke
92            .get_or_init(|| async {
93                match &self.setup {
94                    ProcessWorkRunnerSetup::None => None,
95                    ProcessWorkRunnerSetup::External { driver } => Some(driver.poke_handle()),
96                    ProcessWorkRunnerSetup::LazyDefault { config } => {
97                        let worker = DurableProcessWorker::new((**config).clone());
98                        Some(ProcessWorkRunner::inline(worker).spawn())
99                    }
100                }
101            })
102            .await
103            .clone()
104    }
105}
106
107#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
108pub struct SessionDeleteReport {
109    pub session_id: String,
110    pub process: Option<lash_core::ProcessSessionDeleteReport>,
111}
112
113impl LashCore {
114    pub fn builder() -> LashCoreBuilder {
115        LashCoreBuilder::default()
116    }
117
118    /// Preset for `standard` mode.
119    ///
120    /// Storage and effect durability are still host-owned choices. Provide the
121    /// effect host, Lashlang artifact store, and attachment store facets with
122    /// the builder setters before calling [`LashCoreBuilder::build`].
123    pub fn standard() -> LashCoreBuilder {
124        Self::builder()
125            .install_mode(ModePreset::standard())
126            .default_mode(ModeId::standard())
127            .plugins(default_runtime_stack())
128    }
129
130    /// Preset for `rlm` mode.
131    ///
132    /// Storage and effect durability are still host-owned choices. Provide the
133    /// effect host, Lashlang artifact store, and attachment store facets with
134    /// the builder setters before calling [`LashCoreBuilder::build`].
135    pub fn rlm() -> LashCoreBuilder {
136        Self::builder()
137            .install_mode(ModePreset::rlm())
138            .default_mode(ModeId::rlm())
139            .plugins(default_runtime_stack())
140    }
141
142    pub fn session(&self, session_id: impl Into<String>) -> SessionBuilder {
143        SessionBuilder {
144            core: self.clone(),
145            session_id: session_id.into(),
146            spec: SessionSpec::inherit(),
147            mode: None,
148            parent_session_id: None,
149            store: None,
150            provider: None,
151            active_plugins: Vec::new(),
152            plugin_factories: Vec::new(),
153            rlm_final_answer_format: None,
154        }
155    }
156
157    pub fn host_events(&self) -> crate::control::HostEventsControl {
158        crate::control::HostEventsControl { core: self.clone() }
159    }
160
161    pub fn effect_host(&self) -> Arc<dyn EffectHost> {
162        Arc::clone(&self.env.core.control.effect_host)
163    }
164
165    pub async fn delete_session(
166        &self,
167        session_id: impl AsRef<str>,
168        scoped_effect_controller: ScopedEffectController<'_>,
169    ) -> Result<SessionDeleteReport> {
170        let session_id = session_id.as_ref().to_string();
171        let Some(store_factory) = self.store_factory.as_ref() else {
172            return Err(EmbedError::MissingSessionStoreFactory);
173        };
174        let process = if let Some(process_registry) = self.env.process_registry.as_ref() {
175            let invocation = RuntimeInvocation::effect(
176                RuntimeScope::new(session_id.clone()),
177                format!("process:delete-session:{session_id}"),
178                RuntimeEffectKind::Process,
179                format!("{session_id}:delete-session"),
180            );
181            let outcome = scoped_effect_controller
182                .controller()
183                .execute_effect(
184                    RuntimeEffectEnvelope::new(
185                        invocation,
186                        RuntimeEffectCommand::Process {
187                            command: ProcessCommand::DeleteSession {
188                                session_id: session_id.clone(),
189                            },
190                        },
191                    ),
192                    RuntimeEffectLocalExecutor::process_control(Arc::clone(process_registry)),
193                )
194                .await
195                .map_err(|err| EmbedError::SessionDeleteProcess {
196                    session_id: session_id.clone(),
197                    message: err.to_string(),
198                })?;
199            match outcome {
200                RuntimeEffectOutcome::Process {
201                    result: ProcessEffectOutcome::DeleteSession { report },
202                } => Some(report),
203                other => {
204                    return Err(EmbedError::SessionDeleteProcess {
205                        session_id,
206                        message: format!(
207                            "process delete returned the wrong outcome: {}",
208                            other.kind().as_str()
209                        ),
210                    });
211                }
212            }
213        } else {
214            None
215        };
216        store_factory
217            .delete_session(&session_id)
218            .await
219            .map_err(|message| EmbedError::StoreFactory {
220                session_id: session_id.clone(),
221                message,
222            })?;
223        Ok(SessionDeleteReport {
224            session_id,
225            process,
226        })
227    }
228
229    pub fn installed_modes(&self) -> impl Iterator<Item = &ModeId> {
230        self.modes.keys()
231    }
232
233    pub fn process_observer(&self) -> Option<&ProcessWorkObserver> {
234        self.process_observer.as_ref()
235    }
236
237    pub fn process_registry(&self) -> Option<Arc<dyn ProcessRegistry>> {
238        self.env.process_registry.as_ref().cloned()
239    }
240
241    pub fn durable_process_worker_config(&self) -> Result<DurableProcessWorkerConfig> {
242        self.durable_process_worker_config_with_plugins(std::iter::empty::<Arc<dyn PluginFactory>>())
243    }
244
245    pub fn durable_process_worker_config_with_plugins(
246        &self,
247        extra_plugin_factories: impl IntoIterator<Item = Arc<dyn PluginFactory>>,
248    ) -> Result<DurableProcessWorkerConfig> {
249        let Some(process_registry) = self.process_registry() else {
250            return Err(EmbedError::MissingProcessRegistry);
251        };
252        let Some(store_factory) = self.store_factory.as_ref() else {
253            return Err(EmbedError::MissingProcessWorkerStoreFactory);
254        };
255        let plugin_host = build_plugin_host_for_mode(
256            &self.modes,
257            &self.default_mode,
258            self.plugin_factories.as_ref(),
259            extra_plugin_factories.into_iter().collect(),
260            true,
261        )?;
262        Ok(DurableProcessWorkerConfig::new(
263            Arc::new(plugin_host),
264            self.env.core.clone(),
265            Arc::clone(store_factory),
266            process_registry,
267        )
268        .with_session_policy(self.policy.clone())
269        .with_residency(self.env.residency))
270    }
271}
272
273fn default_runtime_stack() -> PluginStack {
274    lash_plugin_tool_output_budget::tool_output_budget_stack()
275}
276
277#[derive(Default)]
278pub struct LashCoreBuilder {
279    pub(crate) modes: BTreeMap<ModeId, ModePreset>,
280    pub(crate) default_mode: Option<ModeId>,
281    session_spec: SessionSpec,
282    provider: Option<ProviderHandle>,
283    pub(crate) store_factory: Option<Arc<dyn SessionStoreFactory>>,
284    child_store_factory: Option<Arc<dyn SessionStoreFactory>>,
285    // `RuntimeHostConfig` has no `Default`: the three host-owned durability
286    // dependencies must be named. They are collected here and resolved in
287    // `build()`, which errors if any is unset.
288    effect_host: Option<Arc<dyn EffectHost>>,
289    attachment_store: Option<Arc<dyn AttachmentStore>>,
290    lashlang_artifact_store: Option<Arc<dyn lash_core::LashlangArtifactStore>>,
291    host_event_store: Option<Arc<dyn lash_core::HostEventStore>>,
292    // Benign core overrides applied on top of the resolved core.
293    prompt: Option<PromptLayer>,
294    trace_sink: Option<Arc<dyn lash_trace::TraceSink>>,
295    lashlang_execution_sink: Option<Arc<dyn lash_trace::TraceSink>>,
296    trace_level: Option<lash_trace::TraceLevel>,
297    trace_context: Option<lash_trace::TraceContext>,
298    termination: Option<TerminationPolicy>,
299    // Advanced full-config override; used as the base core when present.
300    runtime_host_config: Option<RuntimeHostConfig>,
301    tool_providers: Vec<Arc<dyn ToolProvider>>,
302    plugin_stack: PluginStack,
303    plugin_host: Option<PluginHost>,
304    residency: Option<Residency>,
305    // Single source of truth for process lifecycle support and process-work
306    // consumption.
307    process_work_source: ProcessWorkSource,
308    queued_work_poke: Option<QueuedWorkPoke>,
309    live_replay_store: Option<Arc<dyn LiveReplayStore>>,
310}
311
312impl LashCoreBuilder {
313    pub fn install_mode(mut self, preset: ModePreset) -> Self {
314        let mode_id = preset.mode_id.clone();
315        if self.default_mode.is_none() {
316            self.default_mode = Some(mode_id.clone());
317        }
318        self.modes.insert(mode_id, preset);
319        self
320    }
321
322    pub fn default_mode(mut self, mode: ModeId) -> Self {
323        self.default_mode = Some(mode);
324        self
325    }
326
327    pub fn mode(mut self, mode: ModeId) -> Self {
328        self.default_mode = Some(mode);
329        self
330    }
331
332    pub fn provider(mut self, provider: ProviderHandle) -> Self {
333        self.session_spec = self.session_spec.provider_id(provider.kind());
334        self.provider = Some(provider);
335        self
336    }
337
338    pub fn model(mut self, model: lash_core::ModelSpec) -> Self {
339        self.session_spec = self.session_spec.model(model);
340        self
341    }
342
343    pub fn max_turns(mut self, max_turns: usize) -> Self {
344        self.session_spec = self.session_spec.max_turns(max_turns);
345        self
346    }
347
348    pub fn session_spec(mut self, spec: SessionSpec) -> Self {
349        self.session_spec = spec;
350        self
351    }
352
353    /// Configure a factory that can create a persistence store for any root
354    /// session opened from this core.
355    ///
356    /// The factory must honor `SessionStoreCreateRequest::session_id` and
357    /// return a store for that specific session. Do not use this to wrap one
358    /// pre-opened root store; pass root-only stores with
359    /// `LashCore::session(...).store(store)` instead.
360    pub fn store_factory(mut self, store_factory: Arc<dyn SessionStoreFactory>) -> Self {
361        self.store_factory = Some(store_factory);
362        self
363    }
364
365    /// Configure the persistence factory used by managed child sessions, such
366    /// as local subagents.
367    ///
368    /// Child factories must return a distinct store bound to the requested
369    /// child session id. Hosts that pass an explicit root store with
370    /// `SessionBuilder::store` should set this when child sessions need
371    /// persistence.
372    pub fn child_store_factory(mut self, store_factory: Arc<dyn SessionStoreFactory>) -> Self {
373        self.child_store_factory = Some(store_factory);
374        self
375    }
376
377    pub fn attachment_store(mut self, attachment_store: Arc<dyn AttachmentStore>) -> Self {
378        self.attachment_store = Some(attachment_store);
379        self
380    }
381
382    /// Set the deployment-level Lashlang artifact store (compiled module
383    /// cache, shared across the session tree). A durable store such as
384    /// `lash_sqlite_store::Store` implements it.
385    pub fn lashlang_artifact_store(
386        mut self,
387        artifact_store: Arc<dyn lash_core::LashlangArtifactStore>,
388    ) -> Self {
389        self.lashlang_artifact_store = Some(artifact_store);
390        self
391    }
392
393    /// Set the deployment effect host — the durability boundary every operation
394    /// crosses. Pass [`InlineEffectHost`](crate::durability::InlineEffectHost)
395    /// for in-process execution, or a workflow-backed host for durable
396    /// execution.
397    pub fn effect_host(mut self, effect_host: Arc<dyn EffectHost>) -> Self {
398        self.effect_host = Some(effect_host);
399        self
400    }
401
402    pub fn tools(mut self, tools: Arc<dyn ToolProvider>) -> Self {
403        self.tool_providers.push(tools);
404        self
405    }
406
407    pub fn plugin(mut self, plugin: Arc<dyn PluginFactory>) -> Self {
408        self.plugin_stack.push(plugin);
409        self
410    }
411
412    pub fn plugins(mut self, stack: PluginStack) -> Self {
413        self.plugin_stack = stack;
414        self
415    }
416
417    pub fn configure_plugins(mut self, configure: impl FnOnce(&mut PluginStack)) -> Self {
418        configure(&mut self.plugin_stack);
419        self
420    }
421
422    pub fn trace_sink(mut self, trace_sink: Option<Arc<dyn lash_trace::TraceSink>>) -> Self {
423        self.trace_sink = trace_sink;
424        self
425    }
426
427    pub fn trace_jsonl_path(mut self, path: Option<std::path::PathBuf>) -> Self {
428        self.trace_sink = path.map(|path| {
429            Arc::new(lash_trace::JsonlTraceSink::new(path)) as Arc<dyn lash_trace::TraceSink>
430        });
431        self
432    }
433
434    pub fn lashlang_execution_sink(
435        mut self,
436        lashlang_execution_sink: Option<Arc<dyn lash_trace::TraceSink>>,
437    ) -> Self {
438        self.lashlang_execution_sink = lashlang_execution_sink;
439        self
440    }
441
442    pub fn lashlang_execution_jsonl_path(mut self, path: Option<std::path::PathBuf>) -> Self {
443        self.lashlang_execution_sink = path.map(|path| {
444            Arc::new(lash_trace::JsonlTraceSink::new(path)) as Arc<dyn lash_trace::TraceSink>
445        });
446        self
447    }
448
449    pub fn trace_level(mut self, trace_level: lash_trace::TraceLevel) -> Self {
450        self.trace_level = Some(trace_level);
451        self
452    }
453
454    pub fn trace_context(mut self, trace_context: lash_trace::TraceContext) -> Self {
455        self.trace_context = Some(trace_context);
456        self
457    }
458
459    pub fn termination(mut self, termination: TerminationPolicy) -> Self {
460        self.termination = Some(termination);
461        self
462    }
463
464    pub fn residency(mut self, residency: Residency) -> Self {
465        self.residency = Some(residency);
466        self
467    }
468
469    /// Configure the bounded live replay buffer used by session observation
470    /// cursors. This is best-effort reconnect recovery only; durable state
471    /// still comes from the session store and [`SessionReadView`].
472    pub fn live_replay_store(mut self, live_replay_store: Arc<dyn LiveReplayStore>) -> Self {
473        self.live_replay_store = Some(live_replay_store);
474        self
475    }
476
477    /// Resolve the runtime host config, requiring the three host-owned
478    /// durability dependencies to have been named.
479    fn resolve_runtime_host_config(&mut self) -> Result<RuntimeHostConfig> {
480        if let Some(base) = self.runtime_host_config.take() {
481            return Ok(self.apply_core_overrides(base));
482        }
483        let effect_host = self
484            .effect_host
485            .take()
486            .ok_or(EmbedError::MissingEffectHost)?;
487        let lashlang_artifact_store = self
488            .lashlang_artifact_store
489            .take()
490            .ok_or(EmbedError::MissingLashlangArtifactStore)?;
491        let attachment_store = self
492            .attachment_store
493            .take()
494            .ok_or(EmbedError::MissingAttachmentStore)?;
495        let core = RuntimeHostConfig::new(effect_host, lashlang_artifact_store, attachment_store);
496        Ok(self.apply_core_overrides(core))
497    }
498
499    /// Apply benign + still-set dependency overrides on top of a base core.
500    fn apply_core_overrides(&mut self, mut core: RuntimeHostConfig) -> RuntimeHostConfig {
501        if let Some(effect_host) = self.effect_host.take() {
502            core.control.effect_host = effect_host;
503        }
504        if let Some(attachment_store) = self.attachment_store.take() {
505            core.durability.attachment_store = attachment_store;
506        }
507        if let Some(artifact_store) = self.lashlang_artifact_store.take() {
508            core.durability.lashlang_artifact_store = artifact_store;
509        }
510        if let Some(prompt) = self.prompt.take() {
511            core.prompt.prompt = prompt;
512        }
513        if let Some(trace_sink) = self.trace_sink.take() {
514            core.tracing.trace_sink = Some(trace_sink);
515        }
516        if let Some(lashlang_execution_sink) = self.lashlang_execution_sink.take() {
517            core.tracing.lashlang_execution_sink = Some(lashlang_execution_sink);
518        }
519        if let Some(trace_level) = self.trace_level.take() {
520            core.tracing.trace_level = trace_level;
521        }
522        if let Some(trace_context) = self.trace_context.take() {
523            core.tracing.trace_context = trace_context;
524        }
525        if let Some(termination) = self.termination.take() {
526            core.control.termination = termination;
527        }
528        core
529    }
530
531    /// Validate store peer-coherence of the wired durability dependencies.
532    ///
533    /// Durability is established by what the host wired; the per-invocation
534    /// durable controller is not visible here (the build-time controller is
535    /// inline by construction), so this checks the stores against each other
536    /// only — never the controller (see A5 in the durable-first wiring spec):
537    ///
538    /// - a durable session store factory requires a durable attachment and
539    ///   artifact store (they back the same session state);
540    /// - a durable process registry requires a session store factory that is
541    ///   itself durable (the registry's process records are meaningless without
542    ///   a durable session behind them).
543    fn ensure_store_peer_coherence(&self) -> Result<()> {
544        // Match `build()`'s wiring exactly: the session store factory it installs
545        // is `child_store_factory.or(store_factory)` (child takes precedence, root
546        // is the fallback). The coherence check must read the tier of that same
547        // effective factory, or a host that wires only a durable child factory
548        // (no root) is wrongly rejected though `build()` would wire it durably.
549        let session_store_tier = self
550            .child_store_factory
551            .as_ref()
552            .or(self.store_factory.as_ref())
553            .map(|factory| factory.durability_tier());
554        let attachment_tier = self
555            .attachment_store
556            .as_ref()
557            .map(|store| store.persistence().durability_tier());
558        let artifact_tier = self
559            .lashlang_artifact_store
560            .as_ref()
561            .map(|store| store.durability_tier());
562        let host_event_store_tier = self
563            .host_event_store
564            .as_ref()
565            .map(|store| store.durability_tier());
566
567        if session_store_tier == Some(DurabilityTier::Durable) {
568            if attachment_tier == Some(DurabilityTier::Inline) {
569                return Err(EmbedError::DurableStorePeerRequired {
570                    facet: "attachment store",
571                });
572            }
573            if artifact_tier == Some(DurabilityTier::Inline) {
574                return Err(EmbedError::DurableStorePeerRequired {
575                    facet: "artifact store",
576                });
577            }
578        }
579
580        if let Some(process_registry) = self.process_work_source.process_registry().as_ref() {
581            if process_registry.durability_tier() == DurabilityTier::Durable {
582                if session_store_tier != Some(DurabilityTier::Durable) {
583                    return Err(EmbedError::DurableProcessRegistryRequiresStoreFactory);
584                }
585                if host_event_store_tier != Some(DurabilityTier::Durable) {
586                    return Err(EmbedError::DurableStorePeerRequired {
587                        facet: "host event store",
588                    });
589                }
590            }
591        }
592
593        if host_event_store_tier == Some(DurabilityTier::Durable) {
594            if session_store_tier != Some(DurabilityTier::Durable) {
595                return Err(EmbedError::DurableStorePeerRequired {
596                    facet: "session store factory",
597                });
598            }
599            if let Some(process_registry) = self.process_work_source.process_registry().as_ref()
600                && process_registry.durability_tier() == DurabilityTier::Inline
601            {
602                return Err(EmbedError::DurableStorePeerRequired {
603                    facet: "process registry",
604                });
605            }
606        }
607
608        Ok(())
609    }
610
611    pub fn build(mut self) -> Result<LashCore> {
612        if self.modes.is_empty() {
613            return Err(EmbedError::NoModesInstalled);
614        }
615        self.ensure_store_peer_coherence()?;
616        let default_mode = self
617            .default_mode
618            .clone()
619            .ok_or(EmbedError::NoModesInstalled)?;
620        if !self.modes.contains_key(&default_mode) {
621            return Err(EmbedError::DefaultModeNotInstalled { mode: default_mode });
622        }
623        let provider_id = self
624            .session_spec
625            .provider_id
626            .clone()
627            .or_else(|| {
628                self.provider
629                    .as_ref()
630                    .map(|provider| provider.kind().to_string())
631            })
632            .unwrap_or_default();
633        let model = self
634            .session_spec
635            .model
636            .clone()
637            .ok_or(EmbedError::MissingModelSpec)?;
638
639        let base_policy = SessionPolicy {
640            provider_id,
641            model,
642            max_turns: self.session_spec.max_turns.flatten(),
643            ..SessionPolicy::default()
644        };
645        let policy = self.session_spec.resolve_against(&base_policy);
646
647        let mut core = self.resolve_runtime_host_config()?;
648        if let Some(provider) = self.provider.clone() {
649            core.providers.provider_resolver =
650                Arc::new(lash_core::SingleProviderResolver::new(provider));
651        }
652
653        let plugin_factories = if let Some(plugin_host) = self.plugin_host {
654            plugin_host.factories().to_vec()
655        } else {
656            let mut factories = Vec::new();
657            if !self.tool_providers.is_empty() {
658                let spec = self
659                    .tool_providers
660                    .into_iter()
661                    .fold(PluginSpec::new(), PluginSpec::with_tool_provider);
662                factories.push(Arc::new(StaticPluginFactory::new("embed_tools", spec))
663                    as Arc<dyn PluginFactory>);
664            }
665            factories.extend(self.plugin_stack.into_factories());
666            factories
667        };
668        let default_plugin_host = build_plugin_host_for_mode(
669            &self.modes,
670            &default_mode,
671            &plugin_factories,
672            Vec::new(),
673            self.process_work_source.has_registry(),
674        )?;
675
676        let process_registry = self.process_work_source.process_registry();
677
678        // Resolve the process work runner before the process source is moved
679        // into the environment. The default inline runner's config is built
680        // eagerly so a missing store factory fails loudly at build, not at
681        // first open. It is built from the *default-mode* plugin host (preset
682        // protocol plugin + process-lifecycle abilities), the same host the
683        // live runtime uses, so the worker can rebuild a runtime for a
684        // default-mode process.
685        let process_work_runner = Self::resolve_process_work_runner(
686            &self.process_work_source,
687            &default_plugin_host,
688            &core,
689            // The worker rebuilds sessions with the same factory `build()` wires
690            // below: `child_store_factory.or(store_factory)`.
691            self.child_store_factory
692                .as_ref()
693                .or(self.store_factory.as_ref()),
694            &policy,
695            self.residency.unwrap_or_default(),
696            self.host_event_store.as_ref(),
697        )?;
698
699        let mut env_builder = RuntimeEnvironment::builder()
700            .with_plugin_host(Arc::new(default_plugin_host))
701            .with_runtime_host_config(core);
702        if let Some(process_registry) = process_registry.as_ref() {
703            env_builder = env_builder.with_process_registry(Arc::clone(process_registry));
704        }
705        if let Some(residency) = self.residency {
706            env_builder = env_builder.with_residency(residency);
707        }
708        if let Some(child_store_factory) = self
709            .child_store_factory
710            .as_ref()
711            .or(self.store_factory.as_ref())
712        {
713            env_builder = env_builder.with_session_store_factory(Arc::clone(child_store_factory));
714        }
715        if let Some(host_event_store) = self.host_event_store.as_ref() {
716            env_builder = env_builder.with_host_event_store(Arc::clone(host_event_store));
717        }
718        if let Some(queued_work_poke) = self.queued_work_poke.clone() {
719            env_builder = env_builder.with_queued_work_poke(queued_work_poke);
720        }
721
722        let live_replay_store = self
723            .live_replay_store
724            .take()
725            .unwrap_or_else(|| Arc::new(InMemoryLiveReplayStore::default()));
726
727        Ok(LashCore {
728            env: env_builder.build(),
729            policy,
730            modes: Arc::new(self.modes),
731            default_mode,
732            store_factory: self.store_factory,
733            plugin_factories: Arc::new(plugin_factories),
734            provider: self.provider,
735            live_replay_store,
736            process_observer: process_registry.map(ProcessWorkObserver::new),
737            process_work_runner: Arc::new(ProcessWorkRunnerSlot::new(process_work_runner)),
738        })
739    }
740
741    /// Decide how a built [`LashCore`] sources its process work runner.
742    ///
743    /// - no registry => nothing to run ([`ProcessWorkRunnerSetup::None`]);
744    /// - external driver wired => use it ([`ProcessWorkRunnerSetup::External`]);
745    /// - inline registry wired => lazily spawn the default inline runner on first open. Its
746    ///   [`DurableProcessWorkerConfig`] is built eagerly when a store factory is
747    ///   present; without one the inline worker cannot rebuild session runtimes.
748    fn resolve_process_work_runner(
749        process_work_source: &ProcessWorkSource,
750        worker_plugin_host: &PluginHost,
751        core: &RuntimeHostConfig,
752        store_factory: Option<&Arc<dyn SessionStoreFactory>>,
753        policy: &SessionPolicy,
754        residency: lash_core::Residency,
755        host_event_store: Option<&Arc<dyn lash_core::HostEventStore>>,
756    ) -> Result<ProcessWorkRunnerSetup> {
757        let process_registry = match process_work_source {
758            ProcessWorkSource::None => return Ok(ProcessWorkRunnerSetup::None),
759            ProcessWorkSource::External(driver) => {
760                return Ok(ProcessWorkRunnerSetup::External {
761                    driver: driver.clone(),
762                });
763            }
764            ProcessWorkSource::Inline { registry } => Arc::clone(registry),
765        };
766        // The worker rebuilds a session runtime per process, so it needs a store
767        // factory; without one the default runner could not execute anything, so
768        // fail loudly rather than silently leave processes unexecuted.
769        let Some(store_factory) = store_factory else {
770            return Err(EmbedError::ProcessRegistryRequiresStoreFactory);
771        };
772        // The worker rebuilds with the *same* plugin host the live runtime uses
773        // for the default mode — including the mode preset's protocol plugin
774        // (which supplies the protocol session capability) and the
775        // process-lifecycle abilities. The bare builder `plugin_factories` omit
776        // the preset factory (added per-mode by `build_plugin_host_for_mode`), so
777        // a worker built from them would fail to rebuild a runtime ("missing
778        // protocol session capability").
779        let config = Box::new(
780            DurableProcessWorkerConfig::new(
781                Arc::new(worker_plugin_host.clone()),
782                core.clone(),
783                Arc::clone(store_factory),
784                process_registry,
785            )
786            .with_session_policy(policy.clone())
787            .with_host_event_store(
788                host_event_store
789                    .cloned()
790                    .unwrap_or_else(|| Arc::new(lash_core::InMemoryHostEventStore::default())),
791            )
792            .with_residency(residency),
793        );
794        Ok(ProcessWorkRunnerSetup::LazyDefault { config })
795    }
796
797    pub fn advanced(self) -> AdvancedLashCoreBuilder {
798        AdvancedLashCoreBuilder { builder: self }
799    }
800
801    pub fn process_registry(mut self, process_registry: Arc<dyn ProcessRegistry>) -> Self {
802        self.process_work_source = ProcessWorkSource::Inline {
803            registry: process_registry,
804        };
805        self
806    }
807
808    pub fn host_event_store(mut self, store: Arc<dyn lash_core::HostEventStore>) -> Self {
809        self.host_event_store = Some(store);
810        self
811    }
812
813    /// Configure an externally owned process work runner.
814    ///
815    /// Durable hosts construct a [`ProcessWorkDriver`] from the same process
816    /// registry and wake handle used by their deployment runner, then pass it
817    /// here. The driver registry becomes the core's process registry and no
818    /// inline runner is spawned.
819    pub fn process_work_driver(mut self, driver: ProcessWorkDriver) -> Self {
820        self.process_work_source = ProcessWorkSource::External(driver);
821        self
822    }
823
824    pub fn with_queued_work_runner(mut self, poke: QueuedWorkPoke) -> Self {
825        self.queued_work_poke = Some(poke);
826        self
827    }
828}
829
830pub(crate) fn build_plugin_host_for_mode(
831    modes: &BTreeMap<ModeId, ModePreset>,
832    mode: &ModeId,
833    common_factories: &[Arc<dyn PluginFactory>],
834    extra_factories: Vec<Arc<dyn PluginFactory>>,
835    process_lifecycle: bool,
836) -> Result<PluginHost> {
837    let preset = modes
838        .get(mode)
839        .ok_or_else(|| EmbedError::ModeNotInstalled { mode: mode.clone() })?;
840    let mut factories = Vec::with_capacity(1 + common_factories.len() + extra_factories.len());
841    factories.push(Arc::clone(&preset.factory));
842    factories.extend(common_factories.iter().cloned());
843    factories.extend(extra_factories);
844    let mut plugin_host = PluginHost::new(factories);
845    if process_lifecycle {
846        let abilities = plugin_host
847            .lashlang_abilities()
848            .with_processes()
849            .with_sleep()
850            .with_process_signals();
851        plugin_host = plugin_host.with_lashlang_abilities(abilities);
852    }
853    Ok(plugin_host)
854}
855
856impl PromptLayerSink for LashCoreBuilder {
857    fn prompt_layer_mut(&mut self) -> &mut PromptLayer {
858        self.prompt.get_or_insert_with(PromptLayer::new)
859    }
860}
861
862pub struct AdvancedLashCoreBuilder {
863    builder: LashCoreBuilder,
864}
865
866impl AdvancedLashCoreBuilder {
867    pub fn runtime_host_config(mut self, core: lash_core::RuntimeHostConfig) -> Self {
868        self.builder.runtime_host_config = Some(core);
869        self
870    }
871
872    pub fn plugin_host(mut self, plugin_host: PluginHost) -> Self {
873        self.builder.plugin_host = Some(plugin_host);
874        self
875    }
876
877    pub fn build(self) -> Result<LashCore> {
878        self.builder.build()
879    }
880}