1use std::pin::Pin;
2use std::task::{Context, Poll};
3
4use crate::support::*;
5use futures_util::Stream;
6use lash_core::runtime::{
7 PendingTurnInput, PendingTurnInputCancelOutcome, PendingTurnInputCancelResult,
8 PendingTurnInputCancelTarget, PendingTurnInputSuffixCancelOutcome, QueuedWorkBatch,
9 QueuedWorkClaim, TurnInputClaim, TurnInputIngress,
10};
11use lash_core::{LiveReplayGap, LiveReplayStoreError, SessionObservationEvent};
12use lash_remote_protocol::{
13 RemoteLiveReplayGap, RemoteSessionCursor, RemoteSessionObservation,
14 RemoteSessionObservationEvent,
15};
16
17pub struct SessionBuilder {
18 pub(crate) core: LashCore,
19 pub(crate) session_id: String,
20 pub(crate) spec: SessionSpec,
21 pub(crate) parent_session_id: Option<String>,
22 pub(crate) session_execution_owner: Option<lash_core::LeaseOwnerIdentity>,
23 pub(crate) store: Option<Arc<dyn RuntimePersistence>>,
24 pub(crate) provider: Option<ProviderHandle>,
25 pub(crate) active_plugins: Vec<ActivePluginBinding>,
26 pub(crate) plugin_factories: Vec<Arc<dyn PluginFactory>>,
27 pub(crate) plugin_options: PluginOptions,
32}
33
34impl SessionBuilder {
35 pub fn plugin_options(mut self, plugin_options: PluginOptions) -> Self {
37 self.plugin_options = plugin_options;
38 self
39 }
40
41 pub fn plugin_option<T: serde::Serialize>(
44 mut self,
45 plugin_id: impl Into<String>,
46 extras: T,
47 ) -> Result<Self> {
48 self.plugin_options
49 .insert_typed(plugin_id, extras)
50 .map_err(EmbedError::ProtocolTurnOptions)?;
51 Ok(self)
52 }
53
54 pub fn provider(mut self, provider: ProviderHandle) -> Self {
55 self.spec = self.spec.provider_id(provider.kind());
56 self.provider = Some(provider);
57 self
58 }
59
60 pub fn session_spec(mut self, spec: SessionSpec) -> Self {
61 self.spec = spec;
62 self
63 }
64
65 pub fn parent(mut self, parent_session_id: impl Into<String>) -> Self {
66 self.parent_session_id = Some(parent_session_id.into());
67 self
68 }
69
70 pub fn session_execution_owner(mut self, owner: lash_core::LeaseOwnerIdentity) -> Self {
76 self.session_execution_owner = Some(owner);
77 self
78 }
79
80 pub fn store(mut self, store: Arc<dyn RuntimePersistence>) -> Self {
87 self.store = Some(store);
88 self
89 }
90
91 pub fn plugin<P: PluginBinding>(mut self, config: P::SessionConfig) -> Self {
92 self.active_plugins.push(ActivePluginBinding {
93 id: P::ID,
94 requires_turn_input: P::requires_turn_input(&config),
95 });
96 self.plugin_factories.push(P::factory(&config));
97 self
98 }
99
100 pub async fn open(self) -> Result<LashSession> {
101 let policy = self.session_policy();
102 let store = self.create_store(&policy).await?;
103 let state = self
104 .load_or_default_state(&policy, store.as_deref())
105 .await?;
106 self.open_resolved(policy, state, store).await
107 }
108
109 pub async fn open_fresh(self) -> Result<LashSession> {
119 let policy = self.session_policy();
120 let store = self.create_store(&policy).await?;
121 let state = RuntimeSessionState {
122 session_id: self.session_id.clone(),
123 policy: policy.clone(),
124 graph_replace_required: true,
125 ..RuntimeSessionState::default()
126 };
127 self.open_resolved(policy, state, store).await
128 }
129
130 pub async fn open_with_state(self, mut state: RuntimeSessionState) -> Result<LashSession> {
137 let policy = self.session_policy();
138 let store = self.create_store(&policy).await?;
139 if state.session_id != self.session_id {
140 return Err(EmbedError::StoreSessionMismatch {
141 loaded: state.session_id,
142 requested: self.session_id,
143 });
144 }
145 let recorded_provider_id = state.policy.recorded_provider_id().to_string();
146 state.policy = policy.clone();
147 state.policy.provider_id = recorded_provider_id;
148 self.open_resolved(policy, state, store).await
149 }
150
151 fn session_policy(&self) -> SessionPolicy {
152 let mut policy = self.spec.resolve_against(&self.core.policy);
153 policy.session_id = Some(self.session_id.clone());
154 policy
155 }
156
157 async fn load_or_default_state(
158 &self,
159 policy: &SessionPolicy,
160 store: Option<&dyn RuntimePersistence>,
161 ) -> Result<RuntimeSessionState> {
162 let state = match store {
163 Some(store) => {
164 let loaded = self.load_persisted_state_for_residency(store).await?;
165 let mut state = loaded.unwrap_or_else(|| RuntimeSessionState {
166 session_id: self.session_id.clone(),
167 policy: policy.clone(),
168 ..RuntimeSessionState::default()
169 });
170 if state.session_id != self.session_id {
171 return Err(EmbedError::StoreSessionMismatch {
172 loaded: state.session_id,
173 requested: self.session_id.clone(),
174 });
175 }
176 let recorded_provider_id = state.policy.recorded_provider_id().to_string();
177 state.policy = policy.clone();
178 state.policy.provider_id = recorded_provider_id;
179 state
180 }
181 None => RuntimeSessionState {
182 session_id: self.session_id.clone(),
183 policy: policy.clone(),
184 ..RuntimeSessionState::default()
185 },
186 };
187 Ok(state)
188 }
189
190 async fn load_persisted_state_for_residency(
191 &self,
192 store: &dyn RuntimePersistence,
193 ) -> Result<Option<RuntimeSessionState>> {
194 load_persisted_state_for_residency(self.core.env.residency, store).await
195 }
196
197 async fn open_resolved(
198 self,
199 policy: SessionPolicy,
200 state: RuntimeSessionState,
201 store: Option<Arc<dyn RuntimePersistence>>,
202 ) -> Result<LashSession> {
203 let mut env = self.core.env.clone();
204 if let Some(provider) = self.provider.clone().or_else(|| self.core.provider.clone()) {
205 env.core.providers.provider_resolver =
206 Arc::new(lash_core::SingleProviderResolver::new(provider));
207 }
208 let plugin_host = build_plugin_host(
209 self.core.protocol_factory.as_ref(),
210 self.core.plugin_factories.as_ref(),
211 self.plugin_factories,
212 )?;
213 env.core = plugin_host.install_process_engine_contributions(
214 env.core.clone(),
215 self.core.process_lifecycle_available,
216 )?;
217 env.plugin_host = Some(Arc::new(plugin_host));
218 let effect_host = Arc::clone(&env.core.control.effect_host);
219 let drivers = self.core.work_driver.drivers().await;
220 env.process_work_driver = drivers.process.clone();
221 env.queued_work_driver = drivers.queued.clone();
222 let mut runtime = LashRuntime::from_environment(&env, policy, state, store).await?;
223 runtime.configure_protocol_on_materialize(
227 &self.plugin_options,
228 self.parent_session_id.is_none(),
229 )?;
230 if let Some(owner) = self.session_execution_owner {
231 runtime.set_runtime_lease_owner(owner);
232 }
233 if drivers.drive_process_on_open
234 && let Some(driver) = drivers.process.as_ref()
235 {
236 driver.claim_and_run_pending("session_open").await?;
237 }
238 let handle = RuntimeHandle::with_live_replay_store(
239 runtime,
240 Arc::clone(&self.core.live_replay_store),
241 );
242 Ok(LashSession {
243 runtime: handle,
244 effect_host,
245 parent_session_id: self.parent_session_id,
246 active_plugins: self.active_plugins,
247 process_phase_probe_slot: self.core.work_driver.phase_probe_slot(),
248 turn_cancels: crate::turn::TurnCancelRegistry::default(),
249 })
250 }
251
252 async fn create_store(
253 &self,
254 policy: &SessionPolicy,
255 ) -> Result<Option<Arc<dyn RuntimePersistence>>> {
256 if let Some(store) = self.store.as_ref() {
257 return Ok(Some(Arc::clone(store)));
258 }
259 let Some(factory) = self.core.store_factory.as_ref() else {
260 return Ok(None);
261 };
262 let request = SessionStoreCreateRequest {
263 session_id: self.session_id.clone(),
264 relation: self
265 .parent_session_id
266 .as_ref()
267 .map(|parent_session_id| lash_core::SessionRelation::Child {
268 parent_session_id: parent_session_id.clone(),
269 caused_by: None,
270 })
271 .unwrap_or_default(),
272 policy: policy.clone(),
273 };
274 factory
275 .create_store(&request)
276 .await
277 .map(Some)
278 .map_err(|message| EmbedError::StoreFactory {
279 session_id: self.session_id.clone(),
280 message,
281 })
282 }
283}
284
285pub(crate) async fn load_state_for_residency(
286 residency: Residency,
287 session_id: &str,
288 policy: &SessionPolicy,
289 store: &dyn RuntimePersistence,
290) -> Result<RuntimeSessionState> {
291 let mut state = load_persisted_state_for_residency(residency, store)
292 .await?
293 .unwrap_or_else(|| RuntimeSessionState {
294 session_id: session_id.to_string(),
295 policy: policy.clone(),
296 ..RuntimeSessionState::default()
297 });
298 if state.session_id != session_id {
299 return Err(EmbedError::StoreSessionMismatch {
300 loaded: state.session_id,
301 requested: session_id.to_string(),
302 });
303 }
304 let recorded_provider_id = state.policy.recorded_provider_id().to_string();
305 state.policy = policy.clone();
306 state.policy.provider_id = recorded_provider_id;
307 Ok(state)
308}
309
310async fn load_persisted_state_for_residency(
311 residency: Residency,
312 store: &dyn RuntimePersistence,
313) -> Result<Option<RuntimeSessionState>> {
314 match residency {
315 Residency::KeepAll => {
316 let loaded = lash_core::store::load_persisted_session_state(store)
317 .await
318 .map_err(|err| SessionError::Protocol(format!("failed to load store: {err}")))?;
319 Ok(loaded)
320 }
321 Residency::ActivePathOnly => {
322 let active = lash_core::store::load_persisted_session_state_active_path(store, None)
323 .await
324 .map_err(|err| {
325 SessionError::Protocol(format!("failed to load active-path store: {err}"))
326 })?;
327 if active
328 .as_ref()
329 .is_some_and(|state| state.session_graph.nodes.is_empty())
330 {
331 let mut full = lash_core::store::load_persisted_session_state(store)
332 .await
333 .map_err(|err| {
334 SessionError::Protocol(format!(
335 "failed to heal active-path store from full graph: {err}"
336 ))
337 })?;
338 if let Some(state) = full.as_mut() {
339 state.graph_replace_required = true;
340 }
341 return Ok(full);
342 }
343 Ok(active)
344 }
345 }
346}
347
348impl PromptLayerSink for SessionBuilder {
349 fn prompt_layer_mut(&mut self) -> &mut PromptLayer {
350 self.spec.prompt.get_or_insert_with(PromptLayer::new)
351 }
352}
353
354#[derive(Clone)]
355pub struct LashSession {
356 pub(crate) runtime: RuntimeHandle,
357 pub(crate) effect_host: Arc<dyn EffectHost>,
358 pub(crate) parent_session_id: Option<String>,
359 pub(crate) active_plugins: Vec<ActivePluginBinding>,
360 pub(crate) process_phase_probe_slot: Option<lash_core::runtime::RuntimeTurnPhaseProbeSlot>,
361 pub(crate) turn_cancels: crate::turn::TurnCancelRegistry,
362}
363
364#[derive(Clone, Debug, Default)]
365pub struct SessionConfigPatch {
366 pub provider: Option<ProviderHandle>,
367 pub model: Option<ModelSpec>,
368 pub prompt: Option<PromptLayer>,
369}
370
371pub struct ParkedSession {
384 pub(crate) inner: lash_core::ParkedSession,
385}
386
387impl ParkedSession {
388 pub fn session_id(&self) -> &str {
391 self.inner.session_id()
392 }
393}
394
395impl LashSession {
396 pub async fn close(self) -> Result<()> {
414 let persistent = self.runtime.observe().queue_store.is_some();
418 let runtime = self.into_owned_runtime()?;
419 runtime.unregister_plugin_session()?;
420 if persistent {
421 runtime.park().await?;
424 }
425 Ok(())
427 }
428
429 pub async fn park(self) -> Result<ParkedSession> {
454 let runtime = self.into_owned_runtime()?;
455 runtime.unregister_plugin_session()?;
458 let parked = runtime.park().await?;
459 Ok(ParkedSession { inner: parked })
460 }
461
462 fn into_owned_runtime(self) -> Result<LashRuntime> {
468 let LashSession { runtime, .. } = self;
469 let writer = runtime.writer();
474 drop(runtime);
475 Arc::try_unwrap(writer)
476 .map(|mutex| mutex.into_inner())
477 .map_err(|_| EmbedError::SessionStillInUse)
478 }
479
480 pub fn session_id(&self) -> String {
481 self.runtime.observe().session_id().to_string()
482 }
483
484 pub fn policy_snapshot(&self) -> SessionPolicy {
485 self.runtime.observe().policy.clone()
486 }
487
488 pub fn observe(&self) -> ObservableSession {
489 ObservableSession {
490 runtime: self.runtime.clone(),
491 }
492 }
493
494 pub fn parent_session_id(&self) -> Option<&str> {
495 self.parent_session_id.as_deref()
496 }
497
498 pub fn effect_host(&self) -> Arc<dyn EffectHost> {
499 Arc::clone(&self.effect_host)
500 }
501
502 pub fn turn(&self, input: TurnInput) -> TurnBuilder {
503 TurnBuilder {
504 runtime: self.runtime.clone(),
505 effect_host: Arc::clone(&self.effect_host),
506 active_plugins: self.active_plugins.clone(),
507 input,
508 cancel: CancellationToken::new(),
509 cancels: self.turn_cancels.clone(),
510 protocol_turn_options: None,
511 provider: None,
512 model: None,
513 turn_id: None,
514 }
515 }
516
517 pub fn queued_turn(&self) -> QueuedTurnBuilder {
518 QueuedTurnBuilder {
519 runtime: self.runtime.clone(),
520 effect_host: Arc::clone(&self.effect_host),
521 cancel: CancellationToken::new(),
522 cancels: self.turn_cancels.clone(),
523 batch_ids: Vec::new(),
524 drain_id: None,
525 }
526 }
527
528 pub fn cancel_running_turns(&self) -> usize {
543 self.turn_cancels.cancel_all()
544 }
545
546 pub fn admin(&self) -> SessionAdmin {
547 SessionAdmin {
548 runtime: self.runtime.clone(),
549 }
550 }
551
552 pub async fn configure(&self, patch: SessionConfigPatch) -> Result<()> {
553 self.admin().config().update(patch).await
554 }
555
556 pub fn tools(&self) -> ToolAdmin {
557 ToolAdmin::new(self.admin())
558 }
559
560 pub fn commands(&self) -> SessionCommandAdmin {
561 self.admin().commands()
562 }
563
564 pub fn triggers(&self) -> SessionTriggerAdmin {
565 self.admin().triggers()
566 }
567
568 pub fn processes(&self) -> SessionProcessAdmin {
569 SessionProcessAdmin::new(self.admin())
570 }
571
572 pub fn plugin_operations(&self) -> PluginOperations {
573 PluginOperations {
574 control: self.admin(),
575 }
576 }
577
578 pub fn enqueue(&self, input: TurnInput) -> EnqueueTurnBuilder<'_> {
579 EnqueueTurnBuilder {
580 session: self,
581 input,
582 id: None,
583 ingress: TurnInputIngress::NextTurn,
584 }
585 }
586
587 pub async fn queued_work(&self) -> Result<Vec<QueuedWorkBatch>> {
594 let observation = self.runtime.observe();
595 let store = observation.queue_store.as_ref().ok_or_else(|| {
596 EmbedError::Runtime(lash_core::RuntimeError::new(
597 lash_core::RuntimeErrorCode::StoreCommitFailed,
598 "queued work inspection requires a persistent runtime store",
599 ))
600 })?;
601 store
602 .list_pending_queued_work(observation.session_id())
603 .await
604 .map_err(|err| {
605 EmbedError::Runtime(lash_core::RuntimeError::new(
606 lash_core::RuntimeErrorCode::StoreCommitFailed,
607 err.to_string(),
608 ))
609 })
610 }
611
612 pub async fn pending_turn_inputs(&self) -> Result<Vec<PendingTurnInput>> {
613 let observation = self.runtime.observe();
614 let store = observation.queue_store.as_ref().ok_or_else(|| {
615 EmbedError::Runtime(lash_core::RuntimeError::new(
616 lash_core::RuntimeErrorCode::StoreCommitFailed,
617 "pending turn input inspection requires a persistent runtime store",
618 ))
619 })?;
620 store
621 .list_pending_turn_inputs(observation.session_id())
622 .await
623 .map_err(|err| {
624 EmbedError::Runtime(lash_core::RuntimeError::new(
625 lash_core::RuntimeErrorCode::StoreCommitFailed,
626 err.to_string(),
627 ))
628 })
629 }
630
631 pub async fn cancel_pending_turn_input(
632 &self,
633 input_id: &str,
634 ) -> Result<PendingTurnInputCancelOutcome> {
635 let session_id = self.session_id();
636 self.runtime
637 .cancel_pending_turn_input(&session_id, input_id)
638 .await
639 .map_err(EmbedError::Runtime)
640 }
641
642 pub async fn cancel_pending_turn_inputs(
650 &self,
651 targets: impl IntoIterator<Item = PendingTurnInputCancelTarget>,
652 ) -> Result<Vec<PendingTurnInputCancelResult>> {
653 let session_id = self.session_id();
654 let targets = targets.into_iter().collect::<Vec<_>>();
655 self.runtime
656 .cancel_pending_turn_inputs(&session_id, &targets)
657 .await
658 .map_err(EmbedError::Runtime)
659 }
660
661 pub async fn cancel_pending_turn_input_suffix(
670 &self,
671 anchor: PendingTurnInputCancelTarget,
672 ) -> Result<PendingTurnInputSuffixCancelOutcome> {
673 let session_id = self.session_id();
674 self.runtime
675 .cancel_pending_turn_input_suffix(&session_id, &anchor)
676 .await
677 .map_err(EmbedError::Runtime)
678 }
679
680 pub async fn cancel_queued_work_batch(
681 &self,
682 batch_id: &str,
683 ) -> Result<Option<QueuedWorkBatch>> {
684 let session_id = self.session_id();
685 self.runtime
686 .cancel_queued_work_batch(&session_id, batch_id)
687 .await
688 .map_err(EmbedError::Runtime)
689 }
690
691 pub async fn abandon_queued_work_claim(&self, claim: &QueuedWorkClaim) -> Result<()> {
698 self.runtime
699 .abandon_queued_work_claim(claim)
700 .await
701 .map_err(EmbedError::Runtime)
702 }
703
704 pub async fn abandon_turn_input_claim(&self, claim: &TurnInputClaim) -> Result<()> {
708 self.runtime
709 .abandon_turn_input_claim(claim)
710 .await
711 .map_err(EmbedError::Runtime)
712 }
713
714 pub async fn revoke_durable_waits(&self) -> Result<()> {
724 let session_id = self.session_id();
725 self.effect_host
726 .cancel_await_events_for_session(&session_id)
727 .await
728 .map_err(EmbedError::Runtime)
729 }
730
731 pub async fn await_queued_work_batch(&self, batch_id: &str) -> Result<()> {
743 let observation = self.runtime.observe();
744 let store = observation.queue_store.clone().ok_or_else(|| {
745 EmbedError::Runtime(lash_core::RuntimeError::new(
746 lash_core::RuntimeErrorCode::StoreCommitFailed,
747 "queued work inspection requires a persistent runtime store",
748 ))
749 })?;
750 let session_id = observation.session_id().to_string();
751 drop(observation);
752 let mut delay = std::time::Duration::from_millis(25);
753 loop {
754 let pending = store
755 .list_pending_queued_work(&session_id)
756 .await
757 .map_err(|err| {
758 EmbedError::Runtime(lash_core::RuntimeError::new(
759 lash_core::RuntimeErrorCode::StoreCommitFailed,
760 err.to_string(),
761 ))
762 })?;
763 if !pending.iter().any(|batch| batch.batch_id == batch_id) {
764 return Ok(());
765 }
766 tokio::time::sleep(delay).await;
767 delay = (delay * 2).min(std::time::Duration::from_millis(400));
768 }
769 }
770
771 pub fn read_view(&self) -> SessionReadView {
772 self.runtime.observe().read_view.clone()
773 }
774
775 pub fn usage_report(&self) -> SessionUsageReport {
776 self.runtime.observe().usage_report.clone()
777 }
778
779 pub async fn set_turn_phase_probe(
780 &self,
781 probe: Arc<dyn lash_core::runtime::RuntimeTurnPhaseProbe>,
782 ) {
783 let writer = self.runtime.writer();
784 let mut runtime = writer.lock().await;
785 runtime.set_turn_phase_probe(Arc::clone(&probe));
786 self.runtime.publish_from(&runtime);
787 if let Some(slot) = &self.process_phase_probe_slot {
788 let observation = self.runtime.observe();
789 slot.set_for_session(observation.session_id(), Arc::clone(&probe));
790 let current_frame = observation.persisted_state.current_agent_frame_id.as_str();
791 if !current_frame.is_empty() {
792 let scope = lash_core::SessionScope::for_agent_frame(
793 observation.session_id(),
794 current_frame,
795 );
796 slot.set_for_scope(&scope, probe);
797 }
798 }
799 }
800}
801
802#[derive(Clone)]
803pub struct ObservableSession {
804 pub(crate) runtime: RuntimeHandle,
805}
806
807impl ObservableSession {
808 fn snapshot(&self) -> Arc<RuntimeObservation> {
809 self.runtime.observe()
810 }
811
812 pub fn current_observation(&self) -> SessionObservation {
813 self.runtime.current_session_observation()
814 }
815
816 pub fn current_remote_observation(&self) -> RemoteSessionObservation {
817 RemoteSessionObservation::from_core(self.current_observation())
818 }
819
820 pub fn resume_from_cursor(&self, cursor: &SessionCursor) -> Result<SessionResume> {
821 self.runtime
822 .resume_session_observation(cursor)
823 .map_err(live_replay_error)
824 }
825
826 pub fn subscribe_from_cursor(
827 &self,
828 cursor: &SessionCursor,
829 ) -> Result<SessionObservationSubscription> {
830 self.runtime
831 .subscribe_session_observation(cursor)
832 .map_err(live_replay_error)
833 }
834
835 pub fn subscribe_from_remote_cursor(
836 &self,
837 cursor: &RemoteSessionCursor,
838 ) -> Result<RemoteSessionObservationSubscription> {
839 cursor.validate()?;
840 let cursor = lash_core::SessionCursor::try_from(cursor.clone())?;
841 match self.subscribe_from_cursor(&cursor)? {
842 SessionObservationSubscription::Subscribed(subscription) => {
843 Ok(RemoteSessionObservationSubscription::Subscribed(
844 RemoteSessionObservationEventStream::new(subscription),
845 ))
846 }
847 SessionObservationSubscription::Gap { observation, gap } => {
848 Ok(RemoteSessionObservationSubscription::Gap {
849 observation: observation.into(),
850 gap: gap.into(),
851 })
852 }
853 }
854 }
855
856 pub fn subscribe_and_recover(&self, cursor: SessionCursor) -> SessionObservationStream {
865 SessionObservationStream {
866 observable: self.clone(),
867 cursor,
868 subscription: None,
869 done: false,
870 }
871 }
872
873 pub fn subscribe_and_recover_remote(
876 &self,
877 cursor: RemoteSessionCursor,
878 ) -> Result<RemoteSessionObservationStream> {
879 cursor.validate()?;
880 let cursor = lash_core::SessionCursor::try_from(cursor)?;
881 Ok(RemoteSessionObservationStream {
882 inner: self.subscribe_and_recover(cursor),
883 next_sequence: 0,
884 })
885 }
886
887 pub fn session_id(&self) -> String {
888 self.snapshot().session_id().to_string()
889 }
890
891 pub fn policy_snapshot(&self) -> SessionPolicy {
892 self.snapshot().policy.clone()
893 }
894
895 pub fn read_view(&self) -> SessionReadView {
896 self.snapshot().read_view.clone()
897 }
898
899 pub fn usage_report(&self) -> SessionUsageReport {
900 self.snapshot().usage_report.clone()
901 }
902
903 pub fn tool_state(&self) -> Option<ToolState> {
904 self.snapshot().tool_state.clone()
905 }
906
907 pub fn active_tool_manifests(&self) -> Vec<ToolManifest> {
908 self.snapshot()
909 .tool_state
910 .as_ref()
911 .map(ToolState::tool_manifests)
912 .unwrap_or_default()
913 }
914
915 pub async fn list_process_handles(&self) -> Vec<ProcessHandleSummary> {
916 self.snapshot().list_process_handles().await
917 }
918
919 pub async fn list_all_process_handles(&self) -> Vec<ProcessHandleSummary> {
920 self.snapshot().list_all_process_handles().await
921 }
922
923 pub fn process_scope(&self) -> SessionScope {
924 self.snapshot().process_scope()
925 }
926}
927
928#[allow(clippy::large_enum_variant)]
934#[derive(Clone, Debug)]
935pub enum SessionObservationStreamItem {
936 Event(SessionObservationEvent),
938 Gap {
940 observation: SessionObservation,
941 gap: LiveReplayGap,
942 },
943}
944
945pub enum RemoteSessionObservationSubscription {
946 Subscribed(RemoteSessionObservationEventStream),
947 Gap {
948 observation: RemoteSessionObservation,
949 gap: RemoteLiveReplayGap,
950 },
951}
952
953#[derive(Clone, Debug)]
954pub enum RemoteSessionObservationStreamItem {
955 Event(RemoteSessionObservationEvent),
957 Gap {
959 observation: RemoteSessionObservation,
960 gap: RemoteLiveReplayGap,
961 },
962}
963
964pub struct RemoteSessionObservationEventStream {
965 inner: lash_core::LiveReplaySubscription,
966 next_sequence: u64,
967}
968
969impl RemoteSessionObservationEventStream {
970 fn new(inner: lash_core::LiveReplaySubscription) -> Self {
971 Self {
972 inner,
973 next_sequence: 0,
974 }
975 }
976
977 pub async fn next_event(&mut self) -> Result<RemoteSessionObservationEvent> {
978 futures_util::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx))
979 .await
980 .transpose()?
981 .ok_or_else(|| live_replay_error(LiveReplayStoreError::Closed))
982 }
983}
984
985impl Stream for RemoteSessionObservationEventStream {
986 type Item = Result<RemoteSessionObservationEvent>;
987
988 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
989 match Pin::new(&mut self.inner).poll_next(cx) {
990 Poll::Pending => Poll::Pending,
991 Poll::Ready(Some(Ok(event))) => {
992 let remote = RemoteSessionObservationEvent::from_core(self.next_sequence, event);
993 self.next_sequence = self.next_sequence.saturating_add(1);
994 Poll::Ready(Some(Ok(remote)))
995 }
996 Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(live_replay_error(err)))),
997 Poll::Ready(None) => Poll::Ready(None),
998 }
999 }
1000}
1001
1002pub struct RemoteSessionObservationStream {
1004 inner: SessionObservationStream,
1005 next_sequence: u64,
1006}
1007
1008impl RemoteSessionObservationStream {
1009 pub fn cursor(&self) -> RemoteSessionCursor {
1010 RemoteSessionCursor::from(self.inner.cursor())
1011 }
1012}
1013
1014impl Stream for RemoteSessionObservationStream {
1015 type Item = Result<RemoteSessionObservationStreamItem>;
1016
1017 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1018 match Pin::new(&mut self.inner).poll_next(cx) {
1019 Poll::Pending => Poll::Pending,
1020 Poll::Ready(Some(Ok(SessionObservationStreamItem::Event(event)))) => {
1021 let remote = RemoteSessionObservationEvent::from_core(self.next_sequence, event);
1022 self.next_sequence = self.next_sequence.saturating_add(1);
1023 Poll::Ready(Some(Ok(RemoteSessionObservationStreamItem::Event(remote))))
1024 }
1025 Poll::Ready(Some(Ok(SessionObservationStreamItem::Gap { observation, gap }))) => {
1026 Poll::Ready(Some(Ok(RemoteSessionObservationStreamItem::Gap {
1027 observation: observation.into(),
1028 gap: gap.into(),
1029 })))
1030 }
1031 Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(err))),
1032 Poll::Ready(None) => Poll::Ready(None),
1033 }
1034 }
1035}
1036
1037pub struct SessionObservationStream {
1039 observable: ObservableSession,
1040 cursor: SessionCursor,
1041 subscription: Option<lash_core::LiveReplaySubscription>,
1042 done: bool,
1043}
1044
1045impl SessionObservationStream {
1046 pub fn cursor(&self) -> &SessionCursor {
1047 &self.cursor
1048 }
1049}
1050
1051impl Stream for SessionObservationStream {
1052 type Item = Result<SessionObservationStreamItem>;
1053
1054 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1055 loop {
1056 if self.done {
1057 return Poll::Ready(None);
1058 }
1059 if self.subscription.is_none() {
1060 match self.observable.subscribe_from_cursor(&self.cursor) {
1061 Ok(SessionObservationSubscription::Subscribed(subscription)) => {
1062 self.subscription = Some(subscription);
1063 }
1064 Ok(SessionObservationSubscription::Gap { observation, gap }) => {
1065 self.cursor = gap.latest_cursor.clone();
1066 return Poll::Ready(Some(Ok(SessionObservationStreamItem::Gap {
1067 observation,
1068 gap,
1069 })));
1070 }
1071 Err(err) => {
1072 self.done = true;
1073 return Poll::Ready(Some(Err(err)));
1074 }
1075 }
1076 }
1077
1078 let Some(subscription) = self.subscription.as_mut() else {
1079 continue;
1080 };
1081 match Pin::new(subscription).poll_next(cx) {
1082 Poll::Pending => return Poll::Pending,
1083 Poll::Ready(Some(Ok(event))) => {
1084 self.cursor = event.cursor.clone();
1085 return Poll::Ready(Some(Ok(SessionObservationStreamItem::Event(event))));
1086 }
1087 Poll::Ready(Some(Err(LiveReplayStoreError::SubscriberLagged(_)))) => {
1088 self.subscription = None;
1089 continue;
1090 }
1091 Poll::Ready(Some(Err(err))) => {
1092 self.done = true;
1093 return Poll::Ready(Some(Err(live_replay_error(err))));
1094 }
1095 Poll::Ready(None) => {
1096 self.done = true;
1097 return Poll::Ready(None);
1098 }
1099 }
1100 }
1101 }
1102}
1103
1104fn live_replay_error(err: lash_core::LiveReplayStoreError) -> EmbedError {
1105 EmbedError::Runtime(lash_core::RuntimeError::new(
1106 RuntimeErrorCode::Other("live_replay".to_string()),
1107 err.to_string(),
1108 ))
1109}
1110
1111pub struct EnqueueTurnBuilder<'a> {
1112 session: &'a LashSession,
1113 input: TurnInput,
1114 id: Option<String>,
1115 ingress: TurnInputIngress,
1116}
1117
1118impl<'a> EnqueueTurnBuilder<'a> {
1119 pub fn id(mut self, id: impl Into<String>) -> Self {
1120 self.id = Some(id.into());
1121 self
1122 }
1123
1124 pub fn ingress(mut self, ingress: TurnInputIngress) -> Self {
1125 self.ingress = ingress;
1126 self
1127 }
1128
1129 pub async fn send(self) -> Result<PendingTurnInput> {
1130 let source_key = self.id.map(|id| format!("host:{id}"));
1131 self.session
1132 .runtime
1133 .enqueue_turn_input(self.input, self.ingress, source_key)
1134 .await
1135 .map_err(EmbedError::Runtime)
1136 }
1137}
1138
1139impl<'a> std::future::IntoFuture for EnqueueTurnBuilder<'a> {
1140 type Output = Result<PendingTurnInput>;
1141 type IntoFuture =
1142 std::pin::Pin<Box<dyn std::future::Future<Output = Result<PendingTurnInput>> + 'a>>;
1143
1144 fn into_future(self) -> Self::IntoFuture {
1145 Box::pin(self.send())
1146 }
1147}