rpi-extensions 0.3.23

Rust-native (cdylib) plugin loader + AgentTool adapter for rpi — libloading + spawn_blocking ABI bridge
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
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
//! `AgentEvent → StablePluginEvent` translation, plus the [`ExtensionEmitter`]
//! that impls [`AgentEmitter`] by subscribing to the host's
//! `broadcast::Sender<AgentEvent>`, folding each event into a stable event, and
//! fan-out dispatching to every registered handler for the event's tag — all
//! dispatch wrapped in `catch_unwind` (a panicky plugin handler must not unwind
//! across FFI).
//!
//! The 10 stable lifecycle `AgentEvent` variants fold into their matching
//! `StablePluginEvent` tags. Internal host events such as retry scheduling are
//! intentionally not projected onto the fixed 33-tag plugin ABI.

use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;

use futures::future::BoxFuture;
use rpi_agent::events::{AgentEmitter, AgentEvent};
use rpi_plugin_sdk::{EventTag, StablePluginEvent, StbString};

use crate::host_free_string;
use crate::registry::RegistrySnapshot;

/// Map a native [`AgentEvent`] to its pi `on()` [`EventTag`], or `None` if the
/// host event has no stable-event counterpart. This is the **fold** described
/// in the crate docs: the ten stable lifecycle variants map onto matching tags;
/// internal retry scheduling stays host-only, and the rest of the 33-category
/// surface is driven by direct host emission in B3+.
pub fn event_tag_for(event: &AgentEvent) -> Option<EventTag> {
    match event {
        AgentEvent::AgentStart => Some(EventTag::AgentStart),
        AgentEvent::AgentEnd { .. } => Some(EventTag::AgentEnd),
        AgentEvent::RetryScheduled { .. } => None,
        AgentEvent::TurnStart => Some(EventTag::TurnStart),
        AgentEvent::TurnEnd { .. } => Some(EventTag::TurnEnd),
        AgentEvent::MessageStart { .. } => Some(EventTag::MessageStart),
        AgentEvent::MessageUpdate { .. } => Some(EventTag::MessageUpdate),
        AgentEvent::MessageEnd { .. } => Some(EventTag::MessageEnd),
        AgentEvent::ToolExecutionStart { .. } => Some(EventTag::ToolExecutionStart),
        AgentEvent::ToolExecutionUpdate { .. } => Some(EventTag::ToolExecutionUpdate),
        AgentEvent::ToolExecutionEnd { .. } => Some(EventTag::ToolExecutionEnd),
    }
}

/// Serialize an [`AgentMessage`](rpi_agent::message::AgentMessage) to an owning
/// `StbString` for a message-payload event. The host produced this string, so
/// the **handler** (plugin side) frees it via the host's `free_string`.
fn message_to_stb(message: &rpi_agent::message::AgentMessage) -> StbString {
    // AgentMessage is Serialize (#[serde(tag="kind")]); use serde_json round-trip.
    let text = serde_json::to_string(message).unwrap_or_else(|_| "null".to_string());
    StbString::from_string(text)
}

/// Build the stable event for an `AgentEvent`, or `None` if the event carries
/// no payload that maps onto a stable variant (always maps today, but kept as
/// `Option` for forward-compat with unmapped future variants). Ownership of any
/// `StbString` in the returned event passes to the handler.
pub fn translate(event: &AgentEvent) -> Option<StablePluginEvent> {
    let tag = event_tag_for(event)?;
    match event {
        AgentEvent::MessageStart { message } | AgentEvent::MessageEnd { message } => {
            let stb = message_to_stb(message);
            Some(StablePluginEvent::message(tag, stb))
        }
        AgentEvent::MessageUpdate {
            assistant_message_event,
            ..
        } => {
            // Match native Pi's wire contract: message_update carries the
            // provider event, not a growing message snapshot. Consumers that
            // need live text read assistantMessageEvent.delta directly.
            let payload = assistant_message_event_to_json(assistant_message_event);
            Some(StablePluginEvent::message(
                tag,
                StbString::from_string(payload),
            ))
        }

        AgentEvent::ToolExecutionStart {
            tool_call_id,
            tool_name,
            args,
        }
        | AgentEvent::ToolExecutionUpdate {
            tool_call_id,
            tool_name,
            args,
            ..
        } => Some(StablePluginEvent::tool_call(
            tag,
            StbString::from_string(tool_call_id.clone()),
            StbString::from_string(tool_name.clone()),
            StbString::from_string(serde_json::to_string(args).unwrap_or_else(|_| "null".into())),
        )),

        AgentEvent::ToolExecutionEnd {
            tool_call_id,
            tool_name,
            result,
            is_error,
        } => {
            // Serialize the AgentToolResult to JSON for the result payload.
            let result_json = agent_tool_result_to_json(result);
            Some(StablePluginEvent::tool_result(
                tag,
                StbString::from_string(tool_call_id.clone()),
                StbString::from_string(tool_name.clone()),
                StbString::from_string(result_json),
                *is_error,
            ))
        }

        // No-payload events.
        AgentEvent::AgentStart
        | AgentEvent::TurnStart
        | AgentEvent::AgentEnd { .. }
        | AgentEvent::TurnEnd { .. } => Some(StablePluginEvent::empty(tag)),

        AgentEvent::RetryScheduled { .. } => None,
    }
}

/// Serialize the stream event inside native Pi's `message_update` envelope.
///
/// Do not include `partial`: it is a cumulative snapshot and the native JSON /
/// RPC contract deliberately omits it so consumers process each delta exactly
/// once and stream size stays linear.
fn assistant_message_event_to_json(event: &rpi_ai::types::AssistantMessageEvent) -> String {
    use rpi_ai::types::AssistantMessageEvent as E;

    let value = match event {
        E::TextStart { content_index, .. } => serde_json::json!({
            "type": "text_start",
            "contentIndex": content_index,
        }),
        E::TextDelta {
            content_index,
            delta,
            ..
        } => serde_json::json!({
            "type": "text_delta",
            "contentIndex": content_index,
            "delta": delta,
        }),
        E::TextEnd {
            content_index,
            content,
            ..
        } => serde_json::json!({
            "type": "text_end",
            "contentIndex": content_index,
            "content": content,
        }),
        E::ThinkingStart { content_index, .. } => serde_json::json!({
            "type": "thinking_start",
            "contentIndex": content_index,
        }),
        E::ThinkingDelta {
            content_index,
            delta,
            ..
        } => serde_json::json!({
            "type": "thinking_delta",
            "contentIndex": content_index,
            "delta": delta,
        }),
        E::ThinkingEnd {
            content_index,
            content,
            ..
        } => serde_json::json!({
            "type": "thinking_end",
            "contentIndex": content_index,
            "content": content,
        }),
        E::ToolCallStart { content_index, .. } => serde_json::json!({
            "type": "toolcall_start",
            "contentIndex": content_index,
        }),
        E::ToolCallDelta {
            content_index,
            delta,
            ..
        } => serde_json::json!({
            "type": "toolcall_delta",
            "contentIndex": content_index,
            "delta": delta,
        }),
        E::ToolCallEnd {
            content_index,
            tool_call,
            ..
        } => serde_json::json!({
            "type": "toolcall_end",
            "contentIndex": content_index,
            "toolCall": tool_call,
        }),
        E::Start { .. } | E::Done { .. } | E::Error { .. } => {
            serde_json::json!({ "type": event_type_name(event) })
        }
    };

    serde_json::json!({ "assistantMessageEvent": value }).to_string()
}

fn event_type_name(event: &rpi_ai::types::AssistantMessageEvent) -> &'static str {
    use rpi_ai::types::AssistantMessageEvent as E;
    match event {
        E::Start { .. } => "start",
        E::TextStart { .. } => "text_start",
        E::TextDelta { .. } => "text_delta",
        E::TextEnd { .. } => "text_end",
        E::ThinkingStart { .. } => "thinking_start",
        E::ThinkingDelta { .. } => "thinking_delta",
        E::ThinkingEnd { .. } => "thinking_end",
        E::ToolCallStart { .. } => "toolcall_start",
        E::ToolCallDelta { .. } => "toolcall_delta",
        E::ToolCallEnd { .. } => "toolcall_end",
        E::Done { .. } => "done",
        E::Error { .. } => "error",
    }
}

