1use super::*;
2
3impl LashRuntime {
4 pub fn set_runtime_lease_owner(&mut self, owner: crate::LeaseOwnerIdentity) {
11 self.runtime_lease_owner = owner;
12 }
13
14 pub fn unregister_plugin_session(&self) -> Result<(), crate::PluginError> {
15 if let Some(session) = self.session.as_ref() {
16 session
17 .plugins()
18 .host()
19 .unregister_session(&self.state.session_id)?;
20 }
21 Ok(())
22 }
23
24 pub(super) async fn from_host_state(
25 policy: SessionPolicy,
26 host: RuntimeHost,
27 services: RuntimeServices,
28 mut state: RuntimeSessionState,
29 ) -> Result<Self, SessionError> {
30 if state.session_id.is_empty() {
31 state.session_id = uuid::Uuid::new_v4().to_string();
32 }
33 let state_policy_was_unconfigured = state.policy.recorded_provider_id().is_empty()
39 && state.policy.model.id.trim().is_empty();
40 if state_policy_was_unconfigured {
41 state.policy = policy.clone();
42 }
43 state.ensure_agent_frame_initialized();
44 let state_policy = state.policy.clone();
45 if let Some(frame) = state.current_agent_frame_mut()
46 && frame.assignment.policy.recorded_provider_id().is_empty()
47 && frame.assignment.policy.model.id.trim().is_empty()
48 {
49 frame.assignment.policy = state_policy;
50 }
51 state.policy = state.effective_policy().clone();
52 state.protocol_turn_options = state.effective_protocol_turn_options().clone();
53 normalize_session_graph(&mut state);
54 let policy = state.effective_policy().clone();
55 if policy.model.id.trim().is_empty() {
56 return Err(SessionError::Protocol(
57 "session policy missing model spec; hosts must supply explicit model metadata"
58 .to_string(),
59 ));
60 }
61 let mut host = host;
62 if let Some(store) = services.store.clone() {
69 let manifest: Arc<dyn crate::AttachmentManifest> =
70 Arc::new(crate::attachments::PersistenceManifestAdapter(store));
71 let previous_attachment_store = Arc::clone(&host.core.durability.attachment_store);
78 let inherited_pending_attachment_ids =
79 if previous_attachment_store.session_id() == state.session_id {
80 previous_attachment_store.pending_manifest_commit_ids()
81 } else {
82 Vec::new()
83 };
84 let backend = Arc::clone(previous_attachment_store.backend());
85 let scoped = Arc::new(crate::SessionAttachmentStore::new_with_pending(
86 backend,
87 manifest,
88 state.session_id.clone(),
89 inherited_pending_attachment_ids,
90 ));
91 host.core.durability.attachment_store = scoped;
92 }
93 let services = services
94 .with_attachment_store(Arc::clone(&host.core.durability.attachment_store))
95 .with_process_env_store(Arc::clone(&host.core.durability.process_env_store))
96 .with_clock(Arc::clone(&host.core.clock));
97 let mut session = Session::new(services.clone(), &state.session_id).await?;
98 if let Some(tool_state) = state.tool_state_snapshot.clone() {
99 let report = session
107 .plugins()
108 .tool_registry()
109 .restore_state(tool_state)
110 .map_err(|err| SessionError::Protocol(err.to_string()))?;
111 if !report.orphaned.is_empty() {
112 tracing::warn!(
113 session_id = %state.session_id,
114 orphaned = ?report.orphaned,
115 "session restored with orphaned tools: no registered source \
116 resolves them; they remain non-members until their source returns"
117 );
118 }
119 }
120 session.refresh_tool_catalog().await?;
121 if let Some(snapshot) = state.plugin_snapshot.clone() {
122 session
123 .plugins()
124 .restore(&snapshot)
125 .map_err(|err| SessionError::Protocol(err.to_string()))?;
126 }
127 let protocol_session = Arc::clone(session.plugins().protocol_session());
128 let session_id = state.session_id.clone();
129 protocol_session
130 .restore_session(
131 crate::plugin::ProtocolSessionContext::new(&mut session, &session_id),
132 &state,
133 )
134 .await?;
135 state.discard_runtime_snapshots();
136 session
137 .plugins()
138 .emit_runtime_event(crate::PluginLifecycleEvent::SessionRestored(
139 crate::SessionReadView::from_persisted_state(&state),
140 ))
141 .await;
142 let protocol_turn_options = state.protocol_turn_options.clone();
143 let runtime_scope_id = uuid::Uuid::new_v4().to_string();
144 let runtime_lease_owner = crate::LeaseOwnerIdentity::opaque(
145 runtime_scope_id.clone(),
146 uuid::Uuid::new_v4().to_string(),
147 );
148 Ok(Self {
149 session: Some(session),
150 policy,
151 host,
152 services,
153 state,
154 runtime_scope_id: Arc::<str>::from(runtime_scope_id),
155 runtime_lease_owner,
156 managed_sessions: Arc::new(Mutex::new(HashMap::new())),
157 managed_turns: Arc::new(Mutex::new(HashMap::new())),
158 protocol_turn_options,
159 shared_token_ledger: Arc::new(std::sync::Mutex::new(Vec::new())),
160 process_sync_needed: Arc::new(AtomicBool::new(false)),
161 turn_phase_probe: None,
162 residency: Residency::default(),
163 })
164 }
165
166 pub async fn from_embedded_state(
168 policy: SessionPolicy,
169 host: EmbeddedRuntimeHost,
170 services: RuntimeServices,
171 state: RuntimeSessionState,
172 ) -> Result<Self, SessionError> {
173 Self::from_host_state(policy, host.into(), services, state).await
174 }
175
176 pub async fn from_background_state(
178 policy: SessionPolicy,
179 host: ProcessRuntimeHost,
180 services: RuntimeServices,
181 state: RuntimeSessionState,
182 ) -> Result<Self, SessionError> {
183 Self::from_host_state(policy, host.into(), services, state).await
184 }
185
186 pub async fn from_persistent_embedded_state(
188 policy: SessionPolicy,
189 host: EmbeddedRuntimeHost,
190 services: PersistentRuntimeServices,
191 state: RuntimeSessionState,
192 ) -> Result<Self, SessionError> {
193 Self::from_host_state(policy, host.into(), services.into_runtime_services(), state).await
194 }
195
196 pub async fn from_persistent_background_state(
198 policy: SessionPolicy,
199 host: ProcessRuntimeHost,
200 services: PersistentRuntimeServices,
201 state: RuntimeSessionState,
202 ) -> Result<Self, SessionError> {
203 Self::from_host_state(policy, host.into(), services.into_runtime_services(), state).await
204 }
205
206 pub(crate) async fn assemble_runtime(
217 policy: SessionPolicy,
218 embedded_host: EmbeddedRuntimeHost,
219 plugin_session: Arc<crate::PluginSession>,
220 store: Option<Arc<dyn crate::store::RuntimePersistence>>,
221 process_registry: Option<Arc<dyn ProcessRegistry>>,
222 mut state: RuntimeSessionState,
223 residency: Residency,
224 ) -> Result<Self, SessionError> {
225 if matches!(residency, Residency::ActivePathOnly) && store.is_none() {
228 return Err(SessionError::Protocol(
229 "Residency::ActivePathOnly requires a persistent store — \
230 without one, trimmed orphans are irrecoverable"
231 .to_string(),
232 ));
233 }
234 normalize_session_graph(&mut state);
237 apply_residency_on_load(&mut state, residency);
238 let mut runtime = match (store, process_registry) {
239 (Some(store), Some(registry)) => {
240 let host = ProcessRuntimeHost::new(embedded_host, registry);
241 let services = PersistentRuntimeServices::new(plugin_session, store);
242 Self::from_persistent_background_state(policy, host, services, state).await?
243 }
244 (Some(store), None) => {
245 let services = PersistentRuntimeServices::new(plugin_session, store);
246 Self::from_persistent_embedded_state(policy, embedded_host, services, state).await?
247 }
248 (None, Some(registry)) => {
249 let host = ProcessRuntimeHost::new(embedded_host, registry);
250 let services = RuntimeServices::new(plugin_session);
251 Self::from_background_state(policy, host, services, state).await?
252 }
253 (None, None) => {
254 let services = RuntimeServices::new(plugin_session);
255 Self::from_embedded_state(policy, embedded_host, services, state).await?
256 }
257 };
258 runtime.residency = residency;
259 Ok(runtime)
260 }
261
262 pub async fn from_environment(
278 env: &RuntimeEnvironment,
279 policy: SessionPolicy,
280 state: RuntimeSessionState,
281 store: Option<Arc<dyn crate::store::RuntimePersistence>>,
282 ) -> Result<Self, SessionError> {
283 let plugin_host = env.plugin_host.as_ref().ok_or_else(|| {
284 SessionError::Protocol(
285 "RuntimeEnvironment.plugin_host is required for from_environment".to_string(),
286 )
287 })?;
288 let plugin_session = plugin_host
289 .build_session(state.session_id.as_str(), state.plugin_snapshot.as_ref())
290 .map_err(|err| SessionError::Protocol(err.to_string()))?;
291 let mut embedded = EmbeddedRuntimeHost::new(env.core.clone());
292 if let Some(factory) = env.session_store_factory.as_ref() {
293 embedded = embedded.with_session_store_factory(Arc::clone(factory));
294 }
295 if let Some(store) = env.trigger_store.as_ref() {
296 embedded = embedded.with_trigger_store(Arc::clone(store));
297 }
298 let mut runtime = Self::assemble_runtime(
299 policy,
300 embedded,
301 plugin_session,
302 store,
303 env.process_registry.as_ref().cloned(),
304 state,
305 env.residency,
306 )
307 .await?;
308 runtime.host.process_work_driver = env.process_work_driver.clone();
311 runtime.host.queued_work_driver = env.queued_work_driver.clone();
312 Ok(runtime)
313 }
314
315 pub async fn park(mut self) -> Result<ParkedSession, SessionError> {
321 let store = self.services.store.clone().ok_or_else(|| {
322 SessionError::Protocol(
323 "park() requires a persistent runtime (store is not set)".to_string(),
324 )
325 })?;
326 let session_id = self.state.session_id.clone();
327 let policy = self.policy.clone();
328 if self.state.head_revision.is_none() || self.state.graph_replace_required {
336 let commit = crate::store::RuntimeCommit::persisted_state(&self.state, &[]);
337 let result = commit_runtime_state_with_fresh_session_execution_lease(
338 Arc::clone(&store),
339 commit,
340 &self.runtime_lease_owner,
341 self.host.core.control.lease_timings,
342 Arc::clone(&self.host.core.clock),
343 )
344 .await
345 .map_err(|err| {
346 SessionError::Protocol(format!("failed to persist runtime state: {err}"))
347 })?;
348 self.state.apply_persisted_commit_result(result);
349 }
350 Ok(ParkedSession {
355 session_id,
356 store,
357 policy,
358 })
359 }
360
361 pub async fn resume(
366 parked: ParkedSession,
367 env: &RuntimeEnvironment,
368 ) -> Result<Self, SessionError> {
369 let loaded = match env.residency {
375 Residency::KeepAll => {
376 crate::store::load_persisted_session_state(parked.store.as_ref()).await
377 }
378 Residency::ActivePathOnly => {
379 crate::store::load_persisted_session_state_active_path(parked.store.as_ref(), None)
380 .await
381 }
382 }
383 .map_err(|err| SessionError::Protocol(format!("failed to load runtime state: {err}")))?;
384 let state = loaded.unwrap_or_else(|| RuntimeSessionState {
385 session_id: parked.session_id.clone(),
386 policy: parked.policy.clone(),
387 ..RuntimeSessionState::default()
388 });
389 Self::from_environment(env, parked.policy, state, Some(parked.store)).await
390 }
391
392 pub async fn get_historic_node(
397 &self,
398 node_id: &str,
399 ) -> Result<Option<crate::SessionNodeRecord>, SessionError> {
400 if let Some(node) = self.state.session_graph.find_node(node_id) {
401 return Ok(Some(node.clone()));
402 }
403 let store = self.services.store.clone().ok_or_else(|| {
404 SessionError::Protocol("get_historic_node() requires a persistent runtime".to_string())
405 })?;
406 store
407 .load_node(node_id)
408 .await
409 .map_err(|err| SessionError::Protocol(format!("failed to load historic node: {err}")))
410 }
411
412 pub async fn orphaned_node_ids(&self) -> Result<Vec<String>, SessionError> {
428 let store = self.services.store.clone().ok_or_else(|| {
429 SessionError::Protocol("orphaned_node_ids() requires a persistent runtime".to_string())
430 })?;
431 let Some(read) = store
432 .load_session(crate::store::SessionReadScope::FullGraph)
433 .await
434 .map_err(|err| SessionError::Protocol(format!("failed to load full graph: {err}")))?
435 else {
436 return Ok(Vec::new());
437 };
438 let active: std::collections::HashSet<&str> = read
439 .graph
440 .active_path_nodes()
441 .iter()
442 .map(|node| node.node_id.as_str())
443 .collect();
444 Ok(read
445 .graph
446 .nodes
447 .iter()
448 .filter(|node| !active.contains(node.node_id.as_str()))
449 .map(|node| node.node_id.clone())
450 .collect())
451 }
452}