rpi-extensions 0.1.13

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
//! The `libloading` loader: discover and register cdylib plugins.
//!
//! [`load_one`] loads a single cdylib and prefers `rpi_plugin_register_v2`.
//! Only when that symbol is absent does it use legacy `rpi_plugin_register`.
//! The selected entrypoint is called exactly once; a nonzero return never
//! triggers fallback to the other ABI.
//!
//! [`load_dir`] walks a directory for `.{dll,so,dylib}` files and loads each.
//! The returned [`LoadedPlugin`]s hold the `libloading::Library` (dropping them
//! unloads the cdylib — keep them alive for the session lifetime).

use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use libloading::Library;
use thiserror::Error;

use rpi_plugin_sdk::{
    LegacyPluginApiV1, LegacyRpiPluginRegister, PluginApiVt, RpiPluginRegister,
    LEGACY_PLUGIN_ABI_VERSION, RPI_PLUGIN_ABI_VERSION,
};

use crate::registry::{ExtensionRegistry, RegistrySnapshot};
use crate::{
    clear_current_api, set_current_api, ActionBridge, HostApi, NullDiagnostics, PluginDiagnostics,
};

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Error / skip reason from loading one plugin. `Skip` variants are non-fatal
/// (logged via diagnostics); `Fatal` means the load itself failed.
#[derive(Debug, Error)]
pub enum PluginLoadError {
    #[error("could not open library {path}: {source}")]
    Open {
        path: PathBuf,
        #[source]
        source: libloading::Error,
    },
    #[error(
        "neither `rpi_plugin_register_v2` nor legacy `rpi_plugin_register` was found in {path} (v2: {v2_error}; v1: {legacy_error})"
    )]
    Symbol {
        path: PathBuf,
        v2_error: String,
        legacy_error: String,
    },
    #[error("register returned nonzero code {code} for {path}")]
    RegisterReturned { path: PathBuf, code: i32 },
    /// ABI version reported by the plugin mismatches the host's. Skip + diag.
    #[error(
        "ABI version mismatch in {path}: plugin built for {plugin_version}, host is {host_version}"
    )]
    AbiVersionMismatch {
        path: PathBuf,
        plugin_version: u32,
        host_version: u32,
    },
}

// ---------------------------------------------------------------------------
// LoadedPlugin — the live cdylib handle + where it came from
// ---------------------------------------------------------------------------

/// A successfully loaded + registered plugin. Holds the `Library` so the cdylib
/// stays mapped for the session. Dropping this unloads the plugin (do not drop
/// while any of its tool drivers may still be running).
pub struct LoadedPlugin {
    /// The loaded cdylib. Kept alive for the session.
    pub library: Library,
    /// Where it was loaded from (for diagnostics).
    pub path: PathBuf,
    /// ABI selected from the exported register symbol (`1` or `2`).
    pub abi_version: u32,
    /// The registry snapshot built from this plugin's registrations. The host
    /// merges snapshots from all loaded plugins into one session registry.
    pub registry: ExtensionRegistry,
}

#[derive(Clone, Copy)]
enum RegisterEntrypoint {
    V2(RpiPluginRegister),
    V1(LegacyRpiPluginRegister),
}

impl RegisterEntrypoint {
    fn abi_version(self) -> u32 {
        match self {
            Self::V2(_) => RPI_PLUGIN_ABI_VERSION,
            Self::V1(_) => LEGACY_PLUGIN_ABI_VERSION,
        }
    }
}

fn select_register<V, L, E>(
    v2: Result<V, E>,
    legacy: impl FnOnce() -> Result<L, E>,
) -> Result<Result<V, L>, (E, E)> {
    match v2 {
        Ok(register) => Ok(Ok(register)),
        Err(v2_error) => match legacy() {
            Ok(register) => Ok(Err(register)),
            Err(legacy_error) => Err((v2_error, legacy_error)),
        },
    }
}

fn call_register(entrypoint: RegisterEntrypoint, host_api: &Arc<HostApi>) -> i32 {
    match entrypoint {
        RegisterEntrypoint::V2(register) => {
            let vtable = host_api.build_vtable();
            let vt_ref: &PluginApiVt = &vtable;
            register(vt_ref as *const PluginApiVt, RPI_PLUGIN_ABI_VERSION)
        }
        RegisterEntrypoint::V1(register) => {
            let vtable = host_api.build_legacy_vtable();
            let vt_ref: &LegacyPluginApiV1 = &vtable;
            register(
                vt_ref as *const LegacyPluginApiV1,
                LEGACY_PLUGIN_ABI_VERSION,
            )
        }
    }
}

// ---------------------------------------------------------------------------
// load_one
// ---------------------------------------------------------------------------

