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_surface_from_tool_surface(
10 surface: &crate::ToolSurface,
11 abilities: lashlang::LashlangAbilities,
12 language_features: lashlang::LashlangLanguageFeatures,
13 host_resources: lashlang::ResourceCatalog,
14) -> lashlang::LashlangSurface {
15 let mut resources = lashlang_resources_from_tool_surface(surface);
16 resources.extend(host_resources);
17 lashlang::LashlangSurface::new(resources, abilities).with_language_features(language_features)
18}
19
20pub(crate) fn lashlang_resources_from_tool_surface(
21 surface: &crate::ToolSurface,
22) -> lashlang::ResourceCatalog {
23 let mut catalog = lashlang::ResourceCatalog::new();
24 for entry in surface.tools.iter() {
25 if entry.availability.is_callable() {
26 let agent_surface = entry
27 .manifest
28 .agent_surface
29 .executable_for(&entry.manifest.name);
30 catalog.add_module_operation(
31 agent_surface.module_path.iter().map(String::as_str),
32 agent_surface.authority_type.clone(),
33 agent_surface.operation.clone(),
34 entry.manifest.name.clone(),
35 lashlang::TypeExpr::Any,
36 lashlang::TypeExpr::Any,
37 );
38 }
39 }
40 catalog
41}
42
43#[derive(Clone)]
44pub struct RuntimeExecutionContext<'run> {
45 pub(super) session_id: String,
46 pub(super) dispatch: Arc<ToolDispatchContext<'run>>,
47 lashlang_abilities: lashlang::LashlangAbilities,
48 lashlang_language_features: lashlang::LashlangLanguageFeatures,
49 lashlang_surface: lashlang::LashlangSurface,
50 lashlang_artifact_store: Arc<dyn lashlang::LashlangArtifactStore>,
51 attachment_store: Arc<dyn crate::AttachmentStore>,
52 chronological_projection: Arc<crate::ChronologicalProjection>,
53 protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
54 turn_context: crate::TurnContext,
55 pub(super) parent_invocation: Option<crate::RuntimeInvocation>,
56 lashlang_execution_sink: Option<Arc<dyn lash_trace::TraceSink>>,
57 lashlang_execution_context: lash_trace::TraceContext,
58 pub(super) turn_event_tx: Option<Sender<TurnActivity>>,
59 pub(super) cancellation_token: Option<CancellationToken>,
60}
61
62impl<'run> RuntimeExecutionContext<'run> {
63 pub(crate) fn drain_tool_host_event_outcomes(
64 &self,
65 ) -> Result<Vec<crate::tool_dispatch::ToolHostEventEffectOutcome>, crate::PluginError> {
66 self.dispatch
67 .host_event_outcomes
68 .drain()
69 .map_err(crate::PluginError::Session)
70 }
71
72 pub(super) fn process_scope(
73 &self,
74 parent_invocation: Option<crate::RuntimeInvocation>,
75 ) -> crate::ProcessOpScope<'_> {
76 crate::ProcessOpScope::new(self.dispatch.effect_controller.scoped())
77 .with_parent_invocation(parent_invocation)
78 .with_agent_frame_id(Some(self.dispatch.agent_frame_id.clone()))
79 }
80
81 #[allow(
82 clippy::too_many_arguments,
83 reason = "code execution bridge carries explicit per-turn runtime dependencies"
84 )]
85 pub(crate) fn new(
86 session_id: String,
87 dispatch: Arc<ToolDispatchContext<'run>>,
88 lashlang_abilities: lashlang::LashlangAbilities,
89 lashlang_language_features: lashlang::LashlangLanguageFeatures,
90 lashlang_artifact_store: Arc<dyn lashlang::LashlangArtifactStore>,
91 attachment_store: Arc<dyn crate::AttachmentStore>,
92 chronological_projection: Arc<crate::ChronologicalProjection>,
93 protocol_extension: Option<crate::ProtocolTurnExtensionHandle>,
94 turn_context: crate::TurnContext,
95 ) -> Self {
96 let lashlang_surface = lashlang_surface_from_tool_surface(
97 &dispatch.surface,
98 lashlang_abilities,
99 lashlang_language_features,
100 dispatch.plugins.lashlang_resources(),
101 );
102 Self {
103 session_id,
104 dispatch,
105 lashlang_abilities,
106 lashlang_language_features,
107 lashlang_surface,
108 lashlang_artifact_store,
109 attachment_store,
110 chronological_projection,
111 protocol_extension,
112 turn_context,
113 parent_invocation: None,
114 lashlang_execution_sink: None,
115 lashlang_execution_context: lash_trace::TraceContext::default(),
116 turn_event_tx: None,
117 cancellation_token: None,
118 }
119 }
120
121 pub fn session_id(&self) -> &str {
122 &self.session_id
123 }
124
125 pub fn attachment_store(&self) -> Arc<dyn crate::AttachmentStore> {
126 Arc::clone(&self.attachment_store)
127 }
128
129 pub async fn put_lashlang_module_artifact(
130 &self,
131 artifact: &lashlang::ModuleArtifact,
132 ) -> Result<(), String> {
133 self.lashlang_artifact_store
134 .put_module_artifact(artifact)
135 .await
136 .map_err(|err| err.to_string())
137 }
138
139 pub fn chronological_projection(&self) -> Arc<crate::ChronologicalProjection> {
140 Arc::clone(&self.chronological_projection)
141 }
142
143 pub fn protocol_extension<T: 'static>(&self) -> Option<&T> {
144 self.protocol_extension
145 .as_ref()
146 .and_then(|extension| extension.as_any().downcast_ref::<T>())
147 }
148
149 pub fn turn_context(&self) -> &crate::TurnContext {
150 &self.turn_context
151 }
152
153 pub(crate) fn session_graph_service(&self) -> &dyn crate::plugin::SessionGraphService {
154 self.dispatch.session_graph.as_ref()
155 }
156
157 pub(super) async fn emit_turn_activity(
158 &self,
159 correlation_id: TurnActivityId,
160 event: TurnEvent,
161 ) {
162 if let Some(tx) = &self.turn_event_tx {
163 let _ = tx.send(TurnActivity::new(correlation_id, event)).await;
164 }
165 }
166
167 pub(crate) fn with_turn_event_sender(mut self, turn_event_tx: Sender<TurnActivity>) -> Self {
168 self.turn_event_tx = Some(turn_event_tx);
169 self
170 }
171
172 pub(crate) fn with_parent_invocation(mut self, metadata: crate::RuntimeInvocation) -> Self {
173 self.parent_invocation = Some(metadata);
174 self
175 }
176
177 pub(crate) fn with_lashlang_execution_trace(
178 mut self,
179 sink: Option<Arc<dyn lash_trace::TraceSink>>,
180 context: lash_trace::TraceContext,
181 ) -> Self {
182 self.lashlang_execution_sink = sink;
183 self.lashlang_execution_context = context;
184 self
185 }
186
187 pub fn parent_invocation(&self) -> Option<&crate::RuntimeInvocation> {
188 self.parent_invocation.as_ref()
189 }
190
191 pub fn lashlang_execution_sink(&self) -> Option<Arc<dyn lash_trace::TraceSink>> {
192 self.lashlang_execution_sink.clone()
193 }
194
195 pub fn lashlang_execution_context(&self) -> &lash_trace::TraceContext {
196 &self.lashlang_execution_context
197 }
198
199 pub(crate) fn with_cancellation_token(mut self, cancellation_token: CancellationToken) -> Self {
200 self.cancellation_token = Some(cancellation_token);
201 self
202 }
203
204 pub(crate) fn tool_scheduling(&self, name: &str) -> crate::ToolScheduling {
205 crate::tool_dispatch::resolve_tool_scheduling(&self.dispatch, name)
206 }
207
208 pub fn callable_tool_manifest(&self, name: &str) -> Option<crate::ToolManifest> {
209 crate::tool_dispatch::resolve_callable_manifest(&self.dispatch, name)
210 }
211
212 pub fn callable_tool_manifest_by_id(&self, id: &crate::ToolId) -> Option<crate::ToolManifest> {
213 crate::tool_dispatch::resolve_callable_manifest_by_id(&self.dispatch, id)
214 }
215
216 pub fn resolve_lashlang_host_operation(
217 &self,
218 receiver: &lashlang::ResourceHandle,
219 operation: &str,
220 ) -> Result<String, String> {
221 self.lashlang_surface
222 .resources
223 .resolve_module_operation(&receiver.resource_type, &receiver.alias, operation)
224 .map(|binding| binding.host_operation.clone())
225 .ok_or_else(|| {
226 format!(
227 "module `{}` of type `{}` does not expose operation `{operation}`",
228 receiver.alias, receiver.resource_type
229 )
230 })
231 }
232
233 pub async fn prepare_lashlang_process_start(
234 &self,
235 start: lashlang::ProcessStart,
236 ) -> Result<(crate::ProcessRegistration, Option<String>), String> {
237 let display_name = Some(start.process_name.clone());
238 let artifact = self
239 .lashlang_artifact_store
240 .get_module_artifact(&start.module_ref)
241 .await
242 .map_err(|err| format!("failed to load lashlang module artifact: {err}"))?
243 .ok_or_else(|| {
244 format!(
245 "missing lashlang module artifact `{}` for process `{}`",
246 start.module_ref, start.process_name
247 )
248 })?;
249 if artifact.required_surface_ref != start.required_surface_ref {
250 return Err(format!(
251 "lashlang module artifact `{}` required surface mismatch: process requested {}, artifact has {}",
252 start.module_ref, start.required_surface_ref, artifact.required_surface_ref
253 ));
254 }
255 if artifact.process_ref(&start.process_name) != Some(&start.process_ref) {
256 return Err(format!(
257 "lashlang module artifact `{}` does not export process `{}` as requested ref {:?}",
258 start.module_ref, start.process_name, start.process_ref
259 ));
260 }
261 let args = match serde_json::to_value(lashlang::Value::Record(Arc::new(start.args)))
262 .map_err(|err| format!("failed to serialize process args: {err}"))?
263 {
264 serde_json::Value::Object(map) => map,
265 _ => return Err("process args must serialize as a record".to_string()),
266 };
267 let process_id = format!("process:{}", uuid::Uuid::new_v4());
268 let registration = crate::ProcessRegistration::new(
269 process_id,
270 crate::ProcessInput::LashlangProcess {
271 module_ref: start.module_ref,
272 process_ref: start.process_ref,
273 required_surface_ref: start.required_surface_ref,
274 process_name: start.process_name,
275 args,
276 },
277 )
278 .with_extra_event_types(crate::lashlang_process_event_types());
279 Ok((registration, display_name))
280 }
281
282 pub fn lashlang_surface(&self) -> &lashlang::LashlangSurface {
283 &self.lashlang_surface
284 }
285
286 pub fn lashlang_abilities(&self) -> lashlang::LashlangAbilities {
287 self.lashlang_abilities
288 }
289
290 pub fn lashlang_language_features(&self) -> lashlang::LashlangLanguageFeatures {
291 self.lashlang_language_features
292 }
293
294 pub fn link_lashlang_module(
295 &self,
296 program: lashlang::Program,
297 ) -> Result<lashlang::LinkedModule, String> {
298 lashlang::LinkedModule::link(program, self.lashlang_surface())
299 .map_err(|err| err.to_string())
300 }
301
302 pub async fn perform_lashlang_trigger_operation(
303 &self,
304 operation: &str,
305 payload: serde_json::Value,
306 ) -> Result<serde_json::Value, String> {
307 match lashlang::TriggerHostOperation::from_host_operation(operation) {
308 Some(lashlang::TriggerHostOperation::Register) => self
309 .dispatch
310 .plugins
311 .register_lashlang_trigger(payload, Arc::clone(&self.lashlang_artifact_store))
312 .await
313 .map_err(|err| err.to_string()),
314 Some(lashlang::TriggerHostOperation::List) => self
315 .dispatch
316 .plugins
317 .list_lashlang_triggers(payload)
318 .map_err(|err| err.to_string()),
319 Some(lashlang::TriggerHostOperation::Cancel) => self
320 .dispatch
321 .plugins
322 .cancel_lashlang_trigger(payload)
323 .map_err(|err| err.to_string()),
324 None => Err(format!("unknown trigger operation `{operation}`")),
325 }
326 }
327
328 pub fn tool_argument_projection_policy(
329 &self,
330 name: &str,
331 ) -> crate::ToolArgumentProjectionPolicy {
332 crate::tool_dispatch::resolve_tool_argument_projection_policy(&self.dispatch, name)
333 }
334
335 pub async fn start_lashlang_process(
336 &self,
337 registration: crate::ProcessRegistration,
338 label: Option<String>,
339 ) -> crate::ToolInvocationReply {
340 let process_id = registration.id.clone();
341 match self
342 .dispatch
343 .processes
344 .start(
345 &self.session_id,
346 registration,
347 crate::ProcessStartOptions::new()
348 .with_descriptor(crate::ProcessHandleDescriptor::new(Some("lashlang"), label)),
349 self.process_scope(self.parent_invocation.clone()),
350 )
351 .await
352 {
353 Ok(_) => crate::ToolInvocationReply::success(
354 crate::lashlang_bridge::process_handle_json(&process_id),
355 ),
356 Err(err) => crate::ToolInvocationReply::error(serde_json::json!(err.to_string())),
357 }
358 }
359
360 pub async fn sleep_lashlang(
361 &self,
362 scope: &str,
363 sequence: u64,
364 duration_ms: u64,
365 ) -> Result<(), crate::RuntimeEffectControllerError> {
366 let cancellation = self.cancellation_token.clone().unwrap_or_default();
367 let invocation = crate::runtime::causal::lashlang_sleep_invocation(
368 &self.session_id,
369 self.parent_invocation.as_ref(),
370 scope,
371 sequence,
372 );
373 let outcome = self
374 .dispatch
375 .effect_controller
376 .controller()
377 .execute_effect(
378 crate::RuntimeEffectEnvelope::new(
379 invocation,
380 crate::RuntimeEffectCommand::Sleep { duration_ms },
381 ),
382 crate::RuntimeEffectLocalExecutor::sleep(cancellation),
383 )
384 .await?;
385 match outcome {
386 crate::RuntimeEffectOutcome::Sleep => Ok(()),
387 other => Err(crate::RuntimeEffectControllerError::new(
388 "runtime_effect_wrong_outcome",
389 format!("expected sleep outcome, got {}", other.kind().as_str()),
390 )),
391 }
392 }
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398 use crate::tool_dispatch::ToolDispatchContext;
399 use crate::{ToolCall, ToolProvider, ToolResult};
400
401 struct NoopTools;
402
403 #[async_trait::async_trait]
404 impl ToolProvider for NoopTools {
405 fn tool_manifests(&self) -> Vec<crate::ToolManifest> {
406 Vec::new()
407 }
408
409 fn resolve_contract(&self, _name: &str) -> Option<Arc<crate::ToolContract>> {
410 None
411 }
412
413 async fn execute(&self, _call: ToolCall<'_>) -> ToolResult {
414 ToolResult::err_fmt("not used")
415 }
416 }
417
418 #[test]
419 fn tool_argument_projection_policy_resolves_from_active_surface_and_defaults_unknown() {
420 let tool = crate::ToolDefinition::raw(
421 "tool:seedy",
422 "seedy",
423 "Seed-aware",
424 crate::ToolDefinition::default_input_schema(),
425 serde_json::json!({ "type": "string" }),
426 )
427 .with_argument_projection(
428 crate::ToolArgumentProjectionPolicy::preserve_projected_refs_in_field("seed"),
429 );
430 let plugins = crate::plugin::PluginHost::empty()
431 .build_session("session", None)
432 .expect("plugin session");
433 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
434 let dispatch = Arc::new(ToolDispatchContext {
435 plugins,
436 tools: Arc::new(NoopTools),
437 surface: Arc::new(crate::ToolSurface::from_tools(
438 vec![tool.manifest()],
439 std::collections::BTreeMap::new(),
440 )),
441 sessions: Arc::new(crate::testing::MockSessionManager::default()),
442 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
443 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
444 processes: Arc::new(crate::UnavailableProcessService),
445 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
446 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
447 crate::InlineRuntimeEffectController,
448 )),
449 direct_completions: crate::DirectCompletionClient::unavailable(
450 "direct completions are unavailable in this test context",
451 ),
452 parent_invocation: None,
453 session_id: "session".to_string(),
454 agent_frame_id: String::new(),
455 event_tx,
456 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
457 host_event_outcomes: crate::tool_dispatch::ToolHostEventOutcomeBuffer::default(),
458 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
459 turn_context: crate::TurnContext::default(),
460 });
461 let ctx = RuntimeExecutionContext::new(
462 "session".to_string(),
463 dispatch,
464 Default::default(),
465 Default::default(),
466 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
467 Arc::new(crate::InMemoryAttachmentStore::new()),
468 Arc::new(crate::ChronologicalProjection::default()),
469 None,
470 crate::TurnContext::default(),
471 );
472
473 assert_eq!(
474 ctx.tool_argument_projection_policy("seedy"),
475 crate::ToolArgumentProjectionPolicy::preserve_projected_refs_in_field("seed")
476 );
477 assert_eq!(
478 ctx.tool_argument_projection_policy("missing"),
479 crate::ToolArgumentProjectionPolicy::MaterializeProjectedValues
480 );
481 }
482
483 #[tokio::test]
484 async fn prepare_lashlang_process_start_captures_tool_ids_and_explicit_input() {
485 let tool = crate::ToolDefinition::raw(
486 "tool:alpha",
487 "alpha",
488 "Alpha tool.",
489 crate::ToolDefinition::default_input_schema(),
490 serde_json::json!({ "type": "object", "additionalProperties": true }),
491 );
492 let plugins = crate::plugin::PluginHost::empty()
493 .build_session("session", None)
494 .expect("plugin session");
495 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
496 let dispatch = Arc::new(ToolDispatchContext {
497 plugins,
498 tools: Arc::new(NoopTools),
499 surface: Arc::new(crate::ToolSurface::from_tools(
500 vec![tool.manifest()],
501 std::collections::BTreeMap::new(),
502 )),
503 sessions: Arc::new(crate::testing::MockSessionManager::default()),
504 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
505 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
506 processes: Arc::new(crate::UnavailableProcessService),
507 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
508 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
509 crate::InlineRuntimeEffectController,
510 )),
511 direct_completions: crate::DirectCompletionClient::unavailable(
512 "direct completions are unavailable in this test context",
513 ),
514 parent_invocation: None,
515 session_id: "session".to_string(),
516 agent_frame_id: String::new(),
517 event_tx,
518 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
519 host_event_outcomes: crate::tool_dispatch::ToolHostEventOutcomeBuffer::default(),
520 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
521 turn_context: crate::TurnContext::default(),
522 });
523 let ctx = RuntimeExecutionContext::new(
524 "session".to_string(),
525 dispatch,
526 lashlang::LashlangAbilities::default().with_processes(),
527 Default::default(),
528 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
529 Arc::new(crate::InMemoryAttachmentStore::new()),
530 Arc::new(crate::ChronologicalProjection::default()),
531 None,
532 crate::TurnContext::default(),
533 );
534 let mut input = lashlang::Record::new();
535 input.insert("root".to_string(), lashlang::Value::String(".".into()));
536 let linked = ctx
537 .link_lashlang_module(
538 lashlang::parse("process scan(root: str) { finish root }").expect("process module"),
539 )
540 .expect("link process module");
541 ctx.put_lashlang_module_artifact(&linked.artifact)
542 .await
543 .expect("store module artifact");
544 let process_ref = linked
545 .artifact
546 .process_ref("scan")
547 .expect("scan process ref")
548 .clone();
549 let (registration, label) = ctx
550 .prepare_lashlang_process_start(lashlang::ProcessStart {
551 module_ref: linked.module_ref.clone(),
552 process_ref,
553 required_surface_ref: linked.required_surface_ref.clone(),
554 process_name: "scan".to_string(),
555 args: input,
556 })
557 .await
558 .expect("process start should prepare");
559
560 assert_eq!(label.as_deref(), Some("scan"));
561 assert!(
562 registration
563 .event_types
564 .iter()
565 .any(|event_type| event_type.name == "process.wake")
566 );
567 let crate::ProcessInput::LashlangProcess {
568 args, process_name, ..
569 } = registration.input.as_ref()
570 else {
571 panic!("expected lashlang process input");
572 };
573 assert_eq!(process_name, "scan");
574 assert_eq!(args.get("root"), Some(&serde_json::json!(".")));
575 }
576
577 #[test]
578 fn lashlang_surface_reflects_host_abilities() {
579 let tool = crate::ToolDefinition::raw(
580 "tool:alpha",
581 "alpha",
582 "Alpha tool.",
583 crate::ToolDefinition::default_input_schema(),
584 serde_json::json!({ "type": "object", "additionalProperties": true }),
585 );
586 let plugins = crate::plugin::PluginHost::empty()
587 .build_session("session", None)
588 .expect("plugin session");
589 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
590 let dispatch = Arc::new(ToolDispatchContext {
591 plugins,
592 tools: Arc::new(NoopTools),
593 surface: Arc::new(crate::ToolSurface::from_tools(
594 vec![tool.manifest()],
595 std::collections::BTreeMap::new(),
596 )),
597 sessions: Arc::new(crate::testing::MockSessionManager::default()),
598 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
599 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
600 processes: Arc::new(crate::UnavailableProcessService),
601 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
602 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
603 crate::InlineRuntimeEffectController,
604 )),
605 direct_completions: crate::DirectCompletionClient::unavailable(
606 "direct completions are unavailable in this test context",
607 ),
608 parent_invocation: None,
609 session_id: "session".to_string(),
610 agent_frame_id: String::new(),
611 event_tx,
612 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
613 host_event_outcomes: crate::tool_dispatch::ToolHostEventOutcomeBuffer::default(),
614 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
615 turn_context: crate::TurnContext::default(),
616 });
617 let ctx = RuntimeExecutionContext::new(
618 "session".to_string(),
619 dispatch,
620 lashlang::LashlangAbilities::default()
621 .with_sleep()
622 .with_processes()
623 .with_process_signals(),
624 Default::default(),
625 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
626 Arc::new(crate::InMemoryAttachmentStore::new()),
627 Arc::new(crate::ChronologicalProjection::default()),
628 None,
629 crate::TurnContext::default(),
630 );
631
632 let surface = ctx.lashlang_surface();
633
634 assert!(std::ptr::eq(surface, ctx.lashlang_surface()));
635 assert!(surface.abilities.processes);
636 assert!(surface.abilities.sleep);
637 assert!(surface.abilities.process_signals);
638 assert!(!surface.abilities.triggers);
639 assert!(
640 surface
641 .resources
642 .resolve_operation("Tools", "alpha")
643 .is_some()
644 );
645 }
646
647 #[test]
648 fn lashlang_surface_reflects_host_resource_contributions() {
649 let mut resources = lashlang::ResourceCatalog::new();
650 resources
651 .add_trigger_source_constructor(
652 ["clock", "Alarm"],
653 lashlang::TypeExpr::Object(vec![lashlang::TypeField {
654 name: "at".into(),
655 ty: lashlang::TypeExpr::Str,
656 optional: false,
657 }]),
658 lashlang::NamedDataType::object(
659 "clock.Tick",
660 vec![lashlang::TypeField {
661 name: "fired_at".into(),
662 ty: lashlang::TypeExpr::Str,
663 optional: false,
664 }],
665 )
666 .expect("valid clock tick type"),
667 )
668 .expect("valid clock trigger source");
669 let plugin_host = crate::plugin::PluginHost::empty();
670 let mut merged_resources = plugin_host.lashlang_resources();
671 merged_resources.extend(resources);
672 let plugins = plugin_host
673 .with_lashlang_resources(merged_resources)
674 .build_session("session", None)
675 .expect("plugin session");
676 let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
677 let dispatch = Arc::new(ToolDispatchContext {
678 plugins,
679 tools: Arc::new(NoopTools),
680 surface: Arc::new(crate::ToolSurface::from_tools(
681 Vec::new(),
682 std::collections::BTreeMap::new(),
683 )),
684 sessions: Arc::new(crate::testing::MockSessionManager::default()),
685 session_lifecycle: Arc::new(crate::testing::MockSessionManager::default()),
686 session_graph: Arc::new(crate::testing::MockSessionManager::default()),
687 processes: Arc::new(crate::UnavailableProcessService),
688 process_cancel_ability: Arc::new(crate::DefaultProcessCancelAbility),
689 effect_controller: crate::runtime::RuntimeEffectControllerHandle::shared(Arc::new(
690 crate::InlineRuntimeEffectController,
691 )),
692 direct_completions: crate::DirectCompletionClient::unavailable(
693 "direct completions are unavailable in this test context",
694 ),
695 parent_invocation: None,
696 session_id: "session".to_string(),
697 agent_frame_id: String::new(),
698 event_tx,
699 checkpoint_messages: crate::tool_dispatch::CheckpointMessageBuffer::default(),
700 host_event_outcomes: crate::tool_dispatch::ToolHostEventOutcomeBuffer::default(),
701 attachment_store: Arc::new(crate::InMemoryAttachmentStore::new()),
702 turn_context: crate::TurnContext::default(),
703 });
704 let ctx = RuntimeExecutionContext::new(
705 "session".to_string(),
706 dispatch,
707 lashlang::LashlangAbilities::default()
708 .with_processes()
709 .with_triggers(),
710 Default::default(),
711 Arc::new(lashlang::InMemoryLashlangArtifactStore::new()),
712 Arc::new(crate::InMemoryAttachmentStore::new()),
713 Arc::new(crate::ChronologicalProjection::default()),
714 None,
715 crate::TurnContext::default(),
716 );
717
718 let surface = ctx.lashlang_surface();
719
720 assert!(
721 surface
722 .resources
723 .resolve_value_constructor(&["clock", "Alarm"])
724 .is_some()
725 );
726 assert!(
727 surface
728 .resources
729 .resolve_trigger_source("clock.Alarm")
730 .is_some()
731 );
732 lashlang::LinkedModule::link(
733 lashlang::parse(
734 r#"
735 process remember(tick: clock.Tick) {
736 finish true
737 }
738
739 source = clock.Alarm({ at: "08:00" })
740 await triggers.register({
741 source: source,
742 target: remember,
743 inputs: { tick: trigger.event }
744 })?
745 "#,
746 )
747 .expect("parse trigger registry module"),
748 surface,
749 )
750 .expect("host resource contribution should be linkable");
751 }
752}