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