1use std::sync::Arc;
2
3use tokio::sync::mpsc::Sender;
4use tokio_util::sync::CancellationToken;
5
6use crate::tool_dispatch::ToolDispatchContext;
7use crate::{TurnActivity, TurnActivityId, TurnEvent};
8
9#[derive(Clone)]
10pub struct RuntimeExecutionContext<'run> {
11 pub(super) session_id: String,
12 pub(super) dispatch: Arc<ToolDispatchContext<'run>>,
13 process_env_store: Arc<dyn crate::ProcessExecutionEnvStore>,
14 attachment_store: Arc<dyn crate::AttachmentStore>,
15 chronological_projection: Arc<crate::ChronologicalProjection>,
16 protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
17 turn_context: crate::TurnContext,
18 execution_env_spec: crate::ProcessExecutionEnvSpec,
19 process_originator: Option<crate::ProcessOriginator>,
20 pub(super) runtime_process_id: Option<String>,
21 pub(super) process_event_context: Option<RuntimeExecutionProcessEventContext>,
22 process_env_ref: Option<crate::ProcessExecutionEnvRef>,
23 process_wake_target: Option<crate::SessionScope>,
24 pub(super) parent_invocation: Option<crate::RuntimeInvocation>,
25 turn_phase_probe: Option<Arc<dyn crate::runtime::RuntimeTurnPhaseProbe>>,
26 pub(super) turn_event_tx: Option<Sender<TurnActivity>>,
27 pub(super) cancellation_token: Option<CancellationToken>,
28 started_process_ids: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
33}
34
35#[derive(Clone)]
36pub(super) struct RuntimeExecutionProcessEventContext {
37 pub process_id: String,
38 pub registry: Arc<dyn crate::ProcessRegistry>,
39 pub store: Option<Arc<dyn crate::RuntimePersistence>>,
40 pub session_store_factory: Option<Arc<dyn crate::SessionStoreFactory>>,
41 pub queued_work_poke: Option<crate::QueuedWorkPoke>,
42}
43
44impl<'run> RuntimeExecutionContext<'run> {
45 pub(crate) fn drain_tool_trigger_outcomes(
46 &self,
47 ) -> Result<Vec<crate::tool_dispatch::ToolTriggerEffectOutcome>, crate::PluginError> {
48 self.dispatch
49 .trigger_outcomes
50 .drain()
51 .map_err(crate::PluginError::Session)
52 }
53
54 pub(super) fn process_scope(
55 &self,
56 parent_invocation: Option<crate::RuntimeInvocation>,
57 ) -> crate::ProcessOpScope<'_> {
58 crate::ProcessOpScope::new(self.dispatch.effect_controller.scoped())
59 .with_parent_invocation(parent_invocation)
60 .with_agent_frame_id(Some(self.dispatch.agent_frame_id.clone()))
61 }
62
63 #[allow(
64 clippy::too_many_arguments,
65 reason = "code execution bridge carries explicit per-turn runtime dependencies"
66 )]
67 pub(crate) fn new(
68 session_id: String,
69 dispatch: Arc<ToolDispatchContext<'run>>,
70 process_env_store: Arc<dyn crate::ProcessExecutionEnvStore>,
71 attachment_store: Arc<dyn crate::AttachmentStore>,
72 chronological_projection: Arc<crate::ChronologicalProjection>,
73 protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
74 turn_context: crate::TurnContext,
75 ) -> Self {
76 Self {
77 session_id,
78 dispatch,
79 process_env_store,
80 attachment_store,
81 chronological_projection,
82 protocol_extension,
83 turn_context,
84 execution_env_spec: crate::ProcessExecutionEnvSpec::new(
85 crate::PluginOptions::default(),
86 crate::SessionPolicy::default(),
87 ),
88 process_originator: None,
89 runtime_process_id: None,
90 process_event_context: None,
91 started_process_ids: Arc::default(),
92 process_env_ref: None,
93 process_wake_target: None,
94 parent_invocation: None,
95 turn_phase_probe: None,
96 turn_event_tx: None,
97 cancellation_token: None,
98 }
99 }
100
101 pub fn session_id(&self) -> &str {
102 &self.session_id
103 }
104
105 pub fn execution_scope_id(&self) -> String {
106 self.dispatch
107 .effect_controller
108 .scoped()
109 .scope_id()
110 .to_string()
111 }
112
113 pub fn session_scope(&self) -> crate::SessionScope {
114 self.dispatch
115 .agent_frame_id
116 .as_str()
117 .is_empty()
118 .then(|| crate::SessionScope::new(self.session_id.clone()))
119 .unwrap_or_else(|| {
120 crate::SessionScope::for_agent_frame(
121 self.session_id.clone(),
122 self.dispatch.agent_frame_id.clone(),
123 )
124 })
125 }
126
127 pub fn trigger_store(&self) -> Option<Arc<dyn crate::TriggerStore>> {
128 self.dispatch
129 .trigger_router
130 .as_ref()
131 .map(crate::TriggerRouter::store)
132 }
133
134 pub fn trigger_registration_originator(&self) -> crate::ProcessOriginator {
135 self.process_originator
136 .clone()
137 .unwrap_or_else(|| crate::ProcessOriginator::session(self.session_scope()))
138 }
139
140 pub fn trigger_registration_wake_target(&self) -> Option<crate::SessionScope> {
141 self.process_wake_target
142 .clone()
143 .or_else(|| Some(self.session_scope()))
144 }
145
146 pub fn attachment_store(&self) -> Arc<dyn crate::AttachmentStore> {
147 Arc::clone(&self.attachment_store)
148 }
149
150 pub fn process_env_store(&self) -> Arc<dyn crate::ProcessExecutionEnvStore> {
151 Arc::clone(&self.process_env_store)
152 }
153
154 pub fn chronological_projection(&self) -> Arc<crate::ChronologicalProjection> {
155 Arc::clone(&self.chronological_projection)
156 }
157
158 pub fn protocol_extension<T: 'static>(&self) -> Option<&T> {
159 self.protocol_extension
160 .as_ref()
161 .and_then(|extension| extension.as_any().downcast_ref::<T>())
162 }
163
164 pub fn turn_context(&self) -> &crate::TurnContext {
165 &self.turn_context
166 }
167
168 pub fn tool_catalog(&self) -> Arc<crate::ToolCatalog> {
169 Arc::clone(&self.dispatch.tool_catalog)
170 }
171
172 pub(crate) fn session_graph_service(&self) -> &dyn crate::plugin::SessionGraphService {
173 self.dispatch.session_graph.as_ref()
174 }
175
176 pub(super) async fn emit_turn_activity(
177 &self,
178 correlation_id: TurnActivityId,
179 event: TurnEvent,
180 ) {
181 if let Some(tx) = &self.turn_event_tx {
182 let _ = tx.send(TurnActivity::new(correlation_id, event)).await;
183 }
184 }
185
186 pub(crate) fn with_turn_event_sender(mut self, turn_event_tx: Sender<TurnActivity>) -> Self {
187 self.turn_event_tx = Some(turn_event_tx);
188 self
189 }
190
191 pub(crate) fn with_parent_invocation(mut self, metadata: crate::RuntimeInvocation) -> Self {
192 self.parent_invocation = Some(metadata);
193 self
194 }
195
196 pub(crate) fn with_execution_env_spec(
197 mut self,
198 execution_env_spec: crate::ProcessExecutionEnvSpec,
199 ) -> Self {
200 self.execution_env_spec = execution_env_spec;
201 self
202 }
203
204 pub(crate) fn with_process_registration_context(
205 mut self,
206 registration: &crate::ProcessRegistration,
207 ) -> Self {
208 self.process_originator = Some(registration.provenance.originator.clone());
209 self.runtime_process_id = Some(registration.id.clone());
210 self.process_env_ref = registration.env_ref.clone();
211 self.process_wake_target = registration.wake_target.clone();
212 self
213 }
214
215 pub(crate) fn with_process_event_context(
216 mut self,
217 process_id: impl Into<String>,
218 registry: Arc<dyn crate::ProcessRegistry>,
219 store: Option<Arc<dyn crate::RuntimePersistence>>,
220 session_store_factory: Option<Arc<dyn crate::SessionStoreFactory>>,
221 queued_work_poke: Option<crate::QueuedWorkPoke>,
222 ) -> Self {
223 self.process_event_context = Some(RuntimeExecutionProcessEventContext {
224 process_id: process_id.into(),
225 registry,
226 store,
227 session_store_factory,
228 queued_work_poke,
229 });
230 self
231 }
232
233 pub(super) fn record_started_process(&self, process_id: &str) {
237 self.started_process_ids
238 .lock()
239 .expect("started process ids lock")
240 .insert(process_id.to_string());
241 }
242
243 pub(super) fn is_run_local_process(&self, process_id: &str) -> bool {
244 self.started_process_ids
245 .lock()
246 .expect("started process ids lock")
247 .contains(process_id)
248 }
249
250 pub(crate) fn process_spawn_provenance(&self) -> Option<crate::ProcessSpawnProvenance> {
251 self.process_originator
252 .clone()
253 .map(|originator| crate::ProcessSpawnProvenance {
254 originator,
255 wake_target: self.process_wake_target.clone(),
256 })
257 }
258
259 pub(super) async fn attach_captured_process_execution_env(
260 &self,
261 registration: crate::ProcessRegistration,
262 ) -> Result<crate::ProcessRegistration, crate::PluginError> {
263 if registration.env_ref.is_some() {
264 return Ok(registration);
265 }
266 match registration.input.as_ref() {
267 crate::ProcessInput::ToolCall { .. } | crate::ProcessInput::Engine { .. } => {
268 let env_ref = self.captured_process_execution_env_ref().await?;
269 Ok(registration.with_execution_env_ref(Some(env_ref)))
270 }
271 crate::ProcessInput::External { .. } | crate::ProcessInput::SessionTurn { .. } => {
272 Ok(registration)
273 }
274 }
275 }
276
277 pub async fn captured_process_execution_env_ref(
278 &self,
279 ) -> Result<crate::ProcessExecutionEnvRef, crate::PluginError> {
280 if let Some(env_ref) = self.process_env_ref.clone() {
281 return Ok(env_ref);
282 }
283 crate::persist_process_execution_env(
284 self.process_env_store.as_ref(),
285 &self.execution_env_spec,
286 )
287 .await
288 }
289
290 pub(crate) fn with_turn_phase_probe(
291 mut self,
292 probe: Option<Arc<dyn crate::runtime::RuntimeTurnPhaseProbe>>,
293 ) -> Self {
294 self.turn_phase_probe = probe;
295 self
296 }
297
298 #[doc(hidden)]
299 pub fn named_phase(&self, phase: &'static str) -> crate::runtime::RuntimeNamedPhase {
300 crate::runtime::RuntimeNamedPhase::begin(self.turn_phase_probe.clone(), phase)
301 }
302
303 pub fn parent_invocation(&self) -> Option<&crate::RuntimeInvocation> {
304 self.parent_invocation.as_ref()
305 }
306
307 pub(crate) fn with_cancellation_token(mut self, cancellation_token: CancellationToken) -> Self {
308 self.cancellation_token = Some(cancellation_token);
309 self
310 }
311
312 pub(crate) fn tool_scheduling(&self, name: &str) -> crate::ToolScheduling {
313 crate::tool_dispatch::resolve_tool_scheduling(&self.dispatch, name)
314 }
315
316 pub fn callable_tool_manifest(&self, name: &str) -> Option<crate::ToolManifest> {
317 crate::tool_dispatch::resolve_callable_manifest(&self.dispatch, name)
318 }
319
320 pub fn callable_tool_manifest_by_id(&self, id: &crate::ToolId) -> Option<crate::ToolManifest> {
321 crate::tool_dispatch::resolve_callable_manifest_by_id(&self.dispatch, id)
322 }
323
324 pub fn tool_argument_projection_policy(
325 &self,
326 name: &str,
327 ) -> crate::ToolArgumentProjectionPolicy {
328 crate::tool_dispatch::resolve_tool_argument_projection_policy(&self.dispatch, name)
329 }
330
331 pub async fn start_child_process(
332 &self,
333 registration: crate::ProcessRegistration,
334 kind: impl Into<String>,
335 label: Option<String>,
336 ) -> crate::ToolInvocationReply {
337 let _phase = self.named_phase("process.start_child");
338 let registration = match self
339 .attach_captured_process_execution_env(registration)
340 .await
341 {
342 Ok(registration) => registration,
343 Err(err) => {
344 return crate::ToolInvocationReply::error(serde_json::json!(err.to_string()));
345 }
346 };
347 let process_id = registration.id.clone();
348 let mut options = crate::ProcessStartOptions::new()
349 .with_descriptor(crate::ProcessHandleDescriptor::new(Some(kind), label));
350 if let Some(spawn) = self.process_spawn_provenance() {
351 options = options.with_spawn_provenance(spawn);
352 }
353 match self
354 .dispatch
355 .processes
356 .start(
357 &self.session_id,
358 registration,
359 options,
360 self.process_scope(self.parent_invocation.clone()),
361 )
362 .await
363 {
364 Ok(_) => {
365 self.record_started_process(&process_id);
366 crate::ToolInvocationReply::success(Self::process_handle_json(&process_id))
367 }
368 Err(err) => crate::ToolInvocationReply::error(serde_json::json!(err.to_string())),
369 }
370 }
371
372 pub async fn sleep_process(
373 &self,
374 scope: &str,
375 sequence: u64,
376 duration_ms: u64,
377 ) -> Result<(), crate::RuntimeEffectControllerError> {
378 let cancellation = self.cancellation_token.clone().unwrap_or_default();
379 let invocation = crate::runtime::causal::process_sleep_invocation(
380 &self.session_id,
381 self.parent_invocation.as_ref(),
382 scope,
383 sequence,
384 );
385 let outcome = self
386 .dispatch
387 .effect_controller
388 .controller()
389 .execute_effect(
390 crate::RuntimeEffectEnvelope::new(
391 invocation,
392 crate::RuntimeEffectCommand::Sleep { duration_ms },
393 ),
394 crate::RuntimeEffectLocalExecutor::sleep(cancellation),
395 )
396 .await?;
397 match outcome {
398 crate::RuntimeEffectOutcome::Sleep => Ok(()),
399 other => Err(crate::RuntimeEffectControllerError::new(
400 "runtime_effect_wrong_outcome",
401 format!("expected sleep outcome, got {}", other.kind().as_str()),
402 )),
403 }
404 }
405
406 pub async fn await_process_signal_event(
407 &self,
408 process_id: &str,
409 signal_name: &str,
410 event_ordinal: u64,
411 ) -> Result<serde_json::Value, crate::RuntimeEffectControllerError> {
412 let cancellation = self.cancellation_token.clone().unwrap_or_default();
413 let key = self
414 .dispatch
415 .effect_controller
416 .controller()
417 .await_event_key(
418 &crate::ExecutionScope::process(process_id),
419 crate::AwaitEventWaitIdentity::process_signal(
420 process_id,
421 signal_name,
422 event_ordinal,
423 ),
424 )
425 .await?;
426 let invocation = crate::runtime::causal::process_await_event_invocation(
427 &self.session_id,
428 self.parent_invocation.as_ref(),
429 process_id,
430 signal_name,
431 event_ordinal,
432 );
433 let outcome = self
434 .dispatch
435 .effect_controller
436 .controller()
437 .execute_effect(
438 crate::RuntimeEffectEnvelope::new(
439 invocation,
440 crate::RuntimeEffectCommand::AwaitEvent { key },
441 ),
442 crate::RuntimeEffectLocalExecutor::await_event(cancellation, None),
443 )
444 .await?;
445 match outcome.into_await_event()? {
446 crate::Resolution::Ok(value) => Ok(value),
447 crate::Resolution::Err(err) => Err(crate::RuntimeEffectControllerError::new(
448 err.code,
449 err.message,
450 )),
451 crate::Resolution::Timeout => Err(crate::RuntimeEffectControllerError::new(
452 "process_signal_wait_timeout",
453 "process signal wait timed out",
454 )),
455 crate::Resolution::Cancelled => Err(crate::RuntimeEffectControllerError::new(
456 "process_signal_wait_cancelled",
457 "process signal wait was cancelled",
458 )),
459 }
460 }
461
462 pub async fn signal_process_by_id(
463 &self,
464 registry: Arc<dyn crate::ProcessRegistry>,
465 process_id: &str,
466 signal_name: &str,
467 signal_id: String,
468 payload: serde_json::Value,
469 ) -> Result<crate::ProcessEvent, crate::RuntimeEffectControllerError> {
470 let event_type = crate::process_signal_event_type(signal_name)?;
471 let replay_key = format!("process:{process_id}:signal.{signal_name}:{signal_id}");
472 let signal_payload = payload.clone();
473 let command = crate::ProcessCommand::Signal {
474 process_id: process_id.to_string(),
475 signal_name: signal_name.to_string(),
476 signal_id,
477 request: crate::ProcessEventAppendRequest::new(event_type.clone(), payload)
478 .with_replay_key(replay_key),
479 };
480 let effect_id = command.effect_id();
481 let invocation = crate::runtime::causal::process_effect_invocation(
482 &self.session_id,
483 self.parent_invocation.clone(),
484 &effect_id,
485 );
486 let outcome = self
487 .dispatch
488 .effect_controller
489 .controller()
490 .execute_effect(
491 crate::RuntimeEffectEnvelope::new(
492 invocation,
493 crate::RuntimeEffectCommand::process(command),
494 ),
495 crate::RuntimeEffectLocalExecutor::processes(Arc::clone(®istry)),
496 )
497 .await?;
498 match outcome.into_process()? {
499 crate::ProcessEffectOutcome::Signal { event } => {
500 let waiting_ordinal =
501 registry
502 .get_process(process_id)
503 .await
504 .and_then(|record| match record.wait {
505 Some(crate::WaitState {
506 kind:
507 crate::WaitKind::Signal {
508 name,
509 event_type: wait_event_type,
510 ordinal,
511 ..
512 },
513 ..
514 }) if name == signal_name && wait_event_type == event_type => {
515 Some(ordinal)
516 }
517 _ => None,
518 });
519 let ordinal = match waiting_ordinal {
520 Some(ordinal) => ordinal,
521 None => {
522 registry
523 .count_events_through(process_id, &event_type, event.sequence)
524 .await?
525 }
526 };
527 if ordinal > 0 {
528 let key = self
529 .dispatch
530 .effect_controller
531 .controller()
532 .await_event_key(
533 &crate::ExecutionScope::process(process_id),
534 crate::AwaitEventWaitIdentity::process_signal(
535 process_id,
536 signal_name,
537 ordinal,
538 ),
539 )
540 .await?;
541 let _ = self
542 .dispatch
543 .effect_controller
544 .controller()
545 .resolve_await_event(&key, crate::Resolution::Ok(signal_payload))
546 .await?;
547 }
548 Ok(event)
549 }
550 other => Err(crate::RuntimeEffectControllerError::new(
551 "runtime_effect_wrong_outcome",
552 format!("expected signal outcome, got {other:?}"),
553 )),
554 }
555 }
556
557 pub async fn append_process_event(
558 &self,
559 registry: Arc<dyn crate::ProcessRegistry>,
560 process_id: &str,
561 request: crate::ProcessEventAppendRequest,
562 ) -> Result<crate::ProcessEvent, crate::PluginError> {
563 let result = registry.append_event(process_id, request).await?;
564 if let Some(context) = self.process_event_context.as_ref() {
565 crate::tool_provider::process_events::enqueue_wake_delivery(
566 context.store.clone(),
567 context.session_store_factory.as_ref(),
568 result.wake_delivery,
569 Some(self.session_graph_service()),
570 context.queued_work_poke.as_ref(),
571 )
572 .await?;
573 }
574 Ok(result.event)
575 }
576}
577
578#[cfg(test)]
579mod tests {
580 use super::*;
581 use crate::tool_dispatch::ToolDispatchContext;
582 use crate::{ToolCall, ToolProvider, ToolResult};
583
584 struct NoopTools;
585
586 #[async_trait::async_trait]
587 impl ToolProvider for NoopTools {
588 fn tool_manifests(&self) -> Vec<crate::ToolManifest> {
589 Vec::new()
590 }
591
592 fn resolve_contract(&self, _name: &str) -> Option<Arc<crate::ToolContract>> {
593 None
594 }
595
596 async fn execute(&self, _call: ToolCall<'_>) -> ToolResult {
597 ToolResult::err_fmt("not used")
598 }
599 }
600
601 #[test]
602 fn tool_argument_projection_policy_resolves_from_active_catalog_and_defaults_unknown() {
603 let tool = crate::ToolDefinition::raw(
604 "tool:seedy",
605 "seedy",
606 "Seed-aware",
607 crate::ToolDefinition::default_input_schema(),
608 serde_json::json!({ "type": "string" }),
609 )
610 .with_argument_projection(
611 crate::ToolArgumentProjectionPolicy::preserve_projected_refs_in_field("seed"),
612 );
613 let plugins = crate::plugin::PluginHost::empty()
614 .build_session("session", None)
615 .expect("plugin session");
616 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
617 let dispatch = Arc::new(ToolDispatchContext {
618 plugins,
619 tools: Arc::new(NoopTools),
620 tool_catalog: Arc::new(crate::ToolCatalog::from_tools(
621 vec![tool.manifest()],
622 std::collections::BTreeMap::new(),
623 )),
624 sessions: Arc::new(crate::testing::MockSessionManager::default()),
625 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
626 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
627 processes: Arc::new(crate::UnavailableProcessService),
628 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
629 trigger_router: None,
630 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
631 crate::InlineRuntimeEffectController,
632 )),
633 direct_completions: crate::DirectCompletionClient::unavailable(
634 "direct completions are unavailable in this test context",
635 ),
636 parent_invocation: None,
637 execution_env_spec: crate::ProcessExecutionEnvSpec::new(
638 crate::PluginOptions::default(),
639 crate::SessionPolicy::default(),
640 ),
641 session_id: "session".to_string(),
642 agent_frame_id: String::new(),
643 event_tx,
644 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
645 trigger_outcomes: crate::tool_dispatch::ToolTriggerOutcomeBuffer::default(),
646 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
647 turn_context: crate::TurnContext::default(),
648 });
649 let ctx = RuntimeExecutionContext::new(
650 "session".to_string(),
651 dispatch,
652 Arc::new(crate::InMemoryProcessExecutionEnvStore::new()),
653 Arc::new(crate::InMemoryAttachmentStore::new()),
654 Arc::new(crate::ChronologicalProjection::default()),
655 None,
656 crate::TurnContext::default(),
657 );
658
659 assert_eq!(
660 ctx.tool_argument_projection_policy("seedy"),
661 crate::ToolArgumentProjectionPolicy::preserve_projected_refs_in_field("seed")
662 );
663 assert_eq!(
664 ctx.tool_argument_projection_policy("missing"),
665 crate::ToolArgumentProjectionPolicy::MaterializeProjectedValues
666 );
667 }
668}