mittens-engine 0.7.0

A Vulkan and OpenXR scene engine with ECS, reactive signals, and Meow Meow scripting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
use std::collections::HashMap;
use std::time::{Duration, Instant};

use crate::engine::ecs::{ComponentId, IntentValue, RxWorld, SignalEmitter, World};
use crate::engine::graphics::render_assets::RenderAssets;
use crate::scripting::object::{HeapHandle, MaterializedCE, Value};
use crate::scripting::world_evaluator::{
    EvalRequest, EvalResponse, HostCallKind, HostValue, MeowMeowEvaluator, eval_mms_fn,
    eval_module_source,
};

/// The result of evaluating an MMS script: collected intents and any errors.
#[derive(Debug, Default)]
pub struct EvalOutput {
    pub intents: Vec<IntentValue>,
    pub errors: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct LoadedMmsModule {
    pub named_exports: HashMap<String, Value>,
    pub sequence: Vec<MaterializedCE>,
    pub heap: HeapHandle,
    pub source_path: Option<String>,
}

impl LoadedMmsModule {
    pub fn named_export(&self, name: &str) -> Option<&Value> {
        self.named_exports.get(name)
    }
}

/// Synchronous wrapper around [`MeowMeowEvaluator`].
///
/// Spawns an evaluator thread, sends a script, drains all responses to
/// completion, and returns the collected [`EvalOutput`]. The thread is shut
/// down and joined before returning.
pub struct MeowMeowRunner;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModuleFactoryEvalMode {
    Template,
    Live,
}

fn headers_to_value(headers: &[(String, String)]) -> Value {
    Value::Map(
        headers
            .iter()
            .map(|(name, value)| (name.clone(), Value::String(value.clone())))
            .collect(),
    )
}

pub(crate) fn event_arg_value(signal: &crate::engine::ecs::Signal) -> Value {
    match signal.event.as_ref() {
        Some(crate::engine::ecs::EventSignal::FrameTick { dt_sec }) => {
            Value::Map(HashMap::from([(
                "dt_sec".to_string(),
                Value::Number(*dt_sec as f64),
            )]))
        }
        Some(crate::engine::ecs::EventSignal::GltfInitialized { gltf, uri }) => {
            Value::Map(HashMap::from([
                (
                    "gltf".to_string(),
                    Value::ComponentObject {
                        id: *gltf,
                        component_type: "GLTF".to_string(),
                    },
                ),
                ("uri".to_string(), Value::String(uri.clone())),
            ]))
        }
        Some(crate::engine::ecs::EventSignal::DataEvent { name, .. }) => {
            Value::String(name.clone())
        }
        Some(crate::engine::ecs::EventSignal::ToggleChanged { toggle, value }) => {
            Value::Map(HashMap::from([
                (
                    "toggle".into(),
                    Value::ComponentObject {
                        id: *toggle,
                        component_type: "Toggle".into(),
                    },
                ),
                ("value".into(), Value::Bool(*value)),
            ]))
        }
        Some(crate::engine::ecs::EventSignal::XrButtonDown {
            hand,
            control,
            value,
            ..
        })
        | Some(crate::engine::ecs::EventSignal::XrButtonUp {
            hand,
            control,
            value,
            ..
        })
        | Some(crate::engine::ecs::EventSignal::XrButtonChanged {
            hand,
            control,
            value,
            ..
        }) => Value::Map(HashMap::from([
            ("hand".to_string(), Value::String(format!("{hand:?}"))),
            ("control".to_string(), Value::String(format!("{control:?}"))),
            ("value".to_string(), Value::Number(*value as f64)),
        ])),
        Some(crate::engine::ecs::EventSignal::XrAxisChanged {
            hand,
            control,
            value,
            ..
        }) => Value::Map(HashMap::from([
            ("hand".to_string(), Value::String(format!("{hand:?}"))),
            ("control".to_string(), Value::String(format!("{control:?}"))),
            (
                "value".to_string(),
                Value::Array(vec![
                    Value::Number(value[0] as f64),
                    Value::Number(value[1] as f64),
                ]),
            ),
        ])),
        Some(crate::engine::ecs::EventSignal::TextInputChanged { text, caret, .. }) => {
            Value::Map(HashMap::from([
                ("text".to_string(), Value::String(text.clone())),
                ("caret".to_string(), Value::Number(*caret as f64)),
            ]))
        }
        Some(crate::engine::ecs::EventSignal::HttpRequest {
            request_id,
            method,
            path,
            query,
            url,
            headers,
            body_text,
            remote_addr,
        }) => Value::Map(HashMap::from([
            ("request_id".to_string(), Value::Number(*request_id as f64)),
            ("method".to_string(), Value::String(method.clone())),
            ("path".to_string(), Value::String(path.clone())),
            (
                "query".to_string(),
                query
                    .as_ref()
                    .map(|query| Value::String(query.clone()))
                    .unwrap_or(Value::Null),
            ),
            ("url".to_string(), Value::String(url.clone())),
            ("target".to_string(), Value::String(url.clone())),
            ("headers".to_string(), headers_to_value(headers)),
            ("body_text".to_string(), Value::String(body_text.clone())),
            (
                "remote_addr".to_string(),
                remote_addr
                    .as_ref()
                    .map(|addr| Value::String(addr.clone()))
                    .unwrap_or(Value::Null),
            ),
        ])),
        Some(crate::engine::ecs::EventSignal::HttpResponse {
            request_id,
            status,
            ok,
            headers,
            body_text,
            url,
        }) => Value::Map(HashMap::from([
            ("request_id".to_string(), Value::Number(*request_id as f64)),
            ("status".to_string(), Value::Number(*status as f64)),
            ("ok".to_string(), Value::Bool(*ok)),
            ("headers".to_string(), headers_to_value(headers)),
            ("body_text".to_string(), Value::String(body_text.clone())),
            ("url".to_string(), Value::String(url.clone())),
        ])),
        Some(crate::engine::ecs::EventSignal::HttpError {
            request_id,
            phase,
            message,
            url,
            bind_addr,
        }) => Value::Map(HashMap::from([
            (
                "request_id".to_string(),
                request_id
                    .map(|request_id| Value::Number(request_id as f64))
                    .unwrap_or(Value::Null),
            ),
            ("phase".to_string(), Value::String(phase.clone())),
            ("message".to_string(), Value::String(message.clone())),
            (
                "url".to_string(),
                url.as_ref()
                    .map(|url| Value::String(url.clone()))
                    .unwrap_or(Value::Null),
            ),
            (
                "bind_addr".to_string(),
                bind_addr
                    .as_ref()
                    .map(|bind_addr| Value::String(bind_addr.clone()))
                    .unwrap_or(Value::Null),
            ),
        ])),
        _ => Value::Null,
    }
}

impl MeowMeowRunner {
    /// Evaluate `source` without a live ECS world, collecting emitted intents
    /// and errors.
    ///
    /// This mode cannot allocate live `ComponentId`s during evaluation, so
    /// let-bound component expressions stay as `ComponentExpr` values rather
    /// than becoming live `ComponentObject` handles.
    ///
    /// Times out after 2 seconds if the evaluator stalls.
    pub fn eval(source: &str) -> EvalOutput {
        Self::eval_impl(source, None, Duration::from_secs(2))
    }

