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 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 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 let overlay_unchanged = self.include_base_tools == include_base_tools
175 && self.context_prompt_contributions == prompt_contributions
176 && tool_providers_unchanged;
177 let registry = self
178 .services
179 .plugins
180 .tool_registry()
181 .compose_session_catalog(include_base_tools, tool_providers.clone())
182 .map(Arc::new)
183 .map_err(|err| {
184 crate::PluginError::Session(format!("failed to build session tool registry: {err}"))
185 })?;
186 self.include_base_tools = include_base_tools;
187 if !overlay_unchanged {
188 self.context_overlay_revision = self.context_overlay_revision.wrapping_add(1);
189 }
190 self.context_tools = tool_providers;
191 self.tool_registry = registry;
192 self.context_prompt_contributions = prompt_contributions;
193 self.tool_catalog_cache
194 .lock()
195 .expect("tool catalog cache lock")
196 .clear();
197 Ok(())
198 }
199
200 pub fn prompt_cache(&self) -> Arc<lash_sansio::PromptCache> {
201 Arc::clone(&self.prompt_cache)
202 }
203
204 pub fn context_prompt_contributions(&self) -> &[PromptContribution] {
205 &self.context_prompt_contributions
206 }
207
208 pub fn history_store(&self) -> Option<Arc<dyn crate::store::RuntimePersistence>> {
209 self.services.store.clone()
210 }
211
212 fn tool_catalog_cache_key(&self) -> ToolCatalogCacheKey {
213 ToolCatalogCacheKey {
214 include_base_tools: self.include_base_tools,
215 context_overlay_revision: self.context_overlay_revision,
216 tool_generation: self.tool_registry.generation(),
217 plugin_revision: self.plugins().snapshot_revision_fingerprint(),
218 }
219 }
220
221 fn build_tool_catalog_entry(
222 &self,
223 session_id: &str,
224 ) -> Result<ToolCatalogHandle, crate::PluginError> {
225 let provider = self.tools();
226 let tools = provider.tool_manifests();
227 let contract_provider = Arc::clone(&provider);
228 let resolve_contract: lash_sansio::ToolContractResolver =
229 Arc::new(move |name: &str| contract_provider.resolve_contract(name));
230 let tool_catalog = Arc::new(self.plugins().resolve_tool_catalog(
231 crate::plugin::ToolCatalogContext {
232 session_id: session_id.to_string(),
233 tools,
234 resolve_contract: Some(Arc::clone(&resolve_contract)),
235 tool_access: self.plugins().tool_access().clone(),
236 subagent: self.plugins().subagent_context().cloned(),
237 extensions: self.plugins().extensions().clone(),
238 },
239 )?);
240 let input = crate::ProtocolBuildInput {
241 tool_catalog: Arc::clone(&tool_catalog),
242 plugin_extensions: self.plugins().extensions().clone(),
243 trigger_events: self.plugins().triggers().clone(),
244 extra_prompt_contributions: self.protocol_extra_prompt_contributions(),
245 };
246 let driver = self.plugins().protocol_driver();
247 let preamble = driver.build_preamble(input);
248 Ok(ToolCatalogHandle(Arc::new(ToolCatalogArtifact {
249 tool_catalog,
250 preamble: Arc::new(preamble),
251 derived: ToolCatalogDerived::default(),
252 })))
253 }
254
255 fn tool_catalog_cache_entry(
256 &self,
257 session_id: &str,
258 ) -> Result<ToolCatalogHandle, crate::PluginError> {
259 let key = self.tool_catalog_cache_key();
260 let mut cache = self
261 .tool_catalog_cache
262 .lock()
263 .expect("tool catalog cache lock");
264 if let Some((_, entry)) = cache.iter().find(|(entry_key, _)| *entry_key == key) {
265 return Ok(entry.clone());
266 }
267 let entry = self.build_tool_catalog_entry(session_id)?;
268 cache.push((key, entry.clone()));
269 Ok(entry)
270 }
271
272 pub fn resolved_tool_catalog(
273 &self,
274 session_id: &str,
275 ) -> Result<Arc<crate::ToolCatalog>, crate::PluginError> {
276 Ok(self.tool_catalog_cache_entry(session_id)?.tool_catalog())
277 }
278
279 pub(crate) fn turn_driver_preamble(
280 &self,
281 session_id: &str,
282 ) -> Result<Arc<crate::TurnDriverPreamble>, crate::PluginError> {
283 Ok(self.tool_catalog_cache_entry(session_id)?.preamble())
284 }
285
286 pub(crate) fn shared_tool_catalog(
287 &self,
288 session_id: &str,
289 ) -> Result<Arc<Vec<serde_json::Value>>, crate::PluginError> {
290 Ok(self.tool_catalog_cache_entry(session_id)?.catalog())
291 }
292
293 pub fn tool_catalog(
294 &self,
295 session_id: &str,
296 ) -> Result<Vec<serde_json::Value>, crate::PluginError> {
297 Ok(self.shared_tool_catalog(session_id)?.as_ref().clone())
298 }
299
300 #[allow(
301 clippy::too_many_arguments,
302 reason = "code execution bridge carries explicit per-turn runtime dependencies"
303 )]
304 pub(crate) fn code_execution_context<'run>(
305 &self,
306 session_id: &str,
307 agent_frame_id: &str,
308 sessions: Arc<dyn crate::plugin::SessionStateService>,
309 session_lifecycle: Arc<dyn crate::plugin::SessionLifecycleService>,
310 session_graph: Arc<dyn crate::plugin::SessionGraphService>,
311 processes: Arc<dyn crate::ProcessService>,
312 process_cancel_ability: Arc<dyn crate::ProcessCancelAbility>,
313 effect_controller: crate::runtime::RuntimeEffectControllerHandle<'run>,
314 direct_completions: crate::DirectCompletionClient<'run>,
315 trigger_router: Option<crate::TriggerRouter>,
316 event_tx: tokio::sync::mpsc::Sender<SessionEvent>,
317 chronological_projection: Arc<crate::ChronologicalProjection>,
318 protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
319 turn_context: crate::TurnContext,
320 execution_env_spec: crate::ProcessExecutionEnvSpec,
321 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer,
322 ) -> Result<RuntimeExecutionContext<'run>, crate::PluginError> {
323 let dispatch = Arc::new(ToolDispatchContext {
324 plugins: Arc::clone(self.plugins()),
325 tools: self.tools(),
326 tool_catalog: self.resolved_tool_catalog(session_id)?,
327 sessions,
328 session_lifecycle,
329 session_graph,
330 processes,
331 process_cancel_ability,
332 trigger_router,
333 effect_controller,
334 direct_completions: direct_completions.clone(),
335 parent_invocation: None,
336 execution_env_spec: execution_env_spec.clone(),
337 session_id: session_id.to_string(),
338 agent_frame_id: agent_frame_id.to_string(),
339 event_tx,
340 checkpoint_messages,
341 trigger_outcomes: crate::tool_dispatch::ToolTriggerOutcomeBuffer::default(),
342 attachment_store: Arc::clone(&self.services.attachment_store),
343 turn_context: turn_context.clone(),
344 clock: Arc::clone(&self.services.clock),
345 });
346 Ok(RuntimeExecutionContext::new(
347 session_id.to_string(),
348 dispatch,
349 Arc::clone(&self.services.process_env_store),
350 Arc::clone(&self.services.attachment_store),
351 chronological_projection,
352 protocol_extension,
353 turn_context,
354 ))
355 .map(|context| context.with_execution_env_spec(execution_env_spec))
356 }
357
358 pub fn set_message_sender(&mut self, tx: UnboundedSender<SandboxMessage>) {
360 self.message_tx = Some(tx);
361 }
362
363 pub fn clear_message_sender(&mut self) {
365 self.message_tx = None;
366 }
367
368 pub fn invalidate_runtime_caches(&self) {
369 self.tool_catalog_cache
370 .lock()
371 .expect("tool catalog cache lock")
372 .clear();
373 self.prompt_cache.clear();
374 }
375
376 pub async fn refresh_tool_catalog(&mut self) -> Result<(), SessionError> {
377 self.tool_registry = self
378 .services
379 .plugins
380 .tool_registry()
381 .compose_session_catalog(self.include_base_tools, self.context_tools.clone())
382 .map(Arc::new)
383 .map_err(|err| SessionError::Protocol(format!("tool reconfigure failed: {err}")))?;
384 self.tool_catalog_cache
385 .lock()
386 .expect("tool catalog cache lock")
387 .clear();
388 Ok(())
389 }
390}