/// Load and register one cdylib plugin. Returns the live plugin + its
/// registry, or a [`PluginLoadError`] (skip-fatality distinction is on the
/// caller; both are logged via `diagnostics`).
///
/// `diagnostics` is the host sink for ABI-mismatch/unsupported warnings. The
/// loader creates a fresh `ExtensionRegistry` for THIS plugin (so a plugin that
/// fails partway can't pollute others), and the caller merges per-plugin
/// registries into the session registry in load-order (first-wins on name).
///
/// `action_bridge` (B5a): when `Some`, the plugin's vtable wires the real
/// [`trampoline_runtime_action`] and carries the bridge in `user_data`, so the
/// plugin can invoke host runtime actions post-register from any thread. `None`
/// keeps the v1 stub (actions return `-1`). `rpi-cli` builds ONE master
/// `Arc<ActionBridge>` per session and clones it into every `load_one` — every
/// plugin's `user_data` points at the same bridge (Arc-ptr-stable, kept alive
/// by `rpi-cli` for the harness lifetime).
pub fn load_one(
    path: impl AsRef<Path>,
    diagnostics: Arc<dyn PluginDiagnostics>,
    action_bridge: Option<Arc<ActionBridge>>,
) -> Result<LoadedPlugin, PluginLoadError> {
    let path = path.as_ref().to_path_buf();
    // 1. Open the cdylib.
    let library = unsafe { Library::new(&path) }.map_err(|e| PluginLoadError::Open {
        path: path.clone(),
        source: e,
    })?;

    // 2. Prefer ABI v2. The legacy lookup is lazy, so a plugin exporting both
    // symbols is unambiguously v2 and the legacy path is not even consulted.
    let entrypoint = unsafe {
        select_register(
            library
                .get::<RpiPluginRegister>(rpi_plugin_sdk::REGISTER_SYMBOL_V2)
                .map(|symbol| *symbol),
            || {
                library
                    .get::<LegacyRpiPluginRegister>(rpi_plugin_sdk::LEGACY_REGISTER_SYMBOL)
                    .map(|symbol| *symbol)
            },
        )
    }
    .map(|selected| match selected {
        Ok(register) => RegisterEntrypoint::V2(register),
        Err(register) => RegisterEntrypoint::V1(register),
    })
    .map_err(|(v2_error, legacy_error)| PluginLoadError::Symbol {
        path: path.clone(),
        v2_error: v2_error.to_string(),
        legacy_error: legacy_error.to_string(),
    })?;
    let abi_version = entrypoint.abi_version();

    // 3. Build a fresh registry + HostApi + vtable for this plugin.
    let registry = ExtensionRegistry::new();
    let host_api = match action_bridge {
        Some(bridge) => HostApi::with_action_bridge(registry, Arc::clone(&diagnostics), bridge),
        None => HostApi::new(registry, Arc::clone(&diagnostics)),
    };
    // 4. Set the thread-local current api so the register trampolines can reach
    //    the registry. Register is synchronous + single-threaded per plugin.
    // SAFETY: `host_api` is alive for the duration of the register call (held on
    // this stack); we clear_current_api immediately after.
    unsafe { set_current_api(&host_api) };
    // The selected symbol is invoked exactly once. In particular, a nonzero v2
    // result does not fall back to v1, because registration may have produced
    // side effects before returning. A panic from an `extern "C"` plugin is not
    // recoverable in general and is deliberately not advertised as contained.
    let rc = call_register(entrypoint, &host_api);
    clear_current_api();

    if rc != 0 {
        // The plugin refused (its register returned nonzero — e.g. it saw an
        // ABI version it didn't like). Skip + diag. The registry may have
        // partial registrations; we drop it (no harm — the tools registered so
        // far would reference a plugin that "failed", so we honor the plugin's
        // refusal and discard).
        diagnostics.warn(&format!(
            "plugin {} ABI v{} register returned code {} — skipped",
            path.display(),
            abi_version,
            rc
        ));
        return Err(PluginLoadError::RegisterReturned { path, code: rc });
    }

    // 5. Take the registry out of the HostApi. The host keeps the Library alive
    //    (LoadedPlugin) so the plugin's code + static data remain mapped; the
    //    registry holds fn pointers into that code.
    let registry = host_api
        .take_registry()
        .ok_or_else(|| PluginLoadError::RegisterReturned {
            path: path.clone(),
            code: -2,
        })?;

    tracing::debug!(path = %path.display(), abi_version, "loaded native plugin");

    Ok(LoadedPlugin {
        library,
        path,
        abi_version,
        registry,
    })
}

// ---------------------------------------------------------------------------
// load_dir
// ---------------------------------------------------------------------------

/// Platform cdylib extensions.
const CDYLIB_EXTS: &[&str] = &["dll", "so", "dylib", "pyd"];