/// Serialize an `AgentToolResult` to the JSON shape handlers expect (same shape
/// the tool adapter uses). Kept here (not reusing tool.rs's `result_to_stb`)
/// because the emitter must not depend on adapter internals, and this is the
/// event-side direction.
fn agent_tool_result_to_json(result: &rpi_agent::types::AgentToolResult) -> String {
    let mut txt = String::new();
    txt.push('{');
    txt.push_str("\"content\":[");
    for (i, c) in result.content.iter().enumerate() {
        if i > 0 {
            txt.push(',');
        }
        match c {
            rpi_agent::types::TextContentOrImage::Text(t) => {
                txt.push_str(
                    &serde_json::to_string(&serde_json::json!({ "type": "text", "text": t.text }))
                        .unwrap_or_else(|_| "\"\"".into()),
                );
            }
            rpi_agent::types::TextContentOrImage::Image(img) => {
                txt.push_str(
                    &serde_json::to_string(&serde_json::json!({
                        "type": "image",
                        "data": img.data,
                        "mimeType": img.mime_type,
                    }))
                    .unwrap_or_else(|_| "\"\"".into()),
                );
            }
        }
    }
    txt.push(']');
    txt.push_str(",\"details\":");
    txt.push_str(&serde_json::to_string(&result.details).unwrap_or_else(|_| "null".into()));
    txt.push_str(",\"terminate\":");
    txt.push_str(if result.terminate { "true" } else { "false" });
    txt.push_str(",\"addedToolNames\":");
    txt.push_str(&serde_json::to_string(&result.added_tool_names).unwrap_or_else(|_| "[]".into()));
    txt.push('}');
    txt
}

/// Free every `StbString` owned by a dispatched [[`StablePluginEvent`]] via the
/// host's `free_string`. Called after dispatch completes (the handler SHOULD
/// have freed them, but the host keeps ownership-of-cleanup so a buggy plugin
/// that retains/leaks can't double-free the host's allocation — the host never
/// trusts the plugin to free, per the SDK's "receiver owns" contract: here the
/// host is the producer → receiver is the plugin; if the plugin failed to free,
/// the host's free is a leak fix, not a double-free, because `StbString` is
/// `Copy` and the host's `host_free_string` reconstructs the `Box<[u8]>` and
/// drops it — a second free of the same bytes would be UB, so this must run
/// EXACTLY ONCE per event. The contract is: the plugin frees what it receives.
/// To honor that, we do NOT free here; the plugin owns the free. This fn is
/// therefore a no-op kept for documentation + future audit).
///
/// **In practice:** the plugin handler is contractually required to free every
/// `StbString` it receives via the host `free_string`. The host does not
/// double-free. If a plugin leaks, that is a plugin bug.
#[allow(dead_code)]
fn free_event_strings(_event: &StablePluginEvent) {
    // intentionally empty — see doc comment.
}

// ===========================================================================
// ExtensionEmitter — AgentEmitter impl fanning out to plugin handlers
// ===========================================================================

/// An [`AgentEmitter`] that fans each [`AgentEvent`] out to every plugin handler
/// registered for the event's tag. Built from a [`RegistrySnapshot`] (so it
/// shares the registry's staleness flag) and installed into
/// `AgentHarnessOptions.agent_emitter` **alongside** the host's
/// [`BroadcastEmitter`] — events flow to BOTH the TUI (which drains the
/// broadcast receiver) and the plugin handlers (which receive translated
/// `StablePluginEvent`s). The host composes the two via
/// [`TeeEmitter`](super::TeeEmitter); this emitter alone only dispatches to
/// plugins.
///
/// Dispatch is `catch_unwind`-wrapped: a panicking plugin handler is logged and
/// skipped (abort-on-unwind policy would be too aggressive for event dispatch
/// where one bad handler shouldn't kill the session; we log + continue, unlike
/// tool-partial dispatch which aborts because it cannot unwind across FFI from
/// a blocking thread). The distinction: `emit` runs on the async runtime thread
/// where `catch_unwind` can recover cleanly; the tool partial cb runs inside
/// `spawn_blocking` cross-FFI where recovery is unsafe.
pub struct ExtensionEmitter {
    snapshot: Arc<RegistrySnapshot>,
    /// Keeps the loaded cdylibs mapped for as long as this emitter (installed
    /// into `AgentHarnessOptions.agent_emitter`) may dispatch to handler fn
    /// pointers that live inside them. Cloned from the load session; the
    /// libraries unload only when every holder (adapter + emitter) drops.
    #[allow(dead_code)]
    keepalive: Arc<crate::PluginKeepalive>,
}

impl ExtensionEmitter {
    /// Build an emitter over a snapshot. The `keepalive` keeps the cdylibs that
    /// own the snapshot's handler fn pointers mapped for the emitter's lifetime.
    pub fn new(snapshot: Arc<RegistrySnapshot>, keepalive: Arc<crate::PluginKeepalive>) -> Self {
        Self {
            snapshot,
            keepalive,
        }
    }

    /// Dispatch one stable event to all handlers for its tag. Each handler call
    /// is `catch_unwind`-wrapped; errors (nonzero return) are logged but do not
    /// abort the fan-out (one handler's failure doesn't block the others — mir-
    /// rors pi's per-handler try/catch).
    fn dispatch(&self, event: &StablePluginEvent) {
        dispatch_to_handlers(&self.snapshot, event);
    }
}

/// Fan an already-built event out to the tag's handlers (or free it when no
/// handler subscribes). Shared by [`ExtensionEmitter`] and the provider-hook
/// dispatcher ([`crate::provider_hooks`]). Handlers MUST NOT free the event
/// strings; the host frees exactly once after the fan-out.
pub fn dispatch_to_handlers(snapshot: &RegistrySnapshot, event: &StablePluginEvent) {
    // Staleness guard: a stale registry (swapped-out session) does nothing.
    if !crate::registry::assert_active(snapshot.active_flag()) {
        return;
    }
    let handlers = snapshot.handlers_for(event.tag);
    if handlers.is_empty() {
        // No subscribers — and critically, the event's StbStrings are owned
        // by the host and must still be freed (no handler ran to free them).
        free_dispatched_event(event);
        return;
    }
    for h in handlers {
        // P2: skip a handler whose plugin declared platforms excluding this host.
        if !crate::registry::platform_allows(&h.platforms) {
            crate::event_log::log_handler_invocation(
                event.tag,
                &h.plugin,
                "PlatformSkip",
                0,
                Some(format!("host={}", crate::registry::current_platform())),
            );
            continue;
        }
        // SAFETY: the plugin warrants `handler` + `user_data` are safe to
        // call from this thread. catch_unwind so a panic cannot cross FFI.
        let started = std::time::Instant::now();
        let outcome = catch_unwind(AssertUnwindSafe(|| (h.handler)(*event, h.user_data)));
        let duration_ms = started.elapsed().as_millis() as u64;
        match outcome {
            // `CLAIMED` from an ordinary observe dispatch is not an error — the
            // handler simply consumed the event. Only routing dispatchers act on
            // it (`dispatch_data_event_claiming`).
            Ok(rc) if rc == rpi_plugin_sdk::EVENT_HANDLER_CLAIMED => {
                crate::event_log::log_handler_invocation(
                    event.tag,
                    &h.plugin,
                    "Claimed",
                    duration_ms,
                    None,
                );
            }
            Ok(rc) if rc != 0 => {
                tracing::warn!(tag = ?event.tag, rc, "extension event handler returned nonzero");
                crate::event_log::log_handler_invocation(
                    event.tag,
                    &h.plugin,
                    "Error",
                    duration_ms,
                    Some(format!("rc={rc}")),
                );
            }
            Ok(_) => {
                crate::event_log::log_handler_invocation(
                    event.tag,
                    &h.plugin,
                    "Continue",
                    duration_ms,
                    None,
                );
            }
            Err(_) => {
                tracing::error!(tag = ?event.tag, "extension event handler panicked — skipped");
                crate::event_log::log_handler_invocation(
                    event.tag,
                    &h.plugin,
                    "Panic",
                    duration_ms,
                    None,
                );
            }
        }
    }
    // Host frees the event's strings exactly once after the fan-out.
    free_dispatched_event(event);
}

