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