    /// Evaluate `source` with a caller-provided timeout.
    pub fn eval_with_timeout(source: &str, timeout: Duration) -> EvalOutput {
        Self::eval_impl(source, None, timeout)
    }

    /// Evaluate `source` knowing it came from `path` (enables relative imports).
    pub fn eval_with_path(source: &str, path: &str) -> EvalOutput {
        Self::eval_impl(source, Some(path), Duration::from_secs(2))
    }

    /// Read `path` from disk and evaluate it (enables relative imports).
    pub fn eval_file(path: &str) -> EvalOutput {
        Self::eval_file_with_timeout(path, Duration::from_secs(2))
    }

    /// Read `path` from disk and evaluate it (enables relative imports) with a caller-provided timeout.
    pub fn eval_file_with_timeout(path: &str, timeout: Duration) -> EvalOutput {
        match std::fs::read_to_string(path) {
            Ok(source) => Self::eval_impl(&source, Some(path), timeout),
            Err(e) => {
                let mut output = EvalOutput::default();
                output
                    .errors
                    .push(format!("cannot read file '{}': {}", path, e));
                output
            }
        }
    }

    pub fn load_module_source(
        source: &str,
        source_path: Option<&str>,
    ) -> Result<LoadedMmsModule, String> {
        let module = match eval_module_source(source, source_path)? {
            Value::Module {
                named,
                sequence,
                heap,
            } => Ok(LoadedMmsModule {
                named_exports: named,
                sequence,
                heap,
                source_path: source_path.map(|s| s.to_string()),
            }),
            other => Err(format!(
                "load_module_source: expected module result, got {:?}",
                other
            )),
        }?;
        Ok(module)
    }

