eli 0.3.2

Ease Lives Instantly — hook-first AI agent framework with multi-channel support
Documentation
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//! Hook specifications and runtime for the Eli framework.
//!
//! Replaces Python pluggy with a simple Vec-of-trait-objects approach.
//! Hook precedence: implementations are stored in registration order;
//! `call_first` iterates in **reverse** (last registered wins).

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use futures::FutureExt;

use nexil::tape::{AsyncTapeStore, TapeStore};

use crate::smart_router::RouteDecision;
use crate::types::{Envelope, MessageHandler, PromptValue, State};

// ---------------------------------------------------------------------------
// HookError
// ---------------------------------------------------------------------------

/// Error returned by hook methods that can fail.
#[derive(Debug, thiserror::Error)]
pub enum HookError {
    #[error("{hook_point} failed in plugin '{plugin}': {source}")]
    Plugin {
        plugin: String,
        hook_point: &'static str,
        source: anyhow::Error,
    },
    #[error("hook panicked in plugin '{0}'")]
    Panic(String),
}

impl HookError {
    /// Wrap a hook error with plugin/hook-point context, extracting the inner source.
    fn wrap(plugin: String, hook_point: &'static str, e: HookError) -> Self {
        let source = match e {
            HookError::Plugin { source, .. } => source,
            other => anyhow::anyhow!("{other}"),
        };
        HookError::Plugin {
            plugin,
            hook_point,
            source,
        }
    }
}

/// Iterate plugins, call an async method, and swallow any panics.
macro_rules! call_notify_all {
    ($iter:expr, $hook_name:literal, |$p:ident| $call:expr) => {
        for $p in $iter {
            let name = $p.plugin_name().to_owned();
            let result = std::panic::AssertUnwindSafe($call).catch_unwind().await;
            if result.is_err() {
                tracing::error!(plugin = %name, concat!("hook.", $hook_name, " panicked"));
            }
        }
    };
}

/// Iterate plugins (sync), call a method, and swallow any panics.
macro_rules! call_sync_all {
    ($iter:expr, $hook_name:literal, |$p:ident| $call:expr) => {
        for $p in $iter {
            let name = $p.plugin_name().to_owned();
            if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| $call)).is_err() {
                tracing::error!(plugin = %name, concat!("hook.", $hook_name, " panicked"));
            }
        }
    };
}

fn preview_text(text: &str) -> String {
    const LIMIT: usize = 1000;
    let mut chars = text.chars();
    let preview: String = chars.by_ref().take(LIMIT).collect();
    let normalized = preview.replace('\n', "\\n");
    if chars.next().is_some() {
        format!("{normalized}...(truncated)")
    } else {
        normalized
    }
}

fn preview_json(value: &Envelope) -> String {
    preview_text(&value.to_string())
}

fn trace_hook_call(plugin: &str, session_id: &str, hook: &str, input: &str) {
    tracing::info!(target: "eli_trace", plugin = %plugin, session_id = %session_id, input = %input, "hook.{hook}.call");
}

fn trace_hook_return(plugin: &str, session_id: &str, hook: &str, output: &str) {
    tracing::info!(target: "eli_trace", plugin = %plugin, session_id = %session_id, output = %output, "hook.{hook}.return");
}

fn trace_hook_none(plugin: &str, session_id: &str, hook: &str) {
    tracing::info!(target: "eli_trace", plugin = %plugin, session_id = %session_id, "hook.{hook}.none");
}

// ---------------------------------------------------------------------------
// ChannelHook trait (framework-level channel contract for EliHookSpec)
// ---------------------------------------------------------------------------

/// A framework-level channel that can receive and optionally send messages.
///
/// This is the hook-system's view of a channel, used by [`EliHookSpec::provide_channels`].
/// For the transport-level trait, see [`crate::channels::base::Channel`].
#[async_trait]
pub trait ChannelHook: Send + Sync {
    /// Unique name identifying this channel type.
    fn name(&self) -> &str;

    /// Start listening for events. Runs until `stop` is called or the token is cancelled.
    async fn start(&self, stop: tokio::sync::watch::Receiver<bool>) -> anyhow::Result<()>;

    /// Gracefully stop the channel.
    async fn stop(&self) -> anyhow::Result<()>;

    /// Whether this channel needs debounce to prevent overload.
    fn needs_debounce(&self) -> bool {
        false
    }