/// Build + dispatch a generic `data` event (JSON payload) to the tag's
/// handlers. Returns whether any handler was invoked. Used by the B4
/// provider-hook observer path ([`crate::provider_hooks`]) which has no
/// matching `AgentEvent` to translate.
pub fn dispatch_data_event(snapshot: &RegistrySnapshot, tag: EventTag, data: &str) -> bool {
    let handlers = snapshot.handlers_for(tag);
    if handlers.is_empty() {
        return false;
    }
    let event = StablePluginEvent::data(tag, StbString::from_string(data.to_string()));
    dispatch_to_handlers(snapshot, &event);
    true
}

/// Build + dispatch a **no-payload** event (e.g. `session_start`, `session_shutdown`,
/// the rpi-specific `before_tui_start`) to the tag's handlers. Returns whether any
/// handler was invoked. Mirrors [`dispatch_data_event`] for events whose payload
/// is `EventEmpty`; a handler that subscribes to a no-payload tag receives the
/// event with an empty payload.
pub fn dispatch_empty_event(snapshot: &RegistrySnapshot, tag: EventTag) -> bool {
    let handlers = snapshot.handlers_for(tag);
    if handlers.is_empty() {
        return false;
    }
    let event = StablePluginEvent::empty(tag);
    dispatch_to_handlers(snapshot, &event);
    true
}

/// Timeout budget for a `ToolCall` approval dispatch. Generous because the
/// handler may wait on a human (e.g. an ACP `session/request_permission`).
pub const TOOL_CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);

/// Dispatch a tool approval against a live session. Only a successful continue
/// permits execution; stale sessions, cancellation, timeout and handler errors
/// block it. Blocking callbacks retain the plugin libraries until they return,
/// even when the async caller has already stopped waiting.
pub async fn dispatch_tool_call_event(
    session: &crate::ExtensionSession,
    tool_call_id: &str,
    tool_name: &str,
    params: &serde_json::Value,
    signal: &tokio_util::sync::CancellationToken,
    ui_dialog: &crate::UiDialogMailbox,
) -> Option<String> {
    dispatch_tool_call_event_with_timeout(
        session,
        tool_call_id,
        tool_name,
        params,
        signal,
        ui_dialog,
        TOOL_CALL_TIMEOUT,
    )
    .await
}

async fn dispatch_tool_call_event_with_timeout(
    session: &crate::ExtensionSession,
    tool_call_id: &str,
    tool_name: &str,
    params: &serde_json::Value,
    signal: &tokio_util::sync::CancellationToken,
    ui_dialog: &crate::UiDialogMailbox,
    timeout: std::time::Duration,
) -> Option<String> {
    let snapshot = session.snapshot()?;
    if !crate::registry::assert_active(snapshot.active_flag()) {
        return Some(format!(
            "tool `{tool_name}` approval session is stale; retry after reload"
        ));
    }
    for h in snapshot.handlers_for(EventTag::ToolCall).iter().cloned() {
        if !crate::registry::platform_allows(&h.platforms) {
            continue;
        }
        if signal.is_cancelled() {
            ui_dialog.cancel_tool_call(tool_call_id);
            return Some(format!("tool `{tool_name}` approval cancelled"));
        }
        if !crate::registry::assert_active(snapshot.active_flag()) {
            return Some(format!(
                "tool `{tool_name}` approval session is stale; retry after reload"
            ));
        }
        let plugin_name = h.plugin.clone();
        let id = tool_call_id.to_string();
        let name = tool_name.to_string();
        let payload = params.to_string();
        let keepalive = session.keepalive();
        let started = std::time::Instant::now();
        // Capture the whole RegisteredHandler rather than its raw user_data.
        // The callback's own keepalive also survives timeout/cancellation.
        let mut task = tokio::task::spawn_blocking(move || {
            let _keepalive = keepalive;
            call_tool_call_handler(h, id, name, payload)
        });
        let outcome = tokio::select! {
            biased;
            _ = signal.cancelled() => {
                task.abort(); // Prevent a queued callback from starting.
                ui_dialog.cancel_tool_call(tool_call_id);
                crate::event_log::log_handler_invocation(
                    EventTag::ToolCall, &plugin_name, "Cancelled",
                    started.elapsed().as_millis() as u64, None,
                );
                return Some(format!("tool `{tool_name}` approval cancelled"));
            }
            outcome = tokio::time::timeout(timeout, &mut task) => outcome,
        };
        let duration_ms = started.elapsed().as_millis() as u64;
        let (status, error) = match outcome {
            Ok(Ok(Ok(rc))) if rc == rpi_plugin_sdk::EVENT_HANDLER_CONTINUE => ("Continue", None),
            Ok(Ok(Ok(rc))) if rc == rpi_plugin_sdk::EVENT_HANDLER_ABORT => (
                "Abort",
                Some(format!(
                    "extension `{plugin_name}` blocked tool `{tool_name}`"
                )),
            ),
            Ok(Ok(Ok(rc))) => (
                "Error",
                Some(format!(
                    "extension `{plugin_name}` tool `{tool_name}` approval failed: rc={rc}"
                )),
            ),
            Ok(Ok(Err(_))) => (
                "Panic",
                Some(format!(
                    "extension `{plugin_name}` tool `{tool_name}` approval panicked"
                )),
            ),
            Ok(Err(error)) => (
                "JoinFailed",
                Some(format!(
                    "extension `{plugin_name}` tool `{tool_name}` approval task failed: {error}"
                )),
            ),
            Err(_) => {
                task.abort();
                (
                    "Timeout",
                    Some(format!(
                        "extension `{plugin_name}` tool `{tool_name}` approval timed out"
                    )),
                )
            }
        };
        crate::event_log::log_handler_invocation(
            EventTag::ToolCall,
            &plugin_name,
            status,
            duration_ms,
            error.clone(),
        );
        if let Some(reason) = error {
            ui_dialog.cancel_tool_call(tool_call_id);
            return Some(reason);
        }
        // A reload can invalidate this session while the callback is running.
        if !crate::registry::assert_active(snapshot.active_flag()) {
            ui_dialog.cancel_tool_call(tool_call_id);
            return Some(format!(
                "tool `{tool_name}` approval session is stale; retry after reload"
            ));
        }
    }
    None
}

/// Like [`dispatch_data_event`], but reports whether a handler **claimed** the
/// event by returning [`EVENT_HANDLER_CLAIMED`].
///
/// This exists for input routing: the TUI asks extensions "is this key yours?"
/// and must know whether to swallow the key (skip the editor) or pass it
/// through. A handler that subscribes but is currently inactive (e.g.
/// push-to-talk toggled off) returns the ordinary continue code and the key
/// falls through to normal editor handling.
///
/// Every handler is still invoked (fan-out is not short-circuited) so a later
/// handler can disagree; the event is considered claimed if **any** returned
/// [`EVENT_HANDLER_CLAIMED`].
pub fn dispatch_data_event_claiming(
    snapshot: &RegistrySnapshot,
    tag: EventTag,
    data: &str,
) -> bool {
    if !crate::registry::assert_active(snapshot.active_flag()) {
        return false;
    }
    let handlers = snapshot.handlers_for(tag);
    if handlers.is_empty() {
        return false;
    }
    let event = StablePluginEvent::data(tag, StbString::from_string(data.to_string()));
    let mut claimed = false;
    for h in handlers {
        if !crate::registry::platform_allows(&h.platforms) {
            continue;
        }
        // SAFETY: as in `dispatch_to_handlers` — the plugin warrants the handler
        // and its user_data are safe to call from this thread.
        let outcome = catch_unwind(AssertUnwindSafe(|| (h.handler)(event, h.user_data)));
        match outcome {
            Ok(rc) if rc == rpi_plugin_sdk::EVENT_HANDLER_CLAIMED => claimed = true,
            Ok(rc) if rc != 0 => {
                tracing::warn!(tag = ?tag, rc, "extension event handler returned nonzero");
            }
            Err(_) => {
                tracing::error!(tag = ?tag, "extension event handler panicked — skipped");
            }
            Ok(_) => {}
        }
    }
    free_dispatched_event(&event);
    claimed
}