    pub fn load_module_file(path: &str) -> Result<LoadedMmsModule, String> {
        let source = std::fs::read_to_string(path)
            .map_err(|e| format!("cannot read module '{}': {}", path, e))?;
        Self::load_module_source(&source, Some(path))
    }

    pub fn call_mms_module_fn(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        channels: Option<&mut crate::scripting::world_evaluator::EvalChannels>,
        world_host: Option<&mut World>,
        emit: Option<&mut dyn SignalEmitter>,
    ) -> Result<Value, String> {
        let Some(export) = module.named_export(name) else {
            return Err(format!("call_mms_module_fn: export '{}' not found", name));
        };
        if !matches!(export, Value::Function { .. }) {
            return Err(format!(
                "call_mms_module_fn: export '{}' is not a function",
                name
            ));
        }
        eval_mms_fn(export, args, channels, world_host, emit)
    }

    pub fn materialize_mms_module_component(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        world_host: Option<&mut World>,
        emit: Option<&mut dyn SignalEmitter>,
    ) -> Result<MaterializedCE, String> {
        Self::materialize_mms_module_component_in_mode(
            module,
            name,
            args,
            world_host,
            emit,
            ModuleFactoryEvalMode::Template,
        )
    }

    pub fn materialize_mms_module_component_in_mode(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        world_host: Option<&mut World>,
        emit: Option<&mut dyn SignalEmitter>,
        mode: ModuleFactoryEvalMode,
    ) -> Result<MaterializedCE, String> {
        match mode {
            ModuleFactoryEvalMode::Template => {}
            ModuleFactoryEvalMode::Live => {
                return Err(
                    "materialize_mms_module_component_in_mode: live mode does not return a stable MaterializedCE; use a spawn/instantiate helper instead".to_string()
                )
            }
        }
        let _ = world_host;
        let _ = emit;
        let value = Self::call_mms_module_fn(module, name, args, None, None, None)?;
        let Value::ComponentExpr(component_expr) = value else {
            return Err(format!(
                "materialize_mms_module_component: export '{}' did not return a component tree",
                name
            ));
        };
        Ok(*component_expr)
    }

    pub fn materialize_mms_module_component_from_file(
        path: &str,
        name: &str,
        args: Vec<Value>,
        world_host: Option<&mut World>,
        emit: Option<&mut dyn SignalEmitter>,
    ) -> Result<MaterializedCE, String> {
        let module = Self::load_module_file(path)?;
        Self::materialize_mms_module_component(&module, name, args, world_host, emit)
    }

    pub fn spawn_mms_module_component_uninitialized(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        world: &mut World,
        emit: &mut dyn SignalEmitter,
    ) -> Result<ComponentId, String> {
        Self::spawn_mms_module_component_uninitialized_with_assets(
            module, name, args, world, None, emit,
        )
    }

