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