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
8type RuntimeHostInstaller =
9    Arc<dyn Fn(RuntimeHostConfig, &PluginHost) -> Result<RuntimeHostConfig> + Send + Sync>;
10
11#[derive(Clone)]
12pub struct LashCore {
13    pub(crate) env: RuntimeEnvironment,
14    pub(crate) policy: SessionPolicy,
15    pub(crate) protocol_factory: Option<Arc<dyn PluginFactory>>,
16    pub(crate) store_factory: Option<Arc<dyn SessionStoreFactory>>,
17    pub(crate) plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
18    pub(crate) provider: Option<ProviderHandle>,
19    pub(crate) live_replay_store: Arc<dyn LiveReplayStore>,
20    pub(crate) runtime_host_installer: Option<RuntimeHostInstaller>,
21    /// Shared resolution of host-owned work drivers. Shared across `LashCore`
22    /// clones so inline process and queued drivers are constructed at most once.
23    pub(crate) work_driver: Arc<InlineWorkDriverSlot>,
24}
25
26/// How a [`LashCore`] resolves its process work driver, decided at `build()`
27/// and shared across clones.
28pub(crate) enum ProcessWorkDriverSetup {
29    /// No process registry is wired; there is nothing to run.
30    None,
31    /// Lazily construct the default inline process driver on first
32    /// `session().open()`. A store factory is required to build the config (the
33    /// worker rebuilds a session runtime per process); a registry with no store
34    /// factory is rejected at build with
35    /// [`EmbedError::ProcessRegistryRequiresStoreFactory`].
36    LazyDefault {
37        config: Box<DurableProcessWorkerConfig>,
38    },
39    /// The host wired an external driver.
40    External { driver: ProcessWorkDriver },
41}
42
43#[derive(Clone, Default)]
44pub(crate) enum ProcessWorkSource {
45    #[default]
46    None,
47    Inline {
48        registry: Arc<dyn ProcessRegistry>,
49    },
50    External(ProcessWorkDriver),
51}
52
53impl ProcessWorkSource {
54    fn process_registry(&self) -> Option<Arc<dyn ProcessRegistry>> {
55        match self {
56            Self::None => None,
57            Self::Inline { registry } => Some(Arc::clone(registry)),
58            Self::External(driver) => Some(driver.process_registry()),
59        }
60    }
61
62    #[cfg(feature = "rlm")]
63    fn has_registry(&self) -> bool {
64        !matches!(self, Self::None)
65    }
66}
67
68#[derive(Clone, Default)]
69pub(crate) enum QueuedWorkSource {
70    None,
71    #[default]
72    LazyDefault,
73    External(QueuedWorkDriver),
74}
75
76pub(crate) enum QueuedWorkDriverSetup {
77    None,
78    LazyDefault {
79        config: Arc<InlineQueuedWorkRunConfig>,
80    },
81    External {
82        driver: QueuedWorkDriver,
83    },
84}
85
86pub(crate) struct InlineWorkDriverSetup {
87    process: ProcessWorkDriverSetup,
88    queued: QueuedWorkDriverSetup,
89}
90
91#[derive(Clone, Default)]
92pub(crate) struct ResolvedWorkDrivers {
93    pub(crate) process: Option<ProcessWorkDriver>,
94    pub(crate) queued: Option<QueuedWorkDriver>,
95    pub(crate) drive_process_on_open: bool,
96}
97
98/// Shared, lazily-initialized host-work state for a [`LashCore`].
99///
100/// The once-guard ([`tokio::sync::OnceCell`]) constructs inline drivers exactly
101/// once across `LashCore` clones, on the first `session().open()` or admin path
102/// that needs them.
103pub(crate) struct InlineWorkDriverSlot {
104    setup: InlineWorkDriverSetup,
105    drivers: tokio::sync::OnceCell<ResolvedWorkDrivers>,
106    phase_probe_slot: Option<lash_core::runtime::RuntimeTurnPhaseProbeSlot>,
107}
108
109impl InlineWorkDriverSlot {
110    fn new(setup: InlineWorkDriverSetup) -> Self {
111        let phase_probe_slot = match &setup.process {
112            ProcessWorkDriverSetup::LazyDefault { config } => {
113                Some(config.turn_phase_probe_slot.clone())
114            }
115            ProcessWorkDriverSetup::None | ProcessWorkDriverSetup::External { .. } => None,
116        };
117        Self {
118            setup,
119            drivers: tokio::sync::OnceCell::new(),
120            phase_probe_slot,
121        }
122    }
123
124    /// Resolve host work drivers for a session host. Idempotent: the once-guard
125    /// ensures inline drivers are constructed once.
126    pub(crate) async fn drivers(&self) -> ResolvedWorkDrivers {
127        self.drivers
128            .get_or_init(|| async {
129                let queued = match &self.setup.queued {
130                    QueuedWorkDriverSetup::None => None,
131                    QueuedWorkDriverSetup::External { driver } => Some(driver.clone()),
132                    QueuedWorkDriverSetup::LazyDefault { config } => Some(QueuedWorkDriver::new(
133                        Arc::new(InlineQueuedWorkRunHandle::new(Arc::clone(config))),
134                    )),
135                };
136                let (process, drive_process_on_open) = match &self.setup.process {
137                    ProcessWorkDriverSetup::None => (None, false),
138                    ProcessWorkDriverSetup::External { driver } => (Some(driver.clone()), false),
139                    ProcessWorkDriverSetup::LazyDefault { config } => {
140                        let mut config = (**config).clone();
141                        if let Some(driver) = queued.clone() {
142                            config = config.with_queued_work_driver(driver);
143                        }
144                        let registry = Arc::clone(&config.process_registry);
145                        let worker = DurableProcessWorker::new(config);
146                        (Some(ProcessWorkDriver::inline(registry, worker)), true)
147                    }
148                };
149                ResolvedWorkDrivers {
150                    process,
151                    queued,
152                    drive_process_on_open,
153                }
154            })
155            .await
156            .clone()
157    }
158
159    pub(crate) fn phase_probe_slot(&self) -> Option<lash_core::runtime::RuntimeTurnPhaseProbeSlot> {
160        self.phase_probe_slot.clone()
161    }
162
163    fn configured_process_work_driver(&self) -> Option<ProcessWorkDriver> {
164        match &self.setup.process {
165            ProcessWorkDriverSetup::External { driver } => Some(driver.clone()),
166            ProcessWorkDriverSetup::None | ProcessWorkDriverSetup::LazyDefault { .. } => None,
167        }
168    }
169
170    fn configured_queued_work_driver(&self) -> Option<QueuedWorkDriver> {
171        match &self.setup.queued {
172            QueuedWorkDriverSetup::External { driver } => Some(driver.clone()),
173            QueuedWorkDriverSetup::None | QueuedWorkDriverSetup::LazyDefault { .. } => None,
174        }
175    }
176}
177
178pub(crate) struct InlineQueuedWorkRunConfig {
179    env: RuntimeEnvironment,
180    policy: SessionPolicy,
181    protocol_factory: Option<Arc<dyn PluginFactory>>,
182    plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
183    store_factory: Arc<dyn SessionStoreFactory>,
184    live_replay_store: Arc<dyn LiveReplayStore>,
185    runtime_host_installer: Option<RuntimeHostInstaller>,
186}
187
188impl InlineQueuedWorkRunConfig {
189    fn new(
190        env: RuntimeEnvironment,
191        policy: SessionPolicy,
192        protocol_factory: Option<Arc<dyn PluginFactory>>,
193        plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
194        store_factory: Arc<dyn SessionStoreFactory>,
195        live_replay_store: Arc<dyn LiveReplayStore>,
196        runtime_host_installer: Option<RuntimeHostInstaller>,
197    ) -> Self {
198        Self {
199            env,
200            policy,
201            protocol_factory,
202            plugin_factories,
203            store_factory,
204            live_replay_store,
205            runtime_host_installer,
206        }
207    }
208}
209
210struct InlineQueuedWorkRunHandle {
211    config: Arc<InlineQueuedWorkRunConfig>,
212}
213
214impl InlineQueuedWorkRunHandle {
215    fn new(config: Arc<InlineQueuedWorkRunConfig>) -> Self {
216        Self { config }
217    }
218}
219
220#[async_trait]
221impl QueuedWorkRunHandle for InlineQueuedWorkRunHandle {
222    async fn run_queued_work(
223        &self,
224        request: QueuedWorkRunRequest,
225    ) -> std::result::Result<(), lash_core::PluginError> {
226        let Some(session_id) = request.session_id else {
227            return Ok(());
228        };
229        let reason = request.reason;
230        let mut policy = self.config.policy.clone();
231        policy.session_id = Some(session_id.clone());
232        let store = self
233            .config
234            .store_factory
235            .create_store(&SessionStoreCreateRequest {
236                session_id: session_id.clone(),
237                relation: SessionRelation::default(),
238                policy: policy.clone(),
239            })
240            .await
241            .map_err(lash_core::PluginError::Session)?;
242        let state = crate::session::load_state_for_residency(
243            self.config.env.residency,
244            &session_id,
245            &policy,
246            store.as_ref(),
247        )
248        .await
249        .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
250        let plugin_host = build_plugin_host(
251            self.config.protocol_factory.as_ref(),
252            self.config.plugin_factories.as_ref(),
253            Vec::new(),
254        )
255        .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
256        let mut env = self.config.env.clone();
257        env.core = match &self.config.runtime_host_installer {
258            Some(install) => install(env.core.clone(), &plugin_host)
259                .map_err(|err| lash_core::PluginError::Session(err.to_string()))?,
260            None => env.core.clone(),
261        };
262        env.plugin_host = Some(Arc::new(plugin_host));
263        let effect_host = Arc::clone(&env.core.control.effect_host);
264        let runtime = LashRuntime::from_environment(&env, policy, state, Some(store))
265            .await
266            .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
267        let handle = RuntimeHandle::with_live_replay_store(
268            runtime,
269            Arc::clone(&self.config.live_replay_store),
270        );
271        let scope = lash_core::ExecutionScope::queue_drain(session_id, reason);
272        let scoped = effect_host
273            .scoped(scope)
274            .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
275        crate::turn::stream_next_queued_prepared_turn(
276            &handle,
277            crate::turn::TurnSinks::default(),
278            scoped,
279            CancellationToken::new(),
280            &[],
281        )
282        .await
283        .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
284        Ok(())
285    }
286}
287
288#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
289pub struct SessionDeleteReport {
290    pub session_id: String,
291    pub process: Option<lash_core::ProcessSessionDeleteReport>,
292}
293
294impl LashCore {
295    pub fn builder() -> LashCoreBuilder {
296        LashCoreBuilder::default()
297    }
298
299    pub fn session(&self, session_id: impl Into<String>) -> SessionBuilder {
300        SessionBuilder {
301            core: self.clone(),
302            session_id: session_id.into(),
303            spec: SessionSpec::inherit(),
304            parent_session_id: None,
305            session_execution_owner_id: None,
306            store: None,
307            provider: None,
308            active_plugins: Vec::new(),
309            plugin_factories: Vec::new(),
310        }
311    }
312
313    pub fn triggers(&self) -> crate::admin::CoreTriggerAdmin {
314        crate::admin::CoreTriggerAdmin { core: self.clone() }
315    }
316
317    pub fn processes(&self) -> crate::admin::Processes {
318        crate::admin::Processes { core: self.clone() }
319    }
320
321    pub fn completions(&self) -> crate::admin::Completions {
322        crate::admin::Completions { core: self.clone() }
323    }
324
325    pub fn effect_host(&self) -> Arc<dyn EffectHost> {
326        Arc::clone(&self.env.core.control.effect_host)
327    }
328
329    pub async fn delete_session(
330        &self,
331        session_id: impl AsRef<str>,
332        scoped_effect_controller: ScopedEffectController<'_>,
333    ) -> Result<SessionDeleteReport> {
334        let session_id = session_id.as_ref().to_string();
335        let Some(store_factory) = self.store_factory.as_ref() else {
336            return Err(EmbedError::MissingSessionStoreFactory);
337        };
338        let process = if let Some(process_registry) = self.env.process_registry.as_ref() {
339            let invocation = RuntimeInvocation::effect(
340                RuntimeScope::new(session_id.clone()),
341                format!("process:delete-session:{session_id}"),
342                RuntimeEffectKind::Process,
343                format!("{session_id}:delete-session"),
344            );
345            let outcome = scoped_effect_controller
346                .controller()
347                .execute_effect(
348                    RuntimeEffectEnvelope::new(
349                        invocation,
350                        RuntimeEffectCommand::process(ProcessCommand::DeleteSession {
351                            session_id: session_id.clone(),
352                        }),
353                    ),
354                    RuntimeEffectLocalExecutor::processes(Arc::clone(process_registry)),
355                )
356                .await
357                .map_err(|err| EmbedError::SessionDeleteProcess {
358                    session_id: session_id.clone(),
359                    message: err.to_string(),
360                })?;
361            match outcome {
362                RuntimeEffectOutcome::Process {
363                    result: ProcessEffectOutcome::DeleteSession { report },
364                } => Some(report),
365                other => {
366                    return Err(EmbedError::SessionDeleteProcess {
367                        session_id,
368                        message: format!(
369                            "process delete returned the wrong outcome: {}",
370                            other.kind().as_str()
371                        ),
372                    });
373                }
374            }
375        } else {
376            None
377        };
378        if let Some(trigger_store) = self.env.trigger_store.as_ref() {
379            trigger_store
380                .delete_session_subscriptions(&session_id)
381                .await
382                .map_err(|err| EmbedError::SessionDeleteProcess {
383                    session_id: session_id.clone(),
384                    message: err.to_string(),
385                })?;
386        }
387        self.env
388            .core
389            .control
390            .effect_host
391            .revoke_await_events_for_session(&session_id)
392            .await
393            .map_err(|err| EmbedError::SessionDeleteProcess {
394                session_id: session_id.clone(),
395                message: err.to_string(),
396            })?;
397        store_factory
398            .delete_session(&session_id)
399            .await
400            .map_err(|message| EmbedError::StoreFactory {
401                session_id: session_id.clone(),
402                message,
403            })?;
404        Ok(SessionDeleteReport {
405            session_id,
406            process,
407        })
408    }
409
410    pub fn process_registry(&self) -> Option<Arc<dyn ProcessRegistry>> {
411        self.env.process_registry.as_ref().cloned()
412    }
413
414    pub fn durable_process_worker_config(&self) -> Result<DurableProcessWorkerConfig> {
415        self.durable_process_worker_config_with_plugins(std::iter::empty::<Arc<dyn PluginFactory>>())
416    }
417
418    pub fn durable_process_worker_config_with_plugins(
419        &self,
420        extra_plugin_factories: impl IntoIterator<Item = Arc<dyn PluginFactory>>,
421    ) -> Result<DurableProcessWorkerConfig> {
422        let Some(process_registry) = self.process_registry() else {
423            return Err(EmbedError::MissingProcessRegistry);
424        };
425        let Some(store_factory) = self.store_factory.as_ref() else {
426            return Err(EmbedError::MissingProcessWorkerStoreFactory);
427        };
428        let plugin_host = build_plugin_host(
429            self.protocol_factory.as_ref(),
430            self.plugin_factories.as_ref(),
431            extra_plugin_factories.into_iter().collect(),
432        )?;
433        let runtime_host =
434            self.runtime_host_for_plugin_host(self.env.core.clone(), &plugin_host)?;
435        let mut config = DurableProcessWorkerConfig::new(
436            Arc::new(plugin_host),
437            runtime_host,
438            Arc::clone(store_factory),
439            process_registry,
440        )
441        .with_session_policy(self.policy.clone())
442        .with_residency(self.env.residency);
443        if let Some(trigger_store) = self.env.trigger_store.as_ref() {
444            config = config.with_trigger_store(Arc::clone(trigger_store));
445        }
446        if let Some(driver) = self.work_driver.configured_process_work_driver() {
447            config = config.with_process_work_driver(driver);
448        }
449        if let Some(driver) = self.work_driver.configured_queued_work_driver() {
450            config = config.with_queued_work_driver(driver);
451        }
452        Ok(config)
453    }
454
455    pub(crate) fn runtime_host_for_plugin_host(
456        &self,
457        runtime_host: RuntimeHostConfig,
458        plugin_host: &PluginHost,
459    ) -> Result<RuntimeHostConfig> {
460        match &self.runtime_host_installer {
461            Some(install) => install(runtime_host, plugin_host),
462            None => Ok(runtime_host),
463        }
464    }
465}
466
467fn default_runtime_stack() -> PluginStack {
468    lash_plugin_tool_output_budget::tool_output_budget_stack()
469}
470
471#[derive(Clone)]
472pub struct StandardCore {
473    core: LashCore,
474}
475
476impl StandardCore {
477    pub fn builder() -> StandardCoreBuilder {
478        StandardCoreBuilder {
479            inner: LashCore::builder()
480                .protocol_plugin(Arc::new(
481                    lash_protocol_standard::StandardProtocolPluginFactory::new(),
482                ))
483                .plugins(default_runtime_stack()),
484        }
485    }
486
487    pub fn session(&self, session_id: impl Into<String>) -> SessionBuilder {
488        self.core.session(session_id)
489    }
490
491    pub fn into_inner(self) -> LashCore {
492        self.core
493    }
494}
495
496impl std::ops::Deref for StandardCore {
497    type Target = LashCore;
498
499    fn deref(&self) -> &Self::Target {
500        &self.core
501    }
502}
503
504pub struct StandardCoreBuilder {
505    inner: LashCoreBuilder,
506}
507
508impl StandardCoreBuilder {
509    pub fn build(self) -> Result<StandardCore> {
510        self.inner.build().map(|core| StandardCore { core })
511    }
512}
513
514impl PromptLayerSink for StandardCoreBuilder {
515    fn prompt_layer_mut(&mut self) -> &mut PromptLayer {
516        self.inner.prompt_layer_mut()
517    }
518}
519
520#[cfg(feature = "rlm")]
521#[derive(Clone)]
522pub struct RlmCore {
523    core: LashCore,
524    surface_config: lash_protocol_rlm::RlmProtocolPluginConfig,
525    process_lifecycle_available: bool,
526    lashlang_artifact_store: Arc<dyn lash_lashlang_runtime::LashlangArtifactStore>,
527}
528
529#[cfg(feature = "rlm")]
530impl RlmCore {
531    pub fn builder() -> RlmCoreBuilder {
532        RlmCoreBuilder {
533            inner: LashCore::builder().plugins(default_runtime_stack()),
534            config: lash_protocol_rlm::RlmProtocolPluginConfig::default(),
535            projection_resolver: Arc::new(lash_protocol_rlm::ProjectionRegistry::default()),
536            lashlang_artifact_store: None,
537            lashlang_execution_sink: None,
538        }
539    }
540
541    pub fn session(&self, session_id: impl Into<String>) -> RlmSessionBuilder {
542        RlmSessionBuilder {
543            builder: self.core.session(session_id),
544            rlm_final_answer_format: None,
545        }
546    }
547
548    pub fn into_inner(self) -> LashCore {
549        self.core
550    }
551
552    pub fn lashlang_compile_surface(
553        &self,
554        request: crate::rlm::LashlangCompileSurfaceRequest,
555    ) -> Result<crate::rlm::LashlangCompileSurface> {
556        let plugin_host = build_plugin_host(
557            self.core.protocol_factory.as_ref(),
558            self.core.plugin_factories.as_ref(),
559            request.extra_plugin_factories,
560        )?;
561        let plugins = plugin_host.build_session_with_parent(
562            &request.session_id,
563            None,
564            None,
565            lash_core::plugin::SessionAuthorityContext {
566                plugin_options: request.execution_env_spec.plugin_options,
567                ..Default::default()
568            },
569        )?;
570        let tool_catalog = plugins.resolved_tool_catalog(&request.session_id)?;
571        let surface = crate::rlm::rlm_lashlang_surface(
572            &self.surface_config,
573            self.process_lifecycle_available,
574        )
575        .with_plugin_extensions(plugin_host.extensions())
576        .map_err(lash_core::PluginError::Registration)?;
577        let host_environment = surface
578            .host_environment(&tool_catalog)
579            .map_err(lash_core::PluginError::Registration)?;
580        Ok(crate::rlm::LashlangCompileSurface {
581            host_environment,
582            tool_catalog,
583            surface,
584        })
585    }
586
587    pub async fn compile_lashlang_module(
588        &self,
589        request: crate::rlm::LashlangModuleCompileRequest,
590    ) -> std::result::Result<crate::rlm::ModuleCompileOutput, crate::rlm::LashlangModuleCompileError>
591    {
592        let surface = self
593            .lashlang_compile_surface(crate::rlm::LashlangCompileSurfaceRequest {
594                session_id: request.session_id,
595                execution_env_spec: request.execution_env_spec,
596                extra_plugin_factories: request.extra_plugin_factories,
597            })
598            .map_err(|err| {
599                lashlang::ModuleCompileError::Link(lashlang::ModuleCompileDiagnostic {
600                    stage: lashlang::ModuleCompileStage::Link,
601                    message: err.to_string(),
602                    offset: None,
603                    span: None,
604                    line: None,
605                    column: None,
606                    diagnostic: Some(err.to_string()),
607                })
608            })?;
609        lashlang::compile_module(lashlang::ModuleCompileRequest {
610            source: &request.source,
611            environment: &surface.host_environment,
612            artifact_store: Some(self.lashlang_artifact_store.as_ref()),
613        })
614        .await
615    }
616}
617
618#[cfg(feature = "rlm")]
619impl std::ops::Deref for RlmCore {
620    type Target = LashCore;
621
622    fn deref(&self) -> &Self::Target {
623        &self.core
624    }
625}
626
627#[cfg(feature = "rlm")]
628pub struct RlmCoreBuilder {
629    inner: LashCoreBuilder,
630    config: lash_protocol_rlm::RlmProtocolPluginConfig,
631    projection_resolver: Arc<dyn lash_protocol_rlm::ProjectionResolver>,
632    lashlang_artifact_store: Option<Arc<dyn lash_lashlang_runtime::LashlangArtifactStore>>,
633    lashlang_execution_sink: Option<Arc<dyn lash_trace::TraceSink>>,
634}
635
636#[cfg(feature = "rlm")]
637impl RlmCoreBuilder {
638    pub fn rlm_protocol_config(
639        mut self,
640        config: lash_protocol_rlm::RlmProtocolPluginConfig,
641    ) -> Self {
642        self.config = config;
643        self
644    }
645
646    pub fn projection_resolver(
647        mut self,
648        projection_resolver: Arc<dyn lash_protocol_rlm::ProjectionResolver>,
649    ) -> Self {
650        self.projection_resolver = projection_resolver;
651        self
652    }
653
654    pub fn lashlang_artifact_store(
655        mut self,
656        artifact_store: Arc<dyn lash_lashlang_runtime::LashlangArtifactStore>,
657    ) -> Self {
658        self.lashlang_artifact_store = Some(artifact_store);
659        self
660    }
661
662    pub fn lashlang_execution_sink(
663        mut self,
664        lashlang_execution_sink: Arc<dyn lash_trace::TraceSink>,
665    ) -> Self {
666        self.lashlang_execution_sink = Some(lashlang_execution_sink);
667        self
668    }
669
670    pub fn lashlang_execution_jsonl_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
671        self.lashlang_execution_sink = Some(Arc::new(lash_trace::JsonlTraceSink::new(path.into())));
672        self
673    }
674
675    pub fn build(mut self) -> Result<RlmCore> {
676        let artifact_store = self
677            .lashlang_artifact_store
678            .clone()
679            .ok_or(EmbedError::MissingLashlangArtifactStore)?;
680        if self.inner.effective_session_store_tier() == Some(DurabilityTier::Durable)
681            && artifact_store.durability_tier()
682                == lash_lashlang_runtime::LashlangDurabilityTier::Inline
683        {
684            return Err(EmbedError::DurableStorePeerRequired {
685                facet: "artifact store",
686            });
687        }
688        let process_lifecycle_available = self.inner.process_work_source.has_registry();
689        let config = crate::rlm::rlm_protocol_config(self.config, process_lifecycle_available);
690        let trace_context = self.inner.resolved_trace_context();
691        let protocol_factory = Arc::new(
692            lash_protocol_rlm::RlmProtocolPluginFactory::new(config.clone())
693                .with_projection_resolver(Arc::clone(&self.projection_resolver))
694                .with_lashlang_artifact_store(Arc::clone(&artifact_store))
695                .with_lashlang_execution_trace(
696                    self.lashlang_execution_sink.clone(),
697                    trace_context.clone(),
698                ),
699        );
700        let engine_artifact_store = Arc::clone(&artifact_store);
701        let engine_config = config.clone();
702        let engine_sink = self.lashlang_execution_sink.clone();
703        self.inner.protocol_factory = Some(protocol_factory);
704        self.inner.runtime_host_installer = Some(Arc::new(move |runtime_host, plugin_host| {
705            let surface =
706                crate::rlm::rlm_lashlang_surface(&engine_config, process_lifecycle_available)
707                    .with_plugin_extensions(plugin_host.extensions())
708                    .map_err(lash_core::PluginError::Registration)?;
709            let engine = lash_lashlang_runtime::LashlangProcessEngine::new(
710                Arc::clone(&engine_artifact_store),
711                surface,
712            )
713            .with_execution_trace(
714                engine_sink.clone(),
715                runtime_host.tracing.trace_context.clone(),
716            );
717            Ok(runtime_host.with_process_engine(Arc::new(engine)))
718        }));
719        self.inner.build().map(|core| RlmCore {
720            core,
721            surface_config: config,
722            process_lifecycle_available,
723            lashlang_artifact_store: artifact_store,
724        })
725    }
726}
727
728#[cfg(feature = "rlm")]
729impl PromptLayerSink for RlmCoreBuilder {
730    fn prompt_layer_mut(&mut self) -> &mut PromptLayer {
731        self.inner.prompt_layer_mut()
732    }
733}
734
735macro_rules! forward_core_builder_methods {
736    ($builder:ident) => {
737        impl $builder {
738            pub fn provider(mut self, provider: ProviderHandle) -> Self {
739                self.inner = self.inner.provider(provider);
740                self
741            }
742
743            pub fn model(mut self, model: lash_core::ModelSpec) -> Self {
744                self.inner = self.inner.model(model);
745                self
746            }
747
748            pub fn max_turns(mut self, max_turns: usize) -> Self {
749                self.inner = self.inner.max_turns(max_turns);
750                self
751            }
752
753            pub fn session_spec(mut self, spec: SessionSpec) -> Self {
754                self.inner = self.inner.session_spec(spec);
755                self
756            }
757
758            pub fn store_factory(mut self, store_factory: Arc<dyn SessionStoreFactory>) -> Self {
759                self.inner = self.inner.store_factory(store_factory);
760                self
761            }
762
763            pub fn child_store_factory(
764                mut self,
765                store_factory: Arc<dyn SessionStoreFactory>,
766            ) -> Self {
767                self.inner = self.inner.child_store_factory(store_factory);
768                self
769            }
770
771            pub fn attachment_store(mut self, attachment_store: Arc<dyn AttachmentStore>) -> Self {
772                self.inner = self.inner.attachment_store(attachment_store);
773                self
774            }
775
776            pub fn process_env_store(
777                mut self,
778                process_env_store: Arc<dyn ProcessExecutionEnvStore>,
779            ) -> Self {
780                self.inner = self.inner.process_env_store(process_env_store);
781                self
782            }
783
784            pub fn effect_host(mut self, effect_host: Arc<dyn EffectHost>) -> Self {
785                self.inner = self.inner.effect_host(effect_host);
786                self
787            }
788
789            pub fn tools(mut self, tools: Arc<dyn ToolProvider>) -> Self {
790                self.inner = self.inner.tools(tools);
791                self
792            }
793
794            pub fn plugin(mut self, plugin: Arc<dyn PluginFactory>) -> Self {
795                self.inner = self.inner.plugin(plugin);
796                self
797            }
798
799            pub fn plugins(mut self, stack: PluginStack) -> Self {
800                self.inner = self.inner.plugins(stack);
801                self
802            }
803
804            pub fn configure_plugins(mut self, configure: impl FnOnce(&mut PluginStack)) -> Self {
805                self.inner = self.inner.configure_plugins(configure);
806                self
807            }
808
809            pub fn trace_sink(mut self, trace_sink: Arc<dyn lash_trace::TraceSink>) -> Self {
810                self.inner = self.inner.trace_sink(trace_sink);
811                self
812            }
813
814            pub fn trace_jsonl_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
815                self.inner = self.inner.trace_jsonl_path(path);
816                self
817            }
818
819            pub fn trace_level(mut self, trace_level: lash_trace::TraceLevel) -> Self {
820                self.inner = self.inner.trace_level(trace_level);
821                self
822            }
823
824            pub fn trace_context(mut self, trace_context: lash_trace::TraceContext) -> Self {
825                self.inner = self.inner.trace_context(trace_context);
826                self
827            }
828
829            pub fn termination(mut self, termination: TerminationPolicy) -> Self {
830                self.inner = self.inner.termination(termination);
831                self
832            }
833
834            pub fn residency(mut self, residency: Residency) -> Self {
835                self.inner = self.inner.residency(residency);
836                self
837            }
838
839            pub fn live_replay_store(
840                mut self,
841                live_replay_store: Arc<dyn LiveReplayStore>,
842            ) -> Self {
843                self.inner = self.inner.live_replay_store(live_replay_store);
844                self
845            }
846
847            pub fn process_registry(mut self, process_registry: Arc<dyn ProcessRegistry>) -> Self {
848                self.inner = self.inner.process_registry(process_registry);
849                self
850            }
851
852            pub fn trigger_store(mut self, store: Arc<dyn lash_core::TriggerStore>) -> Self {
853                self.inner = self.inner.trigger_store(store);
854                self
855            }
856
857            pub fn process_work_driver(mut self, driver: ProcessWorkDriver) -> Self {
858                self.inner = self.inner.process_work_driver(driver);
859                self
860            }
861
862            pub fn queued_work_driver(mut self, driver: QueuedWorkDriver) -> Self {
863                self.inner = self.inner.queued_work_driver(driver);
864                self
865            }
866
867            pub fn disable_queued_work_driver(mut self) -> Self {
868                self.inner = self.inner.disable_queued_work_driver();
869                self
870            }
871
872            pub fn runtime_host_config(mut self, core: RuntimeHostConfig) -> Self {
873                self.inner.runtime_host_config = Some(core);
874                self
875            }
876        }
877    };
878}
879
880forward_core_builder_methods!(StandardCoreBuilder);
881#[cfg(feature = "rlm")]
882forward_core_builder_methods!(RlmCoreBuilder);
883
884#[derive(Default)]
885pub struct LashCoreBuilder {
886    pub(crate) protocol_factory: Option<Arc<dyn PluginFactory>>,
887    session_spec: SessionSpec,
888    provider: Option<ProviderHandle>,
889    pub(crate) store_factory: Option<Arc<dyn SessionStoreFactory>>,
890    child_store_factory: Option<Arc<dyn SessionStoreFactory>>,
891    // `RuntimeHostConfig` has no `Default`: the generic host-owned durability
892    // dependencies must be named. They are collected here and resolved in
893    // `build()`, which errors if any is unset.
894    effect_host: Option<Arc<dyn EffectHost>>,
895    attachment_store: Option<Arc<dyn AttachmentStore>>,
896    process_env_store: Option<Arc<dyn ProcessExecutionEnvStore>>,
897    trigger_store: Option<Arc<dyn lash_core::TriggerStore>>,
898    // Benign core overrides applied on top of the resolved core.
899    prompt: Option<PromptLayer>,
900    trace_sink: Option<Arc<dyn lash_trace::TraceSink>>,
901    trace_level: Option<lash_trace::TraceLevel>,
902    trace_context: Option<lash_trace::TraceContext>,
903    termination: Option<TerminationPolicy>,
904    // Advanced full-config override; used as the base core when present.
905    runtime_host_config: Option<RuntimeHostConfig>,
906    tool_providers: Vec<Arc<dyn ToolProvider>>,
907    plugin_stack: PluginStack,
908    plugin_host: Option<PluginHost>,
909    residency: Option<Residency>,
910    // Single source of truth for process lifecycle support and process-work
911    // consumption.
912    process_work_source: ProcessWorkSource,
913    queued_work_source: QueuedWorkSource,
914    live_replay_store: Option<Arc<dyn LiveReplayStore>>,
915    runtime_host_installer: Option<RuntimeHostInstaller>,
916}
917
918impl LashCoreBuilder {
919    pub fn protocol_plugin(mut self, plugin: Arc<dyn PluginFactory>) -> Self {
920        self.protocol_factory = Some(plugin);
921        self
922    }
923
924    pub fn provider(mut self, provider: ProviderHandle) -> Self {
925        self.session_spec = self.session_spec.provider_id(provider.kind());
926        self.provider = Some(provider);
927        self
928    }
929
930    pub fn model(mut self, model: lash_core::ModelSpec) -> Self {
931        self.session_spec = self.session_spec.model(model);
932        self
933    }
934
935    pub fn max_turns(mut self, max_turns: usize) -> Self {
936        self.session_spec = self.session_spec.max_turns(max_turns);
937        self
938    }
939
940    pub fn session_spec(mut self, spec: SessionSpec) -> Self {
941        self.session_spec = spec;
942        self
943    }
944
945    /// Configure a factory that can create a persistence store for any root
946    /// session opened from this core.
947    ///
948    /// The factory must honor `SessionStoreCreateRequest::session_id` and
949    /// return a store for that specific session. Do not use this to wrap one
950    /// pre-opened root store; pass root-only stores with
951    /// `LashCore::session(...).store(store)` instead.
952    pub fn store_factory(mut self, store_factory: Arc<dyn SessionStoreFactory>) -> Self {
953        self.store_factory = Some(store_factory);
954        self
955    }
956
957    /// Configure the persistence factory used by managed child sessions, such
958    /// as local subagents.
959    ///
960    /// Child factories must return a distinct store bound to the requested
961    /// child session id. Hosts that pass an explicit root store with
962    /// `SessionBuilder::store` should set this when child sessions need
963    /// persistence.
964    pub fn child_store_factory(mut self, store_factory: Arc<dyn SessionStoreFactory>) -> Self {
965        self.child_store_factory = Some(store_factory);
966        self
967    }
968
969    pub fn attachment_store(mut self, attachment_store: Arc<dyn AttachmentStore>) -> Self {
970        self.attachment_store = Some(attachment_store);
971        self
972    }
973
974    pub fn process_env_store(
975        mut self,
976        process_env_store: Arc<dyn ProcessExecutionEnvStore>,
977    ) -> Self {
978        self.process_env_store = Some(process_env_store);
979        self
980    }
981
982    /// Set the deployment effect host — the durability boundary every operation
983    /// crosses. Pass [`InlineEffectHost`](crate::durability::InlineEffectHost)
984    /// for in-process execution, or a workflow-backed host for durable
985    /// execution.
986    pub fn effect_host(mut self, effect_host: Arc<dyn EffectHost>) -> Self {
987        self.effect_host = Some(effect_host);
988        self
989    }
990
991    pub fn tools(mut self, tools: Arc<dyn ToolProvider>) -> Self {
992        self.tool_providers.push(tools);
993        self
994    }
995
996    pub fn plugin(mut self, plugin: Arc<dyn PluginFactory>) -> Self {
997        self.plugin_stack.push(plugin);
998        self
999    }
1000
1001    pub fn plugins(mut self, stack: PluginStack) -> Self {
1002        self.plugin_stack = stack;
1003        self
1004    }
1005
1006    pub fn configure_plugins(mut self, configure: impl FnOnce(&mut PluginStack)) -> Self {
1007        configure(&mut self.plugin_stack);
1008        self
1009    }
1010
1011    pub fn trace_sink(mut self, trace_sink: Arc<dyn lash_trace::TraceSink>) -> Self {
1012        self.trace_sink = Some(trace_sink);
1013        self
1014    }
1015
1016    pub fn trace_jsonl_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
1017        self.trace_sink = Some(Arc::new(lash_trace::JsonlTraceSink::new(path.into())));
1018        self
1019    }
1020
1021    pub fn trace_level(mut self, trace_level: lash_trace::TraceLevel) -> Self {
1022        self.trace_level = Some(trace_level);
1023        self
1024    }
1025
1026    pub fn trace_context(mut self, trace_context: lash_trace::TraceContext) -> Self {
1027        self.trace_context = Some(trace_context);
1028        self
1029    }
1030
1031    pub fn termination(mut self, termination: TerminationPolicy) -> Self {
1032        self.termination = Some(termination);
1033        self
1034    }
1035
1036    pub fn residency(mut self, residency: Residency) -> Self {
1037        self.residency = Some(residency);
1038        self
1039    }
1040
1041    /// Configure the bounded live replay buffer used by session observation
1042    /// cursors. This is best-effort reconnect recovery only; durable state
1043    /// still comes from the session store and [`SessionReadView`].
1044    pub fn live_replay_store(mut self, live_replay_store: Arc<dyn LiveReplayStore>) -> Self {
1045        self.live_replay_store = Some(live_replay_store);
1046        self
1047    }
1048
1049    /// Resolve the runtime host config, requiring the generic host-owned
1050    /// durability dependencies to have been named.
1051    fn resolve_runtime_host_config(&mut self) -> Result<RuntimeHostConfig> {
1052        if let Some(base) = self.runtime_host_config.take() {
1053            return Ok(self.apply_core_overrides(base));
1054        }
1055        let effect_host = self
1056            .effect_host
1057            .take()
1058            .ok_or(EmbedError::MissingEffectHost)?;
1059        let attachment_store = self
1060            .attachment_store
1061            .take()
1062            .ok_or(EmbedError::MissingAttachmentStore)?;
1063        let process_env_store = self
1064            .process_env_store
1065            .take()
1066            .ok_or(EmbedError::MissingProcessEnvStore)?;
1067        let core = RuntimeHostConfig::new(effect_host, attachment_store, process_env_store);
1068        Ok(self.apply_core_overrides(core))
1069    }
1070
1071    /// Apply benign + still-set dependency overrides on top of a base core.
1072    fn apply_core_overrides(&mut self, mut core: RuntimeHostConfig) -> RuntimeHostConfig {
1073        if let Some(effect_host) = self.effect_host.take() {
1074            core.control.effect_host = effect_host;
1075        }
1076        if let Some(attachment_store) = self.attachment_store.take() {
1077            core.durability.attachment_store = attachment_store;
1078        }
1079        if let Some(process_env_store) = self.process_env_store.take() {
1080            core.durability.process_env_store = process_env_store;
1081        }
1082        if let Some(prompt) = self.prompt.take() {
1083            core.prompt.prompt = prompt;
1084        }
1085        if let Some(trace_sink) = self.trace_sink.take() {
1086            core.tracing.trace_sink = Some(trace_sink);
1087        }
1088        if let Some(trace_level) = self.trace_level.take() {
1089            core.tracing.trace_level = trace_level;
1090        }
1091        if let Some(trace_context) = self.trace_context.take() {
1092            core.tracing.trace_context = trace_context;
1093        }
1094        if let Some(termination) = self.termination.take() {
1095            core.control.termination = termination;
1096        }
1097        core
1098    }
1099
1100    /// Validate store peer-coherence of the wired durability dependencies.
1101    ///
1102    /// Durability is established by what the host wired; the per-invocation
1103    /// durable controller is not visible here (the build-time controller is
1104    /// inline by construction), so this checks the stores against each other
1105    /// only — never the controller (see A5 in the durable-first wiring spec):
1106    ///
1107    /// - a durable session store factory requires a durable attachment and
1108    ///   artifact store (they back the same session state);
1109    /// - a durable process registry requires a session store factory that is
1110    ///   itself durable (the registry's process records are meaningless without
1111    ///   a durable session behind them).
1112    fn effective_session_store_tier(&self) -> Option<DurabilityTier> {
1113        self.child_store_factory
1114            .as_ref()
1115            .or(self.store_factory.as_ref())
1116            .map(|factory| factory.durability_tier())
1117    }
1118
1119    #[cfg(feature = "rlm")]
1120    fn resolved_trace_context(&self) -> lash_trace::TraceContext {
1121        self.trace_context
1122            .clone()
1123            .or_else(|| {
1124                self.runtime_host_config
1125                    .as_ref()
1126                    .map(|core| core.tracing.trace_context.clone())
1127            })
1128            .unwrap_or_default()
1129    }
1130
1131    fn ensure_store_peer_coherence(&self) -> Result<()> {
1132        // Match `build()`'s wiring exactly: the session store factory it installs
1133        // is `child_store_factory.or(store_factory)` (child takes precedence, root
1134        // is the fallback). The coherence check must read the tier of that same
1135        // effective factory, or a host that wires only a durable child factory
1136        // (no root) is wrongly rejected though `build()` would wire it durably.
1137        let session_store_tier = self.effective_session_store_tier();
1138        let attachment_tier = self
1139            .attachment_store
1140            .as_ref()
1141            .map(|store| store.persistence().durability_tier())
1142            .or_else(|| {
1143                self.runtime_host_config.as_ref().map(|core| {
1144                    core.durability
1145                        .attachment_store
1146                        .persistence()
1147                        .durability_tier()
1148                })
1149            });
1150        let process_env_tier = self
1151            .process_env_store
1152            .as_ref()
1153            .map(|store| store.durability_tier())
1154            .or_else(|| {
1155                self.runtime_host_config
1156                    .as_ref()
1157                    .map(|core| core.durability.process_env_store.durability_tier())
1158            });
1159        let effect_host_tier = self
1160            .effect_host
1161            .as_ref()
1162            .map(|host| host.durability_tier())
1163            .or_else(|| {
1164                self.runtime_host_config
1165                    .as_ref()
1166                    .map(|core| core.control.effect_host.durability_tier())
1167            });
1168        let trigger_store_tier = self
1169            .trigger_store
1170            .as_ref()
1171            .map(|store| store.durability_tier());
1172
1173        if session_store_tier == Some(DurabilityTier::Durable) {
1174            if attachment_tier == Some(DurabilityTier::Inline) {
1175                return Err(EmbedError::DurableStorePeerRequired {
1176                    facet: "attachment store",
1177                });
1178            }
1179            if process_env_tier == Some(DurabilityTier::Inline) {
1180                return Err(EmbedError::DurableStorePeerRequired {
1181                    facet: "process execution environment store",
1182                });
1183            }
1184        }
1185
1186        if let Some(process_registry) = self.process_work_source.process_registry().as_ref()
1187            && process_registry.durability_tier() == DurabilityTier::Durable
1188        {
1189            if session_store_tier != Some(DurabilityTier::Durable) {
1190                return Err(EmbedError::DurableProcessRegistryRequiresStoreFactory);
1191            }
1192            if trigger_store_tier != Some(DurabilityTier::Durable) {
1193                return Err(EmbedError::DurableStorePeerRequired {
1194                    facet: "trigger store",
1195                });
1196            }
1197            if process_env_tier != Some(DurabilityTier::Durable) {
1198                return Err(EmbedError::DurableStorePeerRequired {
1199                    facet: "process execution environment store",
1200                });
1201            }
1202        }
1203
1204        if trigger_store_tier == Some(DurabilityTier::Durable) {
1205            if session_store_tier != Some(DurabilityTier::Durable) {
1206                return Err(EmbedError::DurableStorePeerRequired {
1207                    facet: "session store factory",
1208                });
1209            }
1210            if process_env_tier != Some(DurabilityTier::Durable) {
1211                return Err(EmbedError::DurableStorePeerRequired {
1212                    facet: "process execution environment store",
1213                });
1214            }
1215            if let Some(process_registry) = self.process_work_source.process_registry().as_ref()
1216                && process_registry.durability_tier() == DurabilityTier::Inline
1217            {
1218                return Err(EmbedError::DurableStorePeerRequired {
1219                    facet: "process registry",
1220                });
1221            }
1222        }
1223
1224        if effect_host_tier == Some(DurabilityTier::Durable) {
1225            if attachment_tier != Some(DurabilityTier::Durable) {
1226                return Err(EmbedError::DurableStorePeerRequired {
1227                    facet: "attachment store",
1228                });
1229            }
1230            if process_env_tier != Some(DurabilityTier::Durable) {
1231                return Err(EmbedError::DurableStorePeerRequired {
1232                    facet: "process execution environment store",
1233                });
1234            }
1235        }
1236
1237        Ok(())
1238    }
1239
1240    pub fn build(mut self) -> Result<LashCore> {
1241        self.ensure_store_peer_coherence()?;
1242        let protocol_factory = self.protocol_factory.clone();
1243        if protocol_factory.is_none() && self.plugin_host.is_none() {
1244            return Err(EmbedError::MissingProtocolPlugin);
1245        }
1246        let provider_id = self
1247            .session_spec
1248            .provider_id
1249            .clone()
1250            .or_else(|| {
1251                self.provider
1252                    .as_ref()
1253                    .map(|provider| provider.kind().to_string())
1254            })
1255            .unwrap_or_default();
1256        let model = self
1257            .session_spec
1258            .model
1259            .clone()
1260            .ok_or(EmbedError::MissingModelSpec)?;
1261
1262        let base_policy = SessionPolicy {
1263            provider_id,
1264            model,
1265            max_turns: self.session_spec.max_turns.flatten(),
1266            ..SessionPolicy::default()
1267        };
1268        let policy = self.session_spec.resolve_against(&base_policy);
1269
1270        let mut core = self.resolve_runtime_host_config()?;
1271        if let Some(provider) = self.provider.clone() {
1272            core.providers.provider_resolver =
1273                Arc::new(lash_core::SingleProviderResolver::new(provider));
1274        }
1275        let plugin_factories = if let Some(plugin_host) = self.plugin_host {
1276            plugin_host.factories().to_vec()
1277        } else {
1278            let mut factories = Vec::new();
1279            if !self.tool_providers.is_empty() {
1280                let spec = self
1281                    .tool_providers
1282                    .into_iter()
1283                    .fold(PluginSpec::new(), PluginSpec::with_tool_provider);
1284                factories.push(Arc::new(StaticPluginFactory::new("embed_tools", spec))
1285                    as Arc<dyn PluginFactory>);
1286            }
1287            factories.extend(self.plugin_stack.into_factories());
1288            factories
1289        };
1290        let default_plugin_host =
1291            build_plugin_host(protocol_factory.as_ref(), &plugin_factories, Vec::new())?;
1292        if let Some(install) = &self.runtime_host_installer {
1293            core = install(core, &default_plugin_host)?;
1294        }
1295
1296        let process_registry = self.process_work_source.process_registry();
1297
1298        // Resolve process work before the process source is moved into the
1299        // environment. The default inline driver's config is built
1300        // eagerly so a missing store factory fails loudly at build, not at
1301        // first open. It is built from the same single-protocol plugin host the
1302        // live runtime uses, so the worker can rebuild a runtime for a process.
1303        let process_work_driver = Self::resolve_process_work_driver(
1304            &self.process_work_source,
1305            &default_plugin_host,
1306            &core,
1307            // The worker rebuilds sessions with the same factory `build()` wires
1308            // below: `child_store_factory.or(store_factory)`.
1309            self.child_store_factory
1310                .as_ref()
1311                .or(self.store_factory.as_ref()),
1312            &policy,
1313            self.residency.unwrap_or_default(),
1314            self.trigger_store.as_ref(),
1315        )?;
1316
1317        let live_replay_clock = Arc::clone(&core.clock);
1318        let mut env_builder = RuntimeEnvironment::builder()
1319            .with_plugin_host(Arc::new(default_plugin_host))
1320            .with_runtime_host_config(core);
1321        if let Some(process_registry) = process_registry.as_ref() {
1322            env_builder = env_builder.with_process_registry(Arc::clone(process_registry));
1323        }
1324        if let Some(residency) = self.residency {
1325            env_builder = env_builder.with_residency(residency);
1326        }
1327        if let Some(child_store_factory) = self
1328            .child_store_factory
1329            .as_ref()
1330            .or(self.store_factory.as_ref())
1331        {
1332            env_builder = env_builder.with_session_store_factory(Arc::clone(child_store_factory));
1333        }
1334        if let Some(trigger_store) = self.trigger_store.as_ref() {
1335            env_builder = env_builder.with_trigger_store(Arc::clone(trigger_store));
1336        }
1337        let live_replay_store = self.live_replay_store.take().unwrap_or_else(|| {
1338            Arc::new(InMemoryLiveReplayStore::with_clock(
1339                lash_core::InMemoryLiveReplayStoreConfig::default(),
1340                live_replay_clock,
1341            ))
1342        });
1343        let env = env_builder.build();
1344        let queued_work_driver = Self::resolve_queued_work_driver(
1345            &self.queued_work_source,
1346            env.clone(),
1347            policy.clone(),
1348            protocol_factory.clone(),
1349            Arc::new(plugin_factories.clone()),
1350            self.child_store_factory
1351                .as_ref()
1352                .or(self.store_factory.as_ref()),
1353            Arc::clone(&live_replay_store),
1354            self.runtime_host_installer.clone(),
1355        );
1356        let work_driver = InlineWorkDriverSetup {
1357            process: process_work_driver,
1358            queued: queued_work_driver,
1359        };
1360
1361        Ok(LashCore {
1362            env,
1363            policy,
1364            store_factory: self.store_factory,
1365            plugin_factories: Arc::new(plugin_factories),
1366            provider: self.provider,
1367            live_replay_store,
1368            protocol_factory,
1369            runtime_host_installer: self.runtime_host_installer,
1370            work_driver: Arc::new(InlineWorkDriverSlot::new(work_driver)),
1371        })
1372    }
1373
1374    /// Decide how a built [`LashCore`] sources its process work driver.
1375    ///
1376    /// - no registry => nothing to run ([`ProcessWorkDriverSetup::None`]);
1377    /// - external driver wired => use it ([`ProcessWorkDriverSetup::External`]);
1378    /// - inline registry wired => lazily construct the default inline driver on first open. Its
1379    ///   [`DurableProcessWorkerConfig`] is built eagerly when a store factory is
1380    ///   present; without one the inline worker cannot rebuild session runtimes.
1381    fn resolve_process_work_driver(
1382        process_work_source: &ProcessWorkSource,
1383        worker_plugin_host: &PluginHost,
1384        core: &RuntimeHostConfig,
1385        store_factory: Option<&Arc<dyn SessionStoreFactory>>,
1386        policy: &SessionPolicy,
1387        residency: lash_core::Residency,
1388        trigger_store: Option<&Arc<dyn lash_core::TriggerStore>>,
1389    ) -> Result<ProcessWorkDriverSetup> {
1390        let process_registry = match process_work_source {
1391            ProcessWorkSource::None => return Ok(ProcessWorkDriverSetup::None),
1392            ProcessWorkSource::External(driver) => {
1393                return Ok(ProcessWorkDriverSetup::External {
1394                    driver: driver.clone(),
1395                });
1396            }
1397            ProcessWorkSource::Inline { registry } => Arc::clone(registry),
1398        };
1399        // The worker rebuilds a session runtime per process, so it needs a store
1400        // factory; without one the default runner could not execute anything, so
1401        // fail loudly rather than silently leave processes unexecuted.
1402        let Some(store_factory) = store_factory else {
1403            return Err(EmbedError::ProcessRegistryRequiresStoreFactory);
1404        };
1405        // The worker rebuilds with the same plugin host the live runtime uses,
1406        // including the protocol plugin that supplies the protocol session
1407        // capability.
1408        let phase_probe_slot = lash_core::runtime::RuntimeTurnPhaseProbeSlot::default();
1409        let config = Box::new(
1410            DurableProcessWorkerConfig::new(
1411                Arc::new(worker_plugin_host.clone()),
1412                core.clone(),
1413                Arc::clone(store_factory),
1414                process_registry,
1415            )
1416            .with_session_policy(policy.clone())
1417            .with_trigger_store(trigger_store.cloned().unwrap_or_else(|| {
1418                Arc::new(lash_core::InMemoryTriggerStore::with_clock(Arc::clone(
1419                    &core.clock,
1420                )))
1421            }))
1422            .with_residency(residency)
1423            .with_turn_phase_probe_slot(phase_probe_slot),
1424        );
1425        Ok(ProcessWorkDriverSetup::LazyDefault { config })
1426    }
1427
1428    #[allow(clippy::too_many_arguments)]
1429    fn resolve_queued_work_driver(
1430        queued_work_source: &QueuedWorkSource,
1431        env: RuntimeEnvironment,
1432        policy: SessionPolicy,
1433        protocol_factory: Option<Arc<dyn PluginFactory>>,
1434        plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
1435        store_factory: Option<&Arc<dyn SessionStoreFactory>>,
1436        live_replay_store: Arc<dyn LiveReplayStore>,
1437        runtime_host_installer: Option<RuntimeHostInstaller>,
1438    ) -> QueuedWorkDriverSetup {
1439        match queued_work_source {
1440            QueuedWorkSource::None => QueuedWorkDriverSetup::None,
1441            QueuedWorkSource::External(driver) => QueuedWorkDriverSetup::External {
1442                driver: driver.clone(),
1443            },
1444            QueuedWorkSource::LazyDefault => match store_factory {
1445                Some(store_factory) => QueuedWorkDriverSetup::LazyDefault {
1446                    config: Arc::new(InlineQueuedWorkRunConfig::new(
1447                        env,
1448                        policy,
1449                        protocol_factory,
1450                        plugin_factories,
1451                        Arc::clone(store_factory),
1452                        live_replay_store,
1453                        runtime_host_installer,
1454                    )),
1455                },
1456                None => QueuedWorkDriverSetup::None,
1457            },
1458        }
1459    }
1460
1461    pub fn advanced(self) -> AdvancedLashCoreBuilder {
1462        AdvancedLashCoreBuilder { builder: self }
1463    }
1464
1465    pub fn process_registry(mut self, process_registry: Arc<dyn ProcessRegistry>) -> Self {
1466        self.process_work_source = ProcessWorkSource::Inline {
1467            registry: process_registry,
1468        };
1469        self
1470    }
1471
1472    pub fn trigger_store(mut self, store: Arc<dyn lash_core::TriggerStore>) -> Self {
1473        self.trigger_store = Some(store);
1474        self
1475    }
1476
1477    /// Configure an externally owned process work runner.
1478    ///
1479    /// Durable hosts construct a [`ProcessWorkDriver`] from the same process
1480    /// registry and wake handle used by their deployment runner, then pass it
1481    /// here. The driver registry becomes the core's process registry and no
1482    /// inline runner is spawned.
1483    pub fn process_work_driver(mut self, driver: ProcessWorkDriver) -> Self {
1484        self.process_work_source = ProcessWorkSource::External(driver);
1485        self
1486    }
1487
1488    /// Configure an externally owned queued-work driver.
1489    pub fn queued_work_driver(mut self, driver: QueuedWorkDriver) -> Self {
1490        self.queued_work_source = QueuedWorkSource::External(driver);
1491        self
1492    }
1493
1494    pub fn disable_queued_work_driver(mut self) -> Self {
1495        self.queued_work_source = QueuedWorkSource::None;
1496        self
1497    }
1498}
1499
1500pub(crate) fn build_plugin_host(
1501    protocol_factory: Option<&Arc<dyn PluginFactory>>,
1502    common_factories: &[Arc<dyn PluginFactory>],
1503    extra_factories: Vec<Arc<dyn PluginFactory>>,
1504) -> Result<PluginHost> {
1505    let mut factories = Vec::with_capacity(
1506        usize::from(protocol_factory.is_some()) + common_factories.len() + extra_factories.len(),
1507    );
1508    if let Some(protocol_factory) = protocol_factory {
1509        factories.push(Arc::clone(protocol_factory));
1510    }
1511    factories.extend(common_factories.iter().cloned());
1512    factories.extend(extra_factories);
1513    Ok(PluginHost::new(factories))
1514}
1515
1516impl PromptLayerSink for LashCoreBuilder {
1517    fn prompt_layer_mut(&mut self) -> &mut PromptLayer {
1518        self.prompt.get_or_insert_with(PromptLayer::new)
1519    }
1520}
1521
1522pub struct AdvancedLashCoreBuilder {
1523    builder: LashCoreBuilder,
1524}
1525
1526impl AdvancedLashCoreBuilder {
1527    pub fn runtime_host_config(mut self, core: lash_core::RuntimeHostConfig) -> Self {
1528        self.builder.runtime_host_config = Some(core);
1529        self
1530    }
1531
1532    pub fn plugin_host(mut self, plugin_host: PluginHost) -> Self {
1533        self.builder.plugin_host = Some(plugin_host);
1534        self
1535    }
1536
1537    pub fn build(self) -> Result<LashCore> {
1538        self.builder.build()
1539    }
1540}