    pub fn spawn_mms_module_component_uninitialized_with_assets(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        world: &mut World,
        render_assets: Option<&mut RenderAssets>,
        emit: &mut dyn SignalEmitter,
    ) -> Result<ComponentId, String> {
        Self::spawn_mms_module_component_value(
            module,
            name,
            args,
            None,
            world,
            render_assets,
            emit,
            false,
        )
    }

    pub fn spawn_mms_module_component_uninitialized_from_file(
        path: &str,
        name: &str,
        args: Vec<Value>,
        world: &mut World,
        emit: &mut dyn SignalEmitter,
    ) -> Result<ComponentId, String> {
        let module = Self::load_module_file(path)?;
        Self::spawn_mms_module_component_uninitialized(&module, name, args, world, emit)
    }

    pub fn spawn_mms_module_component(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        parent: Option<ComponentId>,
        world: &mut World,
        emit: &mut dyn SignalEmitter,
    ) -> Result<ComponentId, String> {
        Self::spawn_mms_module_component_value(module, name, args, parent, world, None, emit, true)
    }

    pub fn spawn_mms_module_component_from_file(
        path: &str,
        name: &str,
        args: Vec<Value>,
        parent: Option<ComponentId>,
        world: &mut World,
        emit: &mut dyn SignalEmitter,
    ) -> Result<ComponentId, String> {
        let module = Self::load_module_file(path)?;
        Self::spawn_mms_module_component(&module, name, args, parent, world, emit)
    }

    fn spawn_mms_module_component_value(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        parent: Option<ComponentId>,
        world: &mut World,
        mut render_assets: Option<&mut RenderAssets>,
        emit: &mut dyn SignalEmitter,
        initialize: bool,
    ) -> Result<ComponentId, String> {
        let value = Self::eval_mms_module_component_live(
            module,
            name,
            args,
            world,
            render_assets.as_deref_mut(),
            emit,
        )?;
        match value {
            Value::ComponentObject { id, .. } => {
                if let Some(p) = parent {
                    world
                        .add_child(p, id)
                        .map_err(|e| format!("attach live module component failed: {e}"))?;
                }
                if initialize {
                    let should_init = parent.map(|p| world.is_initialized(p)).unwrap_or(true);
                    if should_init {
                        world.init_component_tree(id, emit);
                    }
                }
                Ok(id)
            }
            Value::ComponentExpr(component_expr) => {
                if let Some(render_assets) = render_assets.as_deref_mut() {
                    crate::scripting::component_registry::with_live_render_assets(
                        render_assets,
                        || {
                            if initialize {
                                crate::scripting::component_registry::spawn_tree(
                                    &component_expr,
                                    parent,
                                    world,
                                    emit,
                                )
                            } else {
                                crate::scripting::component_registry::spawn_tree_uninitialized(
                                    &component_expr,
                                    world,
                                    emit,
                                )
                            }
                        },
                    )
                } else if initialize {
                    crate::scripting::component_registry::spawn_tree(
                        &component_expr,
                        parent,
                        world,
                        emit,
                    )
                } else {
                    crate::scripting::component_registry::spawn_tree_uninitialized(
                        &component_expr,
                        world,
                        emit,
                    )
                }
            }
            other => Err(format!(
                "spawn_mms_module_component: export '{}' did not return a component tree, got {:?}",
                name, other
            )),
        }
    }

    fn eval_mms_module_component_live(
        module: &LoadedMmsModule,
        name: &str,
        args: Vec<Value>,
        world: &mut World,
        render_assets: Option<&mut RenderAssets>,
        emit: &mut dyn SignalEmitter,
    ) -> Result<Value, String> {
        if let Some(render_assets) = render_assets {
            crate::scripting::component_registry::with_live_render_assets(render_assets, || {
                Self::call_mms_module_fn(module, name, args, None, Some(world), Some(emit))
            })
        } else {
            Self::call_mms_module_fn(module, name, args, None, Some(world), Some(emit))
        }
    }

