Skip to main content

evorule_plugin_kit/
lib.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (C) 2026 EvoRule Project
3// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
4//! In-process native plugin mechanism common crate for evorule-services.
5//!
6//! This crate defines the `NativeService` trait, the `NativeServiceDef`
7//! declaration entry, and the generic filter router shared by all plugin
8//! families. Each family keeps its own declaration table; the host mounts
9//! the router with a per-family enable set.
10//!
11//! # Components
12//!
13//! - [`NativeService`]: the uniform in-process service entry point.
14//! - [`NativeServiceDef`]: declarative registration entry (name, sensitivity
15//!   flag, one-line description, optional JSON Schema parameter contract,
16//!   instance constructor).
17//! - [`NativeServiceRouter`]: composite `IoHandler` that dispatches by
18//!   `service_name` to a native service and falls back to HTTP otherwise.
19//! - [`mount_router`]: mount helper producing an `Arc<dyn IoHandler>`.
20//!
21//! # Enable semantics
22//!
23//! `NativeServiceRouter::with_enabled` and [`mount_router`] enforce three
24//! fail-fast rejections: unknown name, duplicate name, empty enable set.
25//! Router lookup always follows declaration order, regardless of the order
26//! of the enable set passed in.
27//!
28//! # Async extension point
29//!
30//! `NativeService::execute_async` is an async extension point whose default
31//! implementation wraps the synchronous `execute` in an immediately-ready
32//! future, so non-overriding services keep byte-for-byte identical behavior.
33//! The router always awaits `execute_async`, which makes overriding fully
34//! transparent to callers.
35//!
36//! Services that need external I/O (HTTP egress, long polling, and similar)
37//! MUST override this method; they must not perform egress from the
38//! synchronous `execute` (no runtime support on that path). Any degraded
39//! result (e.g. a local stub while the external service is unavailable)
40//! must be truthfully labeled in the returned body; a stub must never
41//! impersonate the real service.
42//!
43//! # Usage (plugin side)
44//!
45//! - Export a `&'static [NativeServiceDef]` declaration table: adding a
46//!   native capability = append one entry + enable it in the plugin
47//!   manifest; the host and the mechanism need zero changes.
48//! - Services with a fixed parameter surface declare `parameters` as a JSON
49//!   Schema string (OpenAI function parameters subset); it is forwarded to
50//!   LLM consumers via the capability inventory.
51//! - Wrap the table with [`mount_router`] (or use [`NativeServiceRouter`]
52//!   directly) to obtain the mountable handler.
53
54#![forbid(unsafe_code)]
55
56mod convert;
57mod reexports;
58
59pub use convert::serde_to_tcb;
60pub use reexports::*;
61
62use std::future::Future;
63use std::pin::Pin;
64use std::sync::Arc;
65
66use async_trait::async_trait;
67
68/// Uniform entry point for native services: receives `args` (with `__`
69/// paths already resolved to concrete values by the engine) and returns the
70/// business result.
71pub trait NativeService: Send + Sync {
72    fn execute(&self, args: &JsonValue) -> IoResult;
73
74    /// Async extension point for native services that need **external I/O**
75    /// (HTTP egress, long polling, and similar).
76    ///
77    /// The default implementation wraps the synchronous `execute` in an
78    /// immediately-ready future (byte-for-byte equivalent for existing
79    /// services; invisible to the upper layer). The router uniformly awaits
80    /// `execute_async`, so overriders and non-overriders are fully
81    /// transparent to callers.
82    ///
83    /// # Why this extension point exists
84    ///
85    /// `execute` is synchronous: plugins previously had no regular egress
86    /// path at all. Pure-computation services are fine, but services calling
87    /// external APIs (LLM advisors and similar) had nowhere to go except
88    /// offline stubs. The async extension point brings egress into the
89    /// regular plugin mechanism without changing the core crate's execution
90    /// semantics.
91    ///
92    /// # Discipline
93    ///
94    /// Services that need external I/O **must** override this method; they
95    /// must not perform egress from the synchronous `execute` (no runtime
96    /// support on that path). Any degraded result (e.g. a local stub while
97    /// the external service is unavailable) must be truthfully labeled in
98    /// the returned body; a stub must never impersonate the real service.
99    fn execute_async<'a>(
100        &'a self,
101        args: &'a JsonValue,
102    ) -> Pin<Box<dyn Future<Output = IoResult> + Send + 'a>> {
103        Box::pin(async move { self.execute(args) })
104    }
105}
106
107/// Native service declaration entry (declarative registration: adding a
108/// native capability = appending one entry to the plugin declaration table;
109/// the router, the capability inventory, and binding checks need zero
110/// changes).
111///
112/// `name` aligns with the governance-side service catalog seed; the shared
113/// source of truth is each family's `official_native_services.json`, with
114/// two-sided guards locking drift.
115pub struct NativeServiceDef {
116    /// Globally unique service name (`service_name` of `io_request`; unique
117    /// across families, locked when aggregated on the governance side).
118    pub name: &'static str,
119    /// Whether the service touches credentials or sensitive data (aligned
120    /// with governance-side catalog metadata).
121    pub sensitive: bool,
122    /// One-line description (consumed by the capability inventory / docs).
123    pub description: &'static str,
124    /// Parameter contract (JSON Schema string in the OpenAI function
125    /// parameters subset): `None` = no contract declared, the capability
126    /// inventory omits `parameters`, and LLM consumers degrade to an empty
127    /// schema (byte-for-byte identical to existing behavior, no silent
128    /// semantic change). Adding a service = append an entry to this table;
129    /// services with a fixed parameter surface should also declare
130    /// `parameters` so the LLM side can generate the tool schema.
131    pub parameters: Option<&'static str>,
132    /// Instance constructor (stateful services inject their default state
133    /// here).
134    pub make: fn() -> Arc<dyn NativeService>,
135}
136
137/// Composite IoHandler: a `service_name` hit on a native service name
138/// dispatches natively; otherwise falls back to HTTP.
139///
140/// Mounted for `IoType::call_service` / `IoType::call_external`.
141/// The declaration table is provided by the caller
142/// (`&'static [NativeServiceDef]`, owned per family); router lookup always
143/// follows declaration order (independent of the enable set order).
144pub struct NativeServiceRouter {
145    /// Native service instances
146    instances: Vec<(&'static str, Arc<dyn NativeService>)>,
147    /// HTTP fallback when no native service matches (ServiceRegistryHandler,
148    /// reads service_registry.json)
149    fallback: Arc<dyn IoHandler>,
150}
151
152impl NativeServiceRouter {
153    /// Build a composite router with the full enable set. `fallback` is the
154    /// HTTP handler used when no native service name matches (typically
155    /// `Arc<ServiceRegistryHandler>`, constructed by the caller per
156    /// `--allow-loopback`).
157    pub fn new(defs: &'static [NativeServiceDef], fallback: Arc<dyn IoHandler>) -> Self {
158        Self {
159            instances: defs.iter().map(|d| (d.name, (d.make)())).collect(),
160            fallback,
161        }
162    }
163
164    /// Deployment-time subset constructor.
165    ///
166    /// - `enabled` is the set of enabled service names (order-insensitive;
167    ///   router lookup still follows declaration order);
168    /// - unknown name / duplicate name / empty enable set -> fail-fast
169    ///   `Err` with guidance (never silently ignored);
170    /// - the host never special-cases concrete names: adding a native
171    ///   capability = append to the declaration table + enable in the
172    ///   manifest.
173    pub fn with_enabled(
174        defs: &'static [NativeServiceDef],
175        fallback: Arc<dyn IoHandler>,
176        enabled: &[&str],
177    ) -> Result<Self, String> {
178        if enabled.is_empty() {
179            return Err(
180                "plugin enable set is empty - to disable all native services set enabled=false \
181                 directly (do not mount this router); to enable, list at least one service in \
182                 plugin_manifest.services"
183                    .to_string(),
184            );
185        }
186        let mut seen: Vec<&str> = Vec::new();
187        for name in enabled {
188            let known = defs.iter().any(|d| d.name == *name);
189            if !known {
190                return Err(format!(
191                    "plugin_manifest references an unregistered native service '{name}' - valid \
192                     service names: [{}]. Troubleshooting: (1) check the service_name spelling \
193                     against this list (not the governance-side catalog); (2) to add a native \
194                     service, append an entry to the NATIVE_SERVICES declaration table and then \
195                     enable it in the manifest",
196                    defs.iter().map(|d| d.name).collect::<Vec<_>>().join(", ")
197                ));
198            }
199            if seen.contains(name) {
200                return Err(format!(
201                    "plugin_manifest service '{name}' is declared more than once - deduplicate \
202                     and retry (no silent dedup)"
203                ));
204            }
205            seen.push(name);
206        }
207        Ok(Self {
208            instances: defs
209                .iter()
210                .filter(|d| seen.contains(&d.name))
211                .map(|d| (d.name, (d.make)()))
212                .collect(),
213            fallback,
214        })
215    }
216
217    /// Names of the native services enabled on this instance (for health
218    /// visibility / capability inventory).
219    pub fn enabled_service_names(&self) -> Vec<&'static str> {
220        self.instances.iter().map(|(n, _)| *n).collect()
221    }
222
223    /// Native service names derived from the declaration table (for
224    /// server-side binding checks / capability inventory).
225    pub fn native_service_names(defs: &'static [NativeServiceDef]) -> Vec<&'static str> {
226        defs.iter().map(|d| d.name).collect()
227    }
228
229    /// Resolve `service_name` (top level of `params`) and extract `args`
230    /// (defaults to an empty object).
231    fn split_params(params: &JsonValue) -> (Option<String>, JsonValue) {
232        let service_name = params
233            .get("service_name")
234            .and_then(|v| v.as_str())
235            .or_else(|| params.get("name").and_then(|v| v.as_str()))
236            .map(|s| s.to_string());
237        let args = params
238            .get("args")
239            .cloned()
240            .unwrap_or_else(JsonValue::empty_object);
241        (service_name, args)
242    }
243}
244
245#[async_trait]
246impl IoHandler for NativeServiceRouter {
247    async fn execute(&self, params: &JsonValue) -> IoResult {
248        let (service_name, args) = Self::split_params(params);
249        let name = service_name.as_deref().unwrap_or("");
250        // Declaration-table lookup dispatch: adding a native service = one
251        // entry in the table, zero changes here; lookup only covers the
252        // subset enabled on this router instance (not enabled -> fallback /
253        // truthful error).
254        match self.instances.iter().find(|(n, _)| *n == name) {
255            // Uniformly awaits execute_async: services needing external I/O
256            // override the async extension point to gain egress;
257            // non-overriders take the default implementation (= synchronous
258            // execute, immediately ready), byte-for-byte equivalent.
259            Some((_, svc)) => svc.execute_async(&args).await,
260            _ => self.fallback.execute(params).await,
261        }
262    }
263}
264
265/// Mount helper: builds an `Arc<dyn IoHandler>` with enable semantics
266/// (referenced directly by the server-side `PluginDef`, avoiding per-family
267/// wrapper constructors).
268///
269/// - `None` = full enable (default; existing deployments migrate with zero
270///   changes);
271/// - `Some(slice)` = subset enable (three-rejection validation identical to
272///   [`NativeServiceRouter::with_enabled`]).
273///
274/// `Some(&[])` corresponds to `enabled=false` in manifest semantics (the
275/// router is not mounted at all) and never reaches this function; it would
276/// still be truthfully rejected here under the three-rejection rules rather
277/// than silently becoming full enable.
278pub fn mount_router(
279    defs: &'static [NativeServiceDef],
280    fallback: Arc<dyn IoHandler>,
281    enabled: Option<&[&str]>,
282) -> Result<Arc<dyn IoHandler>, String> {
283    match enabled {
284        None => Ok(Arc::new(NativeServiceRouter::new(defs, fallback))),
285        Some(names) => Ok(Arc::new(NativeServiceRouter::with_enabled(
286            defs, fallback, names,
287        )?)),
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
294    use super::*;
295
296    // ===== Test stubs: two-service declaration table (mechanism cases
297    // consolidated from the isomorphic cases of the plugin families) =====
298
299    struct Echo;
300    impl NativeService for Echo {
301        fn execute(&self, args: &JsonValue) -> IoResult {
302            Ok(JsonValue::object_from_pairs(&[
303                ("svc", JsonValue::string("echo")),
304                ("got", args.get("k").cloned().unwrap_or(JsonValue::Null)),
305            ]))
306        }
307    }
308
309    struct Other;
310    impl NativeService for Other {
311        fn execute(&self, _args: &JsonValue) -> IoResult {
312            Ok(JsonValue::object_from_pairs(&[(
313                "svc",
314                JsonValue::string("other"),
315            )]))
316        }
317    }
318
319    static DEFS: &[NativeServiceDef] = &[
320        NativeServiceDef {
321            name: "kit_echo",
322            sensitive: false,
323            description: "echo stub",
324            parameters: None,
325            make: || Arc::new(Echo),
326        },
327        NativeServiceDef {
328            name: "kit_other",
329            sensitive: false,
330            description: "other stub",
331            parameters: None,
332            make: || Arc::new(Other),
333        },
334    ];
335
336    struct ErrHandler;
337    #[async_trait]
338    impl IoHandler for ErrHandler {
339        async fn execute(&self, _params: &JsonValue) -> IoResult {
340            Err("fallback-called".to_string())
341        }
342    }
343
344    fn params_of(service_name: &str, args: JsonValue) -> JsonValue {
345        JsonValue::object_from_pairs(&[
346            ("service_name", JsonValue::string(service_name)),
347            ("args", args),
348        ])
349    }
350
351    #[tokio::test]
352    async fn test_router_fallback_on_unknown_service() {
353        // Unknown service_name -> fall back to the HTTP fallback (sentinel
354        // error verifies dispatch).
355        let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
356        let p = params_of("unknown_svc", JsonValue::object_from_pairs(&[]));
357        assert_eq!(router.execute(&p).await.unwrap_err(), "fallback-called");
358    }
359
360    #[tokio::test]
361    async fn test_args_passed_through_and_name_alias() {
362        // args passed through as-is + `name` alias resolution (same
363        // semantics as the plugin families).
364        let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
365        let p = JsonValue::object_from_pairs(&[
366            ("name", JsonValue::string("kit_echo")),
367            (
368                "args",
369                JsonValue::object_from_pairs(&[("k", JsonValue::Integer(7))]),
370            ),
371        ]);
372        let r = router.execute(&p).await.unwrap();
373        assert_eq!(r.get("svc").and_then(|v| v.as_str()), Some("echo"));
374        assert_eq!(r.get("got").and_then(|v| v.as_i64()), Some(7));
375    }
376
377    #[tokio::test]
378    async fn test_router_dispatches_through_async_extension_point() {
379        // Async extension point: a service overriding execute_async must take
380        // effect through that path (the regular egress path for external-I/O
381        // services); non-overriders still take the synchronous execute (the
382        // default implementation is equivalent).
383        struct AsyncOnly;
384        impl NativeService for AsyncOnly {
385            fn execute(&self, _args: &JsonValue) -> IoResult {
386                Ok(JsonValue::object_from_pairs(&[(
387                    "path",
388                    JsonValue::string("sync"),
389                )]))
390            }
391            fn execute_async<'a>(
392                &'a self,
393                _args: &'a JsonValue,
394            ) -> Pin<Box<dyn Future<Output = IoResult> + Send + 'a>> {
395                Box::pin(async move {
396                    Ok(JsonValue::object_from_pairs(&[(
397                        "path",
398                        JsonValue::string("async"),
399                    )]))
400                })
401            }
402        }
403
404        static DEFS2: &[NativeServiceDef] = &[NativeServiceDef {
405            name: "kit_async_only",
406            sensitive: false,
407            description: "async extension point stub",
408            parameters: None,
409            make: || Arc::new(AsyncOnly),
410        }];
411
412        let router = NativeServiceRouter::new(DEFS2, Arc::new(ErrHandler));
413        let p = params_of("kit_async_only", JsonValue::object_from_pairs(&[]));
414        let r = router.execute(&p).await.unwrap();
415        assert_eq!(
416            r.get("path").and_then(|v| v.as_str()),
417            Some("async"),
418            "the router must go through execute_async (otherwise egress services have no \
419             regular path)"
420        );
421    }
422
423    #[test]
424    fn test_def_table_invariants() {
425        // Declaration-table invariants: service names unique; every
426        // constructor usable.
427        let mut names: Vec<&str> = DEFS.iter().map(|d| d.name).collect();
428        let total = names.len();
429        names.sort_unstable();
430        names.dedup();
431        assert_eq!(
432            names.len(),
433            total,
434            "declaration table service names must be unique"
435        );
436        for d in DEFS {
437            let _ = (d.make)();
438        }
439    }
440
441    #[tokio::test]
442    async fn test_all_defs_route_natively() {
443        // Every entry of the declaration table must hit native execution
444        // (not the HTTP fallback) - the fallback is a sentinel error, so any
445        // entry landing there fails this test.
446        let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
447        for d in DEFS {
448            let p = params_of(d.name, JsonValue::object_from_pairs(&[]));
449            // With empty arguments the business result may succeed or fail,
450            // but it must never be the fallback sentinel.
451            if let Err(e) = router.execute(&p).await {
452                assert_ne!(
453                    e, "fallback-called",
454                    "service {} fell through to the HTTP fallback",
455                    d.name
456                );
457            }
458        }
459    }
460
461    #[tokio::test]
462    async fn test_with_enabled_subset_filter_deterministic() {
463        // Subset filter: only enabled services hit native execution; disabled
464        // ones fall back.
465        let router =
466            NativeServiceRouter::with_enabled(DEFS, Arc::new(ErrHandler), &["kit_echo"]).unwrap();
467        assert_eq!(router.enabled_service_names(), vec!["kit_echo"]);
468        // Enabled service -> native (no fallback sentinel).
469        let p = params_of("kit_echo", JsonValue::object_from_pairs(&[]));
470        let r = router.execute(&p).await.unwrap();
471        assert_eq!(r.get("svc").and_then(|v| v.as_str()), Some("echo"));
472        // Disabled service -> fallback.
473        let p = params_of("kit_other", JsonValue::object_from_pairs(&[]));
474        assert_eq!(router.execute(&p).await.unwrap_err(), "fallback-called");
475    }
476
477    #[test]
478    fn test_with_enabled_rejects_unknown_duplicate_and_empty() {
479        // The router does not implement Debug; take Err explicitly via match
480        // (same test convention as the plugin families).
481        fn expect_err(r: Result<NativeServiceRouter, String>) -> String {
482            match r {
483                Ok(_) => panic!("construction must fail"),
484                Err(e) => e,
485            }
486        }
487        // Unknown name -> Err with the valid-name list and guidance.
488        let err = expect_err(NativeServiceRouter::with_enabled(
489            DEFS,
490            Arc::new(ErrHandler),
491            &["kit_echo", "no_such_svc"],
492        ));
493        assert!(err.contains("no_such_svc"), "{err}");
494        assert!(
495            err.contains("kit_echo") && err.contains("NATIVE_SERVICES"),
496            "{err}"
497        );
498        // Duplicate name -> Err (no silent dedup).
499        let err = expect_err(NativeServiceRouter::with_enabled(
500            DEFS,
501            Arc::new(ErrHandler),
502            &["kit_echo", "kit_echo"],
503        ));
504        assert!(err.contains("more than once"), "{err}");
505        // Empty enable set -> Err (guidance points at enabled=false).
506        let err = expect_err(NativeServiceRouter::with_enabled(
507            DEFS,
508            Arc::new(ErrHandler),
509            &[],
510        ));
511        assert!(err.contains("enabled=false"), "{err}");
512    }
513
514    #[tokio::test]
515    async fn test_mount_router_all_and_subset() {
516        // mount_router: None = full enable (native hits); Some(subset) =
517        // disabled names fall back, consistent with with_enabled.
518        let all = mount_router(DEFS, Arc::new(ErrHandler), None).unwrap();
519        let p = params_of("kit_other", JsonValue::object_from_pairs(&[]));
520        assert_eq!(
521            all.execute(&p)
522                .await
523                .unwrap()
524                .get("svc")
525                .and_then(|v| v.as_str()),
526            Some("other")
527        );
528        let subset = mount_router(DEFS, Arc::new(ErrHandler), Some(&["kit_echo"])).unwrap();
529        assert_eq!(
530            subset.execute(&p).await.unwrap_err(),
531            "fallback-called",
532            "services outside a Some(subset) must fall back, not silently become full enable"
533        );
534    }
535}