/// Load every cdylib in `dir` (non-recursive). Each load failure is logged via
/// `diagnostics` and skipped (one bad plugin doesn't abort the rest). Returns
/// the successfully loaded plugins in directory order.
///
/// `action_bridge` (B5a) is cloned into each loaded plugin's vtable `user_data`
/// so post-register `runtime_action` calls recover the bridge on any thread.
pub fn load_dir(
    dir: impl AsRef<Path>,
    diagnostics: Arc<dyn PluginDiagnostics>,
    action_bridge: Option<Arc<ActionBridge>>,
) -> Vec<LoadedPlugin> {
    let dir = dir.as_ref();
    let mut out = Vec::new();
    let read = match std::fs::read_dir(dir) {
        Ok(r) => r,
        Err(e) => {
            diagnostics.warn(&format!(
                "extensions dir {} unreadable: {}",
                dir.display(),
                e
            ));
            return out;
        }
    };
    for entry in read.flatten() {
        let path = entry.path();
        if !is_cdylib(&path) {
            continue;
        }
        match load_one(&path, Arc::clone(&diagnostics), action_bridge.clone()) {
            Ok(p) => out.push(p),
            Err(e) => diagnostics.warn(&format!("skipped plugin {}: {e}", path.display())),
        }
    }
    out
}

/// Whether `path`'s extension is a known cdylib extension.
fn is_cdylib(path: &Path) -> bool {
    path.extension()
        .and_then(OsStr::to_str)
        .map(|ext| CDYLIB_EXTS.iter().any(|e| e.eq_ignore_ascii_case(ext)))
        .unwrap_or(false)
}

/// Convenience: merge a slice of per-plugin [`LoadedPlugin`] registries into one
/// session registry, first-wins on name (mirrors pi's cross-extension
/// registration order). Consumes the registries (the `LoadedPlugin`s themselves
/// stay alive — callers keep the `Library` handles).
pub fn merge_registries(plugins: &mut [LoadedPlugin]) -> ExtensionRegistry {
    let mut session = ExtensionRegistry::new();
    // We can't move registries out of LoadedPlugin without taking them; borrow
    // mutably and drain into the session. Since ExtensionRegistry's registrars
    // consume by value, we rebuild from the snapshot instead.
    // Simpler: snapshot each, then re-register by iteration. But ExtensionRegistry
    // has no public "absorb another registry" — so we drain tools/commands/handlers
    // via internal access. For v1 we expose the typed fields via crate-internal
    // methods on ExtensionRegistry used only here.
    for p in plugins.iter_mut() {
        // Take the plugin's registry out (LoadedPlugin keeps the Library).
        let taken = std::mem::take(&mut p.registry);
        session.absorb(taken);
    }
    session
}

// ---------------------------------------------------------------------------
// PluginKeepalive + ExtensionSession — the host session's plugin lifetime
// ---------------------------------------------------------------------------

/// Owns the loaded `Library` handles so the cdylibs stay mapped for as long as
/// any registered tool/handler (whose fn pointers live inside the cdylib) may be
/// called. Shared via `Arc`: every [`PluginToolAdapter`](crate::PluginToolAdapter)
/// (and, in B3, the [`ExtensionEmitter`](crate::ExtensionEmitter)) holds a clone,
/// so the libraries unload only when the last holder drops — which is never
/// before the harness's tool vec (and thus the last possible tool call) drops.
///
/// `libloading::Library` is `Send + Sync` (a handle/HMODULE), so the keepalive is
/// too — required because `AgentTool: Send + Sync` and the adapter carries it.
pub struct PluginKeepalive {
    #[allow(dead_code)]
    libraries: Vec<Library>,
    /// B5a: the session's action bridge. Retained here so the raw pointer a
    /// plugin stored in its vtable `user_data` (`Arc::as_ptr`) stays valid for
    /// the harness lifetime — every `PluginToolAdapter` + the `ExtensionEmitter`
    /// clone the keepalive, so the bridge outlives any plugin→host
    /// `runtime_action` call. `None` under `--no-extensions`, when zero plugins
    /// loaded, or in tests.
    #[allow(dead_code)]
    action_bridge: Option<Arc<ActionBridge>>,
}

impl PluginKeepalive {
    /// Build a keepalive. `pub` so tests + host code can construct an empty
    /// one (no loaded cdylibs) where the plugin lifecycle is exercised without
    /// real plugins.
    pub fn new(libraries: Vec<Library>, action_bridge: Option<Arc<ActionBridge>>) -> Self {
        Self {
            libraries,
            action_bridge,
        }
    }

    /// An empty keepalive owning no libraries — for host code that builds an
    /// adapter outside a real load session (notably in-process tests of the
    /// adapter against stub fns that live in the test binary, not a cdylib).
    pub fn empty() -> Arc<Self> {
        Arc::new(Self::new(Vec::new(), None))
    }
}