    /// Send a message through this channel (optional).
    async fn send(&self, _message: Envelope) -> anyhow::Result<()> {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// TapeStoreKind: unifies sync and async tape stores
// ---------------------------------------------------------------------------

/// Wraps either a sync or async tape store returned by plugins.
pub enum TapeStoreKind {
    Sync(Arc<dyn TapeStore>),
    Async(Arc<dyn AsyncTapeStore>),
}

// ---------------------------------------------------------------------------
// EliHookSpec trait
// ---------------------------------------------------------------------------

/// Hook contract for Eli framework extensions.
///
/// All methods have default implementations that return `None` / empty so that
/// plugins only need to override the hooks they care about.
///
/// # Panic Safety
///
/// Hooks are classified into two categories:
/// - **Chain-aborting** (`resolve_session`, `load_state`, `run_model`): a panic
///   causes `HookError::Panic` to propagate to the caller. These hooks are
///   critical to the turn pipeline and cannot be skipped.
/// - **Best-effort** (all others): a panic is caught and logged, then execution
///   continues to the next plugin.
#[async_trait]
#[allow(unused_variables)]
pub trait EliHookSpec: Send + Sync {
    /// Human-readable name for this plugin (used in diagnostics).
    fn plugin_name(&self) -> &str {
        "unnamed"
    }

    /// Classify an inbound message to determine its processing route.
    /// Returns `None` to defer to the next plugin, or `Some(RouteDecision)`.
    fn classify_inbound(&self, message: &Envelope) -> Option<RouteDecision> {
        None
    }

    /// Resolve session id for one inbound message.
    async fn resolve_session(&self, message: &Envelope) -> Result<Option<String>, HookError> {
        Ok(None)
    }

    /// Load state snapshot for one session.
    async fn load_state(
        &self,
        message: &Envelope,
        session_id: &str,
    ) -> Result<Option<State>, HookError> {
        Ok(None)
    }

    /// Build model prompt for this turn.
    /// Returns either plain text or a list of content parts (multimodal).
    async fn build_user_prompt(
        &self,
        message: &Envelope,
        session_id: &str,
        state: &State,
    ) -> Option<PromptValue> {
        None
    }

    /// Run model for one turn and return plain text output.
    async fn run_model(
        &self,
        prompt: &PromptValue,
        session_id: &str,
        state: &State,
    ) -> Result<Option<String>, HookError> {
        Ok(None)
    }

    /// Persist state updates after one model turn.
    async fn save_state(
        &self,
        session_id: &str,
        state: &State,
        message: &Envelope,
        model_output: &str,
    ) {
    }

    /// Render outbound messages from model output.
    /// Each implementation may return zero or more envelopes.
    async fn render_outbound(
        &self,
        message: &Envelope,
        session_id: &str,
        state: &State,
        model_output: &str,
    ) -> Option<Vec<Envelope>> {
        None
    }

    /// Dispatch one outbound message to external channel(s).
    async fn dispatch_outbound(&self, message: &Envelope) -> Option<bool> {
        None
    }

    /// Register CLI commands (synchronous hook).
    fn register_cli_commands(&self, app: &mut clap::Command) {}

    /// Observe framework errors from any stage.
    async fn on_error(&self, stage: &str, error: &anyhow::Error, message: Option<&Envelope>) {}

    /// Build the full system prompt for the agent loop.
    /// Returns `None` to defer to the next plugin, or `Some(String)` with the assembled prompt.
    fn build_system_prompt(&self, prompt_text: &str, state: &State) -> Option<String> {
        None
    }

    /// Wrap a tool before execution. Returns a `ToolAction` to keep, remove, or replace
    /// the tool. Plugins are called in forward order (first-registered first) so that
    /// safety plugins registered early can remove tools before later plugins see them.
    fn wrap_tool(&self, tool: &nexil::Tool) -> nexil::ToolAction {
        nexil::ToolAction::Keep
    }

    /// Provide a tape store instance for conversation recording.
    fn provide_tape_store(&self) -> Option<TapeStoreKind> {
        None
    }

    /// Provide channels for receiving messages.
    fn provide_channels(&self, message_handler: MessageHandler) -> Vec<Box<dyn ChannelHook>> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// HookRuntime
// ---------------------------------------------------------------------------

/// Executes hooks with fault isolation and precedence semantics.
///
/// # Panic Policy
///
/// - **Upgraded hooks** (`resolve_session`, `load_state`, `run_model`):
///   A panic aborts the hook chain and returns `Err(HookError::Panic)`.
///   No further plugins are consulted.
///
/// - **Non-upgraded hooks** (`build_user_prompt`, `save_state`, `render_outbound`,
///   `dispatch_outbound`, `on_error`, `register_cli_commands`):
///   A panic is caught and logged; execution continues to the next plugin.
pub struct HookRuntime {
    plugins: Vec<Arc<dyn EliHookSpec>>,
}

impl HookRuntime {
    /// Create a new runtime from a list of plugins (in registration order).
    pub fn new(plugins: Vec<Arc<dyn EliHookSpec>>) -> Self {
        Self { plugins }
    }

    /// Add a plugin at the end of the registration list.
    pub fn register(&mut self, plugin: Arc<dyn EliHookSpec>) {
        self.plugins.push(plugin);
    }

    /// Return an iterator over plugins in **reverse** registration order (last-registered first).
    fn reversed(&self) -> impl Iterator<Item = &Arc<dyn EliHookSpec>> {
        self.plugins.iter().rev()
    }

    // -- classify inbound (sync, first-result) --------------------------------

    /// Classify inbound message: return the first non-None result.
    pub fn call_classify_inbound(&self, message: &Envelope) -> Option<RouteDecision> {
        for plugin in self.reversed() {
            let name = plugin.plugin_name().to_owned();
            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                plugin.classify_inbound(message)
            })) {
                Ok(Some(decision)) => {
                    tracing::info!(
                        target: "eli_trace",
                        plugin = %name,
                        decision = ?decision,
                        "hook.classify_inbound"
                    );
                    return Some(decision);
                }
                Ok(None) => {}
                Err(_) => tracing::error!(plugin = %name, "hook.classify_inbound panicked"),
            }
        }
        None
    }

