Repository navigation
Expand file tree
/
Copy pathclient.rs
More file actions
1351 lines (1256 loc) · 51.1 KB
/
Copy pathclient.rs
File metadata and controls
1351 lines (1256 loc) · 51.1 KB
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
// APCore Protocol — Client
// Spec reference: APCore client entry point
use std::sync::Arc;
use serde_json::Value;
use crate::approval::ApprovalHandler;
use crate::bindings::typed_async_handler;
use crate::config::Config;
use crate::context::Context;
use crate::decorator::FunctionModule;
use crate::errors::ModuleError;
use crate::events::emitter::EventEmitter;
use crate::events::subscribers::{EventSubscriber, SubscriberRegistry};
use crate::executor::Executor;
use crate::lifecycle::{
invalid_lifecycle_input, lifecycle_runtime, LifecycleOperation, ShutdownOptions,
UnregisterOptions,
};
use crate::middleware::adapters::{AfterMiddleware, BeforeMiddleware};
use crate::middleware::base::Middleware;
use crate::middleware::manager::MiddlewareHandle;
use crate::module::ModuleAnnotations;
use crate::observability::metrics::MetricsCollector;
use crate::policy::ExecutionPolicy;
use crate::registry::registry::{ModuleDescriptor, Registry, DEFAULT_MODULE_VERSION};
#[cfg(feature = "sys-modules")]
use crate::sys_modules::SysModulesStartup;
use crate::sys_modules::{SysModuleError, SysModulesContext, ToggleState};
/// Options for [`APCore::try_start`] and [`APCore::try_with_options`].
#[derive(Default)]
pub struct APCoreOptions {
pub registry: Option<Registry>,
pub executor: Option<Executor>,
pub config: Option<Config>,
pub metrics_collector: Option<MetricsCollector>,
/// Return the first system-module registration failure during startup.
pub fail_on_error: bool,
/// Approval handler for the Executor built by the client.
pub approval_handler: Option<Box<dyn ApprovalHandler>>,
/// Execution policy for the Executor built by the client.
pub policy: Option<ExecutionPolicy>,
}
/// Failure to initialize a client with [`APCore::try_start`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum APCoreStartupError {
#[error("ACL configuration failed to load: {source}")]
AclLoadFailed {
#[source]
source: ModuleError,
},
#[error("pipeline configuration failed to load: {source}")]
PipelineLoadFailed {
#[source]
source: ModuleError,
},
#[error(transparent)]
SystemModule(#[from] SysModuleError),
}
/// Optional module metadata for [`APCore::typed_module`].
#[derive(Default)]
pub struct TypedModuleOptions {
pub documentation: Option<String>,
pub tags: Vec<String>,
pub version: Option<String>,
pub metadata: Option<std::collections::HashMap<String, Value>>,
pub examples: Vec<crate::module::ModuleExample>,
pub display: Option<Value>,
}
/// Main entry point for interacting with the `APCore` system.
pub struct APCore {
pub config: Config,
/// Shared so a module this client runs can reach it for a nested call
/// through `ctx.executor()`.
executor: Arc<Executor>,
/// Single shared `Arc<Registry>` used by the executor, the pipeline, and
/// all sys modules. Interior mutability on `Registry` removes the need
/// for `Arc::get_mut` or an external `Mutex`.
registry: Arc<Registry>,
// The enabled system event bus shared by the client, registry callbacks,
// system modules, and the Executor the client builds.
event_emitter: Option<Arc<EventEmitter>>,
shutdown_operation: parking_lot::Mutex<Option<ClientShutdown>>,
metrics_collector: Option<MetricsCollector>,
sys_modules_context: Option<SysModulesContext>,
sys_modules_errors: Vec<SysModuleError>,
/// Per-instance toggle store (issue #71). Each `APCore` owns one
/// `Arc<ToggleState>`, injected into BOTH the pipeline `module_lookup` step
/// (read path, via `Executor::set_toggle_state`) and `ToggleFeatureModule`
/// (write path, via `register_sys_modules`). Disabling a module on one
/// instance MUST NOT affect another instance in the same process.
toggle_state: Arc<ToggleState>,
}
#[derive(Clone, Copy)]
enum Bootstrap<'a> {
InMemory,
Configured(Option<&'a SubscriberRegistry>),
}
#[derive(Default)]
struct SystemAssembly {
context: Option<SysModulesContext>,
errors: Vec<SysModuleError>,
emitter: Option<Arc<EventEmitter>>,
}
struct ClientShutdown {
operation: LifecycleOperation,
event_flush_timeout_ms: u32,
}
impl std::fmt::Debug for APCore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("APCore")
.field("config", &self.config)
.field("executor", &"<Executor>")
.field("registry", &self.registry)
.field("event_emitter", &self.event_emitter)
.field(
"shutdown_started",
&self.shutdown_operation.lock().is_some(),
)
.field("metrics_collector", &self.metrics_collector)
.field(
"sys_modules_registered",
&self.sys_modules_context.is_some(),
)
.field("sys_modules_errors", &self.sys_modules_errors.len())
.field("toggle_state", &self.toggle_state)
.finish()
}
}
impl Default for APCore {
fn default() -> Self {
Self::new()
}
}
impl APCore {
/// Create a new `APCore` client with in-memory defaults.
///
/// Use [`Self::with_config`] or [`Self::try_start`] for configured startup.
pub fn new() -> Self {
Self::in_memory()
}
/// Assemble a client from an empty registry and in-memory defaults.
/// File discovery and config-driven integrations are skipped during startup.
#[must_use]
pub fn in_memory() -> Self {
Self::build(APCoreOptions::default(), Bootstrap::InMemory)
}
/// Create a new `APCore` client with all optional parameters.
///
/// A single `Arc<Registry>` is shared between the executor, the pipeline,
/// and every built-in sys module — there is exactly one registry
/// instance per `APCore` client.
///
/// When `sys_modules.enabled` is true in the config (default: false; system
/// modules are opt-in), built-in system modules are automatically
/// registered into the executor pipeline.
/// If a discovered ACL cannot be loaded, invocations fail with
/// `CONFIG_INVALID`. Use [`Self::try_start`] for the startup error.
/// This registration is now fully synchronous and runtime-agnostic because
/// `Registry` uses `parking_lot::RwLock` for interior mutability.
pub fn with_options(
registry: Option<Registry>,
executor: Option<Executor>,
config: Option<Config>,
metrics_collector: Option<MetricsCollector>,
) -> Self {
Self::build(
APCoreOptions {
registry,
executor,
config,
metrics_collector,
..Default::default()
},
Bootstrap::Configured(None),
)
}
/// Create a client with explicit startup and governance options.
///
/// An approval handler and execution policy apply to a client-created
/// Executor. A supplied Executor keeps its own governance configuration.
///
/// # Errors
///
/// Returns the first system-module registration failure when
/// [`APCoreOptions::fail_on_error`] is set. Recovered registration failures
/// are available through [`Self::sys_modules_errors`]. If ACL or pipeline
/// configuration cannot load, invocations fail with the configuration
/// error. Use [`Self::try_start`] to report it during construction.
pub fn try_with_options(options: APCoreOptions) -> Result<Self, SysModuleError> {
let fail_on_error = options.fail_on_error;
let mut client = Self::build(options, Bootstrap::Configured(None));
client.check_system_registration(fail_on_error)?;
Ok(client)
}
/// Create a client and report configuration errors before its first invocation.
///
/// Reports invalid pipeline or ACL configuration, and honours
/// [`APCoreOptions::fail_on_error`] for system-module registration.
pub fn try_start(options: APCoreOptions) -> Result<Self, APCoreStartupError> {
Self::try_start_configured(options, None)
}
/// Start this client with its own factories for configured event subscribers.
/// Reports the same startup errors as [`Self::try_start`].
pub fn try_start_with_subscribers(
options: APCoreOptions,
subscribers: &SubscriberRegistry,
) -> Result<Self, APCoreStartupError> {
Self::try_start_configured(options, Some(subscribers))
}
fn try_start_configured(
options: APCoreOptions,
subscribers: Option<&SubscriberRegistry>,
) -> Result<Self, APCoreStartupError> {
let fail_on_error = options.fail_on_error;
let mut client = Self::build(options, Bootstrap::Configured(subscribers));
if let Some(source) = &client.executor.pipeline_load_error {
return Err(APCoreStartupError::PipelineLoadFailed {
source: source.clone(),
});
}
if let Some(source) = &client.executor.acl_load_error {
return Err(APCoreStartupError::AclLoadFailed {
source: source.clone(),
});
}
client.check_system_registration(fail_on_error)?;
Ok(client)
}
fn check_system_registration(&mut self, fail_on_error: bool) -> Result<(), SysModuleError> {
if fail_on_error {
return self.sys_modules_errors.pop().map_or(Ok(()), Err);
}
Ok(())
}
fn build(options: APCoreOptions, bootstrap: Bootstrap<'_>) -> Self {
let APCoreOptions {
registry,
executor,
config,
metrics_collector,
fail_on_error,
approval_handler,
policy,
} = options;
let (configured, subscribers) = match bootstrap {
Bootstrap::InMemory => (false, None),
Bootstrap::Configured(subscribers) => (true, subscribers),
};
let config = config.unwrap_or_else(|| {
if configured {
Config::default()
} else {
Config::in_memory()
}
});
// Resolve the shared registry: use the executor's if provided,
// otherwise the explicit `registry` arg, otherwise a fresh default.
let registry: Arc<Registry> = match executor.as_ref() {
Some(e) => Arc::clone(&e.registry),
None => Arc::new(registry.unwrap_or_default()),
};
// Config-driven extension roots. `extension_roots` initialises empty and
// was previously written only by `set_extension_roots`, so a client built
// from a `Config` carrying `extensions.root` handed an empty slice to the
// discoverer: `discover()` returned Ok(0), silently, indistinguishable
// from an empty directory. Python and TypeScript both resolve
// explicit > config > default in their Registry constructors; this is the
// Rust equivalent, placed here because `Registry::new()` takes no Config.
// Roots already set explicitly are left alone (see the method's docs).
if configured {
registry.set_extension_roots_from_config(&config);
}
// Track whether the caller supplied their own Executor: if so, respect
// its ACL wiring as-is and skip config-driven ACL discovery below.
let executor_supplied = executor.is_some();
let mut executor = executor
.unwrap_or_else(|| Executor::new(Arc::clone(®istry), Arc::new(config.clone())));
if !executor_supplied {
if let Some(handler) = approval_handler {
executor.set_approval_handler(handler);
}
executor.set_policy(policy);
}
let toggle_state = executor.bind_client_toggle_state(executor_supplied);
if configured && !executor_supplied {
Self::apply_configured_acl(&mut executor, &config);
Self::apply_configured_tracing(&mut executor, &config);
}
let system = if configured
&& executor.pipeline_load_error.is_none()
&& executor.acl_load_error.is_none()
&& Self::sys_modules_enabled(&config)
{
Self::configure_system_modules(
&executor,
&config,
metrics_collector.as_ref(),
&toggle_state,
subscribers,
fail_on_error,
executor_supplied,
)
} else {
SystemAssembly::default()
};
// Thread the shared event bus into the auto-created executor so the
// pipeline publishes governance events (apcore#77:
// `apcore.approval.decision` / `apcore.policy.override` /
// `apcore.acl.denied`) to this instance's `on()` subscribers. A
// caller-supplied executor keeps its own wiring (parity with ACL
// discovery above).
if !executor_supplied {
if let Some(ref emitter) = system.emitter {
executor.set_event_emitter(Some(Arc::clone(emitter)));
}
}
Self {
config,
executor: executor.into_shared(),
registry,
event_emitter: system.emitter,
shutdown_operation: parking_lot::Mutex::new(None),
metrics_collector,
sys_modules_context: system.context,
sys_modules_errors: system.errors,
toggle_state,
}
}
#[cfg(feature = "sys-modules")]
fn configure_system_modules(
executor: &Executor,
config: &Config,
metrics: Option<&MetricsCollector>,
toggle_state: &Arc<ToggleState>,
subscribers: Option<&SubscriberRegistry>,
fail_on_error: bool,
executor_supplied: bool,
) -> SystemAssembly {
let mut startup = SysModulesStartup {
subscribers,
..Default::default()
};
let context = match crate::sys_modules::register_sys_modules_for_client(
Arc::clone(&executor.registry),
executor,
config,
metrics.cloned(),
crate::sys_modules::SysModulesOptions {
toggle_state: Some(Arc::clone(toggle_state)),
fail_on_error,
..Default::default()
},
&mut startup,
executor_supplied,
) {
Ok(context) => Some(context),
Err(error) => {
if !fail_on_error {
tracing::error!(%error, "System modules registration failed");
}
startup.errors.push(error);
None
}
};
let emitter = context
.as_ref()
.filter(|_| startup.events_enabled)
.map(|context| Arc::clone(&context.emitter));
SystemAssembly {
context,
errors: startup.errors,
emitter,
}
}
#[cfg(not(feature = "sys-modules"))]
fn configure_system_modules(
_executor: &Executor,
_config: &Config,
_metrics: Option<&MetricsCollector>,
_toggle_state: &Arc<ToggleState>,
_subscribers: Option<&SubscriberRegistry>,
_fail_on_error: bool,
_executor_supplied: bool,
) -> SystemAssembly {
SystemAssembly {
errors: vec![SysModuleError::RegistrationFailed {
module_id: "system".to_string(),
source: ModuleError::new(
crate::errors::ErrorCode::SysModulesDisabled,
"System-module configuration requires the 'sys-modules' feature",
),
}],
..SystemAssembly::default()
}
}
#[cfg(feature = "config")]
fn apply_configured_acl(executor: &mut Executor, config: &Config) {
// Config discovery only wires ACLs backed by existing documents (D-64).
match crate::acl::ACL::discover(config) {
Ok(Some(acl)) => executor.set_acl(acl),
Ok(None) => {}
Err(e) => {
tracing::error!(error = %e, "ACL discovery failed; module execution is disabled");
executor.acl_load_error = Some(e);
}
}
}
#[cfg(not(feature = "config"))]
fn apply_configured_acl(executor: &mut Executor, config: &Config) {
if config
.get_declared("acl.root")
.is_some_and(|value| !value.is_null() && value.as_str() != Some(""))
{
executor.acl_load_error = Some(ModuleError::new(
crate::errors::ErrorCode::ConfigInvalid,
"ACL file configuration requires the 'config' feature",
));
}
}
fn apply_configured_tracing(executor: &mut Executor, config: &Config) {
// Apply configured tracing only to a client-created executor (§10.1.1).
match crate::observability::tracing_config::build_tracing_middleware(config) {
Ok(Some(mw)) => {
if let Err(e) = executor.use_middleware(Box::new(mw)) {
tracing::error!(error = %e, "Failed to install the configured tracing middleware");
}
}
Ok(None) => {}
Err(e) => {
tracing::error!(error = %e, "observability.tracing.* is invalid; no tracing middleware was installed");
}
}
}
/// System-module registration failures recovered during startup.
#[must_use]
pub fn sys_modules_errors(&self) -> &[SysModuleError] {
&self.sys_modules_errors
}
/// Shared handle to this instance's per-instance toggle store (issue #71).
///
/// The returned `Arc<ToggleState>` is the SAME store consulted by the
/// pipeline `module_lookup` read path and mutated by the
/// `ToggleFeatureModule` write path for this `APCore`. Reading
/// `toggle_state().is_disabled(id)` reflects this instance's view, isolated
/// from other `APCore` instances in the same process.
#[must_use]
pub fn toggle_state(&self) -> Arc<ToggleState> {
Arc::clone(&self.toggle_state)
}
/// Return whether the `sys_modules` auto-registration is enabled
/// according to the given config. Defaults to `false` (opt-in) when the
/// key is absent, matching the spec and the Python/TS peers
/// (registration.py:335 / registration.ts:250). Kept consistent with
/// `register_sys_modules` (sync finding A-D-11).
fn sys_modules_enabled(config: &Config) -> bool {
config
.get("sys_modules.enabled")
.and_then(|v| v.as_bool())
.unwrap_or(false)
}
/// Create a new `APCore` client with the given configuration.
pub fn with_config(config: Config) -> Self {
Self::with_options(None, None, Some(config), None)
}
/// Create a new `APCore` client from a pre-built Registry and Executor.
///
/// Builds an `Executor` from the given `registry` and a default `Config`.
/// To supply a custom config, use [`Self::with_options`] instead.
pub fn with_components(registry: Registry, config: Config) -> Self {
Self::with_options(Some(registry), None, Some(config), None)
}
/// Create a new `APCore` client from a configuration file path.
#[cfg(feature = "config")]
pub fn from_path(path: impl AsRef<std::path::Path>) -> Result<Self, ModuleError> {
let config = Config::load(path.as_ref())?;
let client = Self::with_config(config);
if let Some(error) = client
.executor
.pipeline_load_error
.as_ref()
.or(client.executor.acl_load_error.as_ref())
{
return Err(error.clone());
}
Ok(client)
}
/// Register a function as a module — convenience wrapper that creates a
/// [`FunctionModule`] and registers it in a single call.
///
/// This mirrors the `module()` helper available in the Python and TypeScript
/// SDKs. The handler closure must be an async function that takes
/// `(serde_json::Value, &Context<serde_json::Value>)` and returns
/// `Result<serde_json::Value, ModuleError>`.
///
/// # Example
///
/// ```ignore
/// client.module(
/// "math.add",
/// "Add two numbers",
/// serde_json::json!({"type": "object"}),
/// serde_json::json!({"type": "object"}),
/// None, // documentation
/// vec![], // tags
/// None, // version
/// None, // metadata
/// vec![], // examples
/// |inputs, _ctx| Box::pin(async move { Ok(inputs) }),
/// )?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn module<F>(
&mut self,
module_id: &str,
description: &str,
input_schema: serde_json::Value,
output_schema: serde_json::Value,
documentation: Option<String>,
tags: Vec<String>,
version: Option<&str>,
metadata: Option<std::collections::HashMap<String, serde_json::Value>>,
examples: Vec<crate::module::ModuleExample>,
display: Option<&serde_json::Value>,
handler: F,
) -> Result<&mut Self, ModuleError>
where
F: for<'a> Fn(
serde_json::Value,
&'a Context<serde_json::Value>,
) -> std::pin::Pin<
Box<
dyn std::future::Future<Output = Result<serde_json::Value, ModuleError>>
+ Send
+ 'a,
>,
> + Send
+ Sync
+ 'static,
{
let resolved_version = version.unwrap_or(DEFAULT_MODULE_VERSION).to_string();
let resolved_metadata = metadata.unwrap_or_default();
let descriptor = ModuleDescriptor {
module_id: module_id.to_string(),
name: None,
description: description.to_string(),
documentation: documentation.clone(),
input_schema: input_schema.clone(),
output_schema: output_schema.clone(),
version: resolved_version.clone(),
tags: tags.clone(),
annotations: Some(ModuleAnnotations::default()),
examples: examples.clone(),
metadata: resolved_metadata.clone(),
display: display.cloned(),
sunset_date: None,
dependencies: vec![],
enabled: true,
};
let func_module = FunctionModule::with_description(
ModuleAnnotations::default(),
input_schema,
output_schema,
description,
documentation,
tags,
&resolved_version,
resolved_metadata,
examples,
handler,
);
self.registry
.register(module_id, Box::new(func_module), descriptor)?;
Ok(self)
}
/// Register a function module whose schemas derive from its input and output types.
/// The input type must implement `Deserialize` and `JsonSchema`. The output type
/// must implement `Serialize` and `JsonSchema`.
pub fn typed_module<I, O>(
&mut self,
module_id: &str,
description: &str,
options: TypedModuleOptions,
handler: impl for<'a> Fn(
I,
&'a Context<Value>,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<O, ModuleError>> + Send + 'a>,
> + Send
+ Sync
+ 'static,
) -> Result<&mut Self, ModuleError>
where
I: schemars::JsonSchema + serde::de::DeserializeOwned + Send + 'static,
O: schemars::JsonSchema + serde::Serialize + Send + 'static,
{
let (handler, input_schema, output_schema) = typed_async_handler(handler);
self.module(
module_id,
description,
input_schema,
output_schema,
options.documentation,
options.tags,
options.version.as_deref(),
options.metadata,
options.examples,
options.display.as_ref(),
move |inputs, ctx| handler(inputs, ctx),
)
}
/// Install or remove a provider for capability search.
pub fn set_capability_search_provider(
&self,
provider: Option<Arc<dyn crate::CapabilitySearchProvider>>,
) {
self.executor.set_capability_search_provider(provider);
}
/// List public capability summaries for the supplied caller.
pub fn list_callable(
&self,
context: Option<&Context<Value>>,
query: crate::CapabilityQuery,
) -> Result<crate::CapabilityPage, ModuleError> {
self.executor.list_callable(context, query)
}
/// Expand selected callable definitions for this caller.
#[must_use]
pub fn get_callable_definitions<S: AsRef<str>>(
&self,
module_ids: &[S],
context: Option<&Context<Value>>,
) -> Vec<crate::CallableDefinition> {
self.executor.get_callable_definitions(module_ids, context)
}
/// Read the current governed descriptor for an adapter projection.
#[must_use]
pub fn get_callable_descriptor(
&self,
module_id: &str,
expected_version: Option<&str>,
context: Option<&Context<Value>>,
) -> Option<ModuleDescriptor> {
self.executor
.get_callable_descriptor(module_id, expected_version, context)
}
/// Call (execute) a module by ID with the given inputs.
///
/// `inputs` accepts either a `serde_json::Value` directly or `None`.
/// When `None` is passed, an empty JSON object `{}` is used, matching
/// the Python and TypeScript SDKs where inputs can be `None`/`undefined`.
///
/// In Rust, `call()` is already async — there is no separate sync variant.
/// This method is the equivalent of both `call()` and `call_async()` in the
/// Python and TypeScript SDKs.
#[doc(alias = "call_async")]
pub async fn call(
&self,
module_id: &str,
inputs: impl Into<Option<serde_json::Value>>,
ctx: Option<&Context<serde_json::Value>>,
version_hint: Option<&str>,
) -> Result<serde_json::Value, ModuleError> {
let resolved_inputs = inputs.into().unwrap_or_else(|| serde_json::json!({}));
self.executor
.call(module_id, resolved_inputs, ctx, version_hint)
.await
}
/// Validate module inputs without executing (spec §12.3).
///
/// `inputs` is optional -- pass `None` to validate with an empty `{}`
/// object, matching the Python and TypeScript SDKs where inputs can be
/// `None`/`undefined`. A `&serde_json::Value` reference is also accepted
/// directly for backward compatibility.
///
/// Returns a `PreflightResult` with per-check status. `ctx` enables
/// call-chain checks against real caller state; pass `None` to validate
/// from an anonymous external context.
pub async fn validate<'v>(
&self,
module_id: &str,
inputs: impl Into<Option<&'v serde_json::Value>>,
ctx: Option<&crate::context::Context<serde_json::Value>>,
) -> Result<crate::module::PreflightResult, ModuleError> {
let empty = serde_json::json!({});
let resolved_inputs = inputs.into().unwrap_or(&empty);
self.executor
.validate(module_id, resolved_inputs, ctx)
.await
}
/// Register a module with the given `module_id`.
pub fn register(
&self,
module_id: &str,
module: Box<dyn crate::module::Module>,
) -> Result<(), ModuleError> {
self.registry.register_module(module_id, module)
}
/// Register modules in input order. The first error stops the batch; earlier successes remain.
pub fn register_many<I, S>(&self, modules: I) -> Result<(), ModuleError>
where
I: IntoIterator<Item = (S, Box<dyn crate::module::Module>)>,
S: AsRef<str>,
{
self.registry.register_many(modules)
}
/// Drain and unregister modules in input order, returning one result per ID.
pub async fn unregister_many<I, S>(&self, module_ids: I) -> Result<Vec<bool>, ModuleError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
self.registry.unregister_many(module_ids).await
}
/// Start an ordered batch and observe its progress through an operation handle.
pub fn start_unregister_many<I, S>(
&self,
module_ids: I,
options: Option<UnregisterOptions>,
) -> Result<LifecycleOperation, ModuleError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
self.registry.start_unregister_many(module_ids, options)
}
/// Register a module with its asynchronous lifecycle adapter.
pub async fn register_async(
&self,
module_id: &str,
module: Box<dyn crate::module::Module>,
) -> Result<(), ModuleError> {
self.registry.register_async(module_id, module).await
}
/// Register modules in order, awaiting each asynchronous load.
pub async fn register_many_async<I, S>(&self, modules: I) -> Result<(), ModuleError>
where
I: IntoIterator<Item = (S, Box<dyn crate::module::Module>)>,
S: AsRef<str>,
{
self.registry.register_many_async(modules).await
}
/// Close admission and start or join Registry shutdown with this client's event flush.
pub fn start_shutdown(
&self,
options: Option<ShutdownOptions>,
) -> Result<LifecycleOperation, ModuleError> {
self.start_shutdown_with_policy(options.unwrap_or_default(), false)
}
fn start_shutdown_with_policy(
&self,
options: ShutdownOptions,
legacy_force: bool,
) -> Result<LifecycleOperation, ModuleError> {
const DEFAULT_EVENT_FLUSH_TIMEOUT_MS: u32 = 5_000;
options.validate()?;
let mut attached = self.shutdown_operation.lock();
if let Some(owner) = attached.as_ref() {
if options
.event_flush_timeout_ms
.is_some_and(|ms| ms != owner.event_flush_timeout_ms)
{
return Err(invalid_lifecycle_input(
"Conflicting client shutdown event flush policy",
));
}
self.registry.start_owned_shutdown(options, legacy_force)?;
return Ok(owner.operation.clone());
}
let emitter = self
.event_emitter
.as_ref()
.map(|emitter| lifecycle_runtime().map(|runtime| (Arc::clone(emitter), runtime)))
.transpose()?;
let mut operation = self.registry.start_owned_shutdown(options, legacy_force)?;
let event_flush_timeout_ms = options
.event_flush_timeout_ms
.unwrap_or(DEFAULT_EVENT_FLUSH_TIMEOUT_MS);
if let Some((emitter, runtime)) = emitter {
operation = operation.with_event_delivery(emitter, event_flush_timeout_ms, &runtime);
}
*attached = Some(ClientShutdown {
operation: operation.clone(),
event_flush_timeout_ms,
});
Ok(operation)
}
/// Permanently close the registry, drain current executions, unload modules, and stop client
/// event delivery. Call after the host stops admitting work and shuts down its task managers.
pub async fn shutdown(&self) -> Result<(), ModuleError> {
self.start_shutdown_with_policy(ShutdownOptions::default(), true)?
.wait(None)
.await?;
Ok(())
}
/// Trigger module discovery from configured extension directories.
///
/// Returns the number of newly discovered modules, or 0 if no discoverer
/// is configured on the registry.
pub async fn discover(&self) -> Result<usize, ModuleError> {
Self::discovery_result(self.registry.discover_internal().await)
}
/// Discover from configured roots and select typed async hooks.
pub async fn discover_async(&self) -> Result<usize, ModuleError> {
Self::discovery_result(self.registry.discover_internal_async().await)
}
fn discovery_result(result: Result<usize, ModuleError>) -> Result<usize, ModuleError> {
match result {
Err(error) if error.code == crate::errors::ErrorCode::NoDiscovererConfigured => Ok(0),
result => result,
}
}
/// List all registered modules, optionally filtered by tags and/or prefix.
pub fn list_modules(&self, tags: Option<&[&str]>, prefix: Option<&str>) -> Vec<String> {
self.registry.list(tags, prefix, None)
}
/// Register a middleware in the execution pipeline.
///
/// Returns an error if the middleware's priority exceeds the allowed range.
/// Returns `&Self` for chaining. Takes `&self` — the underlying
/// `MiddlewareManager` uses interior mutability, so middleware can be
/// added after `APCore` has been shared behind an `Arc` or a shared
/// reference.
///
/// **Cross-language note:** The Python and TypeScript SDKs expose this
/// method as `use()`. Rust names it `use_middleware` because `use` is a
/// reserved keyword.
#[track_caller]
pub fn use_middleware(
&self,
middleware: Box<dyn Middleware>,
) -> Result<&Self, crate::errors::ModuleError> {
self.executor.use_middleware(middleware)?;
Ok(self)
}
/// Add a middleware and keep a token that names exactly this registration.
///
/// The chaining form above returns `&Self`, which is what most call sites
/// want; this one returns the [`MiddlewareHandle`] instead, for a caller
/// that intends to remove this specific middleware later via
/// [`remove_handle`](Self::remove_handle).
///
/// `Contract: APCore.remove` removes by IDENTITY — apcore-python and
/// apcore-typescript take the middleware object back and compare it with
/// `is` / `===`. Rust cannot: `use_middleware` consumes the `Box`, so the
/// caller has no object left to hand back. The handle is that identity.
/// It matters because duplicate registration only WARNS — it never fails —
/// so two instances answering the same `name()` is a reachable state, and
/// [`remove`](Self::remove) drops whichever comes first in pipeline order
/// rather than the one the caller meant (sync finding A-C-001).
#[track_caller]
pub fn use_middleware_handle(
&self,
middleware: Box<dyn Middleware>,
) -> Result<MiddlewareHandle, crate::errors::ModuleError> {
self.executor.use_middleware(middleware)
}
/// Remove exactly the middleware that
/// [`use_middleware_handle`](Self::use_middleware_handle) returned `handle`
/// for. Returns `false` if it is no longer registered — idempotent, like
/// the two peer SDKs' `remove`.
pub fn remove_handle(&self, handle: MiddlewareHandle) -> bool {
self.executor.remove_handle(handle)
}
/// Remove a middleware by its name string.
///
/// This is a Rust-specific convenience that accepts a `&str` directly.
/// For an API closer to Python/TypeScript (which accept the middleware
/// object), see [`remove_middleware`](Self::remove_middleware).
///
/// **Deprecation notice (D1-006):** the Python and TypeScript SDKs expose
/// `remove(middleware)` accepting the middleware object — not a name string.
/// Prefer [`remove_middleware`](Self::remove_middleware) for cross-language
/// consistency. The name-based form will be removed in a future major release.
pub fn remove(&self, name: &str) -> bool {
self.executor.remove(name)
}
/// Remove a middleware by reference, extracting its name via
/// [`Middleware::name()`].
///
/// This mirrors the shape of the Python and TypeScript `remove(middleware)`
/// API, which accept the middleware object directly — but not its
/// semantics: the middleware is matched by its
/// [`name()`](Middleware::name), so with two instances answering the same
/// name it removes whichever comes first in pipeline order, not the one
/// passed in.
///
/// The reason is NOT that trait objects cannot be compared by identity —
/// `Arc::ptr_eq` has ignored vtable metadata since Rust 1.76, below this
/// crate's MSRV. It is that [`use_middleware`](Self::use_middleware)
/// consumes the `Box`, so by the time a caller wants to remove one it holds
/// no pointer to compare against. For identity-exact removal, register with
/// [`use_middleware_handle`](Self::use_middleware_handle) and remove with
/// [`remove_handle`](Self::remove_handle) (sync finding A-C-001).
pub fn remove_middleware(&self, middleware: &dyn Middleware) -> bool {
self.executor.remove(middleware.name())
}
/// Get a reference to the registry.
pub fn registry(&self) -> &Registry {
&self.registry
}
/// Get the shared registry as an `Arc<Registry>` (for handing out to
/// components that need to share ownership).
pub fn registry_arc(&self) -> Arc<Registry> {
Arc::clone(&self.registry)
}
/// Get a reference to the executor.
pub fn executor(&self) -> &Executor {
&self.executor
}
/// Get a shared handle to the executor, e.g. for an
/// [`AsyncTaskManager`](crate::AsyncTaskManager).
#[must_use]
pub fn executor_arc(&self) -> Arc<Executor> {
Arc::clone(&self.executor)
}
/// Disable a module by routing through the executor pipeline.
///
/// This calls `system.control.toggle_feature` through the executor,
/// matching the Python and TypeScript SDK behavior (events, ACL, and
/// middleware are applied).
///
/// **Cross-language note:** Python and TypeScript SDKs accept a `reason`
/// string with a default value (e.g. `reason=""` or `reason=None`). In Rust,
/// `reason` is `Option<&str>` — pass `None` to use the default message, or
/// `Some("my reason")` to provide a custom one.
pub async fn disable(
&self,
module_id: &str,