/// The result of loading a session's worth of extensions: a shared keepalive for
/// the cdylib handles + a snapshot of the merged registry. Built by
/// [`load_session`]; the host (pi-cli) stashes one per harness build and hands
/// clones of the keepalive to each adapter it constructs from the snapshot.
///
/// The snapshot is held behind `Arc` so the host can hand a clone to the
/// [`ExtensionEmitter`](crate::ExtensionEmitter) (installed as the harness's
/// `agent_emitter`) without borrowing — the emitter must outlive this session
/// local (it lives for the harness lifetime inside `AgentHarnessOptions`).
///
/// `Clone` (B5d): every field is already cheaply clonable (`Arc<PluginKeepalive>`,
/// `Option<Arc<RegistrySnapshot>>`, `Vec<PathBuf>`, `Option<Arc<ActionBridge>>`),
/// so the reload routine can clone the live session out of its `Mutex` cell for
/// local inspection (snapshot/keepalive/loaded_paths) and store a fresh one back
/// in — without a borrow spanning the store.
#[derive(Clone)]
pub struct ExtensionSession {
    keepalive: Arc<PluginKeepalive>,
    snapshot: Option<Arc<RegistrySnapshot>>,
    loaded_paths: Vec<PathBuf>,
    /// B5a: the session's action bridge (`None` when no plugins / tests / the
    /// `--no-extensions` path). Kept here so `rpi-cli` can recover it after
    /// `AgentHarness::create` to call `set_harness` — the bridge's `user_data`
    /// pointer was already handed out during `register`, so pi-cli must fill the
    /// host's harness cell immediately after create. Cloning is cheap (an `Arc`
    /// clone); the keepalive also holds a clone for the lifetime guarantee.
    action_bridge: Option<Arc<ActionBridge>>,
}

impl ExtensionSession {
    /// Assemble a session from already-loaded parts (explicit `--extension`
    /// files via `load_one` + `merge_registries`). Mirrors `load_session`'s
    /// internal assembly so callers can build a session without a dir scan.
    pub fn from_parts(
        snapshot: Arc<RegistrySnapshot>,
        keepalive: Arc<PluginKeepalive>,
        loaded_paths: Vec<PathBuf>,
        action_bridge: Option<Arc<ActionBridge>>,
    ) -> Self {
        Self {
            keepalive,
            snapshot: Some(snapshot),
            loaded_paths,
            action_bridge,
        }
    }

    /// An empty session (no plugins loaded — `--no-extensions` or no dirs found).
    pub fn none() -> Self {
        Self {
            keepalive: Arc::new(PluginKeepalive::new(Vec::new(), None)),
            snapshot: None,
            loaded_paths: Vec::new(),
            action_bridge: None,
        }
    }

    /// The shared keepalive — clone one per adapter/emitter you build from this
    /// session so the cdylibs outlive them.
    pub fn keepalive(&self) -> Arc<PluginKeepalive> {
        Arc::clone(&self.keepalive)
    }

    /// The merged registry snapshot (tools/commands/handlers), if any plugin
    /// loaded. `None` when no plugins loaded successfully. Borrowed view for
    /// iterating tools/commands; for an owned share (e.g. handing to the
    /// emitter) use [`snapshot_arc`](Self::snapshot_arc).
    pub fn snapshot(&self) -> Option<&RegistrySnapshot> {
        self.snapshot.as_deref()
    }

    /// A shared (`Arc`) clone of the merged registry snapshot, for host code that
    /// must keep the snapshot alive beyond this session local — notably the
    /// [`ExtensionEmitter`](crate::ExtensionEmitter) installed into
    /// `AgentHarnessOptions.agent_emitter`.
    pub fn snapshot_arc(&self) -> Option<Arc<RegistrySnapshot>> {
        self.snapshot.clone()
    }

    /// Paths of the cdylibs that loaded + registered successfully (diagnostics).
    pub fn loaded_paths(&self) -> &[PathBuf] {
        &self.loaded_paths
    }

    /// Whether zero plugins loaded.
    pub fn is_empty(&self) -> bool {
        self.loaded_paths.is_empty()
    }

    /// A one-line human summary for `--verbose` startup output, or `None` when
    /// nothing loaded (so the line is omitted entirely).
    pub fn summary(&self) -> Option<String> {
        if self.is_empty() {
            return None;
        }
        let tools = self.snapshot.as_ref().map(|s| s.tools().len()).unwrap_or(0);
        Some(format!(
            "loaded {} plugin(s) ({} tool(s))",
            self.loaded_paths.len(),
            tools
        ))
    }

    /// B5a: the session's action bridge, if one was threaded into `load_*`.
    /// `rpi-cli` recovers this after `AgentHarness::create` succeeds to call
    /// `HarnessActionHost::set_harness` (filling the host cell the bridge's
    /// `user_data`-recovered host reads on the first plugin→host action). The
    /// bridge pointer was already handed to plugins during `register`, so this
    /// must happen before any run. `None` when no plugins loaded / tests /
    /// `--no-extensions`.
    pub fn action_bridge(&self) -> Option<Arc<ActionBridge>> {
        self.action_bridge.clone()
    }
}