/// Per-lifecycle-event handler timeout budget (see docs/extensions/lifecycle.md):
/// startup 5s, session shutdown 15s, everything else 10s. A handler that
/// exceeds its budget is logged + skipped (it keeps running on its blocking
/// thread, but no longer gates startup/shutdown).
pub fn lifecycle_timeout_for(tag: EventTag) -> std::time::Duration {
    use rpi_plugin_sdk::EventTag as T;
    match tag {
        T::BeforeTuiStart => std::time::Duration::from_secs(5),
        T::SessionShutdown => std::time::Duration::from_secs(15),
        _ => std::time::Duration::from_secs(10),
    }
}

/// Invoke one no-payload lifecycle handler, catching unwinds at the FFI boundary.
///
/// Takes [`RegisteredHandler`](crate::registry::RegisteredHandler) **by value**
/// so the caller's `spawn_blocking` closure captures the whole struct (which has
/// `unsafe impl Send`) rather than its disjoint fields: `user_data` is a raw
/// `*mut c_void` and is NOT `Send` on its own (Rust 2021 disjoint closure
/// capture would otherwise move the raw pointer directly into the closure env
/// and fail the `Send` bound).
fn call_lifecycle_handler(
    h: crate::registry::RegisteredHandler,
    tag: EventTag,
) -> std::thread::Result<i32> {
    let event = StablePluginEvent::empty(tag);
    // SAFETY: the plugin warrants `h.handler` + `h.user_data` are safe to call
    // from any thread; catch_unwind so a panic cannot cross FFI.
    catch_unwind(AssertUnwindSafe(|| (h.handler)(event, h.user_data)))
}

/// Invoke one `ToolCall` handler on a blocking thread. Takes the whole
/// [`RegisteredHandler`](crate::registry::RegisteredHandler) **by value** for the
/// same `Send` reason as [`call_lifecycle_handler`]: the closure must capture the
/// `Send` struct whole, not its non-`Send` `user_data` field. Builds and frees
/// the tool-call event on this thread (a `StablePluginEvent` holds raw pointers).
fn call_tool_call_handler(
    h: crate::registry::RegisteredHandler,
    tool_call_id: String,
    tool_name: String,
    params: String,
) -> std::thread::Result<i32> {
    let event = StablePluginEvent::tool_call(
        EventTag::ToolCall,
        StbString::from_string(tool_call_id),
        StbString::from_string(tool_name),
        StbString::from_string(params),
    );
    // SAFETY: the plugin warrants `h.handler` + `h.user_data` are safe to call
    // from any thread; catch_unwind so a panic cannot cross FFI.
    let rc = catch_unwind(AssertUnwindSafe(|| (h.handler)(event, h.user_data)));
    free_dispatched_event(&event);
    rc
}

/// Veto-aware, timeout-bounded dispatch for a **no-payload lifecycle event**
/// (`BeforeTuiStart` / `SessionStart` / `SessionShutdown`).
///
/// Unlike [`dispatch_empty_event`] (fire-and-forget observe fan-out), this:
///
/// 1. Runs each handler on a blocking thread with a per-event timeout
///    ([`lifecycle_timeout_for`]) — a hung handler is logged + skipped, it
///    does not stall startup or shutdown.
/// 2. Honors the SDK's [`EVENT_HANDLER_ABORT`] veto code: the first handler to
///    return it stops the fan-out and this returns `Some(reason)`.
///
/// Returns `None` when no handler vetoed (continue the lifecycle); `Some` when
/// a handler aborted. A stale registry (swapped-out session) returns `None`.
/// The **caller** decides what a veto means for the phase — e.g. a
/// `BeforeTuiStart` veto aborts startup before the TUI initializes.
pub async fn dispatch_lifecycle_event(
    snapshot: &RegistrySnapshot,
    tag: EventTag,
) -> Option<String> {
    // Staleness guard: a stale registry (swapped-out session) does nothing.
    if !crate::registry::assert_active(snapshot.active_flag()) {
        return None;
    }
    let handlers = snapshot.handlers_for(tag).to_vec();
    if handlers.is_empty() {
        return None;
    }
    // Lifecycle tags are no-payload: the event is `EventEmpty`. We build it
    // inside the helper (via `spawn_blocking`) so the closure env only carries
    // Send values.
    let timeout = lifecycle_timeout_for(tag);
    for h in handlers {
        // P2: skip a handler whose plugin declared platforms excluding this host.
        if !crate::registry::platform_allows(&h.platforms) {
            crate::event_log::log_handler_invocation(
                tag,
                &h.plugin,
                "PlatformSkip",
                0,
                Some(format!("host={}", crate::registry::current_platform())),
            );
            continue;
        }
        // Capture the owning extension's display name for the veto message
        // before the handler is moved into the blocking closure.
        let plugin_name = h.plugin.clone();
        let h_task = h;
        let tag_task = tag;
        let started = std::time::Instant::now();
        let outcome = tokio::time::timeout(
            timeout,
            tokio::task::spawn_blocking(move || call_lifecycle_handler(h_task, tag_task)),
        )
        .await;
        let duration_ms = started.elapsed().as_millis() as u64;
        match outcome {
            Ok(Ok(Ok(rc))) if rc == rpi_plugin_sdk::EVENT_HANDLER_ABORT => {
                tracing::warn!(
                    tag = ?tag,
                    plugin = %plugin_name,
                    "extension handler vetoed lifecycle event"
                );
                crate::event_log::log_handler_invocation(
                    tag,
                    &plugin_name,
                    "Abort",
                    duration_ms,
                    None,
                );
                return Some(format!("extension `{plugin_name}` vetoed {tag:?}"));
            }
            Ok(Ok(Ok(rc))) => {
                let result = if rc == 0 { "Continue" } else { "Error" };
                crate::event_log::log_handler_invocation(
                    tag,
                    &plugin_name,
                    result,
                    duration_ms,
                    if rc == 0 {
                        None
                    } else {
                        Some(format!("rc={rc}"))
                    },
                );
            }
            Ok(Ok(Err(_))) => {
                tracing::error!(tag = ?tag, "extension handler panicked — skipped");
                crate::event_log::log_handler_invocation(
                    tag,
                    &plugin_name,
                    "Panic",
                    duration_ms,
                    None,
                );
            }
            Ok(Err(join_err)) => {
                tracing::error!(
                    tag = ?tag,
                    error = %join_err,
                    "extension handler task join failed — skipped"
                );
                crate::event_log::log_handler_invocation(
                    tag,
                    &plugin_name,
                    "JoinFailed",
                    duration_ms,
                    Some(join_err.to_string()),
                );
            }
            Err(_elapsed) => {
                tracing::warn!(
                    tag = ?tag,
                    timeout_ms = timeout.as_millis(),
                    "extension handler timed out — skipped (still running on its blocking thread)"
                );
                crate::event_log::log_handler_invocation(
                    tag,
                    &plugin_name,
                    "Timeout",
                    duration_ms,
                    Some(format!("budget_ms={}", timeout.as_millis())),
                );
            }
        }
    }
    None
}

impl AgentEmitter for ExtensionEmitter {
    fn emit(&self, event: AgentEvent) -> BoxFuture<'static, ()> {
        // Translate + dispatch synchronously (the emitter's emit is awaited by
        // the loop in event order; dispatch is non-blocking fn-pointer calls).
        // If the event maps to no tag, do nothing.
        if let Some(stable) = translate(&event) {
            self.dispatch(&stable);
        }
        Box::pin(async {})
    }

    fn try_emit(&self, event: AgentEvent) {
        if let Some(stable) = translate(&event) {
            self.dispatch(&stable);
        }
    }
}

