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
9pub(crate) fn lashlang_host_environment_from_tool_catalog(
10 catalog: &crate::ToolCatalog,
11 abilities: lashlang::LashlangAbilities,
12 language_features: lashlang::LashlangLanguageFeatures,
13 host_resources: lashlang::LashlangHostCatalog,
14) -> lashlang::LashlangHostEnvironment {
15 let mut resources = lashlang_resources_from_tool_catalog(catalog);
16 resources.extend(host_resources);
17 lashlang::LashlangHostEnvironment::new(resources, abilities)
18 .with_language_features(language_features)
19}
20
21pub(crate) fn lashlang_resources_from_tool_catalog(
22 catalog: &crate::ToolCatalog,
23) -> lashlang::LashlangHostCatalog {
24 let mut host_catalog = lashlang::LashlangHostCatalog::new();
25 for entry in catalog.tools.iter() {
26 if entry.availability.is_callable() {
27 let lashlang_binding = entry
28 .manifest
29 .lashlang_binding
30 .executable_for(&entry.manifest.name);
31 host_catalog.add_module_operation(
32 lashlang_binding.module_path.iter().map(String::as_str),
33 lashlang_binding.authority_type.clone(),
34 lashlang_binding.operation.clone(),
35 entry.manifest.name.clone(),
36 lashlang::TypeExpr::Any,
37 lashlang::TypeExpr::Any,
38 );
39 }
40 }
41 host_catalog
42}
43
44#[derive(Clone)]
45pub struct RuntimeExecutionContext<'run> {
46 pub(super) session_id: String,
47 pub(super) dispatch: Arc<ToolDispatchContext<'run>>,
48 lashlang_abilities: lashlang::LashlangAbilities,
49 lashlang_language_features: lashlang::LashlangLanguageFeatures,
50 lashlang_host_environment: lashlang::LashlangHostEnvironment,
51 lashlang_artifact_store: Arc<dyn lashlang::LashlangArtifactStore>,
52 attachment_store: Arc<dyn crate::AttachmentStore>,
53 chronological_projection: Arc<crate::ChronologicalProjection>,
54 protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
55 turn_context: crate::TurnContext,
56 execution_env_spec: crate::ProcessExecutionEnvSpec,
57 process_originator: Option<crate::ProcessOriginator>,
58 pub(super) runtime_process_id: Option<String>,
59 pub(super) process_event_context: Option<RuntimeExecutionProcessEventContext>,
60 process_env_ref: Option<crate::ProcessExecutionEnvRef>,
61 process_wake_target: Option<crate::SessionScope>,
62 pub(super) parent_invocation: Option<crate::RuntimeInvocation>,
63 lashlang_execution_sink: Option<Arc<dyn lash_trace::TraceSink>>,
64 lashlang_execution_context: lash_trace::TraceContext,
65 turn_phase_probe: Option<Arc<dyn crate::runtime::RuntimeTurnPhaseProbe>>,
66 pub(super) turn_event_tx: Option<Sender<TurnActivity>>,
67 pub(super) cancellation_token: Option<CancellationToken>,
68 started_process_ids: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
73}
74
75#[derive(Clone)]
76pub(super) struct RuntimeExecutionProcessEventContext {
77 pub process_id: String,
78 pub registry: Arc<dyn crate::ProcessRegistry>,
79 pub store: Option<Arc<dyn crate::RuntimePersistence>>,
80 pub session_store_factory: Option<Arc<dyn crate::SessionStoreFactory>>,
81 pub queued_work_poke: Option<crate::QueuedWorkPoke>,
82}
83
84impl<'run> RuntimeExecutionContext<'run> {
85 pub(crate) fn drain_tool_trigger_outcomes(
86 &self,
87 ) -> Result<Vec<crate::tool_dispatch::ToolTriggerEffectOutcome>, crate::PluginError> {
88 self.dispatch
89 .trigger_outcomes
90 .drain()
91 .map_err(crate::PluginError::Session)
92 }
93
94 pub(super) fn process_scope(
95 &self,
96 parent_invocation: Option<crate::RuntimeInvocation>,
97 ) -> crate::ProcessOpScope<'_> {
98 crate::ProcessOpScope::new(self.dispatch.effect_controller.scoped())
99 .with_parent_invocation(parent_invocation)
100 .with_agent_frame_id(Some(self.dispatch.agent_frame_id.clone()))
101 }
102
103 #[allow(
104 clippy::too_many_arguments,
105 reason = "code execution bridge carries explicit per-turn runtime dependencies"
106 )]
107 pub(crate) fn new(
108 session_id: String,
109 dispatch: Arc<ToolDispatchContext<'run>>,
110 lashlang_abilities: lashlang::LashlangAbilities,
111 lashlang_language_features: lashlang::LashlangLanguageFeatures,
112 lashlang_artifact_store: Arc<dyn lashlang::LashlangArtifactStore>,
113 attachment_store: Arc<dyn crate::AttachmentStore>,
114 chronological_projection: Arc<crate::ChronologicalProjection>,
115 protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
116 turn_context: crate::TurnContext,
117 ) -> Self {
118 let lashlang_host_environment = lashlang_host_environment_from_tool_catalog(
119 &dispatch.tool_catalog,
120 lashlang_abilities,
121 lashlang_language_features,
122 dispatch.plugins.lashlang_resources(),
123 );
124 Self {
125 session_id,
126 dispatch,
127 lashlang_abilities,
128 lashlang_language_features,
129 lashlang_host_environment,
130 lashlang_artifact_store,
131 attachment_store,
132 chronological_projection,
133 protocol_extension,
134 turn_context,
135 execution_env_spec: crate::ProcessExecutionEnvSpec::new(
136 crate::PluginOptions::default(),
137 crate::SessionPolicy::default(),
138 ),
139 process_originator: None,
140 runtime_process_id: None,
141 process_event_context: None,
142 started_process_ids: Arc::default(),
143 process_env_ref: None,
144 process_wake_target: None,
145 parent_invocation: None,
146 lashlang_execution_sink: None,
147 lashlang_execution_context: lash_trace::TraceContext::default(),
148 turn_phase_probe: None,
149 turn_event_tx: None,
150 cancellation_token: None,
151 }
152 }
153
154 pub fn session_id(&self) -> &str {
155 &self.session_id
156 }
157
158 pub fn attachment_store(&self) -> Arc<dyn crate::AttachmentStore> {
159 Arc::clone(&self.attachment_store)
160 }
161
162 pub async fn put_lashlang_module_artifact(
163 &self,
164 artifact: &lashlang::ModuleArtifact,
165 ) -> Result<(), String> {
166 self.lashlang_artifact_store
167 .put_module_artifact(artifact)
168 .await
169 .map_err(|err| err.to_string())
170 }
171
172 pub fn chronological_projection(&self) -> Arc<crate::ChronologicalProjection> {
173 Arc::clone(&self.chronological_projection)
174 }
175
176 pub fn protocol_extension<T: 'static>(&self) -> Option<&T> {
177 self.protocol_extension
178 .as_ref()
179 .and_then(|extension| extension.as_any().downcast_ref::<T>())
180 }
181
182 pub fn turn_context(&self) -> &crate::TurnContext {
183 &self.turn_context
184 }
185
186 pub(crate) fn session_graph_service(&self) -> &dyn crate::plugin::SessionGraphService {
187 self.dispatch.session_graph.as_ref()
188 }
189
190 pub(super) async fn emit_turn_activity(
191 &self,
192 correlation_id: TurnActivityId,
193 event: TurnEvent,
194 ) {
195 if let Some(tx) = &self.turn_event_tx {
196 let _ = tx.send(TurnActivity::new(correlation_id, event)).await;
197 }
198 }
199
200 pub(crate) fn with_turn_event_sender(mut self, turn_event_tx: Sender<TurnActivity>) -> Self {
201 self.turn_event_tx = Some(turn_event_tx);
202 self
203 }
204
205 pub(crate) fn with_parent_invocation(mut self, metadata: crate::RuntimeInvocation) -> Self {
206 self.parent_invocation = Some(metadata);
207 self
208 }
209
210 pub(crate) fn with_execution_env_spec(
211 mut self,
212 execution_env_spec: crate::ProcessExecutionEnvSpec,
213 ) -> Self {
214 self.execution_env_spec = execution_env_spec;
215 self
216 }
217
218 pub(crate) fn with_process_registration_context(
219 mut self,
220 registration: &crate::ProcessRegistration,
221 ) -> Self {
222 self.process_originator = Some(registration.provenance.originator.clone());
223 self.runtime_process_id = Some(registration.id.clone());
224 self.process_env_ref = registration.env_ref.clone();
225 self.process_wake_target = registration.wake_target.clone();
226 self
227 }
228
229 pub(crate) fn with_process_event_context(
230 mut self,
231 process_id: impl Into<String>,
232 registry: Arc<dyn crate::ProcessRegistry>,
233 store: Option<Arc<dyn crate::RuntimePersistence>>,
234 session_store_factory: Option<Arc<dyn crate::SessionStoreFactory>>,
235 queued_work_poke: Option<crate::QueuedWorkPoke>,
236 ) -> Self {
237 self.process_event_context = Some(RuntimeExecutionProcessEventContext {
238 process_id: process_id.into(),
239 registry,
240 store,
241 session_store_factory,
242 queued_work_poke,
243 });
244 self
245 }
246
247 pub(super) fn record_started_process(&self, process_id: &str) {
251 self.started_process_ids
252 .lock()
253 .expect("started process ids lock")
254 .insert(process_id.to_string());
255 }
256
257 pub(super) fn is_run_local_process(&self, process_id: &str) -> bool {
258 self.started_process_ids
259 .lock()
260 .expect("started process ids lock")
261 .contains(process_id)
262 }
263
264 pub(crate) fn process_spawn_provenance(&self) -> Option<crate::ProcessSpawnProvenance> {
265 self.process_originator
266 .clone()
267 .map(|originator| crate::ProcessSpawnProvenance {
268 originator,
269 wake_target: self.process_wake_target.clone(),
270 })
271 }
272
273 pub(super) async fn attach_captured_process_execution_env(
274 &self,
275 registration: crate::ProcessRegistration,
276 ) -> Result<crate::ProcessRegistration, crate::PluginError> {
277 if registration.env_ref.is_some() {
278 return Ok(registration);
279 }
280 match registration.input.as_ref() {
281 crate::ProcessInput::ToolCall { .. } | crate::ProcessInput::LashlangProcess { .. } => {
282 let env_ref = self.captured_process_execution_env_ref().await?;
283 Ok(registration.with_execution_env_ref(Some(env_ref)))
284 }
285 crate::ProcessInput::External { .. } | crate::ProcessInput::SessionTurn { .. } => {
286 Ok(registration)
287 }
288 }
289 }
290
291 async fn captured_process_execution_env_ref(
292 &self,
293 ) -> Result<crate::ProcessExecutionEnvRef, crate::PluginError> {
294 if let Some(env_ref) = self.process_env_ref.clone() {
295 return Ok(env_ref);
296 }
297 crate::persist_process_execution_env(
298 self.lashlang_artifact_store.as_ref(),
299 &self.execution_env_spec,
300 )
301 .await
302 }
303
304 pub(crate) fn with_lashlang_execution_trace(
305 mut self,
306 sink: Option<Arc<dyn lash_trace::TraceSink>>,
307 context: lash_trace::TraceContext,
308 ) -> Self {
309 self.lashlang_execution_sink = sink;
310 self.lashlang_execution_context = context;
311 self
312 }
313
314 pub(crate) fn with_turn_phase_probe(
315 mut self,
316 probe: Option<Arc<dyn crate::runtime::RuntimeTurnPhaseProbe>>,
317 ) -> Self {
318 self.turn_phase_probe = probe;
319 self
320 }
321
322 #[doc(hidden)]
323 pub fn named_phase(&self, phase: &'static str) -> crate::runtime::RuntimeNamedPhase {
324 crate::runtime::RuntimeNamedPhase::begin(self.turn_phase_probe.clone(), phase)
325 }
326
327 pub fn parent_invocation(&self) -> Option<&crate::RuntimeInvocation> {
328 self.parent_invocation.as_ref()
329 }
330
331 pub fn lashlang_execution_sink(&self) -> Option<Arc<dyn lash_trace::TraceSink>> {
332 self.lashlang_execution_sink.clone()
333 }
334
335 pub fn lashlang_execution_context(&self) -> &lash_trace::TraceContext {
336 &self.lashlang_execution_context
337 }
338
339 pub(crate) fn with_cancellation_token(mut self, cancellation_token: CancellationToken) -> Self {
340 self.cancellation_token = Some(cancellation_token);
341 self
342 }
343
344 pub(crate) fn tool_scheduling(&self, name: &str) -> crate::ToolScheduling {
345 crate::tool_dispatch::resolve_tool_scheduling(&self.dispatch, name)
346 }
347
348 pub fn callable_tool_manifest(&self, name: &str) -> Option<crate::ToolManifest> {
349 crate::tool_dispatch::resolve_callable_manifest(&self.dispatch, name)
350 }
351
352 pub fn callable_tool_manifest_by_id(&self, id: &crate::ToolId) -> Option<crate::ToolManifest> {
353 crate::tool_dispatch::resolve_callable_manifest_by_id(&self.dispatch, id)
354 }
355
356 pub fn resolve_lashlang_host_operation(
357 &self,
358 receiver: &lashlang::ResourceHandle,
359 operation: &str,
360 ) -> Result<String, String> {
361 self.lashlang_host_environment
362 .resources
363 .resolve_module_operation(&receiver.resource_type, &receiver.alias, operation)
364 .map(|binding| binding.host_operation.clone())
365 .ok_or_else(|| {
366 format!(
367 "module `{}` of type `{}` does not expose operation `{operation}`",
368 receiver.alias, receiver.resource_type
369 )
370 })
371 }
372
373 pub async fn prepare_lashlang_process_start(
374 &self,
375 start: lashlang::ProcessStart,
376 ) -> Result<(crate::ProcessRegistration, Option<String>), String> {
377 let _phase = self.named_phase("rlm_process.prepare_start");
378 let display_name = Some(start.process_name.clone());
379 let artifact = self
380 .lashlang_artifact_store
381 .get_module_artifact(&start.module_ref)
382 .await
383 .map_err(|err| format!("failed to load lashlang module artifact: {err}"))?
384 .ok_or_else(|| {
385 format!(
386 "missing lashlang module artifact `{}` for process `{}`",
387 start.module_ref, start.process_name
388 )
389 })?;
390 if artifact.host_requirements_ref != start.host_requirements_ref {
391 return Err(format!(
392 "lashlang module artifact `{}` host requirements mismatch: process requested {}, artifact has {}",
393 start.module_ref, start.host_requirements_ref, artifact.host_requirements_ref
394 ));
395 }
396 if artifact.process_ref(&start.process_name) != Some(&start.process_ref) {
397 return Err(format!(
398 "lashlang module artifact `{}` does not export process `{}` as requested ref {:?}",
399 start.module_ref, start.process_name, start.process_ref
400 ));
401 }
402 let args = match serde_json::to_value(lashlang::Value::Record(Arc::new(start.args)))
403 .map_err(|err| format!("failed to serialize process args: {err}"))?
404 {
405 serde_json::Value::Object(map) => map,
406 _ => return Err("process args must serialize as a record".to_string()),
407 };
408 let signal_event_types = artifact
409 .canonical_ir
410 .process(&start.process_name)
411 .map(crate::lashlang_process_signal_event_types)
412 .unwrap_or_default();
413 let process_id = format!("process:{}", uuid::Uuid::new_v4());
414 let registration = crate::ProcessRegistration::session_start_draft(
415 process_id,
416 crate::ProcessInput::LashlangProcess {
417 module_ref: start.module_ref,
418 process_ref: start.process_ref,
419 host_requirements_ref: start.host_requirements_ref,
420 process_name: start.process_name,
421 args,
422 },
423 )
424 .with_extra_event_types(
425 crate::lashlang_process_event_types()
426 .into_iter()
427 .chain(signal_event_types),
428 );
429 Ok((registration, display_name))
430 }
431
432 pub fn lashlang_host_environment(&self) -> &lashlang::LashlangHostEnvironment {
433 &self.lashlang_host_environment
434 }
435
436 pub fn lashlang_abilities(&self) -> lashlang::LashlangAbilities {
437 self.lashlang_abilities
438 }
439
440 pub fn lashlang_language_features(&self) -> lashlang::LashlangLanguageFeatures {
441 self.lashlang_language_features
442 }
443
444 pub fn link_lashlang_module(
445 &self,
446 program: lashlang::Program,
447 ) -> Result<lashlang::LinkedModule, String> {
448 lashlang::LinkedModule::link(program, self.lashlang_host_environment())
449 .map_err(|err| err.to_string())
450 }
451
452 pub async fn perform_lashlang_trigger_operation(
453 &self,
454 operation: &str,
455 payload: serde_json::Value,
456 ) -> Result<serde_json::Value, String> {
457 match lashlang::TriggerHostOperation::from_host_operation(operation) {
458 Some(lashlang::TriggerHostOperation::Register) => self
459 .register_trigger_subscription(payload)
460 .await
461 .map_err(|err| err.to_string()),
462 Some(lashlang::TriggerHostOperation::List) => self
463 .list_trigger_subscriptions(payload)
464 .await
465 .map_err(|err| err.to_string()),
466 Some(lashlang::TriggerHostOperation::Cancel) => self
467 .cancel_trigger_subscription(payload)
468 .await
469 .map_err(|err| err.to_string()),
470 None => Err(format!("unknown trigger operation `{operation}`")),
471 }
472 }
473
474 async fn register_trigger_subscription(
475 &self,
476 payload: serde_json::Value,
477 ) -> Result<serde_json::Value, crate::PluginError> {
478 let router = self.dispatch.trigger_router.as_ref().ok_or_else(|| {
479 crate::PluginError::Session("trigger store is unavailable in this runtime".to_string())
480 })?;
481 let request = lashlang::TriggerRegistrationRequest::decode(&payload)
482 .map_err(|err| crate::PluginError::Session(err.to_string()))?;
483 let source_type = request.source.source_type.clone();
484 let source_value = request.source.value.clone();
485 let source = request.source.to_json();
486 let validation = crate::plugin::validate_target_process(
487 &request.target,
488 &source_type,
489 &request.inputs,
490 self.lashlang_artifact_store.as_ref(),
491 )
492 .await?;
493 let store = router.store();
494 let source_key = store
495 .source_key_for_subscription(&source_type, &source_value)
496 .await?;
497 let env_ref = match self.process_env_ref.clone() {
498 Some(env_ref) => env_ref,
499 None => {
500 crate::persist_process_execution_env(
501 self.lashlang_artifact_store.as_ref(),
502 &self.execution_env_spec,
503 )
504 .await?
505 }
506 };
507 let registrant = self.process_originator.clone().unwrap_or_else(|| {
508 crate::ProcessOriginator::session(crate::SessionScope::new(self.session_id.clone()))
509 });
510 let wake_target = self
511 .process_wake_target
512 .clone()
513 .or_else(|| match ®istrant {
514 crate::ProcessOriginator::Session { scope } => Some(scope.clone()),
515 crate::ProcessOriginator::Host => None,
516 });
517 let record = store
518 .register_subscription(crate::TriggerSubscriptionDraft {
519 registrant,
520 env_ref,
521 wake_target,
522 name: request.name,
523 source_type,
524 source_key,
525 source,
526 event_ty: validation.resolved_event_type,
527 module_ref: validation.definition.module_ref,
528 host_requirements_ref: validation.definition.host_requirements_ref,
529 process_ref: validation.definition.process_ref,
530 process_name: validation.definition.process_name,
531 input_template: validation.inputs,
532 })
533 .await?;
534 Ok(crate::plugin::trigger_handle_json(&record.handle))
535 }
536
537 async fn list_trigger_subscriptions(
538 &self,
539 payload: serde_json::Value,
540 ) -> Result<serde_json::Value, crate::PluginError> {
541 let router = self.dispatch.trigger_router.as_ref().ok_or_else(|| {
542 crate::PluginError::Session("trigger store is unavailable in this runtime".to_string())
543 })?;
544 let request = lashlang::TriggerListRequest::decode(&payload)
545 .map_err(|err| crate::PluginError::Session(err.to_string()))?;
546 let mut filter = crate::TriggerSubscriptionFilter::for_session(&self.session_id);
547 filter.target = request.target;
548 filter.name = request.name;
549 filter.source_type = request.source_type;
550 filter.enabled = request.enabled;
551 let registrations = router
552 .store()
553 .list_subscriptions(filter)
554 .await?
555 .iter()
556 .map(crate::TriggerRegistration::from)
557 .collect::<Vec<_>>();
558 serde_json::to_value(registrations).map_err(|err| {
559 crate::PluginError::Session(format!("failed to encode trigger registrations: {err}"))
560 })
561 }
562
563 async fn cancel_trigger_subscription(
564 &self,
565 payload: serde_json::Value,
566 ) -> Result<serde_json::Value, crate::PluginError> {
567 let router = self.dispatch.trigger_router.as_ref().ok_or_else(|| {
568 crate::PluginError::Session("trigger store is unavailable in this runtime".to_string())
569 })?;
570 let request = lashlang::TriggerCancelRequest::decode(&payload)
571 .map_err(|err| crate::PluginError::Session(err.to_string()))?;
572 let changed = router
573 .store()
574 .cancel_subscription(&self.session_id, &request.handle)
575 .await?;
576 Ok(serde_json::json!(changed))
577 }
578
579 pub fn tool_argument_projection_policy(
580 &self,
581 name: &str,
582 ) -> crate::ToolArgumentProjectionPolicy {
583 crate::tool_dispatch::resolve_tool_argument_projection_policy(&self.dispatch, name)
584 }
585
586 pub async fn start_lashlang_process(
587 &self,
588 registration: crate::ProcessRegistration,
589 label: Option<String>,
590 ) -> crate::ToolInvocationReply {
591 let _phase = self.named_phase("rlm_process.start");
592 let registration = match self
593 .attach_captured_process_execution_env(registration)
594 .await
595 {
596 Ok(registration) => registration,
597 Err(err) => {
598 return crate::ToolInvocationReply::error(serde_json::json!(err.to_string()));
599 }
600 };
601 let process_id = registration.id.clone();
602 let mut options = crate::ProcessStartOptions::new()
603 .with_descriptor(crate::ProcessHandleDescriptor::new(Some("lashlang"), label));
604 if let Some(spawn) = self.process_spawn_provenance() {
605 options = options.with_spawn_provenance(spawn);
606 }
607 match self
608 .dispatch
609 .processes
610 .start(
611 &self.session_id,
612 registration,
613 options,
614 self.process_scope(self.parent_invocation.clone()),
615 )
616 .await
617 {
618 Ok(_) => {
619 self.record_started_process(&process_id);
620 crate::ToolInvocationReply::success(crate::lashlang_bridge::process_handle_json(
621 &process_id,
622 ))
623 }
624 Err(err) => crate::ToolInvocationReply::error(serde_json::json!(err.to_string())),
625 }
626 }
627
628 pub async fn sleep_lashlang(
629 &self,
630 scope: &str,
631 sequence: u64,
632 duration_ms: u64,
633 ) -> Result<(), crate::RuntimeEffectControllerError> {
634 let cancellation = self.cancellation_token.clone().unwrap_or_default();
635 let invocation = crate::runtime::causal::lashlang_sleep_invocation(
636 &self.session_id,
637 self.parent_invocation.as_ref(),
638 scope,
639 sequence,
640 );
641 let outcome = self
642 .dispatch
643 .effect_controller
644 .controller()
645 .execute_effect(
646 crate::RuntimeEffectEnvelope::new(
647 invocation,
648 crate::RuntimeEffectCommand::Sleep { duration_ms },
649 ),
650 crate::RuntimeEffectLocalExecutor::sleep(cancellation),
651 )
652 .await?;
653 match outcome {
654 crate::RuntimeEffectOutcome::Sleep => Ok(()),
655 other => Err(crate::RuntimeEffectControllerError::new(
656 "runtime_effect_wrong_outcome",
657 format!("expected sleep outcome, got {}", other.kind().as_str()),
658 )),
659 }
660 }
661
662 pub async fn await_process_event_lashlang(
663 &self,
664 _registry: Arc<dyn crate::ProcessRegistry>,
665 process_id: &str,
666 signal_name: &str,
667 _event_type: &str,
668 event_ordinal: u64,
669 ) -> Result<serde_json::Value, crate::RuntimeEffectControllerError> {
670 let cancellation = self.cancellation_token.clone().unwrap_or_default();
671 let key = self
672 .dispatch
673 .effect_controller
674 .controller()
675 .await_event_key(
676 &crate::ExecutionScope::process(process_id),
677 crate::AwaitEventWaitIdentity::process_signal(
678 process_id,
679 signal_name,
680 event_ordinal,
681 ),
682 )
683 .await?;
684 let invocation = crate::runtime::causal::lashlang_await_event_invocation(
685 &self.session_id,
686 self.parent_invocation.as_ref(),
687 process_id,
688 signal_name,
689 event_ordinal,
690 );
691 let outcome = self
692 .dispatch
693 .effect_controller
694 .controller()
695 .execute_effect(
696 crate::RuntimeEffectEnvelope::new(
697 invocation,
698 crate::RuntimeEffectCommand::AwaitEvent { key },
699 ),
700 crate::RuntimeEffectLocalExecutor::await_event(cancellation, None),
701 )
702 .await?;
703 match outcome.into_await_event()? {
704 crate::Resolution::Ok(value) => Ok(value),
705 crate::Resolution::Err(err) => Err(crate::RuntimeEffectControllerError::new(
706 err.code,
707 err.message,
708 )),
709 crate::Resolution::Timeout => Err(crate::RuntimeEffectControllerError::new(
710 "process_signal_wait_timeout",
711 "process signal wait timed out",
712 )),
713 crate::Resolution::Cancelled => Err(crate::RuntimeEffectControllerError::new(
714 "process_signal_wait_cancelled",
715 "process signal wait was cancelled",
716 )),
717 }
718 }
719
720 pub async fn signal_lashlang_process(
721 &self,
722 registry: Arc<dyn crate::ProcessRegistry>,
723 process_id: &str,
724 signal_name: &str,
725 signal_id: String,
726 payload: serde_json::Value,
727 ) -> Result<crate::ProcessEvent, crate::RuntimeEffectControllerError> {
728 let event_type = crate::process_signal_event_type(signal_name)?;
729 let replay_key = format!("process:{process_id}:signal.{signal_name}:{signal_id}");
730 let signal_payload = payload.clone();
731 let command = crate::ProcessCommand::Signal {
732 process_id: process_id.to_string(),
733 signal_name: signal_name.to_string(),
734 signal_id,
735 request: crate::ProcessEventAppendRequest::new(event_type.clone(), payload)
736 .with_replay_key(replay_key),
737 };
738 let effect_id = command.effect_id();
739 let invocation = crate::runtime::causal::process_effect_invocation(
740 &self.session_id,
741 self.parent_invocation.clone(),
742 &effect_id,
743 );
744 let outcome = self
745 .dispatch
746 .effect_controller
747 .controller()
748 .execute_effect(
749 crate::RuntimeEffectEnvelope::new(
750 invocation,
751 crate::RuntimeEffectCommand::process(command),
752 ),
753 crate::RuntimeEffectLocalExecutor::processes(Arc::clone(®istry)),
754 )
755 .await?;
756 match outcome.into_process()? {
757 crate::ProcessEffectOutcome::Signal { event } => {
758 let waiting_ordinal =
759 registry
760 .get_process(process_id)
761 .await
762 .and_then(|record| match record.wait {
763 Some(crate::WaitState {
764 kind:
765 crate::WaitKind::Signal {
766 name,
767 event_type: wait_event_type,
768 ordinal,
769 ..
770 },
771 ..
772 }) if name == signal_name && wait_event_type == event_type => {
773 Some(ordinal)
774 }
775 _ => None,
776 });
777 let ordinal = match waiting_ordinal {
778 Some(ordinal) => ordinal,
779 None => {
780 registry
781 .count_events_through(process_id, &event_type, event.sequence)
782 .await?
783 }
784 };
785 if ordinal > 0 {
786 let key = self
787 .dispatch
788 .effect_controller
789 .controller()
790 .await_event_key(
791 &crate::ExecutionScope::process(process_id),
792 crate::AwaitEventWaitIdentity::process_signal(
793 process_id,
794 signal_name,
795 ordinal,
796 ),
797 )
798 .await?;
799 let _ = self
800 .dispatch
801 .effect_controller
802 .controller()
803 .resolve_await_event(&key, crate::Resolution::Ok(signal_payload))
804 .await?;
805 }
806 Ok(event)
807 }
808 other => Err(crate::RuntimeEffectControllerError::new(
809 "runtime_effect_wrong_outcome",
810 format!("expected signal outcome, got {other:?}"),
811 )),
812 }
813 }
814}
815
816#[cfg(test)]
817mod tests {
818 use super::*;
819 use crate::tool_dispatch::ToolDispatchContext;
820 use crate::{ToolCall, ToolProvider, ToolResult};
821
822 struct NoopTools;
823
824 #[async_trait::async_trait]
825 impl ToolProvider for NoopTools {
826 fn tool_manifests(&self) -> Vec<crate::ToolManifest> {
827 Vec::new()
828 }
829
830 fn resolve_contract(&self, _name: &str) -> Option<Arc<crate::ToolContract>> {
831 None
832 }
833
834 async fn execute(&self, _call: ToolCall<'_>) -> ToolResult {
835 ToolResult::err_fmt("not used")
836 }
837 }
838
839 #[test]
840 fn tool_argument_projection_policy_resolves_from_active_catalog_and_defaults_unknown() {
841 let tool = crate::ToolDefinition::raw(
842 "tool:seedy",
843 "seedy",
844 "Seed-aware",
845 crate::ToolDefinition::default_input_schema(),
846 serde_json::json!({ "type": "string" }),
847 )
848 .with_argument_projection(
849 crate::ToolArgumentProjectionPolicy::preserve_projected_refs_in_field("seed"),
850 );
851 let plugins = crate::plugin::PluginHost::empty()
852 .build_session("session", None)
853 .expect("plugin session");
854 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
855 let dispatch = Arc::new(ToolDispatchContext {
856 plugins,
857 tools: Arc::new(NoopTools),
858 tool_catalog: Arc::new(crate::ToolCatalog::from_tools(
859 vec![tool.manifest()],
860 std::collections::BTreeMap::new(),
861 )),
862 sessions: Arc::new(crate::testing::MockSessionManager::default()),
863 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
864 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
865 processes: Arc::new(crate::UnavailableProcessService),
866 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
867 trigger_router: None,
868 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
869 crate::InlineRuntimeEffectController,
870 )),
871 direct_completions: crate::DirectCompletionClient::unavailable(
872 "direct completions are unavailable in this test context",
873 ),
874 parent_invocation: None,
875 execution_env_spec: crate::ProcessExecutionEnvSpec::new(
876 crate::PluginOptions::default(),
877 crate::SessionPolicy::default(),
878 ),
879 session_id: "session".to_string(),
880 agent_frame_id: String::new(),
881 event_tx,
882 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
883 trigger_outcomes: crate::tool_dispatch::ToolTriggerOutcomeBuffer::default(),
884 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
885 turn_context: crate::TurnContext::default(),
886 });
887 let ctx = RuntimeExecutionContext::new(
888 "session".to_string(),
889 dispatch,
890 Default::default(),
891 Default::default(),
892 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
893 Arc::new(crate::InMemoryAttachmentStore::new()),
894 Arc::new(crate::ChronologicalProjection::default()),
895 None,
896 crate::TurnContext::default(),
897 );
898
899 assert_eq!(
900 ctx.tool_argument_projection_policy("seedy"),
901 crate::ToolArgumentProjectionPolicy::preserve_projected_refs_in_field("seed")
902 );
903 assert_eq!(
904 ctx.tool_argument_projection_policy("missing"),
905 crate::ToolArgumentProjectionPolicy::MaterializeProjectedValues
906 );
907 }
908
909 #[tokio::test]
910 async fn prepare_lashlang_process_start_captures_tool_ids_and_explicit_input() {
911 let tool = crate::ToolDefinition::raw(
912 "tool:alpha",
913 "alpha",
914 "Alpha tool.",
915 crate::ToolDefinition::default_input_schema(),
916 serde_json::json!({ "type": "object", "additionalProperties": true }),
917 );
918 let plugins = crate::plugin::PluginHost::empty()
919 .build_session("session", None)
920 .expect("plugin session");
921 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
922 let dispatch = Arc::new(ToolDispatchContext {
923 plugins,
924 tools: Arc::new(NoopTools),
925 tool_catalog: Arc::new(crate::ToolCatalog::from_tools(
926 vec![tool.manifest()],
927 std::collections::BTreeMap::new(),
928 )),
929 sessions: Arc::new(crate::testing::MockSessionManager::default()),
930 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
931 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
932 processes: Arc::new(crate::UnavailableProcessService),
933 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
934 trigger_router: None,
935 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
936 crate::InlineRuntimeEffectController,
937 )),
938 direct_completions: crate::DirectCompletionClient::unavailable(
939 "direct completions are unavailable in this test context",
940 ),
941 parent_invocation: None,
942 execution_env_spec: crate::ProcessExecutionEnvSpec::new(
943 crate::PluginOptions::default(),
944 crate::SessionPolicy::default(),
945 ),
946 session_id: "session".to_string(),
947 agent_frame_id: String::new(),
948 event_tx,
949 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
950 trigger_outcomes: crate::tool_dispatch::ToolTriggerOutcomeBuffer::default(),
951 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
952 turn_context: crate::TurnContext::default(),
953 });
954 let ctx = RuntimeExecutionContext::new(
955 "session".to_string(),
956 dispatch,
957 lashlang::LashlangAbilities::default().with_processes(),
958 Default::default(),
959 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
960 Arc::new(crate::InMemoryAttachmentStore::new()),
961 Arc::new(crate::ChronologicalProjection::default()),
962 None,
963 crate::TurnContext::default(),
964 );
965 let mut input = lashlang::Record::new();
966 input.insert("root".to_string(), lashlang::Value::String(".".into()));
967 let linked = ctx
968 .link_lashlang_module(
969 lashlang::parse("process scan(root: str) { finish root }").expect("process module"),
970 )
971 .expect("link process module");
972 ctx.put_lashlang_module_artifact(&linked.artifact)
973 .await
974 .expect("store module artifact");
975 let process_ref = linked
976 .artifact
977 .process_ref("scan")
978 .expect("scan process ref")
979 .clone();
980 let (registration, label) = ctx
981 .prepare_lashlang_process_start(lashlang::ProcessStart {
982 module_ref: linked.module_ref.clone(),
983 process_ref,
984 host_requirements_ref: linked.host_requirements_ref.clone(),
985 process_name: "scan".to_string(),
986 args: input,
987 })
988 .await
989 .expect("process start should prepare");
990
991 assert_eq!(label.as_deref(), Some("scan"));
992 assert!(
993 registration
994 .event_types
995 .iter()
996 .any(|event_type| event_type.name == "process.wake")
997 );
998 let crate::ProcessInput::LashlangProcess {
999 args, process_name, ..
1000 } = registration.input.as_ref()
1001 else {
1002 panic!("expected lashlang process input");
1003 };
1004 assert_eq!(process_name, "scan");
1005 assert_eq!(args.get("root"), Some(&serde_json::json!(".")));
1006 }
1007
1008 #[test]
1009 fn lashlang_host_environment_reflects_host_abilities() {
1010 let tool = crate::ToolDefinition::raw(
1011 "tool:alpha",
1012 "alpha",
1013 "Alpha tool.",
1014 crate::ToolDefinition::default_input_schema(),
1015 serde_json::json!({ "type": "object", "additionalProperties": true }),
1016 );
1017 let plugins = crate::plugin::PluginHost::empty()
1018 .build_session("session", None)
1019 .expect("plugin session");
1020 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
1021 let dispatch = Arc::new(ToolDispatchContext {
1022 plugins,
1023 tools: Arc::new(NoopTools),
1024 tool_catalog: Arc::new(crate::ToolCatalog::from_tools(
1025 vec![tool.manifest()],
1026 std::collections::BTreeMap::new(),
1027 )),
1028 sessions: Arc::new(crate::testing::MockSessionManager::default()),
1029 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
1030 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
1031 processes: Arc::new(crate::UnavailableProcessService),
1032 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
1033 trigger_router: None,
1034 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
1035 crate::InlineRuntimeEffectController,
1036 )),
1037 direct_completions: crate::DirectCompletionClient::unavailable(
1038 "direct completions are unavailable in this test context",
1039 ),
1040 parent_invocation: None,
1041 execution_env_spec: crate::ProcessExecutionEnvSpec::new(
1042 crate::PluginOptions::default(),
1043 crate::SessionPolicy::default(),
1044 ),
1045 session_id: "session".to_string(),
1046 agent_frame_id: String::new(),
1047 event_tx,
1048 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
1049 trigger_outcomes: crate::tool_dispatch::ToolTriggerOutcomeBuffer::default(),
1050 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
1051 turn_context: crate::TurnContext::default(),
1052 });
1053 let ctx = RuntimeExecutionContext::new(
1054 "session".to_string(),
1055 dispatch,
1056 lashlang::LashlangAbilities::default()
1057 .with_sleep()
1058 .with_processes()
1059 .with_process_signals(),
1060 Default::default(),
1061 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
1062 Arc::new(crate::InMemoryAttachmentStore::new()),
1063 Arc::new(crate::ChronologicalProjection::default()),
1064 None,
1065 crate::TurnContext::default(),
1066 );
1067
1068 let environment = ctx.lashlang_host_environment();
1069
1070 assert!(std::ptr::eq(environment, ctx.lashlang_host_environment()));
1071 assert!(environment.abilities.processes);
1072 assert!(environment.abilities.sleep);
1073 assert!(environment.abilities.process_signals);
1074 assert!(!environment.abilities.triggers);
1075 assert!(
1076 environment
1077 .resources
1078 .resolve_operation("Tools", "alpha")
1079 .is_some()
1080 );
1081 }
1082
1083 #[test]
1084 fn lashlang_host_environment_reflects_host_resource_contributions() {
1085 let mut resources = lashlang::LashlangHostCatalog::new();
1086 resources
1087 .add_trigger_source_constructor(
1088 ["clock", "Alarm"],
1089 lashlang::TypeExpr::Object(vec![lashlang::TypeField {
1090 name: "at".into(),
1091 ty: lashlang::TypeExpr::Str,
1092 optional: false,
1093 }]),
1094 lashlang::NamedDataType::object(
1095 "clock.Tick",
1096 vec![lashlang::TypeField {
1097 name: "fired_at".into(),
1098 ty: lashlang::TypeExpr::Str,
1099 optional: false,
1100 }],
1101 )
1102 .expect("valid clock tick type"),
1103 )
1104 .expect("valid clock trigger source");
1105 let plugin_host = crate::plugin::PluginHost::empty();
1106 let mut merged_resources = plugin_host.lashlang_resources();
1107 merged_resources.extend(resources);
1108 let plugins = plugin_host
1109 .with_lashlang_resources(merged_resources)
1110 .build_session("session", None)
1111 .expect("plugin session");
1112 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
1113 let dispatch = Arc::new(ToolDispatchContext {
1114 plugins,
1115 tools: Arc::new(NoopTools),
1116 tool_catalog: Arc::new(crate::ToolCatalog::from_tools(
1117 Vec::new(),
1118 std::collections::BTreeMap::new(),
1119 )),
1120 sessions: Arc::new(crate::testing::MockSessionManager::default()),
1121 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
1122 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
1123 processes: Arc::new(crate::UnavailableProcessService),
1124 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
1125 trigger_router: None,
1126 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
1127 crate::InlineRuntimeEffectController,
1128 )),
1129 direct_completions: crate::DirectCompletionClient::unavailable(
1130 "direct completions are unavailable in this test context",
1131 ),
1132 parent_invocation: None,
1133 execution_env_spec: crate::ProcessExecutionEnvSpec::new(
1134 crate::PluginOptions::default(),
1135 crate::SessionPolicy::default(),
1136 ),
1137 session_id: "session".to_string(),
1138 agent_frame_id: String::new(),
1139 event_tx,
1140 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
1141 trigger_outcomes: crate::tool_dispatch::ToolTriggerOutcomeBuffer::default(),
1142 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
1143 turn_context: crate::TurnContext::default(),
1144 });
1145 let ctx = RuntimeExecutionContext::new(
1146 "session".to_string(),
1147 dispatch,
1148 lashlang::LashlangAbilities::default()
1149 .with_processes()
1150 .with_triggers(),
1151 Default::default(),
1152 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
1153 Arc::new(crate::InMemoryAttachmentStore::new()),
1154 Arc::new(crate::ChronologicalProjection::default()),
1155 None,
1156 crate::TurnContext::default(),
1157 );
1158
1159 let host_environment = ctx.lashlang_host_environment();
1160
1161 assert!(
1162 host_environment
1163 .resources
1164 .resolve_value_constructor(&["clock", "Alarm"])
1165 .is_some()
1166 );
1167 assert!(
1168 host_environment
1169 .resources
1170 .resolve_trigger_source("clock.Alarm")
1171 .is_some()
1172 );
1173 lashlang::LinkedModule::link(
1174 lashlang::parse(
1175 r#"
1176 process remember(tick: clock.Tick) {
1177 finish true
1178 }
1179
1180 source = clock.Alarm({ at: "08:00" })
1181 await triggers.register({
1182 source: source,
1183 target: remember,
1184 inputs: { tick: trigger.event }
1185 })?
1186 "#,
1187 )
1188 .expect("parse trigger registry module"),
1189 host_environment,
1190 )
1191 .expect("host resource contribution should be linkable");
1192 }
1193}