/// Load + register every cdylib in the given dirs (in order, non-recursive),
/// merge their registries first-wins, and return a session with a shared
/// keepalive over the `Library` handles + the merged snapshot. Dirs that don't
/// exist are skipped silently; individual plugin load failures are logged via
/// `diagnostics` and skipped (one bad plugin doesn't abort the rest).
///
/// The order of `dirs` matters: earlier dirs win on tool/command name collision
/// (pi registration order). Callers pass default dirs first, then `--extensions-dir`
/// extras, so a same-named tool in a default-dir plugin wins over an extra-dir one.
///
/// `action_bridge` (B5a) is cloned into every loaded plugin's vtable so
/// post-register `runtime_action` calls recover the bridge on any thread.
/// `rpi-cli` builds one master `Arc<ActionBridge>` per session and passes it
/// here; `None` keeps the v1 stub (used by tests / `--no-extensions` no-ops).
pub fn load_session(
    dirs: &[PathBuf],
    diagnostics: Arc<dyn PluginDiagnostics>,
    action_bridge: Option<Arc<ActionBridge>>,
) -> ExtensionSession {
    load_session_mixed(dirs, &[], diagnostics, action_bridge)
}

/// Load plugins from a mix of scanned dirs and explicit cdylib files
/// (the `--extension`/`-e` CLI paths), assembled into one session. Mirrors
/// `load_session` but additionally `load_one`s each explicit file.
pub fn load_session_mixed(
    dirs: &[PathBuf],
    files: &[PathBuf],
    diagnostics: Arc<dyn PluginDiagnostics>,
    action_bridge: Option<Arc<ActionBridge>>,
) -> ExtensionSession {
    let mut loaded: Vec<LoadedPlugin> = Vec::new();
    for dir in dirs {
        loaded.extend(load_dir(
            dir,
            Arc::clone(&diagnostics),
            action_bridge.clone(),
        ));
    }
    for f in files {
        if let Ok(plugin) = load_one(f, Arc::clone(&diagnostics), action_bridge.clone()) {
            loaded.push(plugin);
        }
    }
    if loaded.is_empty() {
        return ExtensionSession::none();
    }
    let loaded_paths: Vec<PathBuf> = loaded.iter().map(|p| p.path.clone()).collect();
    // Merge the per-plugin registries first-wins. This drains each `registry`
    // field (via mem::take inside `absorb`) but leaves `library` intact, so we
    // can then destructure-own each Library into the keepalive below.
    let session_registry = merge_registries(&mut loaded);
    // Now move each Library out of its (registry-hollowed) LoadedPlugin by struct
    // destructuring, collecting them into the keepalive. `registry`/`path` were
    // left valid-but-empty / cloned already, and `library` is a move into `libs`.
    let mut libs: Vec<Library> = Vec::with_capacity(loaded.len());
    for p in loaded {
        let LoadedPlugin {
            library,
            registry: _,
            path: _,
            abi_version: _,
        } = p;
        libs.push(library);
    }
    let snapshot = Arc::new(session_registry.snapshot());
    ExtensionSession {
        keepalive: Arc::new(PluginKeepalive::new(libs, action_bridge.clone())),
        snapshot: Some(snapshot),
        loaded_paths,
        action_bridge,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::process::Command;
    use std::sync::atomic::{AtomicI32, AtomicU32, AtomicUsize, Ordering};
    use std::sync::Mutex;

    static V2_CALLS: AtomicUsize = AtomicUsize::new(0);
    static V1_CALLS: AtomicUsize = AtomicUsize::new(0);
    static V1_LOOKUPS: AtomicUsize = AtomicUsize::new(0);
    static V2_SEEN_VERSION: AtomicU32 = AtomicU32::new(0);
    static V1_SEEN_VERSION: AtomicU32 = AtomicU32::new(0);
    static V2_RETURN: AtomicI32 = AtomicI32::new(0);

    extern "C" fn test_register_v2(api: *const PluginApiVt, abi_version: u32) -> i32 {
        if api.is_null() {
            return -99;
        }
        V2_CALLS.fetch_add(1, Ordering::SeqCst);
        V2_SEEN_VERSION.store(abi_version, Ordering::SeqCst);
        V2_RETURN.load(Ordering::SeqCst)
    }

    extern "C" fn test_register_v1(api: *const LegacyPluginApiV1, abi_version: u32) -> i32 {
        if api.is_null() {
            return -99;
        }
        V1_CALLS.fetch_add(1, Ordering::SeqCst);
        V1_SEEN_VERSION.store(abi_version, Ordering::SeqCst);
        0
    }

    #[derive(Default)]
    struct CapturingDiag {
        warns: Mutex<Vec<String>>,
    }
    impl PluginDiagnostics for CapturingDiag {
        fn warn(&self, msg: &str) {
            self.warns.lock().unwrap().push(msg.to_string());
        }
        fn unsupported(&self, msg: &str) {
            self.warn(msg);
        }
    }

    fn test_host_api() -> Arc<HostApi> {
        HostApi::new(ExtensionRegistry::new(), Arc::new(CapturingDiag::default()))
    }

    struct CdylibFixture {
        dir: PathBuf,
        path: PathBuf,
    }

    impl Drop for CdylibFixture {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.dir);
        }
    }

    fn build_cdylib_fixture(name: &str, source: &str) -> CdylibFixture {
        static NEXT_FIXTURE: AtomicUsize = AtomicUsize::new(0);
        let unique = NEXT_FIXTURE.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!(
            "rpi-abi-loader-{}-{name}-{unique}",
            std::process::id()
        ));
        fs::create_dir_all(&dir).expect("create ABI fixture directory");
        let source_path = dir.join("fixture.rs");
        fs::write(&source_path, source).expect("write ABI fixture source");
        let filename = if cfg!(windows) {
            format!("{name}.dll")
        } else if cfg!(target_os = "macos") {
            format!("lib{name}.dylib")
        } else {
            format!("lib{name}.so")
        };
        let path = dir.join(filename);
        let output = Command::new(std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()))
            .arg("--crate-name")
            .arg(name)
            .arg("--crate-type")
            .arg("cdylib")
            .arg("--edition")
            .arg("2021")
            .arg(&source_path)
            .arg("-o")
            .arg(&path)
            .output()
            .expect("run rustc for ABI fixture");
        assert!(
            output.status.success(),
            "fixture build failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        CdylibFixture { dir, path }
    }

    // Self-contained copy of the minimum ABI surface emitted by
    // rpi-plugin-sdk v0.1.11. It intentionally does not import this workspace's
    // LegacyPluginApiV1. Unused registrar callback signatures are represented
    // as opaque C function pointers: they have the same pointer layout and are
    // never invoked. The exercised free_string and runtime_action slots retain
    // their exact old signatures, including the RuntimeActionId enum boundary.
    const V011_PLUGIN_SOURCE: &str = r#"
