evorule-plugin-kit 0.1.0

In-process native plugin mechanism common crate: NativeService trait, service declaration entries, and a generic filter router shared by all evorule-services plugin families
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 EvoRule Project
// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
//! In-process native plugin mechanism common crate for evorule-services.
//!
//! This crate defines the `NativeService` trait, the `NativeServiceDef`
//! declaration entry, and the generic filter router shared by all plugin
//! families. Each family keeps its own declaration table; the host mounts
//! the router with a per-family enable set.
//!
//! # Components
//!
//! - [`NativeService`]: the uniform in-process service entry point.
//! - [`NativeServiceDef`]: declarative registration entry (name, sensitivity
//!   flag, one-line description, optional JSON Schema parameter contract,
//!   instance constructor).
//! - [`NativeServiceRouter`]: composite `IoHandler` that dispatches by
//!   `service_name` to a native service and falls back to HTTP otherwise.
//! - [`mount_router`]: mount helper producing an `Arc<dyn IoHandler>`.
//!
//! # Enable semantics
//!
//! `NativeServiceRouter::with_enabled` and [`mount_router`] enforce three
//! fail-fast rejections: unknown name, duplicate name, empty enable set.
//! Router lookup always follows declaration order, regardless of the order
//! of the enable set passed in.
//!
//! # Async extension point
//!
//! `NativeService::execute_async` is an async extension point whose default
//! implementation wraps the synchronous `execute` in an immediately-ready
//! future, so non-overriding services keep byte-for-byte identical behavior.
//! The router always awaits `execute_async`, which makes overriding fully
//! transparent to callers.
//!
//! Services that need external I/O (HTTP egress, long polling, and similar)
//! MUST override this method; they must not perform egress from the
//! synchronous `execute` (no runtime support on that path). Any degraded
//! result (e.g. a local stub while the external service is unavailable)
//! must be truthfully labeled in the returned body; a stub must never
//! impersonate the real service.
//!
//! # Usage (plugin side)
//!
//! - Export a `&'static [NativeServiceDef]` declaration table: adding a
//!   native capability = append one entry + enable it in the plugin
//!   manifest; the host and the mechanism need zero changes.
//! - Services with a fixed parameter surface declare `parameters` as a JSON
//!   Schema string (OpenAI function parameters subset); it is forwarded to
//!   LLM consumers via the capability inventory.
//! - Wrap the table with [`mount_router`] (or use [`NativeServiceRouter`]
//!   directly) to obtain the mountable handler.

#![forbid(unsafe_code)]

mod reexports;

pub use reexports::*;

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use async_trait::async_trait;

/// Uniform entry point for native services: receives `args` (with `__`
/// paths already resolved to concrete values by the engine) and returns the
/// business result.
pub trait NativeService: Send + Sync {
    fn execute(&self, args: &JsonValue) -> IoResult;

    /// Async extension point for native services that need **external I/O**
    /// (HTTP egress, long polling, and similar).
    ///
    /// The default implementation wraps the synchronous `execute` in an
    /// immediately-ready future (byte-for-byte equivalent for existing
    /// services; invisible to the upper layer). The router uniformly awaits
    /// `execute_async`, so overriders and non-overriders are fully
    /// transparent to callers.
    ///
    /// # Why this extension point exists
    ///
    /// `execute` is synchronous: plugins previously had no regular egress
    /// path at all. Pure-computation services are fine, but services calling
    /// external APIs (LLM advisors and similar) had nowhere to go except
    /// offline stubs. The async extension point brings egress into the
    /// regular plugin mechanism without changing the core crate's execution
    /// semantics.
    ///
    /// # Discipline
    ///
    /// Services that need external I/O **must** override this method; they
    /// must not perform egress from the synchronous `execute` (no runtime
    /// support on that path). Any degraded result (e.g. a local stub while
    /// the external service is unavailable) must be truthfully labeled in
    /// the returned body; a stub must never impersonate the real service.
    fn execute_async<'a>(
        &'a self,
        args: &'a JsonValue,
    ) -> Pin<Box<dyn Future<Output = IoResult> + Send + 'a>> {
        Box::pin(async move { self.execute(args) })
    }
}