    /// Evaluate `source` with live world access.
    ///
    /// Handles two HostCall kinds during evaluation:
    /// - `Spawn`: spawns the component tree into `world` and returns the root `ComponentId`.
    ///   `let x = T {}` binds a `ComponentObject(id)` instead of a dead `ComponentExpr`.
    /// - `RegisterHandler`: installs an MMS function as a scoped signal handler in `rx`.
    ///   `on(obj, "Click", fn(e) { ... })` registers without blocking the evaluator.
    pub fn eval_with_world(
        source: &str,
        world: &mut World,
        rx: &mut RxWorld,
        emit: &mut dyn SignalEmitter,
    ) -> EvalOutput {
        Self::eval_with_world_at_path(source, None, world, rx, emit)
    }

    /// Like `eval_with_world`, but also records the source file path so
    /// `import` statements resolve relative to it.
    pub fn eval_with_world_at_path(
        source: &str,
        source_path: Option<&str>,
        world: &mut World,
        rx: &mut RxWorld,
        emit: &mut dyn SignalEmitter,
    ) -> EvalOutput {
        Self::eval_with_world_and_assets_at_path(source, source_path, world, rx, None, emit)
    }

    /// Evaluate `source` with live world + render-asset access.
    pub fn eval_with_world_and_assets(
        source: &str,
        world: &mut World,
        rx: &mut RxWorld,
        render_assets: &mut RenderAssets,
        emit: &mut dyn SignalEmitter,
    ) -> EvalOutput {
        Self::eval_with_world_and_assets_at_path(source, None, world, rx, Some(render_assets), emit)
    }