use std::ffi::c_void;

#[repr(C)]
#[derive(Clone, Copy)]
pub struct StbString {
    pub ptr: *mut u8,
    pub len: usize,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct StbStringRef {
    pub ptr: *const u8,
    pub len: usize,
}

#[repr(u32)]
#[derive(Clone, Copy)]
pub enum RuntimeActionId {
    SendMessage = 0,
    SendUserMessage = 1,
    AppendEntry = 2,
    SetSessionName = 3,
    GetActiveTools = 4,
    SetActiveTools = 5,
    SetModel = 6,
    GetThinkingLevel = 7,
    SetThinkingLevel = 8,
    Compact = 9,
    GetSystemPrompt = 10,
    NewSession = 11,
    Fork = 12,
    NavigateTree = 13,
    SwitchSession = 14,
    Reload = 15,
}

pub type FreeStringFn = extern "C" fn(StbString);
pub type OpaqueRegistrarFn = extern "C" fn();
pub type RuntimeActionFn = extern "C" fn(
    action: RuntimeActionId,
    args_json: StbStringRef,
    out: *mut StbString,
    user_data: *mut c_void,
) -> i32;

#[repr(C)]
pub struct PluginApiVt {
    pub free_string: FreeStringFn,
    pub register_tool: Option<OpaqueRegistrarFn>,
    pub register_command: Option<OpaqueRegistrarFn>,
    pub register_shortcut: Option<OpaqueRegistrarFn>,
    pub register_flag: Option<OpaqueRegistrarFn>,
    pub register_provider: Option<OpaqueRegistrarFn>,
    pub register_message_renderer: Option<OpaqueRegistrarFn>,
    pub register_markdown_transformer: Option<OpaqueRegistrarFn>,
    pub register_entry_renderer: Option<OpaqueRegistrarFn>,
    pub register_event_handler: Option<OpaqueRegistrarFn>,
    pub register_resources_discover: Option<OpaqueRegistrarFn>,
    pub runtime_action: RuntimeActionFn,
    pub dispatch_event: Option<OpaqueRegistrarFn>,
    pub user_data: *mut c_void,
}

#[no_mangle]
pub extern "C" fn rpi_plugin_register(api: *const PluginApiVt, abi_version: u32) -> i32 {
    if abi_version != 1 {
        return 91;
    }
    if api.is_null() {
        return 92;
    }

    let api = unsafe { &*api };
    let args = b"{}";
    let args_ref = StbStringRef {
        ptr: args.as_ptr(),
        len: args.len(),
    };
    let mut out = StbString {
        ptr: std::ptr::null_mut(),
        len: 0,
    };
    let rc = (api.runtime_action)(
        RuntimeActionId::Reload,
        args_ref,
        &mut out,
        api.user_data,
    );
    if !out.ptr.is_null() {
        (api.free_string)(out);
    }
    rc
}
"#;

