Skip to main content

lash/
core.rs

1use crate::support::*;
2use lash_core::runtime::{
3    ProcessCommand, ProcessEffectOutcome, RuntimeEffectCommand, RuntimeEffectEnvelope,
4    RuntimeEffectKind, RuntimeEffectLocalExecutor, RuntimeEffectOutcome, RuntimeInvocation,
5    RuntimeScope,
6};
7
8#[derive(Clone)]
9pub struct LashCore {
10    pub(crate) env: RuntimeEnvironment,
11    pub(crate) policy: SessionPolicy,
12    pub(crate) protocol_factory: Option<Arc<dyn PluginFactory>>,
13    pub(crate) store_factory: Option<Arc<dyn SessionStoreFactory>>,
14    pub(crate) plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
15    pub(crate) provider: Option<ProviderHandle>,
16    pub(crate) live_replay_store: Arc<dyn LiveReplayStore>,
17    /// Whether this deployment has process lifecycle available (a process
18    /// registry is wired). Threaded to every plugin host so core can install the
19    /// same plugin-contributed process engines when it rebuilds a runtime.
20    pub(crate) process_lifecycle_available: bool,
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        hub: Option<lash_core::ProcessChangeHub>,
50    },
51    External(ProcessWorkDriver),
52}
53
54impl ProcessWorkSource {
55    fn process_registry(&self) -> Option<Arc<dyn ProcessRegistry>> {
56        match self {
57            Self::None => None,
58            Self::Inline { registry, .. } => Some(Arc::clone(registry)),
59            Self::External(driver) => Some(driver.process_registry()),
60        }
61    }
62
63    fn has_registry(&self) -> bool {
64        !matches!(self, Self::None)
65    }
66
67    fn watched(self, sink: Option<Arc<dyn lash_core::ProcessEventSink>>) -> Self {
68        match self {
69            Self::Inline {
70                registry,
71                hub: None,
72            } => {
73                let (registry, hub) = lash_core::watch_process_registry_with_sink(registry, sink);
74                Self::Inline {
75                    registry,
76                    hub: Some(hub),
77                }
78            }
79            // An external driver was wrapped by its host, which installs any
80            // sink through the driver constructor; the inline sink does not
81            // apply here. Already-watched inline sources keep their wrap.
82            other => other,
83        }
84    }
85}
86
87#[derive(Clone, Default)]
88pub(crate) enum QueuedWorkSource {
89    None,
90    #[default]
91    LazyDefault,
92    External(QueuedWorkDriver),
93}
94
95pub(crate) enum QueuedWorkDriverSetup {
96    None,
97    LazyDefault {
98        config: Arc<InlineQueuedWorkRunConfig>,
99    },
100    External {
101        driver: QueuedWorkDriver,
102    },
103}
104
105pub(crate) struct InlineWorkDriverSetup {
106    process: ProcessWorkDriverSetup,
107    queued: QueuedWorkDriverSetup,
108}
109
110#[derive(Clone, Default)]
111pub(crate) struct ResolvedWorkDrivers {
112    pub(crate) process: Option<ProcessWorkDriver>,
113    pub(crate) queued: Option<QueuedWorkDriver>,
114    pub(crate) drive_process_on_open: bool,
115}
116
117/// Shared, lazily-initialized host-work state for a [`LashCore`].
118///
119/// The once-guard ([`tokio::sync::OnceCell`]) constructs inline drivers exactly
120/// once across `LashCore` clones, on the first `session().open()` or admin path
121/// that needs them.
122pub(crate) struct InlineWorkDriverSlot {
123    setup: InlineWorkDriverSetup,
124    drivers: tokio::sync::OnceCell<ResolvedWorkDrivers>,
125    phase_probe_slot: Option<lash_core::runtime::RuntimeTurnPhaseProbeSlot>,
126}
127
128impl InlineWorkDriverSlot {
129    fn new(setup: InlineWorkDriverSetup) -> Self {
130        let phase_probe_slot = match &setup.process {
131            ProcessWorkDriverSetup::LazyDefault { config } => {
132                Some(config.turn_phase_probe_slot.clone())
133            }
134            ProcessWorkDriverSetup::None | ProcessWorkDriverSetup::External { .. } => None,
135        };
136        Self {
137            setup,
138            drivers: tokio::sync::OnceCell::new(),
139            phase_probe_slot,
140        }
141    }
142
143    /// Resolve host work drivers for a session host. Idempotent: the once-guard
144    /// ensures inline drivers are constructed once.
145    pub(crate) async fn drivers(&self) -> ResolvedWorkDrivers {
146        self.drivers
147            .get_or_init(|| async {
148                let queued = match &self.setup.queued {
149                    QueuedWorkDriverSetup::None => None,
150                    QueuedWorkDriverSetup::External { driver } => Some(driver.clone()),
151                    QueuedWorkDriverSetup::LazyDefault { config } => Some(QueuedWorkDriver::new(
152                        Arc::new(InlineQueuedWorkRunHandle::new(Arc::clone(config))),
153                    )),
154                };
155                let (process, drive_process_on_open) = match &self.setup.process {
156                    ProcessWorkDriverSetup::None => (None, false),
157                    ProcessWorkDriverSetup::External { driver } => (Some(driver.clone()), false),
158                    ProcessWorkDriverSetup::LazyDefault { config } => {
159                        let mut config = (**config).clone();
160                        if let Some(driver) = queued.clone() {
161                            config = config.with_queued_work_driver(driver);
162                        }
163                        let registry = Arc::clone(&config.process_registry);
164                        let hub = config.process_change_hub.clone();
165                        let worker = DurableProcessWorker::new(config);
166                        let driver = if let Some(hub) = hub {
167                            ProcessWorkDriver::from_watched(
168                                registry,
169                                hub,
170                                Arc::new(lash_core::InlineProcessRunHandle::new(worker)),
171                            )
172                        } else {
173                            ProcessWorkDriver::inline(registry, worker)
174                        };
175                        (Some(driver), true)
176                    }
177                };
178                ResolvedWorkDrivers {
179                    process,
180                    queued,
181                    drive_process_on_open,
182                }
183            })
184            .await
185            .clone()
186    }
187
188    pub(crate) fn phase_probe_slot(&self) -> Option<lash_core::runtime::RuntimeTurnPhaseProbeSlot> {
189        self.phase_probe_slot.clone()
190    }
191
192    fn configured_process_work_driver(&self) -> Option<ProcessWorkDriver> {
193        match &self.setup.process {
194            ProcessWorkDriverSetup::External { driver } => Some(driver.clone()),
195            ProcessWorkDriverSetup::None | ProcessWorkDriverSetup::LazyDefault { .. } => None,
196        }
197    }
198
199    fn configured_queued_work_driver(&self) -> Option<QueuedWorkDriver> {
200        match &self.setup.queued {
201            QueuedWorkDriverSetup::External { driver } => Some(driver.clone()),
202            QueuedWorkDriverSetup::None | QueuedWorkDriverSetup::LazyDefault { .. } => None,
203        }
204    }
205}
206
207pub(crate) struct InlineQueuedWorkRunConfig {
208    env: RuntimeEnvironment,
209    policy: SessionPolicy,
210    protocol_factory: Option<Arc<dyn PluginFactory>>,
211    plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
212    store_factory: Arc<dyn SessionStoreFactory>,
213    live_replay_store: Arc<dyn LiveReplayStore>,
214    process_lifecycle_available: bool,
215}
216
217impl InlineQueuedWorkRunConfig {
218    fn new(
219        env: RuntimeEnvironment,
220        policy: SessionPolicy,
221        protocol_factory: Option<Arc<dyn PluginFactory>>,
222        plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
223        store_factory: Arc<dyn SessionStoreFactory>,
224        live_replay_store: Arc<dyn LiveReplayStore>,
225        process_lifecycle_available: bool,
226    ) -> Self {
227        Self {
228            env,
229            policy,
230            protocol_factory,
231            plugin_factories,
232            store_factory,
233            live_replay_store,
234            process_lifecycle_available,
235        }
236    }
237}
238
239struct InlineQueuedWorkRunHandle {
240    config: Arc<InlineQueuedWorkRunConfig>,
241}
242
243impl InlineQueuedWorkRunHandle {
244    fn new(config: Arc<InlineQueuedWorkRunConfig>) -> Self {
245        Self { config }
246    }
247}
248
249#[async_trait]
250impl QueuedWorkRunHandle for InlineQueuedWorkRunHandle {
251    async fn run_queued_work(
252        &self,
253        request: QueuedWorkRunRequest,
254    ) -> std::result::Result<(), lash_core::PluginError> {
255        let Some(session_id) = request.session_id else {
256            return Ok(());
257        };
258        let reason = request.reason;
259        let mut policy = self.config.policy.clone();
260        policy.session_id = Some(session_id.clone());
261        let store = self
262            .config
263            .store_factory
264            .create_store(&SessionStoreCreateRequest {
265                session_id: session_id.clone(),
266                relation: SessionRelation::default(),
267                policy: policy.clone(),
268            })
269            .await
270            .map_err(lash_core::PluginError::Session)?;
271        let state = crate::session::load_state_for_residency(
272            self.config.env.residency,
273            &session_id,
274            &policy,
275            store.as_ref(),
276        )
277        .await
278        .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
279        let plugin_host = build_plugin_host(
280            self.config.protocol_factory.as_ref(),
281            self.config.plugin_factories.as_ref(),
282            Vec::new(),
283        )
284        .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
285        let mut env = self.config.env.clone();
286        env.core = plugin_host
287            .install_process_engine_contributions(
288                env.core.clone(),
289                self.config.process_lifecycle_available,
290            )
291            .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
292        env.plugin_host = Some(Arc::new(plugin_host));
293        let effect_host = Arc::clone(&env.core.control.effect_host);
294        let runtime = LashRuntime::from_environment(&env, policy, state, Some(store))
295            .await
296            .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
297        let handle = RuntimeHandle::with_live_replay_store(
298            runtime,
299            Arc::clone(&self.config.live_replay_store),
300        );
301        let scope = lash_core::ExecutionScope::queue_drain(session_id, reason);
302        let scoped = effect_host
303            .scoped(scope)
304            .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
305        crate::turn::stream_next_queued_prepared_turn(
306            &handle,
307            crate::turn::TurnSinks::default(),
308            scoped,
309            CancellationToken::new(),
310            &[],
311        )
312        .await
313        .map_err(|err| lash_core::PluginError::Session(err.to_string()))?;
314        Ok(())
315    }
316}
317
318#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
319pub struct SessionDeleteReport {
320    pub session_id: String,
321    pub process: Option<lash_core::ProcessSessionDeleteReport>,
322}
323
324impl LashCore {
325    pub fn builder() -> LashCoreBuilder {
326        LashCoreBuilder::default()
327    }
328
329    /// Sugar entry point: a [`LashCoreBuilder`] pre-seeded with the standard
330    /// protocol plugin and the default runtime plugin stack.
331    pub fn standard_builder() -> LashCoreBuilder {
332        LashCore::builder()
333            .protocol_plugin(Arc::new(
334                lash_protocol_standard::StandardProtocolPluginFactory::new(),
335            ))
336            .plugins(default_runtime_stack())
337    }
338
339    /// Sugar entry point: a [`LashCoreBuilder`] pre-seeded with a
340    /// host-configured RLM protocol factory and the default runtime plugin
341    /// stack.
342    ///
343    /// The host configures the factory (projection resolver, deferred tool
344    /// resolver, execution sink/jsonl path, and — required at construction — the
345    /// Lashlang artifact store) before passing it in.
346    #[cfg(feature = "rlm")]
347    pub fn rlm_builder(factory: crate::rlm::RlmProtocolPluginFactory) -> LashCoreBuilder {
348        LashCore::builder()
349            .protocol_plugin(Arc::new(factory))
350            .plugins(default_runtime_stack())
351    }
352
353    pub fn session(&self, session_id: impl Into<String>) -> SessionBuilder {
354        SessionBuilder {
355            core: self.clone(),
356            session_id: session_id.into(),
357            spec: SessionSpec::inherit(),
358            parent_session_id: None,
359            session_execution_owner: None,
360            store: None,
361            provider: None,
362            active_plugins: Vec::new(),
363            plugin_factories: Vec::new(),
364            plugin_options: PluginOptions::default(),
365        }
366    }
367
368    /// Rebuild a live session from a [`ParkedSession`](crate::ParkedSession)
369    /// handle produced by [`LashSession::park`](crate::LashSession::park).
370    ///
371    /// Resume reloads the flushed state from the parked store (honoring this
372    /// core's residency), reinstalls this core's plugin configuration and work
373    /// drivers, and returns a ready [`LashSession`]. The parked store instance
374    /// is reused directly, so the transcript the session flushed at park time is
375    /// visible again after resume.
376    ///
377    /// This restores the core-level plugin stack. Session-specific plugins added
378    /// per open via [`SessionBuilder::plugin`] are not re-applied here; parking
379    /// is the round-trip for the core's own configuration.
380    pub async fn resume(&self, parked: ParkedSession) -> Result<LashSession> {
381        // Build the per-session env exactly like `SessionBuilder::open_resolved`
382        // (minus builder-scoped plugins): a fresh plugin host with this core's
383        // factories, the shared work drivers, and the core provider resolver
384        // already carried on `self.env`.
385        let plugin_host = build_plugin_host(
386            self.protocol_factory.as_ref(),
387            self.plugin_factories.as_ref(),
388            Vec::new(),
389        )?;
390        let mut env = self.env.clone();
391        env.core = plugin_host.install_process_engine_contributions(
392            env.core.clone(),
393            self.process_lifecycle_available,
394        )?;
395        env.plugin_host = Some(Arc::new(plugin_host));
396        let effect_host = Arc::clone(&env.core.control.effect_host);
397        let drivers = self.work_driver.drivers().await;
398        env.process_work_driver = drivers.process.clone();
399        env.queued_work_driver = drivers.queued.clone();
400        let runtime = LashRuntime::resume(parked.inner, &env).await?;
401        let handle =
402            RuntimeHandle::with_live_replay_store(runtime, Arc::clone(&self.live_replay_store));
403        Ok(LashSession {
404            runtime: handle,
405            effect_host,
406            parent_session_id: None,
407            active_plugins: Vec::new(),
408            process_phase_probe_slot: self.work_driver.phase_probe_slot(),
409            turn_cancels: crate::turn::TurnCancelRegistry::default(),
410        })
411    }
412
413    /// Flush this core's configured trace sink, if any.
414    ///
415    /// Hosts that hand `lash` a trace sink via
416    /// [`LashCoreBuilder::trace_sink`] already hold their own `Arc` and can
417    /// flush it directly; this is the equivalent lever for hosts that did not
418    /// retain the handle. It flushes the core's copy — for a
419    /// [`JsonlTraceSink`](lash_trace::JsonlTraceSink) that fsyncs the file, and
420    /// for an OTel sink it is a no-op (the host still owns provider flush; see
421    /// the tracing docs). Call it before process exit alongside the host's own
422    /// exporter/provider shutdown.
423    pub fn flush_trace_sink(&self) -> Result<()> {
424        if let Some(sink) = self.env.core.tracing.trace_sink.as_ref() {
425            sink.flush()?;
426        }
427        Ok(())
428    }
429
430    pub fn triggers(&self) -> crate::admin::CoreTriggerAdmin {
431        crate::admin::CoreTriggerAdmin { core: self.clone() }
432    }
433
434    pub fn processes(&self) -> crate::process_admin::Processes {
435        crate::process_admin::Processes { core: self.clone() }
436    }
437
438    pub fn completions(&self) -> crate::admin::Completions {
439        crate::admin::Completions { core: self.clone() }
440    }
441
442    pub fn effect_host(&self) -> Arc<dyn EffectHost> {
443        Arc::clone(&self.env.core.control.effect_host)
444    }
445
446    pub async fn delete_session(
447        &self,
448        session_id: impl AsRef<str>,
449        scoped_effect_controller: ScopedEffectController<'_>,
450    ) -> Result<SessionDeleteReport> {
451        let session_id = session_id.as_ref().to_string();
452        let Some(store_factory) = self.store_factory.as_ref() else {
453            return Err(EmbedError::MissingSessionStoreFactory);
454        };
455        let process = if let Some(process_registry) = self.env.process_registry.as_ref() {
456            let invocation = RuntimeInvocation::effect(
457                RuntimeScope::new(session_id.clone()),
458                format!("process:delete-session:{session_id}"),
459                RuntimeEffectKind::Process,
460                format!("{session_id}:delete-session"),
461            );
462            let outcome = scoped_effect_controller
463                .controller()
464                .execute_effect(
465                    RuntimeEffectEnvelope::new(
466                        invocation,
467                        RuntimeEffectCommand::process(ProcessCommand::DeleteSession {
468                            session_id: session_id.clone(),
469                        }),
470                    ),
471                    RuntimeEffectLocalExecutor::processes(
472                        Arc::clone(process_registry),
473                        self.env.process_work_driver.clone(),
474                    ),
475                )
476                .await
477                .map_err(|err| EmbedError::SessionDeleteProcess {
478                    session_id: session_id.clone(),
479                    message: err.to_string(),
480                })?;
481            match outcome {
482                RuntimeEffectOutcome::Process {
483                    result: ProcessEffectOutcome::DeleteSession { report },
484                } => Some(report),
485                other => {
486                    return Err(EmbedError::SessionDeleteProcess {
487                        session_id,
488                        message: format!(
489                            "process delete returned the wrong outcome: {}",
490                            other.kind().as_str()
491                        ),
492                    });
493                }
494            }
495        } else {
496            None
497        };
498        if let Some(trigger_store) = self.env.trigger_store.as_ref() {
499            trigger_store
500                .delete_session_subscriptions(&session_id)
501                .await
502                .map_err(|err| EmbedError::SessionDeleteProcess {
503                    session_id: session_id.clone(),
504                    message: err.to_string(),
505                })?;
506        }
507        self.env
508            .core
509            .control
510            .effect_host
511            .revoke_await_events_for_session(&session_id)
512            .await
513            .map_err(|err| EmbedError::SessionDeleteProcess {
514                session_id: session_id.clone(),
515                message: err.to_string(),
516            })?;
517        store_factory
518            .delete_session(&session_id)
519            .await
520            .map_err(|message| EmbedError::StoreFactory {
521                session_id: session_id.clone(),
522                message,
523            })?;
524        Ok(SessionDeleteReport {
525            session_id,
526            process,
527        })
528    }
529
530    pub fn process_registry(&self) -> Option<Arc<dyn ProcessRegistry>> {
531        self.env.process_registry.as_ref().cloned()
532    }
533
534    pub fn durable_process_worker_config(&self) -> Result<DurableProcessWorkerConfig> {
535        self.durable_process_worker_config_with_plugins(std::iter::empty::<Arc<dyn PluginFactory>>())
536    }
537
538    pub fn durable_process_worker_config_with_plugins(
539        &self,
540        extra_plugin_factories: impl IntoIterator<Item = Arc<dyn PluginFactory>>,
541    ) -> Result<DurableProcessWorkerConfig> {
542        let Some(process_registry) = self.process_registry() else {
543            return Err(EmbedError::MissingProcessRegistry);
544        };
545        let Some(store_factory) = self.store_factory.as_ref() else {
546            return Err(EmbedError::MissingProcessWorkerStoreFactory);
547        };
548        let plugin_host = build_plugin_host(
549            self.protocol_factory.as_ref(),
550            self.plugin_factories.as_ref(),
551            extra_plugin_factories.into_iter().collect(),
552        )?;
553        let runtime_host = plugin_host.install_process_engine_contributions(
554            self.env.core.clone(),
555            self.process_lifecycle_available,
556        )?;
557        let mut config = DurableProcessWorkerConfig::new(
558            Arc::new(plugin_host),
559            runtime_host,
560            Arc::clone(store_factory),
561            process_registry,
562        )
563        .with_session_policy(self.policy.clone())
564        .with_residency(self.env.residency);
565        if let Some(trigger_store) = self.env.trigger_store.as_ref() {
566            config = config.with_trigger_store(Arc::clone(trigger_store));
567        }
568        if let Some(driver) = self.work_driver.configured_process_work_driver() {
569            config = config
570                .with_change_hub(driver.change_hub())
571                .with_process_work_driver(driver);
572        }
573        if let Some(driver) = self.work_driver.configured_queued_work_driver() {
574            config = config.with_queued_work_driver(driver);
575        }
576        Ok(config)
577    }
578}
579
580fn default_runtime_stack() -> PluginStack {
581    lash_plugin_tool_output_budget::tool_output_budget_stack()
582}
583
584#[derive(Default)]
585pub struct LashCoreBuilder {
586    pub(crate) protocol_factory: Option<Arc<dyn PluginFactory>>,
587    session_spec: SessionSpec,
588    provider: Option<ProviderHandle>,
589    pub(crate) store_factory: Option<Arc<dyn SessionStoreFactory>>,
590    child_store_factory: Option<Arc<dyn SessionStoreFactory>>,
591    // `RuntimeHostConfig` has no `Default`: the generic host-owned durability
592    // dependencies must be named. They are collected here and resolved in
593    // `build()`, which errors if any is unset.
594    effect_host: Option<Arc<dyn EffectHost>>,
595    attachment_store: Option<Arc<dyn AttachmentStore>>,
596    process_env_store: Option<Arc<dyn ProcessExecutionEnvStore>>,
597    trigger_store: Option<Arc<dyn lash_core::TriggerStore>>,
598    // Benign core overrides applied on top of the resolved core.
599    prompt: Option<PromptLayer>,
600    trace_sink: Option<Arc<dyn lash_trace::TraceSink>>,
601    trace_level: Option<lash_trace::TraceLevel>,
602    trace_context: Option<lash_trace::TraceContext>,
603    termination: Option<TerminationPolicy>,
604    // Advanced full-config override; used as the base core when present.
605    runtime_host_config: Option<RuntimeHostConfig>,
606    tool_providers: Vec<Arc<dyn ToolProvider>>,
607    plugin_stack: PluginStack,
608    plugin_host: Option<PluginHost>,
609    residency: Option<Residency>,
610    lease_timings: Option<lash_core::LeaseTimings>,
611    clock: Option<Arc<dyn lash_core::Clock>>,
612    // Single source of truth for process lifecycle support and process-work
613    // consumption.
614    process_work_source: ProcessWorkSource,
615    // Optional host-facing best-effort feed of appended process events,
616    // installed on the inline process-registry decorator at build time.
617    process_event_sink: Option<Arc<dyn lash_core::ProcessEventSink>>,
618    queued_work_source: QueuedWorkSource,
619    live_replay_store: Option<Arc<dyn LiveReplayStore>>,
620}
621
622impl LashCoreBuilder {
623    pub fn protocol_plugin(mut self, plugin: Arc<dyn PluginFactory>) -> Self {
624        self.protocol_factory = Some(plugin);
625        self
626    }
627
628    pub fn provider(mut self, provider: ProviderHandle) -> Self {
629        self.session_spec = self.session_spec.provider_id(provider.kind());
630        self.provider = Some(provider);
631        self
632    }
633
634    pub fn model(mut self, model: lash_core::ModelSpec) -> Self {
635        self.session_spec = self.session_spec.model(model);
636        self
637    }
638
639    pub fn max_turns(mut self, max_turns: usize) -> Self {
640        self.session_spec = self.session_spec.max_turns(max_turns);
641        self
642    }
643
644    pub fn session_spec(mut self, spec: SessionSpec) -> Self {
645        self.session_spec = spec;
646        self
647    }
648
649    /// Configure a factory that can create a persistence store for any root
650    /// session opened from this core.
651    ///
652    /// The factory must honor `SessionStoreCreateRequest::session_id` and
653    /// return a store for that specific session. Do not use this to wrap one
654    /// pre-opened root store; pass root-only stores with
655    /// `LashCore::session(...).store(store)` instead.
656    pub fn store_factory(mut self, store_factory: Arc<dyn SessionStoreFactory>) -> Self {
657        self.store_factory = Some(store_factory);
658        self
659    }
660
661    /// Configure the persistence factory used by managed child sessions, such
662    /// as local subagents.
663    ///
664    /// Child factories must return a distinct store bound to the requested
665    /// child session id. Hosts that pass an explicit root store with
666    /// `SessionBuilder::store` should set this when child sessions need
667    /// persistence.
668    pub fn child_store_factory(mut self, store_factory: Arc<dyn SessionStoreFactory>) -> Self {
669        self.child_store_factory = Some(store_factory);
670        self
671    }
672
673    pub fn attachment_store(mut self, attachment_store: Arc<dyn AttachmentStore>) -> Self {
674        self.attachment_store = Some(attachment_store);
675        self
676    }
677
678    pub fn process_env_store(
679        mut self,
680        process_env_store: Arc<dyn ProcessExecutionEnvStore>,
681    ) -> Self {
682        self.process_env_store = Some(process_env_store);
683        self
684    }
685
686    /// Set the deployment effect host — the durability boundary every operation
687    /// crosses. Pass [`InlineEffectHost`](crate::durability::InlineEffectHost)
688    /// for in-process execution, or a workflow-backed host for durable
689    /// execution.
690    pub fn effect_host(mut self, effect_host: Arc<dyn EffectHost>) -> Self {
691        self.effect_host = Some(effect_host);
692        self
693    }
694
695    pub fn tools(mut self, tools: Arc<dyn ToolProvider>) -> Self {
696        self.tool_providers.push(tools);
697        self
698    }
699
700    pub fn plugin(mut self, plugin: Arc<dyn PluginFactory>) -> Self {
701        self.plugin_stack.push(plugin);
702        self
703    }
704
705    pub fn plugins(mut self, stack: PluginStack) -> Self {
706        self.plugin_stack = stack;
707        self
708    }
709
710    pub fn configure_plugins(mut self, configure: impl FnOnce(&mut PluginStack)) -> Self {
711        configure(&mut self.plugin_stack);
712        self
713    }
714
715    pub fn trace_sink(mut self, trace_sink: Arc<dyn lash_trace::TraceSink>) -> Self {
716        self.trace_sink = Some(trace_sink);
717        self
718    }
719
720    pub fn trace_jsonl_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
721        self.trace_sink = Some(Arc::new(lash_trace::JsonlTraceSink::new(path.into())));
722        self
723    }
724
725    pub fn trace_level(mut self, trace_level: lash_trace::TraceLevel) -> Self {
726        self.trace_level = Some(trace_level);
727        self
728    }
729
730    pub fn trace_context(mut self, trace_context: lash_trace::TraceContext) -> Self {
731        self.trace_context = Some(trace_context);
732        self
733    }
734
735    pub fn termination(mut self, termination: TerminationPolicy) -> Self {
736        self.termination = Some(termination);
737        self
738    }
739
740    pub fn residency(mut self, residency: Residency) -> Self {
741        self.residency = Some(residency);
742        self
743    }
744
745    /// Configure the lease timing capability for every durable single-writer
746    /// lane this deployment claims: session execution leases, turn-input and
747    /// queued-work claims, and process leases.
748    ///
749    /// This is the failover-latency vs false-takeover-risk knob. Like
750    /// [`residency`](Self::residency) it is an operational deployment decision,
751    /// so it lives on the main builder tier rather than behind
752    /// [`advanced`](Self::advanced). Construct the value with
753    /// [`LeaseTimings::new`](lash_core::LeaseTimings::new), which enforces
754    /// `ttl >= 3 * renew_interval`. Effect hosts accept the same type at
755    /// construction (e.g. SQLite/Postgres effect-replay options), so a host can
756    /// share one timing decision across both boundaries.
757    pub fn lease_timings(mut self, lease_timings: lash_core::LeaseTimings) -> Self {
758        self.lease_timings = Some(lease_timings);
759        self
760    }
761
762    /// Use one host clock for runtime sleeps and embedded-store time.
763    pub fn clock(mut self, clock: Arc<dyn lash_core::Clock>) -> Self {
764        self.clock = Some(clock);
765        self
766    }
767
768    /// Configure the bounded live replay buffer used by session observation
769    /// cursors. This is best-effort reconnect recovery only; durable state
770    /// still comes from the session store and [`SessionReadView`].
771    pub fn live_replay_store(mut self, live_replay_store: Arc<dyn LiveReplayStore>) -> Self {
772        self.live_replay_store = Some(live_replay_store);
773        self
774    }
775
776    /// Resolve the runtime host config, requiring the generic host-owned
777    /// durability dependencies to have been named.
778    fn resolve_runtime_host_config(&mut self) -> Result<RuntimeHostConfig> {
779        if let Some(base) = self.runtime_host_config.take() {
780            return Ok(self.apply_core_overrides(base));
781        }
782        let effect_host = self
783            .effect_host
784            .take()
785            .ok_or(EmbedError::MissingEffectHost)?;
786        let attachment_store = self
787            .attachment_store
788            .take()
789            .ok_or(EmbedError::MissingAttachmentStore)?;
790        let process_env_store = self
791            .process_env_store
792            .take()
793            .ok_or(EmbedError::MissingProcessEnvStore)?;
794        let core = RuntimeHostConfig::new(effect_host, attachment_store, process_env_store);
795        Ok(self.apply_core_overrides(core))
796    }
797
798    /// Apply benign + still-set dependency overrides on top of a base core.
799    fn apply_core_overrides(&mut self, mut core: RuntimeHostConfig) -> RuntimeHostConfig {
800        if let Some(effect_host) = self.effect_host.take() {
801            core.control.effect_host = effect_host;
802        }
803        if let Some(attachment_store) = self.attachment_store.take() {
804            core.durability.attachment_store = Arc::new(
805                lash_core::SessionAttachmentStore::ephemeral(attachment_store),
806            );
807        }
808        if let Some(process_env_store) = self.process_env_store.take() {
809            core.durability.process_env_store = process_env_store;
810        }
811        if let Some(prompt) = self.prompt.take() {
812            core.prompt.prompt = prompt;
813        }
814        if let Some(trace_sink) = self.trace_sink.take() {
815            core.tracing.trace_sink = Some(trace_sink);
816        }
817        if let Some(trace_level) = self.trace_level.take() {
818            core.tracing.trace_level = trace_level;
819        }
820        if let Some(trace_context) = self.trace_context.take() {
821            core.tracing.trace_context = trace_context;
822        }
823        if let Some(termination) = self.termination.take() {
824            core.control.termination = termination;
825        }
826        if let Some(lease_timings) = self.lease_timings.take() {
827            core.control.lease_timings = lease_timings;
828        }
829        if let Some(clock) = self.clock.take() {
830            core.clock = clock;
831        }
832        core
833    }
834
835    /// Validate store peer-coherence of the wired durability dependencies.
836    ///
837    /// Durability is established by what the host wired; the per-invocation
838    /// durable controller is not visible here (the build-time controller is
839    /// inline by construction), so this checks the stores against each other
840    /// only — never the controller (see A5 in the durable-first wiring spec):
841    ///
842    /// - a durable session store factory requires a durable attachment and
843    ///   artifact store (they back the same session state);
844    /// - a durable process registry requires a session store factory that is
845    ///   itself durable (the registry's process records are meaningless without
846    ///   a durable session behind them).
847    fn effective_session_store_tier(&self) -> Option<DurabilityTier> {
848        self.child_store_factory
849            .as_ref()
850            .or(self.store_factory.as_ref())
851            .map(|factory| factory.durability_tier())
852    }
853
854    /// Validate store peer-coherence, sweeping every registered process engine.
855    ///
856    /// Runs after the runtime host is resolved and process-engine contributions
857    /// are installed, so it reads the effective effect host / attachment /
858    /// process-env tiers off `core`, and the session-store / trigger-store /
859    /// process-registry tiers captured from the builder before its plugin stack
860    /// was consumed. A durable session store requires every registered engine to
861    /// be durable too.
862    fn ensure_store_peer_coherence(
863        session_store_tier: Option<DurabilityTier>,
864        trigger_store_tier: Option<DurabilityTier>,
865        process_registry_tier: Option<DurabilityTier>,
866        core: &RuntimeHostConfig,
867    ) -> Result<()> {
868        let attachment_tier = Some(
869            core.durability
870                .attachment_store
871                .persistence()
872                .durability_tier(),
873        );
874        let process_env_tier = Some(core.durability.process_env_store.durability_tier());
875        let effect_host_tier = Some(core.control.effect_host.durability_tier());
876
877        if session_store_tier == Some(DurabilityTier::Durable) {
878            if attachment_tier == Some(DurabilityTier::Inline) {
879                return Err(EmbedError::DurableStorePeerRequired {
880                    facet: "attachment store",
881                });
882            }
883            if process_env_tier == Some(DurabilityTier::Inline) {
884                return Err(EmbedError::DurableStorePeerRequired {
885                    facet: "process execution environment store",
886                });
887            }
888            // Every registered process engine must be durable behind a durable
889            // session store, regardless of how it was contributed.
890            for engine in core.process_engines.engines() {
891                if engine.durability_tier() == DurabilityTier::Inline {
892                    return Err(EmbedError::DurableStorePeerRequired {
893                        facet: engine.kind(),
894                    });
895                }
896            }
897        }
898
899        if process_registry_tier == Some(DurabilityTier::Durable) {
900            if session_store_tier != Some(DurabilityTier::Durable) {
901                return Err(EmbedError::DurableProcessRegistryRequiresStoreFactory);
902            }
903            if trigger_store_tier != Some(DurabilityTier::Durable) {
904                return Err(EmbedError::DurableStorePeerRequired {
905                    facet: "trigger store",
906                });
907            }
908            if process_env_tier != Some(DurabilityTier::Durable) {
909                return Err(EmbedError::DurableStorePeerRequired {
910                    facet: "process execution environment store",
911                });
912            }
913        }
914
915        if trigger_store_tier == Some(DurabilityTier::Durable) {
916            if session_store_tier != Some(DurabilityTier::Durable) {
917                return Err(EmbedError::DurableStorePeerRequired {
918                    facet: "session store factory",
919                });
920            }
921            if process_env_tier != Some(DurabilityTier::Durable) {
922                return Err(EmbedError::DurableStorePeerRequired {
923                    facet: "process execution environment store",
924                });
925            }
926            if process_registry_tier == Some(DurabilityTier::Inline) {
927                return Err(EmbedError::DurableStorePeerRequired {
928                    facet: "process registry",
929                });
930            }
931        }
932
933        if effect_host_tier == Some(DurabilityTier::Durable) {
934            if attachment_tier != Some(DurabilityTier::Durable) {
935                return Err(EmbedError::DurableStorePeerRequired {
936                    facet: "attachment store",
937                });
938            }
939            if process_env_tier != Some(DurabilityTier::Durable) {
940                return Err(EmbedError::DurableStorePeerRequired {
941                    facet: "process execution environment store",
942                });
943            }
944        }
945
946        Ok(())
947    }
948
949    pub fn build(mut self) -> Result<LashCore> {
950        let protocol_factory = self.protocol_factory.clone();
951        if protocol_factory.is_none() && self.plugin_host.is_none() {
952            return Err(EmbedError::MissingProtocolPlugin);
953        }
954        let provider_id = self
955            .session_spec
956            .provider_id
957            .clone()
958            .or_else(|| {
959                self.provider
960                    .as_ref()
961                    .map(|provider| provider.kind().to_string())
962            })
963            .unwrap_or_default();
964        let model = self
965            .session_spec
966            .model
967            .clone()
968            .ok_or(EmbedError::MissingModelSpec)?;
969
970        let base_policy = SessionPolicy {
971            provider_id,
972            model,
973            max_turns: self.session_spec.max_turns.flatten(),
974            ..SessionPolicy::default()
975        };
976        let policy = self.session_spec.resolve_against(&base_policy);
977
978        // Capture the store-peer tiers that live on builder fields before the
979        // plugin stack is consumed below; the engine sweep happens after install.
980        let session_store_tier = self.effective_session_store_tier();
981        let trigger_store_tier = self
982            .trigger_store
983            .as_ref()
984            .map(|store| store.durability_tier());
985        let process_work_source = self
986            .process_work_source
987            .clone()
988            .watched(self.process_event_sink.clone());
989        let process_registry_tier = process_work_source
990            .process_registry()
991            .map(|registry| registry.durability_tier());
992
993        let mut core = self.resolve_runtime_host_config()?;
994        if let Some(provider) = self.provider.clone() {
995            core.providers.provider_resolver =
996                Arc::new(lash_core::SingleProviderResolver::new(provider));
997        }
998        let plugin_factories = if let Some(plugin_host) = self.plugin_host {
999            plugin_host.factories().to_vec()
1000        } else {
1001            let mut factories = Vec::new();
1002            if !self.tool_providers.is_empty() {
1003                let spec = self
1004                    .tool_providers
1005                    .into_iter()
1006                    .fold(PluginSpec::new(), PluginSpec::with_tool_provider);
1007                factories.push(Arc::new(StaticPluginFactory::new("embed_tools", spec))
1008                    as Arc<dyn PluginFactory>);
1009            }
1010            factories.extend(self.plugin_stack.into_factories());
1011            factories
1012        };
1013        let default_plugin_host =
1014            build_plugin_host(protocol_factory.as_ref(), &plugin_factories, Vec::new())?;
1015        // Whether process lifecycle is available (a process registry is wired).
1016        // Threaded to every plugin host so core installs the same
1017        // plugin-contributed process engines wherever it rebuilds a runtime.
1018        let process_lifecycle_available = process_work_source.has_registry();
1019        // Install onto a throwaway clone purely to sweep every registered
1020        // engine's durability tier for the coherence check. `env.core` stays
1021        // free of plugin-contributed engines so that each runtime-construction
1022        // site (session open, queued-work drain, durable process worker)
1023        // installs them fresh onto a clean registry — keeping the unique-kind
1024        // enforcement in `try_with_engine` a genuine cross-factory check rather
1025        // than a self-collision on a registry that already carries them.
1026        let core_with_engines = default_plugin_host
1027            .install_process_engine_contributions(core.clone(), process_lifecycle_available)?;
1028        // Coherence runs after engines are installed so it can sweep every
1029        // registered engine's durability tier.
1030        Self::ensure_store_peer_coherence(
1031            session_store_tier,
1032            trigger_store_tier,
1033            process_registry_tier,
1034            &core_with_engines,
1035        )?;
1036
1037        let process_registry = process_work_source.process_registry();
1038
1039        // Resolve process work before the process source is moved into the
1040        // environment. The default inline driver's config is built
1041        // eagerly so a missing store factory fails loudly at build, not at
1042        // first open. It is built from the same single-protocol plugin host the
1043        // live runtime uses, so the worker can rebuild a runtime for a process.
1044        let process_work_driver = Self::resolve_process_work_driver(
1045            &process_work_source,
1046            &default_plugin_host,
1047            &core,
1048            process_lifecycle_available,
1049            // The worker rebuilds sessions with the same factory `build()` wires
1050            // below: `child_store_factory.or(store_factory)`.
1051            self.child_store_factory
1052                .as_ref()
1053                .or(self.store_factory.as_ref()),
1054            &policy,
1055            self.residency.unwrap_or_default(),
1056            self.trigger_store.as_ref(),
1057        )?;
1058
1059        let live_replay_clock = Arc::clone(&core.clock);
1060        let mut env_builder = RuntimeEnvironment::builder()
1061            .with_plugin_host(Arc::new(default_plugin_host))
1062            .with_runtime_host_config(core);
1063        if let Some(process_registry) = process_registry.as_ref() {
1064            env_builder = env_builder.with_process_registry(Arc::clone(process_registry));
1065        }
1066        if let Some(residency) = self.residency {
1067            env_builder = env_builder.with_residency(residency);
1068        }
1069        if let Some(child_store_factory) = self
1070            .child_store_factory
1071            .as_ref()
1072            .or(self.store_factory.as_ref())
1073        {
1074            env_builder = env_builder.with_session_store_factory(Arc::clone(child_store_factory));
1075        }
1076        if let Some(trigger_store) = self.trigger_store.as_ref() {
1077            env_builder = env_builder.with_trigger_store(Arc::clone(trigger_store));
1078        }
1079        let live_replay_store = self.live_replay_store.take().unwrap_or_else(|| {
1080            Arc::new(InMemoryLiveReplayStore::with_clock(
1081                lash_core::InMemoryLiveReplayStoreConfig::default(),
1082                live_replay_clock,
1083            ))
1084        });
1085        let env = env_builder.build();
1086        let queued_work_driver = Self::resolve_queued_work_driver(
1087            &self.queued_work_source,
1088            env.clone(),
1089            policy.clone(),
1090            protocol_factory.clone(),
1091            Arc::new(plugin_factories.clone()),
1092            self.child_store_factory
1093                .as_ref()
1094                .or(self.store_factory.as_ref()),
1095            Arc::clone(&live_replay_store),
1096            process_lifecycle_available,
1097        );
1098        let work_driver = InlineWorkDriverSetup {
1099            process: process_work_driver,
1100            queued: queued_work_driver,
1101        };
1102
1103        Ok(LashCore {
1104            env,
1105            policy,
1106            store_factory: self.store_factory,
1107            plugin_factories: Arc::new(plugin_factories),
1108            provider: self.provider,
1109            live_replay_store,
1110            protocol_factory,
1111            process_lifecycle_available,
1112            work_driver: Arc::new(InlineWorkDriverSlot::new(work_driver)),
1113        })
1114    }
1115
1116    /// Decide how a built [`LashCore`] sources its process work driver.
1117    ///
1118    /// - no registry => nothing to run ([`ProcessWorkDriverSetup::None`]);
1119    /// - external driver wired => use it ([`ProcessWorkDriverSetup::External`]);
1120    /// - inline registry wired => lazily construct the default inline driver on first open. Its
1121    ///   [`DurableProcessWorkerConfig`] is built eagerly when a store factory is
1122    ///   present; without one the inline worker cannot rebuild session runtimes.
1123    // Mirrors the sibling `resolve_queued_work_driver`: a builder helper whose
1124    // inputs are the heterogeneous, all-required driver-resolution state and
1125    // have no cohesive sub-grouping.
1126    #[allow(clippy::too_many_arguments)]
1127    fn resolve_process_work_driver(
1128        process_work_source: &ProcessWorkSource,
1129        worker_plugin_host: &PluginHost,
1130        core: &RuntimeHostConfig,
1131        process_lifecycle_available: bool,
1132        store_factory: Option<&Arc<dyn SessionStoreFactory>>,
1133        policy: &SessionPolicy,
1134        residency: lash_core::Residency,
1135        trigger_store: Option<&Arc<dyn lash_core::TriggerStore>>,
1136    ) -> Result<ProcessWorkDriverSetup> {
1137        let (process_registry, process_change_hub) = match process_work_source {
1138            ProcessWorkSource::None => return Ok(ProcessWorkDriverSetup::None),
1139            ProcessWorkSource::External(driver) => {
1140                return Ok(ProcessWorkDriverSetup::External {
1141                    driver: driver.clone(),
1142                });
1143            }
1144            ProcessWorkSource::Inline { registry, hub } => (Arc::clone(registry), hub.clone()),
1145        };
1146        // The worker rebuilds a session runtime per process, so it needs a store
1147        // factory; without one the default runner could not execute anything, so
1148        // fail loudly rather than silently leave processes unexecuted.
1149        let Some(store_factory) = store_factory else {
1150            return Err(EmbedError::ProcessRegistryRequiresStoreFactory);
1151        };
1152        // The worker rebuilds with the same plugin host the live runtime uses,
1153        // including the protocol plugin that supplies the protocol session
1154        // capability. Install its plugin-contributed process engines onto a
1155        // clean copy of the base host — `core` deliberately carries none.
1156        let runtime_host = worker_plugin_host
1157            .install_process_engine_contributions(core.clone(), process_lifecycle_available)?;
1158        let phase_probe_slot = lash_core::runtime::RuntimeTurnPhaseProbeSlot::default();
1159        let mut config = DurableProcessWorkerConfig::new(
1160            Arc::new(worker_plugin_host.clone()),
1161            runtime_host,
1162            Arc::clone(store_factory),
1163            process_registry,
1164        )
1165        .with_session_policy(policy.clone())
1166        .with_trigger_store(trigger_store.cloned().unwrap_or_else(|| {
1167            Arc::new(lash_core::InMemoryTriggerStore::with_clock(Arc::clone(
1168                &core.clock,
1169            )))
1170        }))
1171        .with_residency(residency)
1172        .with_turn_phase_probe_slot(phase_probe_slot);
1173        if let Some(hub) = process_change_hub {
1174            config = config.with_change_hub(hub);
1175        }
1176        let config = Box::new(config);
1177        Ok(ProcessWorkDriverSetup::LazyDefault { config })
1178    }
1179
1180    #[allow(clippy::too_many_arguments)]
1181    fn resolve_queued_work_driver(
1182        queued_work_source: &QueuedWorkSource,
1183        env: RuntimeEnvironment,
1184        policy: SessionPolicy,
1185        protocol_factory: Option<Arc<dyn PluginFactory>>,
1186        plugin_factories: Arc<Vec<Arc<dyn PluginFactory>>>,
1187        store_factory: Option<&Arc<dyn SessionStoreFactory>>,
1188        live_replay_store: Arc<dyn LiveReplayStore>,
1189        process_lifecycle_available: bool,
1190    ) -> QueuedWorkDriverSetup {
1191        match queued_work_source {
1192            QueuedWorkSource::None => QueuedWorkDriverSetup::None,
1193            QueuedWorkSource::External(driver) => QueuedWorkDriverSetup::External {
1194                driver: driver.clone(),
1195            },
1196            QueuedWorkSource::LazyDefault => match store_factory {
1197                Some(store_factory) => QueuedWorkDriverSetup::LazyDefault {
1198                    config: Arc::new(InlineQueuedWorkRunConfig::new(
1199                        env,
1200                        policy,
1201                        protocol_factory,
1202                        plugin_factories,
1203                        Arc::clone(store_factory),
1204                        live_replay_store,
1205                        process_lifecycle_available,
1206                    )),
1207                },
1208                None => QueuedWorkDriverSetup::None,
1209            },
1210        }
1211    }
1212
1213    pub fn advanced(self) -> AdvancedLashCoreBuilder {
1214        AdvancedLashCoreBuilder { builder: self }
1215    }
1216
1217    pub fn process_registry(mut self, process_registry: Arc<dyn ProcessRegistry>) -> Self {
1218        self.process_work_source = ProcessWorkSource::Inline {
1219            registry: process_registry,
1220            hub: None,
1221        };
1222        self
1223    }
1224
1225    /// Install a best-effort, host-facing [`ProcessEventSink`] on the inline
1226    /// process registry.
1227    ///
1228    /// Each appended process event is pushed to the sink after its durable
1229    /// write, in per-process append order. This is freshness, not truth: it
1230    /// never buffers or retries, terminal events are not emitted through it
1231    /// (observe completion via the await seam), and consumers reconcile from
1232    /// the durable event log. See [`ProcessEventSink`] for the full contract.
1233    ///
1234    /// Applies to the inline registry path ([`Self::process_registry`]); a host
1235    /// that supplies its own [`ProcessWorkDriver`](lash_core::ProcessWorkDriver)
1236    /// installs the sink through the driver's constructor instead.
1237    ///
1238    /// [`ProcessEventSink`]: lash_core::ProcessEventSink
1239    pub fn process_event_sink(mut self, sink: Arc<dyn lash_core::ProcessEventSink>) -> Self {
1240        self.process_event_sink = Some(sink);
1241        self
1242    }
1243
1244    pub fn trigger_store(mut self, store: Arc<dyn lash_core::TriggerStore>) -> Self {
1245        self.trigger_store = Some(store);
1246        self
1247    }
1248
1249    /// Configure an externally owned process work runner.
1250    ///
1251    /// Durable hosts construct a [`ProcessWorkDriver`] from the same process
1252    /// registry and wake handle used by their deployment runner, then pass it
1253    /// here. The driver registry becomes the core's process registry and no
1254    /// inline runner is spawned.
1255    pub fn process_work_driver(mut self, driver: ProcessWorkDriver) -> Self {
1256        self.process_work_source = ProcessWorkSource::External(driver);
1257        self
1258    }
1259
1260    /// Configure an externally owned queued-work driver.
1261    pub fn queued_work_driver(mut self, driver: QueuedWorkDriver) -> Self {
1262        self.queued_work_source = QueuedWorkSource::External(driver);
1263        self
1264    }
1265
1266    pub fn disable_queued_work_driver(mut self) -> Self {
1267        self.queued_work_source = QueuedWorkSource::None;
1268        self
1269    }
1270}
1271
1272pub(crate) fn build_plugin_host(
1273    protocol_factory: Option<&Arc<dyn PluginFactory>>,
1274    common_factories: &[Arc<dyn PluginFactory>],
1275    extra_factories: Vec<Arc<dyn PluginFactory>>,
1276) -> Result<PluginHost> {
1277    let mut factories = Vec::with_capacity(
1278        usize::from(protocol_factory.is_some()) + common_factories.len() + extra_factories.len(),
1279    );
1280    if let Some(protocol_factory) = protocol_factory {
1281        factories.push(Arc::clone(protocol_factory));
1282    }
1283    factories.extend(common_factories.iter().cloned());
1284    factories.extend(extra_factories);
1285    Ok(PluginHost::new(factories))
1286}
1287
1288impl PromptLayerSink for LashCoreBuilder {
1289    fn prompt_layer_mut(&mut self) -> &mut PromptLayer {
1290        self.prompt.get_or_insert_with(PromptLayer::new)
1291    }
1292}
1293
1294pub struct AdvancedLashCoreBuilder {
1295    builder: LashCoreBuilder,
1296}
1297
1298impl AdvancedLashCoreBuilder {
1299    pub fn runtime_host_config(mut self, core: lash_core::RuntimeHostConfig) -> Self {
1300        self.builder.runtime_host_config = Some(core);
1301        self
1302    }
1303
1304    pub fn plugin_host(mut self, plugin_host: PluginHost) -> Self {
1305        self.builder.plugin_host = Some(plugin_host);
1306        self
1307    }
1308
1309    pub fn build(self) -> Result<LashCore> {
1310        self.builder.build()
1311    }
1312}