// ===========================================================================
// TeeEmitter — fan an AgentEvent out to N AgentEmitters (host + plugins)
// ===========================================================================

/// An [`AgentEmitter`] that forwards every event to each of its children, in
/// registration order. The host builds one around `[BroadcastEmitter (→ TUI),
/// ExtensionEmitter (→ plugin handlers)]` so a single `AgentHarnessOptions
/// .agent_emitter` slot feeds both consumers: the TUI keeps rendering from its
/// broadcast receiver, and plugin `on()` handlers receive translated
/// `StablePluginEvent`s.
///
/// `emit` awaits each child in turn (the loop awaits `emit`, so order matches
/// registration); `try_emit` calls each child's `try_emit` (the tool
/// `on_update` path — non-blocking). A child that panics is isolated by the
/// child's own `catch_unwind` where applicable (the `ExtensionEmitter` does);
/// the `BroadcastEmitter` cannot panic (it's a `tx.send`). We do NOT wrap the
/// fan-out itself in `catch_unwind` — each child is responsible for its own
/// soundness, and a generic wrapper would mask a child's contract violation.
pub struct TeeEmitter {
    emitters: Vec<Arc<dyn AgentEmitter>>,
}

impl TeeEmitter {
    /// Build a tee over the given emitters. Order is preserved: `emit`/`try_emit`
    /// visit them front-to-back. A single-child tee is a trivial passthrough
    /// (the host uses that when no extensions loaded, so the code path is
    /// uniform).
    pub fn new(emitters: Vec<Arc<dyn AgentEmitter>>) -> Self {
        Self { emitters }
    }
}

impl AgentEmitter for TeeEmitter {
    fn emit(&self, event: AgentEvent) -> BoxFuture<'static, ()> {
        // We can't hold `&self` across an await boundary into a 'static future
        // cheaply here without cloning the Arcs — so clone them and drive the
        // fan-out inside a pinned async block. Each child's emit returns a
        // no-op future (both BroadcastEmitter and ExtensionEmitter complete
        // synchronously), so this is effectively a synchronous loop in practice.
        let emitters = self.emitters.clone();
        Box::pin(async move {
            for e in &emitters {
                e.emit(event.clone()).await;
            }
        })
    }

    fn try_emit(&self, event: AgentEvent) {
        for e in &self.emitters {
            e.try_emit(event.clone());
        }
    }
}

/// Free every owning `StbString` in a dispatched event exactly once via the
/// host's `free_string`. Called by [`ExtensionEmitter::dispatch`] after the
/// fan-out completes. Handlers MUST NOT free event strings (host owns cleanup).
fn free_dispatched_event(event: &StablePluginEvent) {
    use rpi_plugin_sdk::EventTag as T;
    match event.tag {
        T::MessageStart | T::MessageUpdate | T::MessageEnd => {
            // SAFETY: tag matches the message variant.
            unsafe { host_free_string(event.payload.message.message) };
        }
        T::ToolCall | T::ToolExecutionStart | T::ToolExecutionUpdate => {
            // SAFETY: tag matches the tool_call variant.
            unsafe {
                let tc = &event.payload.tool_call;
                host_free_string(tc.tool_call_id);
                host_free_string(tc.tool_name);
                host_free_string(tc.params);
            }
        }
        T::ToolResult | T::ToolExecutionEnd => {
            // SAFETY: tag matches the tool_result variant.
            unsafe {
                let tr = &event.payload.tool_result;
                host_free_string(tr.tool_call_id);
                host_free_string(tr.tool_name);
                host_free_string(tr.result);
            }
        }
        T::ProjectTrust
        | T::ResourcesDiscover
        | T::SessionStart
        | T::SessionInfoChanged
        | T::SessionBeforeSwitch
        | T::SessionBeforeFork
        | T::SessionBeforeCompact
        | T::SessionCompact
        | T::SessionShutdown
        | T::SessionBeforeTree
        | T::SessionTree
        | T::Context
        | T::BeforeAgentStart
        | T::AgentStart
        | T::AgentEnd
        | T::AgentSettled
        | T::TurnStart
        | T::TurnEnd
        | T::ModelSelect
        | T::ThinkingLevelSelect
        | T::UserBash
        | T::BeforeTuiStart
        | T::UiPromptStart
        | T::UiPromptEnd => {
            // no payload today.
        }
        // The B4 provider-hook observer events, and the `Input` /`EditorChange`
        // events dispatched by the TUI, carry a generic data payload (built by
        // `dispatch_data_event`); free the single StbString.
        T::BeforeProviderRequest
        | T::BeforeProviderHeaders
        | T::AfterProviderResponse
        | T::Input
        | T::EditorChange => {
            // SAFETY: these tags are only ever constructed as data payloads.
            unsafe { host_free_string(event.payload.data.data) };
        }
    }
}

// SAFETY note on the `unsafe { host_free_string(...) }` calls above:
// Each arm selects the initialized union payload and transfers its live
// host-produced allocation to host_free_string exactly once. Both the union
// access and the deallocator's ownership contract require this boundary.

#[cfg(test)]
mod tests {
    use super::*;
    use rpi_agent::message::AgentMessage;
    use rpi_agent::types::AgentToolResult;
    use rpi_ai::types::{AssistantMessage, AssistantMessageEvent, Usage};
    use rpi_plugin_sdk::EventTag;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Mutex;