    struct LegacyReloadHost {
        reloads: Arc<AtomicUsize>,
    }

    fn unexpected_legacy_action() -> Result<serde_json::Value, String> {
        Err("unexpected action from ABI v1 fixture".to_string())
    }

    #[async_trait::async_trait]
    impl crate::RuntimeActionHost for LegacyReloadHost {
        async fn send_message(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn send_user_message(
            &self,
            _: serde_json::Value,
        ) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn append_entry(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn set_session_name(
            &self,
            _: serde_json::Value,
        ) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn get_active_tools(
            &self,
            _: serde_json::Value,
        ) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn set_active_tools(
            &self,
            _: serde_json::Value,
        ) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn set_model(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn get_thinking_level(
            &self,
            _: serde_json::Value,
        ) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn set_thinking_level(
            &self,
            _: serde_json::Value,
        ) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn compact(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn get_system_prompt(
            &self,
            _: serde_json::Value,
        ) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn new_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn fork(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn navigate_tree(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn switch_session(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            unexpected_legacy_action()
        }

        async fn reload(&self, _: serde_json::Value) -> Result<serde_json::Value, String> {
            self.reloads.fetch_add(1, Ordering::SeqCst);
            Ok(serde_json::Value::Null)
        }
    }

    #[test]
    fn entrypoint_selection_supports_v1_v2_and_never_falls_back_after_call() {
        V2_CALLS.store(0, Ordering::SeqCst);
        V1_CALLS.store(0, Ordering::SeqCst);
        V1_LOOKUPS.store(0, Ordering::SeqCst);
        V2_RETURN.store(0, Ordering::SeqCst);

        let selected = select_register::<RpiPluginRegister, LegacyRpiPluginRegister, &str>(
            Ok(test_register_v2),
            || {
                V1_LOOKUPS.fetch_add(1, Ordering::SeqCst);
                Ok(test_register_v1)
            },
        )
        .expect("v2 selected");
        let entrypoint = match selected {
            Ok(register) => RegisterEntrypoint::V2(register),
            Err(register) => RegisterEntrypoint::V1(register),
        };
        assert_eq!(call_register(entrypoint, &test_host_api()), 0);
        assert_eq!(V2_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(V1_CALLS.load(Ordering::SeqCst), 0);
        assert_eq!(V1_LOOKUPS.load(Ordering::SeqCst), 0);
        assert_eq!(V2_SEEN_VERSION.load(Ordering::SeqCst), 2);

        let selected = select_register::<RpiPluginRegister, LegacyRpiPluginRegister, &str>(
            Err("v2 missing"),
            || {
                V1_LOOKUPS.fetch_add(1, Ordering::SeqCst);
                Ok(test_register_v1)
            },
        )
        .expect("legacy selected");
        let entrypoint = match selected {
            Ok(register) => RegisterEntrypoint::V2(register),
            Err(register) => RegisterEntrypoint::V1(register),
        };
        assert_eq!(call_register(entrypoint, &test_host_api()), 0);
        assert_eq!(V1_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(V1_LOOKUPS.load(Ordering::SeqCst), 1);
        assert_eq!(V1_SEEN_VERSION.load(Ordering::SeqCst), 1);

        // A selected v2 entrypoint that fails is still called once and is not
        // followed by a legacy call.
        V2_RETURN.store(73, Ordering::SeqCst);
        let selected = select_register::<RpiPluginRegister, LegacyRpiPluginRegister, &str>(
            Ok(test_register_v2),
            || {
                V1_LOOKUPS.fetch_add(1, Ordering::SeqCst);
                Ok(test_register_v1)
            },
        )
        .expect("v2 selected even though its later call will fail");
        let entrypoint = match selected {
            Ok(register) => RegisterEntrypoint::V2(register),
            Err(register) => RegisterEntrypoint::V1(register),
        };
        assert_eq!(call_register(entrypoint, &test_host_api()), 73);
        assert_eq!(V2_CALLS.load(Ordering::SeqCst), 2);
        assert_eq!(V1_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(V1_LOOKUPS.load(Ordering::SeqCst), 1);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn loads_real_v011_plugin_and_dispatches_old_enum_reload() {
        let fixture = build_cdylib_fixture("abi_v011_real", V011_PLUGIN_SOURCE);
        let reloads = Arc::new(AtomicUsize::new(0));
        let host: Arc<dyn crate::RuntimeActionHost> = Arc::new(LegacyReloadHost {
            reloads: Arc::clone(&reloads),
        });
        let bridge = ActionBridge::new(tokio::runtime::Handle::current(), host);
        let diagnostics = Arc::new(CapturingDiag::default());

        let loaded = load_one(
            &fixture.path,
            Arc::clone(&diagnostics) as Arc<dyn PluginDiagnostics>,
            Some(bridge),
        )
        .expect("load plugin built against the vendored v0.1.11 ABI");

        assert_eq!(loaded.abi_version, LEGACY_PLUGIN_ABI_VERSION);
        assert_eq!(reloads.load(Ordering::SeqCst), 1);
        assert!(diagnostics.warns.lock().unwrap().is_empty());
        drop(loaded);
        drop(fixture);
    }

    #[test]
    fn load_one_supports_both_abis_prefers_v2_and_never_retries_failed_v2() {
        const PREFIX: &str = "use std::ffi::c_void;\n";
        let diag: Arc<dyn PluginDiagnostics> = Arc::new(CapturingDiag::default());

        let v1 = build_cdylib_fixture(
            "abi_v1_only",
            &format!(
                "{PREFIX}#[no_mangle]\npub extern \"C\" fn rpi_plugin_register(api: *const c_void, abi: u32) -> i32 {{ if !api.is_null() && abi == 1 {{ 0 }} else {{ 91 }} }}\n"
            ),
        );
        let loaded_v1 = load_one(&v1.path, Arc::clone(&diag), None).expect("load ABI v1 plugin");
        assert_eq!(loaded_v1.abi_version, 1);
        drop(loaded_v1);
        drop(v1);

        let v2 = build_cdylib_fixture(
            "abi_v2_only",
            &format!(
                "{PREFIX}#[no_mangle]\npub extern \"C\" fn rpi_plugin_register_v2(api: *const c_void, abi: u32) -> i32 {{ if !api.is_null() && abi == 2 {{ 0 }} else {{ 92 }} }}\n"
            ),
        );
        let loaded_v2 = load_one(&v2.path, Arc::clone(&diag), None).expect("load ABI v2 plugin");
        assert_eq!(loaded_v2.abi_version, 2);
        drop(loaded_v2);
        drop(v2);

        let dual = build_cdylib_fixture(
            "abi_dual",
            &format!(
                "{PREFIX}#[no_mangle]\npub extern \"C\" fn rpi_plugin_register(_: *const c_void, _: u32) -> i32 {{ 93 }}\n#[no_mangle]\npub extern \"C\" fn rpi_plugin_register_v2(api: *const c_void, abi: u32) -> i32 {{ if !api.is_null() && abi == 2 {{ 0 }} else {{ 94 }} }}\n"
            ),
        );
        let loaded_dual =
            load_one(&dual.path, Arc::clone(&diag), None).expect("dual-symbol plugin uses v2");
        assert_eq!(loaded_dual.abi_version, 2);
        drop(loaded_dual);
        drop(dual);

        let failed_v2 = build_cdylib_fixture(
            "abi_v2_failure",
            &format!(
                "{PREFIX}#[no_mangle]\npub extern \"C\" fn rpi_plugin_register(_: *const c_void, _: u32) -> i32 {{ 0 }}\n#[no_mangle]\npub extern \"C\" fn rpi_plugin_register_v2(_: *const c_void, _: u32) -> i32 {{ 73 }}\n"
            ),
        );
        let error = match load_one(&failed_v2.path, diag, None) {
            Ok(_) => panic!("failed v2 registration must not fall back to v1"),
            Err(error) => error,
        };
        assert!(matches!(
            error,
            PluginLoadError::RegisterReturned { code: 73, .. }
        ));
        drop(failed_v2);
    }

    #[test]
    fn load_one_missing_file_reports_open_error() {
        let diag: Arc<dyn PluginDiagnostics> = Arc::new(CapturingDiag::default());
        let res = load_one("definitely_not_a_plugin.dll", diag, None);
        assert!(matches!(res, Err(PluginLoadError::Open { .. })));
    }

    #[test]
    fn load_dir_missing_dir_returns_empty_and_warns() {
        let empty = load_dir(
            "no_such_dir_xyz",
            Arc::new(CapturingDiag::default()) as Arc<dyn PluginDiagnostics>,
            None,
        );
        assert!(empty.is_empty());
    }

    #[test]
    fn is_cdylib_recognizes_extensions() {
        assert!(is_cdylib(Path::new("foo.dll")));
        assert!(is_cdylib(Path::new("foo.so")));
        assert!(is_cdylib(Path::new("foo.dylib")));
        assert!(is_cdylib(Path::new("FOO.DLL")));
        assert!(!is_cdylib(Path::new("foo.md")));
        assert!(!is_cdylib(Path::new("foo")));
    }
}

// Silence the unused-default-import warning for NullDiagnostics re-exported by the crate.
#[allow(dead_code)]
fn _ensure_nulldiagnostics_referenced() -> Arc<dyn PluginDiagnostics> {
    Arc::new(NullDiagnostics)
}