    // -- build system prompt (sync, first-result) -----------------------------

    /// Build system prompt: return the first non-None result.
    pub fn call_build_system_prompt(&self, prompt_text: &str, state: &State) -> Option<String> {
        for plugin in self.reversed() {
            let name = plugin.plugin_name().to_owned();
            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                plugin.build_system_prompt(prompt_text, state)
            })) {
                Ok(Some(prompt)) => return Some(prompt),
                Ok(None) => {}
                Err(_) => tracing::error!(plugin = %name, "hook.build_system_prompt panicked"),
            }
        }
        None
    }

    // -- wrap tool (sync, all plugins) ----------------------------------------

    /// Wrap tools through all plugins. Each plugin can modify/wrap a tool.
    pub fn call_wrap_tools(&self, tools: Vec<nexil::Tool>) -> Vec<nexil::Tool> {
        let mut result = tools;
        for plugin in self.plugins.iter() {
            let name = plugin.plugin_name().to_owned();
            result = result
                .into_iter()
                .filter_map(|tool| {
                    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        plugin.wrap_tool(&tool)
                    })) {
                        Ok(nexil::ToolAction::Keep) => Some(tool),
                        Ok(nexil::ToolAction::Remove) => {
                            tracing::info!(
                                plugin = %name,
                                tool = %tool.name,
                                "hook.wrap_tool removed tool"
                            );
                            None
                        }
                        Ok(nexil::ToolAction::Replace(wrapped)) => Some(wrapped),
                        Err(_) => {
                            tracing::error!(plugin = %name, "hook.wrap_tool panicked");
                            Some(tool)
                        }
                    }
                })
                .collect();
        }
        result
    }

    // -- firstresult hooks (async) ------------------------------------------

    /// Resolve session: return the first non-None result.
    pub async fn call_resolve_session(
        &self,
        message: &Envelope,
    ) -> Result<Option<String>, HookError> {
        let session_id = "<resolving>";
        for p in self.reversed() {
            let name = p.plugin_name().to_owned();
            trace_hook_call(&name, session_id, "resolve_session", &preview_json(message));
            let result = std::panic::AssertUnwindSafe(p.resolve_session(message))
                .catch_unwind()
                .await;
            match result {
                Ok(Ok(Some(val))) => {
                    trace_hook_return(&name, &val, "resolve_session", &preview_text(&val));
                    return Ok(Some(val));
                }
                Ok(Ok(None)) => {
                    trace_hook_none(&name, session_id, "resolve_session");
                    continue;
                }
                Ok(Err(e)) => {
                    tracing::warn!(plugin = %name, error = %e, "hook.resolve_session failed");
                    return Err(HookError::wrap(name, "resolve_session", e));
                }
                Err(_) => {
                    tracing::warn!(plugin = %name, "hook.resolve_session panicked");
                    return Err(HookError::Panic(name));
                }
            }
        }
        Ok(None)
    }

    /// Load state: collect all results and merge.
    pub async fn call_load_state(
        &self,
        message: &Envelope,
        session_id: &str,
    ) -> Result<Vec<Option<State>>, HookError> {
        let mut results = Vec::new();
        for p in self.plugins.iter() {
            let name = p.plugin_name().to_owned();
            trace_hook_call(&name, session_id, "load_state", &preview_json(message));
            let result = std::panic::AssertUnwindSafe(p.load_state(message, session_id))
                .catch_unwind()
                .await;
            match result {
                Ok(Ok(val)) => {
                    let preview = format!("{} keys", val.as_ref().map_or(0, |s| s.len()));
                    trace_hook_return(&name, session_id, "load_state", &preview);
                    results.push(val);
                }
                Ok(Err(e)) => {
                    tracing::warn!(plugin = %name, error = %e, "hook.load_state failed");
                    return Err(HookError::wrap(name, "load_state", e));
                }
                Err(_) => {
                    tracing::warn!(plugin = %name, "hook.load_state panicked");
                    return Err(HookError::Panic(name));
                }
            }
        }
        Ok(results)
    }

    /// Build prompt: return the first non-None result (non-upgraded — panics skip).
    pub async fn call_build_user_prompt(
        &self,
        message: &Envelope,
        session_id: &str,
        state: &State,
    ) -> Option<PromptValue> {
        for plugin in self.reversed() {
            let name = plugin.plugin_name().to_owned();
            trace_hook_call(
                &name,
                session_id,
                "build_user_prompt",
                &preview_json(message),
            );
            let result =
                std::panic::AssertUnwindSafe(plugin.build_user_prompt(message, session_id, state))
                    .catch_unwind()
                    .await;
            match result {
                Ok(Some(val)) => {
                    trace_hook_return(
                        &name,
                        session_id,
                        "build_user_prompt",
                        &preview_text(&val.as_text()),
                    );
                    return Some(val);
                }
                Ok(None) => {
                    trace_hook_none(&name, session_id, "build_user_prompt");
                    continue;
                }
                Err(_) => {
                    tracing::error!(plugin = %name, session_id = %session_id, "hook.build_user_prompt panicked");
                    continue;
                }
            }
        }
        None
    }

    /// Run model: return the first non-None result (upgraded — errors propagate).
    pub async fn call_run_model(
        &self,
        prompt: &PromptValue,
        session_id: &str,
        state: &State,
    ) -> Result<Option<String>, HookError> {
        for plugin in self.reversed() {
            let name = plugin.plugin_name().to_owned();
            trace_hook_call(
                &name,
                session_id,
                "run_model",
                &preview_text(&prompt.as_text()),
            );
            let result = std::panic::AssertUnwindSafe(plugin.run_model(prompt, session_id, state))
                .catch_unwind()
                .await;
            match result {
                Ok(Ok(Some(val))) => {
                    trace_hook_return(&name, session_id, "run_model", &preview_text(&val));
                    return Ok(Some(val));
                }
                Ok(Ok(None)) => {
                    trace_hook_none(&name, session_id, "run_model");
                    continue;
                }
                Ok(Err(e)) => {
                    tracing::warn!(plugin = %name, error = %e, "hook.run_model failed");
                    return Err(HookError::wrap(name, "run_model", e));
                }
                Err(_) => {
                    tracing::warn!(plugin = %name, "hook.run_model panicked");
                    return Err(HookError::Panic(name));
                }
            }
        }
        Ok(None)
    }

    /// Save state: call all implementations (notify pattern).
    pub async fn call_save_state(
        &self,
        session_id: &str,
        state: &State,
        message: &Envelope,
        model_output: &str,
    ) {
        for p in self.plugins.iter() {
            let name = p.plugin_name().to_owned();
            trace_hook_call(&name, session_id, "save_state", &preview_text(model_output));
            let result = std::panic::AssertUnwindSafe(p.save_state(
                session_id,
                state,
                message,
                model_output,
            ))
            .catch_unwind()
            .await;
            match result {
                Ok(()) => trace_hook_return(&name, session_id, "save_state", "ok"),
                Err(_) => {
                    tracing::error!(plugin = %name, "hook.save_state panicked");
                }
            }
        }
    }

    /// Render outbound: collect results from all implementations.
    pub async fn call_render_outbound(
        &self,
        message: &Envelope,
        session_id: &str,
        state: &State,
        model_output: &str,
    ) -> Vec<Vec<Envelope>> {
        let mut results = Vec::new();
        for plugin in self.plugins.iter() {
            let name = plugin.plugin_name().to_owned();
            trace_hook_call(
                &name,
                session_id,
                "render_outbound",
                &preview_text(model_output),
            );
            let result = std::panic::AssertUnwindSafe(plugin.render_outbound(
                message,
                session_id,
                state,
                model_output,
            ))
            .catch_unwind()
            .await;
            match result {
                Ok(Some(batch)) => {
                    let preview = batch.first().map(preview_json).unwrap_or_default();
                    trace_hook_return(&name, session_id, "render_outbound", &preview);
                    results.push(batch);
                }
                Ok(None) => trace_hook_none(&name, session_id, "render_outbound"),
                Err(_) => {
                    tracing::error!(plugin = %name, "hook.render_outbound panicked");
                }
            }
        }
        results
    }

    /// Dispatch outbound: call all implementations.
    pub async fn call_dispatch_outbound(&self, message: &Envelope) {
        let session_id = message
            .get("session_id")
            .and_then(|v| v.as_str())
            .unwrap_or("<unknown>");
        for p in self.plugins.iter() {
            let name = p.plugin_name().to_owned();
            trace_hook_call(
                &name,
                session_id,
                "dispatch_outbound",
                &preview_json(message),
            );
            let result = std::panic::AssertUnwindSafe(p.dispatch_outbound(message))
                .catch_unwind()
                .await;
            match result {
                Ok(Some(delivered)) => {
                    trace_hook_return(
                        &name,
                        session_id,
                        "dispatch_outbound",
                        if delivered {
                            "delivered"
                        } else {
                            "not_delivered"
                        },
                    );
                }
                Ok(None) => trace_hook_none(&name, session_id, "dispatch_outbound"),
                Err(_) => {
                    tracing::error!(plugin = %name, "hook.dispatch_outbound panicked");
                }
            }
        }
    }

    /// Register CLI commands on all plugins (synchronous).
    pub fn call_register_cli_commands(&self, app: &mut clap::Command) {
        call_sync_all!(self.plugins.iter(), "register_cli_commands", |p| p
            .register_cli_commands(app));
    }

    /// Notify all error observers, swallowing any panics/errors from the observers.
    pub async fn notify_error(
        &self,
        stage: &str,
        error: &anyhow::Error,
        message: Option<&Envelope>,
    ) {
        call_notify_all!(self.plugins.iter(), "on_error", |p| p
            .on_error(stage, error, message));
    }

    /// Get the first provided tape store.
    pub fn call_provide_tape_store(&self) -> Option<TapeStoreKind> {
        for plugin in self.reversed() {
            let name = plugin.plugin_name().to_owned();
            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                plugin.provide_tape_store()
            })) {
                Ok(Some(store)) => return Some(store),
                Ok(None) => {}
                Err(_) => tracing::error!(plugin = %name, "hook.provide_tape_store panicked"),
            }
        }
        None
    }

    /// Collect channels from all plugins.
    pub fn call_provide_channels(
        &self,
        message_handler: MessageHandler,
    ) -> Vec<Box<dyn ChannelHook>> {
        let mut channels = Vec::new();
        call_sync_all!(self.plugins.iter(), "provide_channels", |p| {
            channels.append(&mut p.provide_channels(message_handler.clone()));
        });
        channels
    }

    /// Build a hook-name to adapter-names mapping for diagnostics.
    pub fn hook_report(&self) -> HashMap<String, Vec<String>> {
        // We report which plugins implement each hook by checking if their
        // return value differs from the default. Since we can't introspect
        // trait overrides in Rust the way pluggy can, we just list all
        // registered plugin names for each hook.
        let hook_names = [
            "classify_inbound",
            "resolve_session",
            "load_state",
            "build_user_prompt",
            "build_system_prompt",
            "run_model",
            "save_state",
            "render_outbound",
            "dispatch_outbound",
            "register_cli_commands",
            "on_error",
            "wrap_tool",
            "provide_tape_store",
            "provide_channels",
        ];

        let mut report = HashMap::new();
        let names: Vec<String> = self
            .plugins
            .iter()
            .map(|p| p.plugin_name().to_string())
            .collect();

        for hook_name in &hook_names {
            if !names.is_empty() {
                report.insert(hook_name.to_string(), names.clone());
            }
        }
        report
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::Arc;

    // -- Test plugins ---------------------------------------------------------

    struct HighPriorityPlugin;

    #[async_trait]
    impl EliHookSpec for HighPriorityPlugin {
        fn plugin_name(&self) -> &str {
            "high"
        }

        async fn resolve_session(&self, _message: &Envelope) -> Result<Option<String>, HookError> {
            Ok(Some("high-session".into()))
        }

        fn build_system_prompt(&self, _prompt_text: &str, _state: &State) -> Option<String> {
            Some("high-prompt".into())
        }

        async fn render_outbound(
            &self,
            _message: &Envelope,
            _session_id: &str,
            _state: &State,
            _model_output: &str,
        ) -> Option<Vec<Envelope>> {
            Some(vec![json!({"content": "high-out"})])
        }
    }

    struct LowPriorityPlugin;

    #[async_trait]
    impl EliHookSpec for LowPriorityPlugin {
        fn plugin_name(&self) -> &str {
            "low"
        }

        async fn resolve_session(&self, _message: &Envelope) -> Result<Option<String>, HookError> {
            Ok(Some("low-session".into()))
        }

        fn build_system_prompt(&self, _prompt_text: &str, _state: &State) -> Option<String> {
            Some("low-prompt".into())
        }
    }

    struct ReturnsNonePlugin;

    #[async_trait]
    impl EliHookSpec for ReturnsNonePlugin {
        fn plugin_name(&self) -> &str {
            "none-plugin"
        }
    }

    struct ErrorObserver {
        observed: std::sync::Mutex<Vec<String>>,
    }

    #[async_trait]
    impl EliHookSpec for ErrorObserver {
        fn plugin_name(&self) -> &str {
            "error-observer"
        }

        async fn on_error(&self, stage: &str, _error: &anyhow::Error, _message: Option<&Envelope>) {
            self.observed
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(stage.to_owned());
        }
    }

    struct FailingErrorObserver;

    #[async_trait]
    impl EliHookSpec for FailingErrorObserver {
        fn plugin_name(&self) -> &str {
            "failing-observer"
        }

        async fn on_error(
            &self,
            _stage: &str,
            _error: &anyhow::Error,
            _message: Option<&Envelope>,
        ) {
            panic!("observer panic");
        }
    }

    struct PanicSessionPlugin;

    #[async_trait]
    impl EliHookSpec for PanicSessionPlugin {
        fn plugin_name(&self) -> &str {
            "panic-session"
        }

        async fn resolve_session(&self, _message: &Envelope) -> Result<Option<String>, HookError> {
            panic!("resolve_session panic");
        }
    }

    // -- call_resolve_session (call_first semantics) -------------------------

    #[tokio::test]
    async fn test_call_first_returns_last_registered_non_none() {
        // Low registered first, High registered last.
        // reversed() iterates High first, which returns Some -> wins.
        let rt = HookRuntime::new(vec![
            Arc::new(LowPriorityPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(HighPriorityPlugin),
        ]);
        let msg = json!({"content": "hello"});
        let result = rt.call_resolve_session(&msg).await.unwrap();
        assert_eq!(result, Some("high-session".into()));
    }

    #[tokio::test]
    async fn test_call_first_skips_none_and_returns_next() {
        // ReturnsNone registered last -> reversed first, returns None.
        // LowPriority next -> returns Some("low-session").
        let rt = HookRuntime::new(vec![
            Arc::new(LowPriorityPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(ReturnsNonePlugin),
        ]);
        let msg = json!({"content": "hello"});
        let result = rt.call_resolve_session(&msg).await.unwrap();
        assert_eq!(result, Some("low-session".into()));
    }

    #[tokio::test]
    async fn test_call_first_returns_none_when_all_return_none() {
        let rt = HookRuntime::new(vec![Arc::new(ReturnsNonePlugin) as Arc<dyn EliHookSpec>]);
        let msg = json!({"content": "hello"});
        let result = rt.call_resolve_session(&msg).await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_call_first_propagates_panic_as_error() {
        let rt = HookRuntime::new(vec![
            Arc::new(LowPriorityPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(PanicSessionPlugin),
        ]);
        let msg = json!({"content": "hello"});
        let result = rt.call_resolve_session(&msg).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, HookError::Panic(ref name) if name == "panic-session"));
    }

    // -- call_build_system_prompt (first-result sync) -------------------------

    #[tokio::test]
    async fn test_call_build_system_prompt_returns_first_result() {
        let rt = HookRuntime::new(vec![
            Arc::new(LowPriorityPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(HighPriorityPlugin),
        ]);
        let state = State::new();
        let result = rt.call_build_system_prompt("hello", &state);
        // Last-registered (High) wins
        assert_eq!(result, Some("high-prompt".into()));
    }

    #[tokio::test]
    async fn test_call_build_system_prompt_skips_none_results() {
        let rt = HookRuntime::new(vec![
            Arc::new(LowPriorityPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(ReturnsNonePlugin),
        ]);
        let state = State::new();
        let result = rt.call_build_system_prompt("hello", &state);
        assert_eq!(result, Some("low-prompt".into()));
    }

    // -- call_render_outbound (call_many async) ------------------------------

    #[tokio::test]
    async fn test_call_render_outbound_collects_all() {
        let rt = HookRuntime::new(vec![
            Arc::new(HighPriorityPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(ReturnsNonePlugin),
        ]);
        let msg = json!({"content": "hello"});
        let state = State::new();
        let result = rt.call_render_outbound(&msg, "s1", &state, "output").await;
        // Only HighPriorityPlugin returns Some
        assert_eq!(result.len(), 1);
        assert_eq!(result[0][0], json!({"content": "high-out"}));
    }

    // -- notify_error swallows observer failures -----------------------------

    #[tokio::test]
    async fn test_notify_error_calls_all_observers() {
        let observer = Arc::new(ErrorObserver {
            observed: std::sync::Mutex::new(Vec::new()),
        });
        let rt = HookRuntime::new(vec![
            Arc::new(FailingErrorObserver) as Arc<dyn EliHookSpec>,
            observer.clone() as Arc<dyn EliHookSpec>,
        ]);
        let err = anyhow::anyhow!("test error");
        rt.notify_error("turn", &err, None).await;
        let observed = observer.observed.lock().unwrap_or_else(|e| e.into_inner());
        assert_eq!(*observed, vec!["turn"]);
    }

    #[tokio::test]
    async fn test_notify_error_with_message() {
        let observer = Arc::new(ErrorObserver {
            observed: std::sync::Mutex::new(Vec::new()),
        });
        let rt = HookRuntime::new(vec![observer.clone() as Arc<dyn EliHookSpec>]);
        let err = anyhow::anyhow!("test error");
        let msg = json!({"content": "hello"});
        rt.notify_error("pipeline", &err, Some(&msg)).await;
        let observed = observer.observed.lock().unwrap_or_else(|e| e.into_inner());
        assert_eq!(*observed, vec!["pipeline"]);
    }

    // -- hook_report ---------------------------------------------------------

    #[test]
    fn test_hook_report_lists_all_registered_plugins() {
        let rt = HookRuntime::new(vec![
            Arc::new(LowPriorityPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(HighPriorityPlugin),
        ]);
        let report = rt.hook_report();
        assert!(report.contains_key("resolve_session"));
        assert_eq!(report["resolve_session"], vec!["low", "high"]);
        assert!(report.contains_key("build_system_prompt"));
    }

    #[test]
    fn test_hook_report_empty_when_no_plugins() {
        let rt = HookRuntime::new(vec![]);
        let report = rt.hook_report();
        assert!(report.is_empty());
    }

    // -- register ------------------------------------------------------------

    #[test]
    fn test_register_adds_plugin() {
        let mut rt = HookRuntime::new(vec![]);
        assert!(rt.hook_report().is_empty());
        rt.register(Arc::new(LowPriorityPlugin));
        let report = rt.hook_report();
        assert_eq!(report["resolve_session"], vec!["low"]);
    }

    // -- call_load_state error/panic handling ---------------------------------

    struct PanicLoadStatePlugin;

    #[async_trait]
    impl EliHookSpec for PanicLoadStatePlugin {
        fn plugin_name(&self) -> &str {
            "panic-load-state"
        }

        async fn load_state(
            &self,
            _message: &Envelope,
            _session_id: &str,
        ) -> Result<Option<State>, HookError> {
            panic!("load_state panic");
        }
    }

    struct ErrorLoadStatePlugin;

    #[async_trait]
    impl EliHookSpec for ErrorLoadStatePlugin {
        fn plugin_name(&self) -> &str {
            "error-load-state"
        }

        async fn load_state(
            &self,
            _message: &Envelope,
            _session_id: &str,
        ) -> Result<Option<State>, HookError> {
            Err(HookError::Plugin {
                plugin: "error-load-state".into(),
                hook_point: "load_state",
                source: anyhow::anyhow!("state unavailable"),
            })
        }
    }

    #[tokio::test]
    async fn test_call_load_state_propagates_panic_as_error() {
        let rt = HookRuntime::new(vec![Arc::new(PanicLoadStatePlugin) as Arc<dyn EliHookSpec>]);
        let msg = json!({"content": "hello"});
        let result = rt.call_load_state(&msg, "s1").await;
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), HookError::Panic(ref name) if name == "panic-load-state")
        );
    }

    #[tokio::test]
    async fn test_call_load_state_propagates_plugin_error() {
        let rt = HookRuntime::new(vec![Arc::new(ErrorLoadStatePlugin) as Arc<dyn EliHookSpec>]);
        let msg = json!({"content": "hello"});
        let result = rt.call_load_state(&msg, "s1").await;
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), HookError::Plugin { ref hook_point, .. } if *hook_point == "load_state")
        );
    }

    // -- call_run_model error/panic handling ----------------------------------

    struct PanicRunModelPlugin;

    #[async_trait]
    impl EliHookSpec for PanicRunModelPlugin {
        fn plugin_name(&self) -> &str {
            "panic-run-model"
        }

        async fn run_model(
            &self,
            _prompt: &PromptValue,
            _session_id: &str,
            _state: &State,
        ) -> Result<Option<String>, HookError> {
            panic!("run_model panic");
        }
    }

    struct ErrorRunModelPlugin;

    #[async_trait]
    impl EliHookSpec for ErrorRunModelPlugin {
        fn plugin_name(&self) -> &str {
            "error-run-model"
        }

        async fn run_model(
            &self,
            _prompt: &PromptValue,
            _session_id: &str,
            _state: &State,
        ) -> Result<Option<String>, HookError> {
            Err(HookError::Plugin {
                plugin: "error-run-model".into(),
                hook_point: "run_model",
                source: anyhow::anyhow!("model unavailable"),
            })
        }
    }

    #[tokio::test]
    async fn test_call_run_model_propagates_panic_as_error() {
        let rt = HookRuntime::new(vec![Arc::new(PanicRunModelPlugin) as Arc<dyn EliHookSpec>]);
        let prompt = PromptValue::Text("hello".into());
        let state = State::new();
        let result = rt.call_run_model(&prompt, "s1", &state).await;
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), HookError::Panic(ref name) if name == "panic-run-model")
        );
    }

    #[tokio::test]
    async fn test_call_run_model_propagates_plugin_error() {
        let rt = HookRuntime::new(vec![Arc::new(ErrorRunModelPlugin) as Arc<dyn EliHookSpec>]);
        let prompt = PromptValue::Text("hello".into());
        let state = State::new();
        let result = rt.call_run_model(&prompt, "s1", &state).await;
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), HookError::Plugin { ref hook_point, .. } if *hook_point == "run_model")
        );
    }

    // -- call_build_user_prompt panic skipping ------------------------------------

    struct PanicBuildPromptPlugin;

    #[async_trait]
    impl EliHookSpec for PanicBuildPromptPlugin {
        fn plugin_name(&self) -> &str {
            "panic-build-prompt"
        }

        async fn build_user_prompt(
            &self,
            _message: &Envelope,
            _session_id: &str,
            _state: &State,
        ) -> Option<PromptValue> {
            panic!("build_user_prompt panic");
        }
    }

    struct BuildPromptFallbackPlugin;

    #[async_trait]
    impl EliHookSpec for BuildPromptFallbackPlugin {
        fn plugin_name(&self) -> &str {
            "build-prompt-fallback"
        }

        async fn build_user_prompt(
            &self,
            _message: &Envelope,
            _session_id: &str,
            _state: &State,
        ) -> Option<PromptValue> {
            Some(PromptValue::Text("fallback-prompt".into()))
        }
    }

    #[tokio::test]
    async fn test_call_build_user_prompt_skips_panicking_plugin() {
        // PanicBuildPromptPlugin registered last (highest priority, tried first in reversed).
        // It panics → skipped. BuildPromptFallbackPlugin tried next → returns Some.
        let rt = HookRuntime::new(vec![
            Arc::new(BuildPromptFallbackPlugin) as Arc<dyn EliHookSpec>,
            Arc::new(PanicBuildPromptPlugin),
        ]);
        let msg = json!({"content": "hello"});
        let state = State::new();
        let result = rt.call_build_user_prompt(&msg, "s1", &state).await;
        assert!(result.is_some());
        assert_eq!(result.unwrap().as_text(), "fallback-prompt");
    }
}