    /// Like `eval_with_world_and_assets`, but also records the source file path so
    /// `import` statements resolve relative to it.
    pub fn eval_with_world_and_assets_at_path(
        source: &str,
        source_path: Option<&str>,
        world: &mut World,
        rx: &mut RxWorld,
        mut render_assets: Option<&mut RenderAssets>,
        emit: &mut dyn SignalEmitter,
    ) -> EvalOutput {
        let mut handle = MeowMeowEvaluator::spawn(64);
        handle
            .requests
            .push(EvalRequest::EvalScript {
                source: source.to_string(),
                source_path: source_path.map(|s| s.to_string()),
            })
            .expect("MeowMeowRunner: push EvalScript");
        handle
            .requests
            .push(EvalRequest::Shutdown)
            .expect("MeowMeowRunner: push Shutdown");

        let mut output = EvalOutput::default();
        let deadline = Instant::now() + Duration::from_secs(5);

        loop {
            match handle.responses.pop() {
                Ok(EvalResponse::Intent(iv)) => output.intents.push(iv),
                Ok(EvalResponse::Error { message }) => output.errors.push(message),
                Ok(EvalResponse::ParsedOk { .. }) => {}
                Ok(EvalResponse::SnippetComplete { .. }) => {}
                Ok(EvalResponse::NavigationComplete { .. } | EvalResponse::ReplReset) => {}
                Ok(EvalResponse::ShutdownAck) => break,
                Ok(EvalResponse::HostCall { id, kind }) => {
                    let reply = match kind {
                        HostCallKind::Spawn(ce) => {
                            let result = if let Some(render_assets) = render_assets.as_deref_mut() {
                                crate::scripting::component_registry::with_live_render_assets(
                                    render_assets,
                                    || {
                                        crate::scripting::component_registry::spawn_tree(
                                            &ce, None, world, emit,
                                        )
                                    },
                                )
                            } else {
                                crate::scripting::component_registry::spawn_tree(
                                    &ce, None, world, emit,
                                )
                            };
                            match result {
                                Ok(component_id) => HostValue::ComponentId(component_id),
                                Err(e) => {
                                    output.errors.push(format!("HostCall::Spawn error: {e}"));
                                    HostValue::Null
                                }
                            }
                        }
                        HostCallKind::Register(ce) => {
                            let result = if let Some(render_assets) = render_assets.as_deref_mut() {
                                crate::scripting::component_registry::with_live_render_assets(
                                    render_assets,
                                    || {
                                        crate::scripting::component_registry::spawn_tree_uninitialized(
                                            &ce, world, emit,
                                        )
                                    },
                                )
                            } else {
                                crate::scripting::component_registry::spawn_tree_uninitialized(
                                    &ce, world, emit,
                                )
                            };
                            match result {
                                Ok(component_id) => HostValue::ComponentId(component_id),
                                Err(e) => {
                                    output.errors.push(format!("HostCall::Register error: {e}"));
                                    HostValue::Null
                                }
                            }
                        }
                        HostCallKind::Attach { parent, child } => {
                            if let Some(p) = parent {
                                if let Err(e) = world.add_child(p, child) {
                                    output.errors.push(format!("HostCall::Attach error: {e}"));
                                }
                            }
                            // Run the deferred init walk on the (now-attached, or root) subtree.
                            world.init_component_tree(child, emit);
                            HostValue::Null
                        }
                        HostCallKind::Query {
                            selector,
                            scope,
                            multiple,
                        } => {
                            let roots: Vec<crate::engine::ecs::ComponentId> = match scope {
                                Some(id) => world.scripting_query_roots(id),
                                None => world
                                    .all_components()
                                    .filter(|&id| world.parent_of(id).is_none())
                                    .collect(),
                            };
                            let mut all_ids: Vec<crate::engine::ecs::ComponentId> = Vec::new();
                            for r in roots {
                                if multiple {
                                    all_ids.extend(world.find_all_components(r, &selector));
                                } else if let Some(found) = world.find_component(r, &selector) {
                                    all_ids.push(found);
                                    break;
                                }
                            }
                            if multiple {
                                let list = all_ids
                                    .into_iter()
                                    .filter_map(|id| {
                                        world.component_name(id).map(|t| (id, t.to_string()))
                                    })
                                    .collect();
                                HostValue::ComponentList(list)
                            } else {
                                match all_ids.into_iter().next() {
                                    Some(id) => match world.component_name(id) {
                                        Some(t) => HostValue::Component {
                                            id,
                                            component_type: t.to_string(),
                                        },
                                        None => HostValue::Null,
                                    },
                                    None => HostValue::Null,
                                }
                            }
                        }
                        HostCallKind::RegisterHandler {
                            scope,
                            signal_kind,
                            name,
                            handler,
                        } => {
                            let callback =
                                move |world: &mut World,
                                      emit: &mut dyn SignalEmitter,
                                      signal: &crate::engine::ecs::Signal| {
                                    let arg = event_arg_value(signal);
                                    if let Err(e) = eval_mms_fn(
                                        &handler,
                                        vec![arg],
                                        None,
                                        Some(world),
                                        Some(emit),
                                    ) {
                                        eprintln!("[mms] handler error: {e}");
                                    }
                                };
                            if let Some(name) = name {
                                rx.add_handler_closure_named(
                                    signal_kind,
                                    scope,
                                    Some(name),
                                    callback,
                                );
                            } else {
                                rx.add_handler_closure(signal_kind, scope, callback);
                            }
                            HostValue::Null
                        }
                        HostCallKind::RegisterGlobalHandler {
                            signal_kind,
                            name,
                            handler,
                        } => {
                            let callback = move |world: &mut World,
                                                 emit: &mut dyn SignalEmitter,
                                                 signal: &crate::engine::ecs::Signal| {
                                let arg = event_arg_value(signal);
                                if let Err(e) = eval_mms_fn(
                                    &handler,
                                    vec![arg],
                                    None,
                                    Some(world),
                                    Some(emit),
                                ) {
                                    eprintln!("[mms] global handler error: {e}");
                                }
                            };
                            if let Some(name) = name {
                                rx.add_global_handler_closure_named(
                                    signal_kind,
                                    Some(name),
                                    callback,
                                );
                            } else {
                                rx.add_global_handler_closure(signal_kind, callback);
                            }
                            HostValue::Null
                        }
                        HostCallKind::AudioClipInstance {
                            source,
                            start_beat,
                            stop_beat,
                        } => {
                            use crate::engine::ecs::component::AudioClipComponent;
                            match world.get_component_by_id_as::<AudioClipComponent>(source) {
                                Some(src) => {
                                    let mut c = AudioClipComponent::instance_of(src);
                                    if let Some(sb) = start_beat {
                                        c.start_beat = sb;
                                    }
                                    if let Some(eb) = stop_beat {
                                        c.stop_beat = Some(eb);
                                    }
                                    let id = world.add_component(c);
                                    HostValue::ComponentId(id)
                                }
                                None => {
                                    output.errors.push(
                                        "HostCall::AudioClipInstance: source is not an AudioClip"
                                            .to_string(),
                                    );
                                    HostValue::Null
                                }
                            }
                        }
                        HostCallKind::InvokeComponentMethod {
                            id,
                            component_type,
                            method,
                            args,
                        } => match crate::scripting::component_method_registry::invoke_component_method(
                            world,
                            id,
                            &component_type,
                            &method,
                            &args,
                            |intent| output.intents.push(intent),
                        ) {
                            Ok(value) => match value {
                                Value::Null => HostValue::Null,
                                Value::ComponentObject { id, component_type } => {
                                    HostValue::Component { id, component_type }
                                }
                                other => HostValue::Value(other),
                            },
                            Err(e) => {
                                output
                                    .errors
                                    .push(format!("HostCall::InvokeComponentMethod error: {e}"));
                                HostValue::Null
                            }
                        },
                        HostCallKind::ReplTree { .. }
                        | HostCallKind::ReplDump { .. }
                        | HostCallKind::ReplHelp
                        | HostCallKind::ReplClear => HostValue::Null,
                    };
                    let _ = handle
                        .requests
                        .push(EvalRequest::HostCallResult { id, value: reply });
                }
                Err(rtrb::PopError::Empty) => {
                    if Instant::now() > deadline {
                        output
                            .errors
                            .push("MeowMeowRunner: timed out waiting for evaluator".into());
                        break;
                    }
                    std::thread::yield_now();
                }
            }
        }

        handle.shutdown_and_join();
        output
    }