/// Native service declaration entry (declarative registration: adding a
/// native capability = appending one entry to the plugin declaration table;
/// the router, the capability inventory, and binding checks need zero
/// changes).
///
/// `name` aligns with the governance-side service catalog seed; the shared
/// source of truth is each family's `official_native_services.json`, with
/// two-sided guards locking drift.
pub struct NativeServiceDef {
    /// Globally unique service name (`service_name` of `io_request`; unique
    /// across families, locked when aggregated on the governance side).
    pub name: &'static str,
    /// Whether the service touches credentials or sensitive data (aligned
    /// with governance-side catalog metadata).
    pub sensitive: bool,
    /// One-line description (consumed by the capability inventory / docs).
    pub description: &'static str,
    /// Parameter contract (JSON Schema string in the OpenAI function
    /// parameters subset): `None` = no contract declared, the capability
    /// inventory omits `parameters`, and LLM consumers degrade to an empty
    /// schema (byte-for-byte identical to existing behavior, no silent
    /// semantic change). Adding a service = append an entry to this table;
    /// services with a fixed parameter surface should also declare
    /// `parameters` so the LLM side can generate the tool schema.
    pub parameters: Option<&'static str>,
    /// Instance constructor (stateful services inject their default state
    /// here).
    pub make: fn() -> Arc<dyn NativeService>,
}

/// Composite IoHandler: a `service_name` hit on a native service name
/// dispatches natively; otherwise falls back to HTTP.
///
/// Mounted for `IoType::call_service` / `IoType::call_external`.
/// The declaration table is provided by the caller
/// (`&'static [NativeServiceDef]`, owned per family); router lookup always
/// follows declaration order (independent of the enable set order).
pub struct NativeServiceRouter {
    /// Native service instances
    instances: Vec<(&'static str, Arc<dyn NativeService>)>,
    /// HTTP fallback when no native service matches (ServiceRegistryHandler,
    /// reads service_registry.json)
    fallback: Arc<dyn IoHandler>,
}

impl NativeServiceRouter {
    /// Build a composite router with the full enable set. `fallback` is the
    /// HTTP handler used when no native service name matches (typically
    /// `Arc<ServiceRegistryHandler>`, constructed by the caller per
    /// `--allow-loopback`).
    pub fn new(defs: &'static [NativeServiceDef], fallback: Arc<dyn IoHandler>) -> Self {
        Self {
            instances: defs.iter().map(|d| (d.name, (d.make)())).collect(),
            fallback,
        }
    }

    /// Deployment-time subset constructor.
    ///
    /// - `enabled` is the set of enabled service names (order-insensitive;
    ///   router lookup still follows declaration order);
    /// - unknown name / duplicate name / empty enable set -> fail-fast
    ///   `Err` with guidance (never silently ignored);
    /// - the host never special-cases concrete names: adding a native
    ///   capability = append to the declaration table + enable in the
    ///   manifest.
    pub fn with_enabled(
        defs: &'static [NativeServiceDef],
        fallback: Arc<dyn IoHandler>,
        enabled: &[&str],
    ) -> Result<Self, String> {
        if enabled.is_empty() {
            return Err(
                "plugin enable set is empty - to disable all native services set enabled=false \
                 directly (do not mount this router); to enable, list at least one service in \
                 plugin_manifest.services"
                    .to_string(),
            );
        }
        let mut seen: Vec<&str> = Vec::new();
        for name in enabled {
            let known = defs.iter().any(|d| d.name == *name);
            if !known {
                return Err(format!(
                    "plugin_manifest references an unregistered native service '{name}' - valid \
                     service names: [{}]. Troubleshooting: (1) check the service_name spelling \
                     against this list (not the governance-side catalog); (2) to add a native \
                     service, append an entry to the NATIVE_SERVICES declaration table and then \
                     enable it in the manifest",
                    defs.iter().map(|d| d.name).collect::<Vec<_>>().join(", ")
                ));
            }
            if seen.contains(name) {
                return Err(format!(
                    "plugin_manifest service '{name}' is declared more than once - deduplicate \
                     and retry (no silent dedup)"
                ));
            }
            seen.push(name);
        }
        Ok(Self {
            instances: defs
                .iter()
                .filter(|d| seen.contains(&d.name))
                .map(|d| (d.name, (d.make)()))
                .collect(),
            fallback,
        })
    }

