Skip to main content

lash_core/
session.rs

1use std::sync::{Arc, OnceLock};
2
3use tokio::sync::mpsc::UnboundedSender;
4
5use crate::PluginMessage;
6use crate::tool_dispatch::ToolDispatchContext;
7use crate::{PromptContribution, RuntimeServices, SandboxMessage, SessionEvent, ToolProvider};
8
9mod execution_context;
10pub(crate) mod process_handles;
11mod tool_execution;
12
13pub use execution_context::RuntimeExecutionContext;
14pub(crate) use execution_context::RuntimeExecutionTracing;
15pub use tool_execution::{ToolInvocation, ToolInvocationReply};
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18struct ToolCatalogCacheKey {
19    include_base_tools: bool,
20    context_overlay_revision: u64,
21    tool_generation: u64,
22    plugin_revision: u64,
23}
24
25#[derive(Debug, Default)]
26struct ToolCatalogDerived {
27    catalog: OnceLock<Arc<Vec<serde_json::Value>>>,
28}
29
30struct ToolCatalogArtifact {
31    tool_catalog: Arc<crate::ToolCatalog>,
32    preamble: Arc<crate::TurnDriverPreamble>,
33    derived: ToolCatalogDerived,
34}
35
36#[derive(Clone)]
37pub(crate) struct ToolCatalogHandle(Arc<ToolCatalogArtifact>);
38
39impl ToolCatalogHandle {
40    fn tool_catalog(&self) -> Arc<crate::ToolCatalog> {
41        Arc::clone(&self.0.tool_catalog)
42    }
43
44    fn preamble(&self) -> Arc<crate::TurnDriverPreamble> {
45        Arc::clone(&self.0.preamble)
46    }
47
48    fn catalog(&self) -> Arc<Vec<serde_json::Value>> {
49        Arc::clone(self.0.derived.catalog.get_or_init(|| {
50            Arc::new(crate::tool_registry::project_tool_catalog(
51                self.0.tool_catalog.tools.iter().cloned(),
52            ))
53        }))
54    }
55}
56
57#[derive(Clone, Debug)]
58pub struct InjectedTurnInput {
59    pub id: Option<String>,
60    pub message: PluginMessage,
61}
62
63#[derive(Debug, thiserror::Error)]
64pub enum SessionError {
65    #[error("I/O error: {0}")]
66    Io(#[from] std::io::Error),
67    #[error("JSON error: {0}")]
68    Json(#[from] serde_json::Error),
69    #[error("code execution is not available in this session")]
70    CodeExecutionUnavailable,
71    #[error("code execution runtime exited unexpectedly")]
72    CodeExecutionRuntimeStopped,
73    #[error(
74        "provider mismatch for session `{session_id}`: persisted provider `{expected}` does not match live provider `{actual}`"
75    )]
76    ProviderMismatch {
77        expected: String,
78        actual: String,
79        session_id: String,
80    },
81    #[error("provider is not configured for session `{session_id}`")]
82    ProviderUnconfigured { session_id: String },
83    #[error("provider `{provider_id}` is not registered for session `{session_id}`")]
84    ProviderUnavailable {
85        provider_id: String,
86        session_id: String,
87    },
88    #[error("protocol error: {0}")]
89    Protocol(String),
90}
91
92#[derive(Clone, Debug)]
93pub struct ExecRequest {
94    pub language: String,
95    pub code: String,
96    pub accept_finish: bool,
97}
98
99pub struct Session {
100    session_id: String,
101    services: RuntimeServices,
102    include_base_tools: bool,
103    context_overlay_revision: u64,
104    context_tools: Vec<Arc<dyn ToolProvider>>,
105    tool_registry: Arc<crate::ToolRegistry>,
106    context_prompt_contributions: Vec<PromptContribution>,
107    message_tx: Option<UnboundedSender<SandboxMessage>>,
108    tool_catalog_cache: std::sync::Mutex<Vec<(ToolCatalogCacheKey, ToolCatalogHandle)>>,
109    /// Memoizes the rendered system prompt across turns. Most consecutive
110    /// turns reuse the same template + context overlay, so the cache hits
111    /// and we skip the section/Vec-join work in
112    /// `lash_sansio::PromptTemplate::render`.
113    prompt_cache: Arc<lash_sansio::PromptCache>,
114}
115
116impl Session {
117    pub async fn new(services: RuntimeServices, session_id: &str) -> Result<Self, SessionError> {
118        let tool_registry = services.plugins.tool_registry();
119        let mut session = Self {
120            session_id: session_id.to_string(),
121            services,
122            include_base_tools: true,
123            context_overlay_revision: 0,
124            context_tools: Vec::new(),
125            tool_registry,
126            context_prompt_contributions: Vec::new(),
127            message_tx: None,
128            tool_catalog_cache: std::sync::Mutex::new(Vec::new()),
129            prompt_cache: Arc::new(lash_sansio::PromptCache::new()),
130        };
131
132        let protocol_session = Arc::clone(session.plugins().protocol_session());
133        protocol_session
134            .initialize_session(crate::plugin::ProtocolSessionContext::new(
135                &mut session,
136                session_id,
137            ))
138            .await?;
139
140        Ok(session)
141    }
142
143    pub fn session_id(&self) -> &str {
144        &self.session_id
145    }
146
147    pub(crate) fn protocol_extra_prompt_contributions(&self) -> Vec<PromptContribution> {
148        // Protocol-specific prompt contributions are owned by the protocol
149        // plugins via their
150        // `reg.prompt().contribute(...)` hooks. Nothing to add here.
151        Vec::new()
152    }
153
154    pub fn tools(&self) -> Arc<dyn ToolProvider> {
155        Arc::clone(&self.tool_registry) as Arc<dyn ToolProvider>
156    }
157
158    pub fn plugins(&self) -> &Arc<crate::PluginSession> {
159        &self.services.plugins
160    }
161
162    pub fn set_context_overlay(
163        &mut self,
164        tool_providers: Vec<Arc<dyn ToolProvider>>,
165        prompt_contributions: Vec<PromptContribution>,
166        include_base_tools: bool,
167    ) -> Result<(), crate::PluginError> {
168        let tool_providers_unchanged = self.context_tools.len() == tool_providers.len()
169            && self
170                .context_tools
171                .iter()
172                .zip(&tool_providers)
173                .all(|(current, next)| Arc::ptr_eq(current, next));
174        if self.include_base_tools == include_base_tools
175            && self.context_prompt_contributions == prompt_contributions
176            && tool_providers_unchanged
177        {
178            return Ok(());
179        }
180        let registry = self
181            .services
182            .plugins
183            .tool_registry()
184            .compose_session_catalog(include_base_tools, tool_providers.clone())
185            .map(Arc::new)
186            .map_err(|err| {
187                crate::PluginError::Session(format!("failed to build session tool registry: {err}"))
188            })?;
189        self.include_base_tools = include_base_tools;
190        self.context_overlay_revision = self.context_overlay_revision.wrapping_add(1);
191        self.context_tools = tool_providers;
192        self.tool_registry = registry;
193        self.context_prompt_contributions = prompt_contributions;
194        self.tool_catalog_cache
195            .lock()
196            .expect("tool catalog cache lock")
197            .clear();
198        Ok(())
199    }
200
201    pub fn prompt_cache(&self) -> Arc<lash_sansio::PromptCache> {
202        Arc::clone(&self.prompt_cache)
203    }
204
205    pub fn context_prompt_contributions(&self) -> &[PromptContribution] {
206        &self.context_prompt_contributions
207    }
208
209    pub fn history_store(&self) -> Option<Arc<dyn crate::store::RuntimePersistence>> {
210        self.services.store.clone()
211    }
212
213    fn tool_catalog_cache_key(&self) -> ToolCatalogCacheKey {
214        ToolCatalogCacheKey {
215            include_base_tools: self.include_base_tools,
216            context_overlay_revision: self.context_overlay_revision,
217            tool_generation: self.tool_registry.generation(),
218            plugin_revision: self.plugins().snapshot_revision_fingerprint(),
219        }
220    }
221
222    fn build_tool_catalog_entry(
223        &self,
224        session_id: &str,
225    ) -> Result<ToolCatalogHandle, crate::PluginError> {
226        let provider = self.tools();
227        let tools = provider.tool_manifests();
228        let contract_provider = Arc::clone(&provider);
229        let resolve_contract: lash_sansio::ToolContractResolver =
230            Arc::new(move |name: &str| contract_provider.resolve_contract(name));
231        let tool_catalog = Arc::new(self.plugins().resolve_tool_catalog(
232            crate::plugin::ToolCatalogContext {
233                session_id: session_id.to_string(),
234                tools,
235                resolve_contract: Some(Arc::clone(&resolve_contract)),
236                tool_access: self.plugins().tool_access().clone(),
237                subagent: self.plugins().subagent_context().cloned(),
238                extensions: self.plugins().extensions().clone(),
239            },
240        )?);
241        let input = crate::ProtocolBuildInput {
242            tool_catalog: Arc::clone(&tool_catalog),
243            plugin_extensions: self.plugins().extensions().clone(),
244            trigger_events: self.plugins().triggers().clone(),
245            extra_prompt_contributions: self.protocol_extra_prompt_contributions(),
246        };
247        let driver = self.plugins().protocol_driver();
248        let preamble = driver.build_preamble(input);
249        Ok(ToolCatalogHandle(Arc::new(ToolCatalogArtifact {
250            tool_catalog,
251            preamble: Arc::new(preamble),
252            derived: ToolCatalogDerived::default(),
253        })))
254    }
255
256    fn tool_catalog_cache_entry(
257        &self,
258        session_id: &str,
259    ) -> Result<ToolCatalogHandle, crate::PluginError> {
260        let key = self.tool_catalog_cache_key();
261        let mut cache = self
262            .tool_catalog_cache
263            .lock()
264            .expect("tool catalog cache lock");
265        if let Some((_, entry)) = cache.iter().find(|(entry_key, _)| *entry_key == key) {
266            return Ok(entry.clone());
267        }
268        let entry = self.build_tool_catalog_entry(session_id)?;
269        cache.push((key, entry.clone()));
270        Ok(entry)
271    }
272
273    pub fn resolved_tool_catalog(
274        &self,
275        session_id: &str,
276    ) -> Result<Arc<crate::ToolCatalog>, crate::PluginError> {
277        Ok(self.tool_catalog_cache_entry(session_id)?.tool_catalog())
278    }
279
280    pub(crate) fn turn_driver_preamble(
281        &self,
282        session_id: &str,
283    ) -> Result<Arc<crate::TurnDriverPreamble>, crate::PluginError> {
284        Ok(self.tool_catalog_cache_entry(session_id)?.preamble())
285    }
286
287    pub(crate) fn shared_tool_catalog(
288        &self,
289        session_id: &str,
290    ) -> Result<Arc<Vec<serde_json::Value>>, crate::PluginError> {
291        Ok(self.tool_catalog_cache_entry(session_id)?.catalog())
292    }
293
294    pub fn tool_catalog(
295        &self,
296        session_id: &str,
297    ) -> Result<Vec<serde_json::Value>, crate::PluginError> {
298        Ok(self.shared_tool_catalog(session_id)?.as_ref().clone())
299    }
300
301    #[allow(
302        clippy::too_many_arguments,
303        reason = "code execution bridge carries explicit per-turn runtime dependencies"
304    )]
305    pub(crate) fn code_execution_context<'run>(
306        &self,
307        session_id: &str,
308        agent_frame_id: &str,
309        sessions: Arc<dyn crate::plugin::SessionStateService>,
310        session_lifecycle: Arc<dyn crate::plugin::SessionLifecycleService>,
311        session_graph: Arc<dyn crate::plugin::SessionGraphService>,
312        processes: Arc<dyn crate::ProcessService>,
313        process_cancel_ability: Arc<dyn crate::ProcessCancelAbility>,
314        effect_controller: crate::runtime::RuntimeEffectControllerHandle<'run>,
315        direct_completions: crate::DirectCompletionClient<'run>,
316        trigger_router: Option<crate::TriggerRouter>,
317        event_tx: tokio::sync::mpsc::Sender<SessionEvent>,
318        chronological_projection: Arc<crate::ChronologicalProjection>,
319        protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
320        turn_context: crate::TurnContext,
321        execution_env_spec: crate::ProcessExecutionEnvSpec,
322        checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer,
323    ) -> Result<RuntimeExecutionContext<'run>, crate::PluginError> {
324        let dispatch = Arc::new(ToolDispatchContext {
325            plugins: Arc::clone(self.plugins()),
326            tools: self.tools(),
327            tool_catalog: self.resolved_tool_catalog(session_id)?,
328            sessions,
329            session_lifecycle,
330            session_graph,
331            processes,
332            process_cancel_ability,
333            trigger_router,
334            effect_controller,
335            direct_completions: direct_completions.clone(),
336            parent_invocation: None,
337            execution_env_spec: execution_env_spec.clone(),
338            session_id: session_id.to_string(),
339            agent_frame_id: agent_frame_id.to_string(),
340            event_tx,
341            checkpoint_messages,
342            trigger_outcomes: crate::tool_dispatch::ToolTriggerOutcomeBuffer::default(),
343            attachment_store: Arc::clone(&self.services.attachment_store),
344            turn_context: turn_context.clone(),
345            clock: Arc::clone(&self.services.clock),
346        });
347        Ok(RuntimeExecutionContext::new(
348            session_id.to_string(),
349            dispatch,
350            Arc::clone(&self.services.process_env_store),
351            Arc::clone(&self.services.attachment_store),
352            chronological_projection,
353            protocol_extension,
354            turn_context,
355        ))
356        .map(|context| context.with_execution_env_spec(execution_env_spec))
357    }
358
359    /// Set the message sender for streaming messages during execution.
360    pub fn set_message_sender(&mut self, tx: UnboundedSender<SandboxMessage>) {
361        self.message_tx = Some(tx);
362    }
363
364    /// Clear the message sender (drops the sender, causing receivers to terminate).
365    pub fn clear_message_sender(&mut self) {
366        self.message_tx = None;
367    }
368
369    pub fn invalidate_runtime_caches(&self) {
370        self.tool_catalog_cache
371            .lock()
372            .expect("tool catalog cache lock")
373            .clear();
374        self.prompt_cache.clear();
375    }
376
377    pub async fn refresh_tool_catalog(&mut self) -> Result<(), SessionError> {
378        self.tool_registry = self
379            .services
380            .plugins
381            .tool_registry()
382            .compose_session_catalog(self.include_base_tools, self.context_tools.clone())
383            .map(Arc::new)
384            .map_err(|err| SessionError::Protocol(format!("tool reconfigure failed: {err}")))?;
385        self.tool_catalog_cache
386            .lock()
387            .expect("tool catalog cache lock")
388            .clear();
389        Ok(())
390    }
391}