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