    fn eval_impl(source: &str, source_path: Option<&str>, timeout: Duration) -> EvalOutput {
        let mut handle = MeowMeowEvaluator::spawn(64);

        handle
            .requests
            .push(EvalRequest::EvalScript {
                source: source.to_string(),
                source_path: source_path.map(|s| s.to_string()),
            })
            .expect("MeowMeowRunner: push EvalScript");
        handle
            .requests
            .push(EvalRequest::Shutdown)
            .expect("MeowMeowRunner: push Shutdown");

        let mut output = EvalOutput::default();
        let deadline = Instant::now() + timeout;

        loop {
            match handle.responses.pop() {
                Ok(EvalResponse::Intent(iv)) => output.intents.push(iv),
                Ok(EvalResponse::Error { message }) => output.errors.push(message),
                Ok(EvalResponse::ParsedOk { .. }) => {}
                Ok(EvalResponse::SnippetComplete { .. }) => {}
                Ok(EvalResponse::NavigationComplete { .. } | EvalResponse::ReplReset) => {}
                Ok(EvalResponse::ShutdownAck) => break,
                // Fire-and-forget runner has no world — reply null so the evaluator
                // falls back to ComponentExpr and continues without blocking.
                Ok(EvalResponse::HostCall { id, .. }) => {
                    let _ = handle.requests.push(EvalRequest::HostCallResult {
                        id,
                        value: HostValue::Null,
                    });
                }
                Err(rtrb::PopError::Empty) => {
                    if Instant::now() > deadline {
                        output
                            .errors
                            .push("MeowMeowRunner: timed out waiting for evaluator".into());
                        break;
                    }
                    std::thread::yield_now();
                }
            }
        }

        handle.shutdown_and_join();
        output
    }
}