    // The two handler-fan-out tests share the process-global `HANDLER_HITS`
    // counter (the handler is an `extern "C" fn` that can't capture per-test
    // state). Parallel #[test] execution would have one test's `store(0)`
    // wipe the other's in-flight increment. Hold this lock for the ENTIRE
    // body of both tests so their reset/dispatch windows don't overlap. The
    // dispatch is synchronous (fn-pointer calls), so the guard is released
    // before the test returns — no handler outlives the test.
    static HANDLER_TEST_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn all_ten_agent_events_map_to_a_tag() {
        let am = AgentMessage::Assistant(Box::new(AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![rpi_ai::types::Content::text("hi")],
            api: rpi_ai::types::Api::AnthropicMessages,
            provider: "anthropic".to_string(),
            model: "m".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: rpi_ai::types::StopReason::Stop,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        }));
        let events = vec![
            AgentEvent::AgentStart,
            AgentEvent::AgentEnd { messages: vec![] },
            AgentEvent::TurnStart,
            AgentEvent::TurnEnd {
                message: am.clone(),
                tool_results: vec![],
            },
            AgentEvent::MessageStart {
                message: am.clone(),
            },
            AgentEvent::MessageUpdate {
                // `MessageUpdate` carries the shared partial snapshot, so build
                // the same `Arc` the provider would have handed over.
                message: std::sync::Arc::new((*am.as_assistant().unwrap()).clone()),
                assistant_message_event: rpi_ai::types::AssistantMessageEvent::Start {
                    partial: std::sync::Arc::new((*am.as_assistant().unwrap()).clone()),
                },
            },
            AgentEvent::MessageEnd { message: am },
            AgentEvent::ToolExecutionStart {
                tool_call_id: "c1".into(),
                tool_name: "echo".into(),
                args: serde_json::json!({}),
            },
            AgentEvent::ToolExecutionUpdate {
                tool_call_id: "c1".into(),
                tool_name: "echo".into(),
                args: serde_json::json!({}),
                partial_result: std::sync::Arc::new(AgentToolResult::text("...")),
            },
            AgentEvent::ToolExecutionEnd {
                tool_call_id: "c1".into(),
                tool_name: "echo".into(),
                result: AgentToolResult::text("done"),
                is_error: false,
            },
        ];
        for e in &events {
            assert!(
                event_tag_for(e).is_some(),
                "event {:?} should map",
                e.type_tag()
            );
        }
        // Spot-check the fold targets.
        assert_eq!(event_tag_for(&events[0]), Some(EventTag::AgentStart));
        assert_eq!(event_tag_for(&events[2]), Some(EventTag::TurnStart));
        assert_eq!(
            event_tag_for(&events[7]),
            Some(EventTag::ToolExecutionStart)
        );
        assert!(event_tag_for(&AgentEvent::RetryScheduled {
            attempt: 1,
            max_retries: 10,
            delay_ms: 2_000,
            error: "503".into(),
        })
        .is_none());
    }

    #[test]
    fn translate_message_update_forwards_native_text_deltas_without_snapshot() {
        let partial = Arc::new(AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![rpi_ai::types::Content::text("你好世界")],
            api: rpi_ai::types::Api::AnthropicMessages,
            provider: "anthropic".to_string(),
            model: "m".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: rpi_ai::types::StopReason::Pending,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        });
        let translate_delta = |delta: &str| {
            let event = AgentEvent::MessageUpdate {
                message: Arc::clone(&partial),
                assistant_message_event: AssistantMessageEvent::TextDelta {
                    content_index: 0,
                    delta: delta.to_string(),
                    partial: Arc::clone(&partial),
                },
            };
            let stable = translate(&event).expect("message_update maps");
            let payload = unsafe { stable.payload.message.message.to_string_lossy() };
            unsafe { host_free_string(stable.payload.message.message) };
            serde_json::from_str::<serde_json::Value>(&payload).expect("valid payload")
        };

        let first = translate_delta("你好");
        let second = translate_delta("世界");
        assert_eq!(first["assistantMessageEvent"]["type"], "text_delta");
        assert_eq!(first["assistantMessageEvent"]["contentIndex"], 0);
        assert_eq!(first["assistantMessageEvent"]["delta"], "你好");
        assert_eq!(second["assistantMessageEvent"]["delta"], "世界");
        assert!(first.get("message").is_none());
        assert!(first["assistantMessageEvent"].get("partial").is_none());
    }

    #[test]
    fn translate_message_end_produces_message_payload() {
        let am = AgentMessage::Assistant(Box::new(AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![rpi_ai::types::Content::text("hi")],
            api: rpi_ai::types::Api::AnthropicMessages,
            provider: "anthropic".to_string(),
            model: "m".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: rpi_ai::types::StopReason::Stop,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        }));
        let ev = AgentEvent::MessageEnd { message: am };
        let stable = translate(&ev).expect("maps");
        assert_eq!(stable.tag, EventTag::MessageEnd);
        // free the payload string (host owns cleanup).
        // SAFETY: tag == MessageEnd.
        unsafe { host_free_string(stable.payload.message.message) };
    }

    // --- an emitter fan-out test with an in-process handler -----------------

    static HANDLER_HITS: AtomicUsize = AtomicUsize::new(0);

    extern "C" fn counting_handler(_ev: StablePluginEvent, _ud: *mut std::ffi::c_void) -> i32 {
        HANDLER_HITS.fetch_add(1, Ordering::SeqCst);
        0
    }

    #[test]
    fn emitter_dispatches_to_registered_handlers() {
        let _guard = HANDLER_TEST_LOCK.lock().unwrap();
        HANDLER_HITS.store(0, Ordering::SeqCst);
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "test-plugin".to_string(),
            EventTag::MessageEnd,
            counting_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());
        let emitter = ExtensionEmitter::new(snap, crate::loader::PluginKeepalive::empty());

        let am = AgentMessage::Assistant(Box::new(AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![rpi_ai::types::Content::text("hi")],
            api: rpi_ai::types::Api::AnthropicMessages,
            provider: "anthropic".to_string(),
            model: "m".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: rpi_ai::types::StopReason::Stop,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        }));
        // Use try_emit (sync) — no runtime needed.
        emitter.try_emit(AgentEvent::MessageEnd { message: am });
        assert_eq!(HANDLER_HITS.load(Ordering::SeqCst), 1);

        // Stale registry → no dispatch.
        reg.invalidate();
        let am2 = AgentMessage::Assistant(Box::new(AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![rpi_ai::types::Content::text("hi")],
            api: rpi_ai::types::Api::AnthropicMessages,
            provider: "anthropic".to_string(),
            model: "m".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: rpi_ai::types::StopReason::Stop,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        }));
        emitter.try_emit(AgentEvent::MessageEnd { message: am2 });
        assert_eq!(
            HANDLER_HITS.load(Ordering::SeqCst),
            1,
            "stale registry must not dispatch"
        );
    }

    // --- TeeEmitter: fan-out to both the broadcast + the extension emitter ----

    #[tokio::test]
    async fn tee_emitter_fans_out_to_every_child() {
        let _guard = HANDLER_TEST_LOCK.lock().unwrap();
        use rpi_agent::events::{AgentEmitter, CollectorEmitter};

        // Two collector emitters + record how many plugin handler hits land.
        let (collector_a, events_a) = CollectorEmitter::new();
        let (collector_b, events_b) = CollectorEmitter::new();
        HANDLER_HITS.store(0, Ordering::SeqCst);
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "test-plugin".to_string(),
            EventTag::MessageEnd,
            counting_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());
        let ext = ExtensionEmitter::new(snap, crate::loader::PluginKeepalive::empty());

        let tee = TeeEmitter::new(vec![
            Arc::new(collector_a),
            Arc::new(collector_b),
            Arc::new(ext),
        ]);

        let am = AgentMessage::Assistant(Box::new(AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![rpi_ai::types::Content::text("hi")],
            api: rpi_ai::types::Api::AnthropicMessages,
            provider: "anthropic".to_string(),
            model: "m".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: rpi_ai::types::StopReason::Stop,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        }));
        // Broadcast path: both collectors receive the event, and the extension
        // emitter dispatches to the one registered handler.
        tee.emit(AgentEvent::MessageEnd { message: am }).await;
        assert_eq!(
            events_a.lock().unwrap().len(),
            1,
            "collector A got the event"
        );
        assert_eq!(
            events_b.lock().unwrap().len(),
            1,
            "collector B got the event"
        );
        assert_eq!(
            HANDLER_HITS.load(Ordering::SeqCst),
            1,
            "plugin handler fired once"
        );
    }

    // --- dispatch_empty_event: no-payload lifecycle events (P0 session events)

    /// Verifies `dispatch_empty_event` fans a no-payload event (e.g. the
    /// rpi-specific `BeforeTuiStart` / session lifecycle tags) to every
    /// subscriber and reports whether any handler was invoked.
    #[test]
    fn dispatch_empty_event_fans_out_to_subscribers() {
        let _guard = HANDLER_TEST_LOCK.lock().unwrap();
        HANDLER_HITS.store(0, Ordering::SeqCst);
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "test-plugin".to_string(),
            EventTag::SessionStart,
            counting_handler,
            std::ptr::null_mut(),
        );
        reg.register_event_handler(
            "test-plugin".to_string(),
            EventTag::BeforeTuiStart,
            counting_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());

        // No subscriber for SessionShutdown → no handler invoked.
        assert!(!dispatch_empty_event(&snap, EventTag::SessionShutdown));
        assert_eq!(HANDLER_HITS.load(Ordering::SeqCst), 0);

        // SessionStart + BeforeTuiStart both have one subscriber each.
        assert!(dispatch_empty_event(&snap, EventTag::SessionStart));
        assert!(dispatch_empty_event(&snap, EventTag::BeforeTuiStart));
        assert_eq!(HANDLER_HITS.load(Ordering::SeqCst), 2);

        // Stale registry (session swapped): dispatch is a silent no-op inside
        // `dispatch_to_handlers` — no handler is invoked — though the fn still
        // reports subscribers existed (matches `dispatch_data_event` semantics).
        reg.invalidate();
        assert!(dispatch_empty_event(&snap, EventTag::SessionStart));
        assert!(dispatch_empty_event(&snap, EventTag::BeforeTuiStart));
        assert_eq!(HANDLER_HITS.load(Ordering::SeqCst), 2);
    }

    // --- dispatch_lifecycle_event: veto + timeout (P1) ---

    /// A lifecycle handler that vetoes (returns the SDK abort code).
    extern "C" fn aborting_handler(_ev: StablePluginEvent, _ud: *mut std::ffi::c_void) -> i32 {
        rpi_plugin_sdk::EVENT_HANDLER_ABORT
    }

    /// A lifecycle handler that returns success (`0`) — no veto.
    extern "C" fn continue_handler(_ev: StablePluginEvent, _ud: *mut std::ffi::c_void) -> i32 {
        rpi_plugin_sdk::EVENT_HANDLER_CONTINUE
    }

    /// A lifecycle handler that returns a generic handled error — no veto.
    extern "C" fn error_handler(_ev: StablePluginEvent, _ud: *mut std::ffi::c_void) -> i32 {
        rpi_plugin_sdk::EVENT_HANDLER_ERROR
    }

    #[test]
    fn lifecycle_timeout_budget_matches_spec() {
        assert_eq!(
            lifecycle_timeout_for(EventTag::BeforeTuiStart),
            std::time::Duration::from_secs(5)
        );
        assert_eq!(
            lifecycle_timeout_for(EventTag::SessionShutdown),
            std::time::Duration::from_secs(15)
        );
        assert_eq!(
            lifecycle_timeout_for(EventTag::SessionStart),
            std::time::Duration::from_secs(10)
        );
    }

    /// A handler returning `EVENT_HANDLER_ABORT` vetoes the phase; the returned
    /// reason names the owning extension.
    #[tokio::test]
    async fn dispatch_lifecycle_event_honors_veto() {
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "veto-ext".to_string(),
            EventTag::BeforeTuiStart,
            aborting_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());
        let result = dispatch_lifecycle_event(&snap, EventTag::BeforeTuiStart).await;
        assert_eq!(
            result.as_deref(),
            Some("extension `veto-ext` vetoed BeforeTuiStart")
        );
    }

    /// A `0` (continue) or generic nonzero (handled error) return does NOT veto;
    /// the fan-out still visits every handler and returns `None`.
    #[tokio::test]
    async fn dispatch_lifecycle_event_continue_and_error_do_not_veto() {
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "ok-ext".to_string(),
            EventTag::SessionStart,
            continue_handler,
            std::ptr::null_mut(),
        );
        reg.register_event_handler(
            "err-ext".to_string(),
            EventTag::SessionStart,
            error_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());
        assert!(dispatch_lifecycle_event(&snap, EventTag::SessionStart)
            .await
            .is_none());
    }

    fn tool_call_session(reg: &crate::ExtensionRegistry) -> crate::ExtensionSession {
        crate::ExtensionSession::from_parts(
            Arc::new(reg.snapshot()),
            crate::PluginKeepalive::empty(),
            Vec::new(),
            None,
        )
    }

    #[tokio::test]
    async fn tool_call_approval_error_and_stale_session_block_execution() {
        let mut reg = crate::ExtensionRegistry::new();
        reg.register_event_handler(
            "broken-gate".into(),
            EventTag::ToolCall,
            error_handler,
            std::ptr::null_mut(),
        );
        let session = tool_call_session(&reg);
        let signal = tokio_util::sync::CancellationToken::new();
        let ui = crate::UiDialogMailbox::new();
        let reason =
            dispatch_tool_call_event(&session, "c1", "bash", &serde_json::json!({}), &signal, &ui)
                .await
                .unwrap();
        assert!(reason.contains("approval failed: rc="), "{reason}");
        reg.invalidate();
        let reason =
            dispatch_tool_call_event(&session, "c2", "bash", &serde_json::json!({}), &signal, &ui)
                .await
                .unwrap();
        assert!(reason.contains("stale"), "{reason}");
    }

    struct WaitingApproval {
        ui: crate::UiDialogMailbox,
        entered: tokio::sync::Notify,
        finished: tokio::sync::Notify,
        release: std::sync::atomic::AtomicBool,
    }

    static APPROVAL_CONTEXTS: rpi_plugin_sdk::handles::ToolHandles<Arc<WaitingApproval>> =
        rpi_plugin_sdk::handles::ToolHandles::new();

    rpi_plugin_sdk::event_handler! { fn waiting_approval(event, data) {
        let Some(context) = APPROVAL_CONTEXTS.get(data) else {
            return rpi_plugin_sdk::EVENT_HANDLER_ERROR;
        };
        let state = context.lock().clone();
        let call_id = event.tool_call().expect("tool call event").tool_call_id;
        state
            .ui
            .handle(serde_json::json!({
                "op": "open", "requestId": "approval", "toolCallId": call_id,
                "ui": {"question": "Allow?"},
            }))
            .unwrap();
        state.entered.notify_one();
        loop {
            if state.release.load(Ordering::SeqCst) {
                break;
            }
            if state.ui.poll("approval").unwrap()["status"] == "cancelled" {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
        // Stay inside the callback so the test can check library retention
        // after the async dispatch has already returned.
        while !state.release.load(Ordering::SeqCst) {
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
        state.finished.notify_one();
        rpi_plugin_sdk::EVENT_HANDLER_ABORT
    } }

    async fn check_interrupted_approval(cancel: bool) {
        let ui = crate::UiDialogMailbox::new();
        ui.attach();
        ui.handle(serde_json::json!({
            "requestId": "other", "toolCallId": "other-call", "ui": {},
        }))
        .unwrap();
        let state = Arc::new(WaitingApproval {
            ui: ui.clone(),
            entered: tokio::sync::Notify::new(),
            finished: tokio::sync::Notify::new(),
            release: std::sync::atomic::AtomicBool::new(false),
        });
        // Release on failed assertions too, so the blocking runtime can exit.
        struct ReleaseWorker(Arc<WaitingApproval>, usize);
        impl Drop for ReleaseWorker {
            fn drop(&mut self) {
                self.0.release.store(true, Ordering::SeqCst);
                drop(APPROVAL_CONTEXTS.remove(self.1 as rpi_plugin_sdk::StepHandle));
            }
        }
        let context = APPROVAL_CONTEXTS.insert(state.clone());
        let _release = ReleaseWorker(state.clone(), context as usize);
        let mut reg = crate::ExtensionRegistry::new();
        reg.register_event_handler(
            "waiting-gate".into(),
            EventTag::ToolCall,
            waiting_approval,
            context,
        );
        let keepalive = crate::PluginKeepalive::empty();
        let weak = Arc::downgrade(&keepalive);
        let session = crate::ExtensionSession::from_parts(
            Arc::new(reg.snapshot()),
            keepalive,
            Vec::new(),
            None,
        );
        let signal = tokio_util::sync::CancellationToken::new();
        let task_signal = signal.clone();
        let task_ui = ui.clone();
        let task = tokio::spawn(async move {
            dispatch_tool_call_event_with_timeout(
                &session,
                "call",
                "bash",
                &serde_json::json!({}),
                &task_signal,
                &task_ui,
                if cancel {
                    TOOL_CALL_TIMEOUT
                } else {
                    std::time::Duration::from_millis(200)
                },
            )
            .await
        });
        tokio::time::timeout(std::time::Duration::from_secs(2), state.entered.notified())
            .await
            .unwrap();
        if cancel {
            signal.cancel();
        }
        let reason = tokio::time::timeout(std::time::Duration::from_secs(2), task)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert!(
            reason.contains(if cancel { "cancelled" } else { "timed out" }),
            "{reason}"
        );
        assert!(
            weak.upgrade().is_some(),
            "running callback must keep its library mapped"
        );
        assert_eq!(ui.poll("other").unwrap()["status"], "pending");
        state.release.store(true, Ordering::SeqCst);
        tokio::time::timeout(std::time::Duration::from_secs(2), state.finished.notified())
            .await
            .unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            while weak.upgrade().is_some() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn tool_call_approval_cancel_releases_waiter_and_retains_running_library() {
        check_interrupted_approval(true).await;
    }

    #[tokio::test]
    async fn tool_call_approval_timeout_blocks_and_retains_running_library() {
        check_interrupted_approval(false).await;
    }

    // --- dispatch_tool_call_event: veto (B3b before_tool_call) ---

    /// A `ToolCall` handler that vetoes blocks the tool and names the tool.
    #[tokio::test]
    async fn dispatch_tool_call_event_honors_veto() {
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "gate-ext".to_string(),
            EventTag::ToolCall,
            aborting_handler,
            std::ptr::null_mut(),
        );
        let session = tool_call_session(&reg);
        let veto = dispatch_tool_call_event(
            &session,
            "call_1",
            "bash",
            &serde_json::json!({"command": "rm -rf /"}),
            &tokio_util::sync::CancellationToken::new(),
            &crate::UiDialogMailbox::new(),
        )
        .await;
        assert_eq!(
            veto.as_deref(),
            Some("extension `gate-ext` blocked tool `bash`")
        );
    }

    /// A continue code does not veto; no subscribers is also `None`.
    #[tokio::test]
    async fn dispatch_tool_call_event_continue_and_empty_do_not_veto() {
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "ok-ext".to_string(),
            EventTag::ToolCall,
            continue_handler,
            std::ptr::null_mut(),
        );
        let session = tool_call_session(&reg);
        assert!(dispatch_tool_call_event(
            &session,
            "call_1",
            "read",
            &serde_json::json!({"path": "x"}),
            &tokio_util::sync::CancellationToken::new(),
            &crate::UiDialogMailbox::new(),
        )
        .await
        .is_none());

        let empty = crate::registry::ExtensionRegistry::new();
        let empty_session = tool_call_session(&empty);
        assert!(dispatch_tool_call_event(
            &empty_session,
            "call_2",
            "read",
            &serde_json::json!({}),
            &tokio_util::sync::CancellationToken::new(),
            &crate::UiDialogMailbox::new()
        )
        .await
        .is_none());
    }

    /// No subscribers → no veto, no work.
    #[tokio::test]
    async fn dispatch_lifecycle_event_no_subscribers_is_none() {
        let reg = crate::registry::ExtensionRegistry::new();
        let snap = Arc::new(reg.snapshot());
        assert!(dispatch_lifecycle_event(&snap, EventTag::BeforeTuiStart)
            .await
            .is_none());
    }

    /// A stale registry (swapped-out session) is a no-op — a veto from a stale
    /// handler must NOT abort the new session's startup.
    #[tokio::test]
    async fn dispatch_lifecycle_event_stale_is_none() {
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "veto-ext".to_string(),
            EventTag::BeforeTuiStart,
            aborting_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());
        reg.invalidate();
        assert!(dispatch_lifecycle_event(&snap, EventTag::BeforeTuiStart)
            .await
            .is_none());
    }

    /// The observe fan-out records one JSONL line per handler when the global
    /// event logger is enabled.
    #[test]
    fn dispatch_records_handler_invocation_to_event_log() {
        let _guard = HANDLER_TEST_LOCK.lock().unwrap();
        HANDLER_HITS.store(0, Ordering::SeqCst);
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("events.jsonl");
        crate::event_log::set_event_logger_for_test(crate::event_log::EventLogger::open(
            path.clone(),
        ));

        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "log-ext".to_string(),
            EventTag::MessageEnd,
            counting_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());
        let event = StablePluginEvent::message(
            EventTag::MessageEnd,
            StbString::from_string("m".to_string()),
        );
        dispatch_to_handlers(&snap, &event);

        // Restore the disabled default so later tests don't write into the
        // (soon-deleted) temp file.
        crate::event_log::set_event_logger_for_test(crate::event_log::EventLogger::disabled());

        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains(r#""event":"MessageEnd""#), "log: {text}");
        assert!(text.contains(r#""plugin":"log-ext""#), "log: {text}");
        assert!(text.contains(r#""result":"Continue""#), "log: {text}");
        assert_eq!(HANDLER_HITS.load(Ordering::SeqCst), 1);
    }

    // --- key-routing (`dispatch_data_event_claiming`) ----------------------

    /// Handler that claims the event unless `CLAIM_ROUTING` says otherwise.
    /// `CLAIM_ROUTING` is global because an `extern "C" fn` cannot capture.
    static CLAIM_ROUTING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);

    rpi_plugin_sdk::event_handler! { fn claiming_handler(ev, _ud) {
        // The payload must be readable as a data event (this is also what
        // exercises the `Input` free path not leaking/aliasing).
        let seen = ev.data_text().expect("input data event");
        assert!(seen.contains("space"), "payload not delivered: {seen}");
        if CLAIM_ROUTING.load(Ordering::SeqCst) {
            rpi_plugin_sdk::EVENT_HANDLER_CLAIMED
        } else {
            rpi_plugin_sdk::EVENT_HANDLER_CONTINUE
        }
    } }

    fn input_snapshot(with_handler: bool) -> Arc<crate::registry::RegistrySnapshot> {
        let mut reg = crate::registry::ExtensionRegistry::new();
        if with_handler {
            reg.register_event_handler(
                "voice".to_string(),
                EventTag::Input,
                claiming_handler,
                std::ptr::null_mut(),
            );
        }
        Arc::new(reg.snapshot())
    }

    #[test]
    fn claiming_dispatch_reports_claim_and_passthrough() {
        let _guard = HANDLER_TEST_LOCK.lock().unwrap();
        let snap = input_snapshot(true);

        CLAIM_ROUTING.store(true, Ordering::SeqCst);
        assert!(
            dispatch_data_event_claiming(&snap, EventTag::Input, r#"{"key":"space"}"#),
            "a CLAIMED handler must swallow the key"
        );

        CLAIM_ROUTING.store(false, Ordering::SeqCst);
        assert!(
            !dispatch_data_event_claiming(&snap, EventTag::Input, r#"{"key":"space"}"#),
            "a CONTINUE handler must let the key reach the editor"
        );
        CLAIM_ROUTING.store(true, Ordering::SeqCst);
    }

    #[test]
    fn claiming_dispatch_without_subscribers_is_false() {
        let snap = input_snapshot(false);
        assert!(!dispatch_data_event_claiming(
            &snap,
            EventTag::Input,
            r#"{"key":"space"}"#
        ));
    }

    // --- editor-change (`dispatch_data_event`) -----------------------------

    /// The `EditorChange` notification reaches subscribers with its payload
    /// intact and returns "no veto" (it is an observer event: the draft change
    /// has already happened and must never be blocked).
    #[test]
    fn editor_change_reaches_subscribers_with_its_payload() {
        let _guard = HANDLER_TEST_LOCK.lock().unwrap();
        let mut reg = crate::registry::ExtensionRegistry::new();
        reg.register_event_handler(
            "voice".to_string(),
            EventTag::EditorChange,
            editor_change_handler,
            std::ptr::null_mut(),
        );
        let snap = Arc::new(reg.snapshot());

        EDITOR_CHANGE_SEEN.store(false, Ordering::SeqCst);
        assert!(
            dispatch_data_event(
                &snap,
                EventTag::EditorChange,
                r#"{"chars":4,"empty":false}"#
            ),
            "a subscribed handler must be invoked"
        );
        assert!(
            EDITOR_CHANGE_SEEN.load(Ordering::SeqCst),
            "payload missing or handler not called"
        );
    }

    // Handler that records it saw a well-formed editor-change payload. The
    // flag is global because an `extern "C" fn` cannot capture.
    static EDITOR_CHANGE_SEEN: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);

    rpi_plugin_sdk::event_handler! { fn editor_change_handler(ev, _ud) {
        // Reading the data payload here also exercises the `EditorChange` free
        // path (a wrong arm in `free_dispatched_event` would corrupt/leak).
        let seen = ev.data_text().expect("editor change data event");
        if seen.contains("chars") && seen.contains("empty") {
            EDITOR_CHANGE_SEEN.store(true, Ordering::SeqCst);
        }
        rpi_plugin_sdk::EVENT_HANDLER_CONTINUE
    } }
}