    /// Names of the native services enabled on this instance (for health
    /// visibility / capability inventory).
    pub fn enabled_service_names(&self) -> Vec<&'static str> {
        self.instances.iter().map(|(n, _)| *n).collect()
    }

    /// Native service names derived from the declaration table (for
    /// server-side binding checks / capability inventory).
    pub fn native_service_names(defs: &'static [NativeServiceDef]) -> Vec<&'static str> {
        defs.iter().map(|d| d.name).collect()
    }

    /// Resolve `service_name` (top level of `params`) and extract `args`
    /// (defaults to an empty object).
    fn split_params(params: &JsonValue) -> (Option<String>, JsonValue) {
        let service_name = params
            .get("service_name")
            .and_then(|v| v.as_str())
            .or_else(|| params.get("name").and_then(|v| v.as_str()))
            .map(|s| s.to_string());
        let args = params
            .get("args")
            .cloned()
            .unwrap_or_else(JsonValue::empty_object);
        (service_name, args)
    }
}

#[async_trait]
impl IoHandler for NativeServiceRouter {
    async fn execute(&self, params: &JsonValue) -> IoResult {
        let (service_name, args) = Self::split_params(params);
        let name = service_name.as_deref().unwrap_or("");
        // Declaration-table lookup dispatch: adding a native service = one
        // entry in the table, zero changes here; lookup only covers the
        // subset enabled on this router instance (not enabled -> fallback /
        // truthful error).
        match self.instances.iter().find(|(n, _)| *n == name) {
            // Uniformly awaits execute_async: services needing external I/O
            // override the async extension point to gain egress;
            // non-overriders take the default implementation (= synchronous
            // execute, immediately ready), byte-for-byte equivalent.
            Some((_, svc)) => svc.execute_async(&args).await,
            _ => self.fallback.execute(params).await,
        }
    }
}

/// Mount helper: builds an `Arc<dyn IoHandler>` with enable semantics
/// (referenced directly by the server-side `PluginDef`, avoiding per-family
/// wrapper constructors).
///
/// - `None` = full enable (default; existing deployments migrate with zero
///   changes);
/// - `Some(slice)` = subset enable (three-rejection validation identical to
///   [`NativeServiceRouter::with_enabled`]).
///
/// `Some(&[])` corresponds to `enabled=false` in manifest semantics (the
/// router is not mounted at all) and never reaches this function; it would
/// still be truthfully rejected here under the three-rejection rules rather
/// than silently becoming full enable.
pub fn mount_router(
    defs: &'static [NativeServiceDef],
    fallback: Arc<dyn IoHandler>,
    enabled: Option<&[&str]>,
) -> Result<Arc<dyn IoHandler>, String> {
    match enabled {
        None => Ok(Arc::new(NativeServiceRouter::new(defs, fallback))),
        Some(names) => Ok(Arc::new(NativeServiceRouter::with_enabled(
            defs, fallback, names,
        )?)),
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;

    // ===== Test stubs: two-service declaration table (mechanism cases
    // consolidated from the isomorphic cases of the plugin families) =====

    struct Echo;
    impl NativeService for Echo {
        fn execute(&self, args: &JsonValue) -> IoResult {
            Ok(JsonValue::object_from_pairs(&[
                ("svc", JsonValue::string("echo")),
                ("got", args.get("k").cloned().unwrap_or(JsonValue::Null)),
            ]))
        }
    }

    struct Other;
    impl NativeService for Other {
        fn execute(&self, _args: &JsonValue) -> IoResult {
            Ok(JsonValue::object_from_pairs(&[(
                "svc",
                JsonValue::string("other"),
            )]))
        }
    }

    static DEFS: &[NativeServiceDef] = &[
        NativeServiceDef {
            name: "kit_echo",
            sensitive: false,
            description: "echo stub",
            parameters: None,
            make: || Arc::new(Echo),
        },
        NativeServiceDef {
            name: "kit_other",
            sensitive: false,
            description: "other stub",
            parameters: None,
            make: || Arc::new(Other),
        },
    ];

    struct ErrHandler;
    #[async_trait]
    impl IoHandler for ErrHandler {
        async fn execute(&self, _params: &JsonValue) -> IoResult {
            Err("fallback-called".to_string())
        }
    }

    fn params_of(service_name: &str, args: JsonValue) -> JsonValue {
        JsonValue::object_from_pairs(&[
            ("service_name", JsonValue::string(service_name)),
            ("args", args),
        ])
    }

    #[tokio::test]
    async fn test_router_fallback_on_unknown_service() {
        // Unknown service_name -> fall back to the HTTP fallback (sentinel
        // error verifies dispatch).
        let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
        let p = params_of("unknown_svc", JsonValue::object_from_pairs(&[]));
        assert_eq!(router.execute(&p).await.unwrap_err(), "fallback-called");
    }

    #[tokio::test]
    async fn test_args_passed_through_and_name_alias() {
        // args passed through as-is + `name` alias resolution (same
        // semantics as the plugin families).
        let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
        let p = JsonValue::object_from_pairs(&[
            ("name", JsonValue::string("kit_echo")),
            (
                "args",
                JsonValue::object_from_pairs(&[("k", JsonValue::Integer(7))]),
            ),
        ]);
        let r = router.execute(&p).await.unwrap();
        assert_eq!(r.get("svc").and_then(|v| v.as_str()), Some("echo"));
        assert_eq!(r.get("got").and_then(|v| v.as_i64()), Some(7));
    }

    #[tokio::test]
    async fn test_router_dispatches_through_async_extension_point() {
        // Async extension point: a service overriding execute_async must take
        // effect through that path (the regular egress path for external-I/O
        // services); non-overriders still take the synchronous execute (the
        // default implementation is equivalent).
        struct AsyncOnly;
        impl NativeService for AsyncOnly {
            fn execute(&self, _args: &JsonValue) -> IoResult {
                Ok(JsonValue::object_from_pairs(&[(
                    "path",
                    JsonValue::string("sync"),
                )]))
            }
            fn execute_async<'a>(
                &'a self,
                _args: &'a JsonValue,
            ) -> Pin<Box<dyn Future<Output = IoResult> + Send + 'a>> {
                Box::pin(async move {
                    Ok(JsonValue::object_from_pairs(&[(
                        "path",
                        JsonValue::string("async"),
                    )]))
                })
            }
        }

        static DEFS2: &[NativeServiceDef] = &[NativeServiceDef {
            name: "kit_async_only",
            sensitive: false,
            description: "async extension point stub",
            parameters: None,
            make: || Arc::new(AsyncOnly),
        }];

        let router = NativeServiceRouter::new(DEFS2, Arc::new(ErrHandler));
        let p = params_of("kit_async_only", JsonValue::object_from_pairs(&[]));
        let r = router.execute(&p).await.unwrap();
        assert_eq!(
            r.get("path").and_then(|v| v.as_str()),
            Some("async"),
            "the router must go through execute_async (otherwise egress services have no \
             regular path)"
        );
    }

    #[test]
    fn test_def_table_invariants() {
        // Declaration-table invariants: service names unique; every
        // constructor usable.
        let mut names: Vec<&str> = DEFS.iter().map(|d| d.name).collect();
        let total = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(
            names.len(),
            total,
            "declaration table service names must be unique"
        );
        for d in DEFS {
            let _ = (d.make)();
        }
    }

    #[tokio::test]
    async fn test_all_defs_route_natively() {
        // Every entry of the declaration table must hit native execution
        // (not the HTTP fallback) - the fallback is a sentinel error, so any
        // entry landing there fails this test.
        let router = NativeServiceRouter::new(DEFS, Arc::new(ErrHandler));
        for d in DEFS {
            let p = params_of(d.name, JsonValue::object_from_pairs(&[]));
            // With empty arguments the business result may succeed or fail,
            // but it must never be the fallback sentinel.
            if let Err(e) = router.execute(&p).await {
                assert_ne!(
                    e, "fallback-called",
                    "service {} fell through to the HTTP fallback",
                    d.name
                );
            }
        }
    }

    #[tokio::test]
    async fn test_with_enabled_subset_filter_deterministic() {
        // Subset filter: only enabled services hit native execution; disabled
        // ones fall back.
        let router =
            NativeServiceRouter::with_enabled(DEFS, Arc::new(ErrHandler), &["kit_echo"]).unwrap();
        assert_eq!(router.enabled_service_names(), vec!["kit_echo"]);
        // Enabled service -> native (no fallback sentinel).
        let p = params_of("kit_echo", JsonValue::object_from_pairs(&[]));
        let r = router.execute(&p).await.unwrap();
        assert_eq!(r.get("svc").and_then(|v| v.as_str()), Some("echo"));
        // Disabled service -> fallback.
        let p = params_of("kit_other", JsonValue::object_from_pairs(&[]));
        assert_eq!(router.execute(&p).await.unwrap_err(), "fallback-called");
    }

    #[test]
    fn test_with_enabled_rejects_unknown_duplicate_and_empty() {
        // The router does not implement Debug; take Err explicitly via match
        // (same test convention as the plugin families).
        fn expect_err(r: Result<NativeServiceRouter, String>) -> String {
            match r {
                Ok(_) => panic!("construction must fail"),
                Err(e) => e,
            }
        }
        // Unknown name -> Err with the valid-name list and guidance.
        let err = expect_err(NativeServiceRouter::with_enabled(
            DEFS,
            Arc::new(ErrHandler),
            &["kit_echo", "no_such_svc"],
        ));
        assert!(err.contains("no_such_svc"), "{err}");
        assert!(
            err.contains("kit_echo") && err.contains("NATIVE_SERVICES"),
            "{err}"
        );
        // Duplicate name -> Err (no silent dedup).
        let err = expect_err(NativeServiceRouter::with_enabled(
            DEFS,
            Arc::new(ErrHandler),
            &["kit_echo", "kit_echo"],
        ));
        assert!(err.contains("more than once"), "{err}");
        // Empty enable set -> Err (guidance points at enabled=false).
        let err = expect_err(NativeServiceRouter::with_enabled(
            DEFS,
            Arc::new(ErrHandler),
            &[],
        ));
        assert!(err.contains("enabled=false"), "{err}");
    }

    #[tokio::test]
    async fn test_mount_router_all_and_subset() {
        // mount_router: None = full enable (native hits); Some(subset) =
        // disabled names fall back, consistent with with_enabled.
        let all = mount_router(DEFS, Arc::new(ErrHandler), None).unwrap();
        let p = params_of("kit_other", JsonValue::object_from_pairs(&[]));
        assert_eq!(
            all.execute(&p)
                .await
                .unwrap()
                .get("svc")
                .and_then(|v| v.as_str()),
            Some("other")
        );
        let subset = mount_router(DEFS, Arc::new(ErrHandler), Some(&["kit_echo"])).unwrap();
        assert_eq!(
            subset.execute(&p).await.unwrap_err(),
            "fallback-called",
            "services outside a Some(subset) must fall back, not silently become full enable"
        );
    }
}