Skip to main content

adk_plugin/
enhanced_manager.rs

1//! Enhanced Plugin Manager with priority-based pipeline execution.
2//!
3//! [`EnhancedPluginManager`] manages a collection of [`EnhancedPlugin`] instances,
4//! executing their hooks in priority order with pipeline semantics where each
5//! plugin's output feeds the next plugin's input.
6//!
7//! # Overview
8//!
9//! The manager provides four pipeline methods:
10//!
11//! - [`run_before_tool_call`](EnhancedPluginManager::run_before_tool_call) — intercept tool calls before execution
12//! - [`run_after_tool_call`](EnhancedPluginManager::run_after_tool_call) — transform tool results after execution
13//! - [`run_before_model_call`](EnhancedPluginManager::run_before_model_call) — intercept model calls before execution
14//! - [`run_after_model_call`](EnhancedPluginManager::run_after_model_call) — transform model responses after execution
15//!
16//! # Pipeline Semantics
17//!
18//! - **Continue**: The (possibly modified) value is passed to the next plugin in the chain.
19//! - **ShortCircuit** (before-hooks only): Stops the pipeline immediately, skips the
20//!   underlying operation, and returns the synthetic result.
21//! - **Error**: Stops the pipeline immediately and propagates the error to the caller.
22//!
23//! # Priority Ordering
24//!
25//! Plugins execute in ascending priority order (lower values run first).
26//! Plugins with the same priority execute in registration order (stable sort).
27//!
28//! # Plugin state
29//!
30//! Every hook of one invocation receives that invocation's [`PluginContext`], so two users'
31//! concurrent runs of the same agent never see each other's plugin state. The per-agent
32//! context ([`EnhancedPluginManager::context`], or [`PluginContext::shared`] from a hook)
33//! holds state meant for every invocation.
34//!
35//! # Examples
36//!
37//! ```rust,ignore
38//! use std::sync::Arc;
39//! use adk_plugin::{EnhancedPluginManager, EnhancedPlugin};
40//!
41//! let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
42//!     Arc::new(SecurityPlugin),   // priority = 10
43//!     Arc::new(CachePlugin),      // priority = 50
44//!     Arc::new(LoggingPlugin),    // priority = 100
45//! ];
46//!
47//! let manager = EnhancedPluginManager::new(plugins);
48//! // Plugins will execute in order: Security → Cache → Logging
49//! ```
50
51use std::collections::HashMap;
52use std::sync::{Arc, Mutex, PoisonError};
53
54use adk_core::{CallbackContext, LlmRequest, LlmResponse, ReadonlyContext, Result, Tool};
55use serde_json::Value;
56use tracing::{debug, warn};
57
58use crate::context::PluginContext;
59use crate::enhanced_plugin::EnhancedPlugin;
60use crate::hook_result::{
61    AfterModelCallResult, AfterToolCallResult, BeforeModelCallResult, BeforeToolCallResult,
62};
63use crate::manager::PluginManagerConfig;
64
65/// The most invocation contexts a manager keeps; the least recently used is dropped first.
66const MAX_INVOCATION_CONTEXTS: usize = 1024;
67
68/// An invocation's app, user, session, and invocation id.
69type InvocationKey = (String, String, String, String);
70
71/// Invocation contexts with the logical time each was last used.
72#[derive(Default)]
73struct InvocationContexts {
74    by_invocation: HashMap<InvocationKey, (Arc<PluginContext>, u64)>,
75    clock: u64,
76}
77
78/// Manages enhanced plugins with priority-based pipeline execution.
79///
80/// Plugins are stored sorted by priority (ascending). All pipeline methods
81/// iterate plugins in this order, passing each plugin's output as input to
82/// the next plugin in the chain.
83///
84/// Each invocation's hooks share one [`PluginContext`] of their own
85/// ([`invocation_context`](Self::invocation_context)); the manager keeps the 1024 most
86/// recently used and drops the least recently used beyond that.
87///
88/// # Thread Safety
89///
90/// `EnhancedPluginManager` is `Send + Sync` and can be shared across async tasks
91/// via `Arc<EnhancedPluginManager>`.
92pub struct EnhancedPluginManager {
93    /// Plugins sorted by priority (ascending). Same-priority preserves registration order.
94    plugins: Vec<Arc<dyn EnhancedPlugin>>,
95    /// The per-agent context every invocation's context links to.
96    context: Arc<PluginContext>,
97    /// One context per invocation, so concurrent runs never share plugin state.
98    invocations: Mutex<InvocationContexts>,
99    /// Configuration for the manager (e.g., close timeout).
100    config: PluginManagerConfig,
101}
102
103impl EnhancedPluginManager {
104    /// Creates a new `EnhancedPluginManager` with the given plugins.
105    ///
106    /// Plugins are sorted by priority in ascending order using a stable sort,
107    /// so plugins with the same priority retain their registration order.
108    ///
109    /// # Examples
110    ///
111    /// ```rust,ignore
112    /// use std::sync::Arc;
113    /// use adk_plugin::{EnhancedPluginManager, EnhancedPlugin};
114    ///
115    /// let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
116    ///     Arc::new(MyPlugin),
117    /// ];
118    /// let manager = EnhancedPluginManager::new(plugins);
119    /// ```
120    pub fn new(mut plugins: Vec<Arc<dyn EnhancedPlugin>>) -> Self {
121        plugins.sort_by_key(|p| p.priority());
122        Self {
123            plugins,
124            context: Arc::new(PluginContext::new()),
125            invocations: Mutex::default(),
126            config: PluginManagerConfig::default(),
127        }
128    }
129
130    /// Creates a new `EnhancedPluginManager` with custom configuration.
131    pub fn with_config(
132        mut plugins: Vec<Arc<dyn EnhancedPlugin>>,
133        config: PluginManagerConfig,
134    ) -> Self {
135        plugins.sort_by_key(|p| p.priority());
136        Self {
137            plugins,
138            context: Arc::new(PluginContext::new()),
139            invocations: Mutex::default(),
140            config,
141        }
142    }
143
144    /// Adds a plugin after construction, re-sorting by priority.
145    ///
146    /// The plugin is inserted and the entire list is re-sorted using a stable sort
147    /// to maintain registration order for same-priority plugins.
148    pub fn add_plugin(&mut self, plugin: Arc<dyn EnhancedPlugin>) {
149        self.plugins.push(plugin);
150        self.plugins.sort_by_key(|p| p.priority());
151    }
152
153    /// Returns the per-agent plugin context.
154    ///
155    /// Every invocation of the agent shares it, and it lives as long as the manager. Hooks
156    /// receive their invocation's context instead and reach this one through
157    /// [`PluginContext::shared`].
158    pub fn context(&self) -> &Arc<PluginContext> {
159        &self.context
160    }
161
162    /// Returns the plugin context of the invocation `ctx` belongs to, creating it on first use.
163    ///
164    /// An invocation is identified by its app, user, session, and invocation id; every hook
165    /// of the invocation receives this context. Its [`shared`](PluginContext::shared) context
166    /// is [`context`](Self::context). Implements spec 3.1 §12 phase 0 (`PluginContext` per
167    /// invocation).
168    ///
169    /// # Examples
170    ///
171    /// ```rust,ignore
172    /// let manager = EnhancedPluginManager::new(plugins);
173    /// let alice = manager.invocation_context(alice_ctx.as_ref());
174    /// let bob = manager.invocation_context(bob_ctx.as_ref());
175    /// assert!(!Arc::ptr_eq(&alice, &bob));
176    /// assert!(std::ptr::eq(alice.shared(), manager.context().as_ref()));
177    /// ```
178    pub fn invocation_context(&self, ctx: &dyn ReadonlyContext) -> Arc<PluginContext> {
179        let key = (
180            ctx.app_name().to_string(),
181            ctx.user_id().to_string(),
182            ctx.session_id().to_string(),
183            ctx.invocation_id().to_string(),
184        );
185        let mut invocations = self.invocations.lock().unwrap_or_else(PoisonError::into_inner);
186        invocations.clock += 1;
187        let now = invocations.clock;
188        if let Some((context, last_used)) = invocations.by_invocation.get_mut(&key) {
189            *last_used = now;
190            return Arc::clone(context);
191        }
192        if invocations.by_invocation.len() >= MAX_INVOCATION_CONTEXTS
193            && let Some(oldest) = invocations
194                .by_invocation
195                .iter()
196                .min_by_key(|(_, (_, last_used))| *last_used)
197                .map(|(key, _)| key.clone())
198        {
199            invocations.by_invocation.remove(&oldest);
200        }
201        let context = Arc::new(PluginContext::with_shared(Arc::clone(&self.context)));
202        invocations.by_invocation.insert(key, (Arc::clone(&context), now));
203        context
204    }
205
206    /// Returns the number of registered plugins.
207    pub fn plugin_count(&self) -> usize {
208        self.plugins.len()
209    }
210
211    /// Returns the names of all registered plugins in execution order.
212    pub fn plugin_names(&self) -> Vec<&str> {
213        self.plugins.iter().map(|p| p.name()).collect()
214    }
215
216    /// Executes the `before_tool_call` pipeline across all plugins in priority order.
217    ///
218    /// Each plugin receives the (possibly modified) arguments from the previous plugin.
219    /// If a plugin returns `ShortCircuit`, the pipeline stops and the synthetic result
220    /// is returned. If a plugin returns an error, the pipeline stops and the error
221    /// is propagated.
222    ///
223    /// # Arguments
224    ///
225    /// * `tool` - The tool about to be executed
226    /// * `args` - The initial tool call arguments
227    /// * `ctx` - The callback context for the current invocation
228    ///
229    /// # Returns
230    ///
231    /// - `Ok(BeforeToolCallResult::Continue(args))` — final modified arguments for tool execution
232    /// - `Ok(BeforeToolCallResult::ShortCircuit(result))` — synthetic result, skip tool execution
233    /// - `Err(e)` — pipeline error, skip tool execution
234    pub async fn run_before_tool_call(
235        &self,
236        tool: Arc<dyn Tool>,
237        args: Value,
238        ctx: Arc<dyn CallbackContext>,
239    ) -> Result<BeforeToolCallResult> {
240        let mut current_args = args;
241        let plugin_ctx = self.invocation_context(ctx.as_ref());
242
243        for plugin in &self.plugins {
244            debug!(plugin = plugin.name(), "running before_tool_call");
245            // A plugin that panics fails the call closed, as one that errs does.
246            let decided = adk_core::guard_callback(
247                "before_tool_call plugin",
248                plugin.before_tool_call(tool.clone(), current_args, ctx.clone(), &plugin_ctx),
249            )
250            .await?;
251            match decided {
252                BeforeToolCallResult::Continue(modified_args) => {
253                    current_args = modified_args;
254                }
255                BeforeToolCallResult::ShortCircuit(result) => {
256                    debug!(plugin = plugin.name(), "before_tool_call short-circuited");
257                    return Ok(BeforeToolCallResult::ShortCircuit(result));
258                }
259            }
260        }
261
262        Ok(BeforeToolCallResult::Continue(current_args))
263    }
264
265    /// Executes the `after_tool_call` pipeline across all plugins in priority order.
266    ///
267    /// Each plugin receives the (possibly modified) result from the previous plugin.
268    /// The `args` parameter contains the final modified arguments from the before-hook
269    /// pipeline (not the original arguments).
270    ///
271    /// # Arguments
272    ///
273    /// * `tool` - The tool that was executed
274    /// * `args` - The final arguments used for tool execution (after before-hook modifications)
275    /// * `result` - The initial tool execution result
276    /// * `ctx` - The callback context for the current invocation
277    ///
278    /// # Returns
279    ///
280    /// - `Ok(AfterToolCallResult::Continue(result))` — final modified result
281    /// - `Err(e)` — pipeline error
282    pub async fn run_after_tool_call(
283        &self,
284        tool: Arc<dyn Tool>,
285        args: &Value,
286        result: Value,
287        ctx: Arc<dyn CallbackContext>,
288    ) -> Result<AfterToolCallResult> {
289        let mut current_result = result;
290        let plugin_ctx = self.invocation_context(ctx.as_ref());
291
292        for plugin in &self.plugins {
293            debug!(plugin = plugin.name(), "running after_tool_call");
294            match plugin
295                .after_tool_call(tool.clone(), args, current_result, ctx.clone(), &plugin_ctx)
296                .await?
297            {
298                AfterToolCallResult::Continue(modified_result) => {
299                    current_result = modified_result;
300                }
301            }
302        }
303
304        Ok(AfterToolCallResult::Continue(current_result))
305    }
306
307    /// Executes the `before_model_call` pipeline across all plugins in priority order.
308    ///
309    /// Each plugin receives the (possibly modified) request from the previous plugin.
310    /// If a plugin returns `ShortCircuit`, the pipeline stops and the synthetic response
311    /// is returned. If a plugin returns an error, the pipeline stops and the error
312    /// is propagated.
313    ///
314    /// # Arguments
315    ///
316    /// * `request` - The initial LLM request
317    /// * `ctx` - The callback context for the current invocation
318    ///
319    /// # Returns
320    ///
321    /// - `Ok(BeforeModelCallResult::Continue(request))` — final modified request for model call
322    /// - `Ok(BeforeModelCallResult::ShortCircuit(response))` — synthetic response, skip model call
323    /// - `Err(e)` — pipeline error, skip model call
324    pub async fn run_before_model_call(
325        &self,
326        request: LlmRequest,
327        ctx: Arc<dyn CallbackContext>,
328    ) -> Result<BeforeModelCallResult> {
329        let mut current_request = request;
330        let plugin_ctx = self.invocation_context(ctx.as_ref());
331
332        for plugin in &self.plugins {
333            debug!(plugin = plugin.name(), "running before_model_call");
334            match plugin.before_model_call(current_request, ctx.clone(), &plugin_ctx).await? {
335                BeforeModelCallResult::Continue(modified_request) => {
336                    current_request = modified_request;
337                }
338                BeforeModelCallResult::ShortCircuit(response) => {
339                    debug!(plugin = plugin.name(), "before_model_call short-circuited");
340                    return Ok(BeforeModelCallResult::ShortCircuit(response));
341                }
342            }
343        }
344
345        Ok(BeforeModelCallResult::Continue(current_request))
346    }
347
348    /// Executes the `after_model_call` pipeline across all plugins in priority order.
349    ///
350    /// Each plugin receives the (possibly modified) response from the previous plugin.
351    /// If a plugin returns an error, the pipeline stops and the error is propagated.
352    ///
353    /// # Arguments
354    ///
355    /// * `response` - The initial LLM response
356    /// * `ctx` - The callback context for the current invocation
357    ///
358    /// # Returns
359    ///
360    /// - `Ok(AfterModelCallResult::Continue(response))` — final modified response
361    /// - `Err(e)` — pipeline error
362    pub async fn run_after_model_call(
363        &self,
364        response: LlmResponse,
365        ctx: Arc<dyn CallbackContext>,
366    ) -> Result<AfterModelCallResult> {
367        let mut current_response = response;
368        let plugin_ctx = self.invocation_context(ctx.as_ref());
369
370        for plugin in &self.plugins {
371            debug!(plugin = plugin.name(), "running after_model_call");
372            match plugin.after_model_call(current_response, ctx.clone(), &plugin_ctx).await? {
373                AfterModelCallResult::Continue(modified_response) => {
374                    current_response = modified_response;
375                }
376            }
377        }
378
379        Ok(AfterModelCallResult::Continue(current_response))
380    }
381
382    /// Closes all plugins, ignoring individual close errors.
383    ///
384    /// Each plugin's `close()` method is called in sequence. Errors during
385    /// close are logged but do not prevent other plugins from being closed.
386    pub async fn close(&self) {
387        debug!("closing {} enhanced plugins", self.plugins.len());
388
389        for plugin in &self.plugins {
390            let close_future = plugin.close();
391            match tokio::time::timeout(self.config.close_timeout, close_future).await {
392                Ok(()) => {
393                    debug!(plugin = plugin.name(), "enhanced plugin closed successfully");
394                }
395                Err(_) => {
396                    warn!(plugin = plugin.name(), "enhanced plugin close timed out");
397                }
398            }
399        }
400    }
401}
402
403impl std::fmt::Debug for EnhancedPluginManager {
404    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405        f.debug_struct("EnhancedPluginManager")
406            .field("plugin_count", &self.plugins.len())
407            .field("plugin_names", &self.plugin_names())
408            .field("close_timeout", &self.config.close_timeout)
409            .finish()
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use adk_core::Content as AdkContent;
417    use adk_core::{AdkError, LlmRequest, LlmResponse, async_trait};
418    use serde_json::json;
419    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
420
421    // --- Test helpers ---
422
423    /// A simple plugin that passes through unchanged.
424    struct NoOpPlugin {
425        name: String,
426        priority: i32,
427    }
428
429    impl NoOpPlugin {
430        fn new(name: &str, priority: i32) -> Self {
431            Self { name: name.to_string(), priority }
432        }
433    }
434
435    #[async_trait]
436    impl EnhancedPlugin for NoOpPlugin {
437        fn name(&self) -> &str {
438            &self.name
439        }
440
441        fn priority(&self) -> i32 {
442            self.priority
443        }
444    }
445
446    /// A plugin that appends a field to tool call arguments.
447    struct ArgModifierPlugin {
448        name: String,
449        priority: i32,
450        key: String,
451        value: Value,
452    }
453
454    #[async_trait]
455    impl EnhancedPlugin for ArgModifierPlugin {
456        fn name(&self) -> &str {
457            &self.name
458        }
459
460        fn priority(&self) -> i32 {
461            self.priority
462        }
463
464        async fn before_tool_call(
465            &self,
466            _tool: Arc<dyn Tool>,
467            args: Value,
468            _ctx: Arc<dyn CallbackContext>,
469            _plugin_ctx: &PluginContext,
470        ) -> Result<BeforeToolCallResult> {
471            let mut modified = args;
472            if let Value::Object(ref mut map) = modified {
473                map.insert(self.key.clone(), self.value.clone());
474            }
475            Ok(BeforeToolCallResult::Continue(modified))
476        }
477    }
478
479    /// A plugin that modifies tool results.
480    struct ResultModifierPlugin {
481        name: String,
482        priority: i32,
483        key: String,
484        value: Value,
485    }
486
487    #[async_trait]
488    impl EnhancedPlugin for ResultModifierPlugin {
489        fn name(&self) -> &str {
490            &self.name
491        }
492
493        fn priority(&self) -> i32 {
494            self.priority
495        }
496
497        async fn after_tool_call(
498            &self,
499            _tool: Arc<dyn Tool>,
500            _args: &Value,
501            result: Value,
502            _ctx: Arc<dyn CallbackContext>,
503            _plugin_ctx: &PluginContext,
504        ) -> Result<AfterToolCallResult> {
505            let mut modified = result;
506            if let Value::Object(ref mut map) = modified {
507                map.insert(self.key.clone(), self.value.clone());
508            }
509            Ok(AfterToolCallResult::Continue(modified))
510        }
511    }
512
513    /// A plugin that short-circuits before_tool_call.
514    struct ShortCircuitPlugin {
515        name: String,
516        priority: i32,
517        result: Value,
518    }
519
520    #[async_trait]
521    impl EnhancedPlugin for ShortCircuitPlugin {
522        fn name(&self) -> &str {
523            &self.name
524        }
525
526        fn priority(&self) -> i32 {
527            self.priority
528        }
529
530        async fn before_tool_call(
531            &self,
532            _tool: Arc<dyn Tool>,
533            _args: Value,
534            _ctx: Arc<dyn CallbackContext>,
535            _plugin_ctx: &PluginContext,
536        ) -> Result<BeforeToolCallResult> {
537            Ok(BeforeToolCallResult::ShortCircuit(self.result.clone()))
538        }
539    }
540
541    /// A plugin that returns an error from before_tool_call.
542    struct ErrorPlugin {
543        name: String,
544        priority: i32,
545    }
546
547    #[async_trait]
548    impl EnhancedPlugin for ErrorPlugin {
549        fn name(&self) -> &str {
550            &self.name
551        }
552
553        fn priority(&self) -> i32 {
554            self.priority
555        }
556
557        async fn before_tool_call(
558            &self,
559            _tool: Arc<dyn Tool>,
560            _args: Value,
561            _ctx: Arc<dyn CallbackContext>,
562            _plugin_ctx: &PluginContext,
563        ) -> Result<BeforeToolCallResult> {
564            Err(AdkError::agent("test error from plugin"))
565        }
566
567        async fn after_tool_call(
568            &self,
569            _tool: Arc<dyn Tool>,
570            _args: &Value,
571            _result: Value,
572            _ctx: Arc<dyn CallbackContext>,
573            _plugin_ctx: &PluginContext,
574        ) -> Result<AfterToolCallResult> {
575            Err(AdkError::agent("test error from after_tool"))
576        }
577
578        async fn before_model_call(
579            &self,
580            _request: LlmRequest,
581            _ctx: Arc<dyn CallbackContext>,
582            _plugin_ctx: &PluginContext,
583        ) -> Result<BeforeModelCallResult> {
584            Err(AdkError::agent("test error from before_model"))
585        }
586
587        async fn after_model_call(
588            &self,
589            _response: LlmResponse,
590            _ctx: Arc<dyn CallbackContext>,
591            _plugin_ctx: &PluginContext,
592        ) -> Result<AfterModelCallResult> {
593            Err(AdkError::agent("test error from after_model"))
594        }
595    }
596
597    /// A plugin that tracks whether it was called.
598    struct TrackingPlugin {
599        name: String,
600        priority: i32,
601        before_tool_called: AtomicBool,
602        after_tool_called: AtomicBool,
603        before_model_called: AtomicBool,
604        after_model_called: AtomicBool,
605    }
606
607    impl TrackingPlugin {
608        fn new(name: &str, priority: i32) -> Self {
609            Self {
610                name: name.to_string(),
611                priority,
612                before_tool_called: AtomicBool::new(false),
613                after_tool_called: AtomicBool::new(false),
614                before_model_called: AtomicBool::new(false),
615                after_model_called: AtomicBool::new(false),
616            }
617        }
618    }
619
620    #[async_trait]
621    impl EnhancedPlugin for TrackingPlugin {
622        fn name(&self) -> &str {
623            &self.name
624        }
625
626        fn priority(&self) -> i32 {
627            self.priority
628        }
629
630        async fn before_tool_call(
631            &self,
632            _tool: Arc<dyn Tool>,
633            args: Value,
634            _ctx: Arc<dyn CallbackContext>,
635            _plugin_ctx: &PluginContext,
636        ) -> Result<BeforeToolCallResult> {
637            self.before_tool_called.store(true, Ordering::SeqCst);
638            Ok(BeforeToolCallResult::Continue(args))
639        }
640
641        async fn after_tool_call(
642            &self,
643            _tool: Arc<dyn Tool>,
644            _args: &Value,
645            result: Value,
646            _ctx: Arc<dyn CallbackContext>,
647            _plugin_ctx: &PluginContext,
648        ) -> Result<AfterToolCallResult> {
649            self.after_tool_called.store(true, Ordering::SeqCst);
650            Ok(AfterToolCallResult::Continue(result))
651        }
652
653        async fn before_model_call(
654            &self,
655            request: LlmRequest,
656            _ctx: Arc<dyn CallbackContext>,
657            _plugin_ctx: &PluginContext,
658        ) -> Result<BeforeModelCallResult> {
659            self.before_model_called.store(true, Ordering::SeqCst);
660            Ok(BeforeModelCallResult::Continue(request))
661        }
662
663        async fn after_model_call(
664            &self,
665            response: LlmResponse,
666            _ctx: Arc<dyn CallbackContext>,
667            _plugin_ctx: &PluginContext,
668        ) -> Result<AfterModelCallResult> {
669            self.after_model_called.store(true, Ordering::SeqCst);
670            Ok(AfterModelCallResult::Continue(response))
671        }
672    }
673
674    /// A plugin that short-circuits before_model_call.
675    struct ModelShortCircuitPlugin {
676        name: String,
677        priority: i32,
678    }
679
680    #[async_trait]
681    impl EnhancedPlugin for ModelShortCircuitPlugin {
682        fn name(&self) -> &str {
683            &self.name
684        }
685
686        fn priority(&self) -> i32 {
687            self.priority
688        }
689
690        async fn before_model_call(
691            &self,
692            _request: LlmRequest,
693            _ctx: Arc<dyn CallbackContext>,
694            _plugin_ctx: &PluginContext,
695        ) -> Result<BeforeModelCallResult> {
696            Ok(BeforeModelCallResult::ShortCircuit(LlmResponse::default()))
697        }
698    }
699
700    /// A plugin that records execution order via a shared counter.
701    struct OrderTrackingPlugin {
702        name: String,
703        priority: i32,
704        order_counter: Arc<AtomicUsize>,
705        recorded_order: AtomicUsize,
706    }
707
708    impl OrderTrackingPlugin {
709        fn new(name: &str, priority: i32, counter: Arc<AtomicUsize>) -> Self {
710            Self {
711                name: name.to_string(),
712                priority,
713                order_counter: counter,
714                recorded_order: AtomicUsize::new(0),
715            }
716        }
717
718        fn execution_order(&self) -> usize {
719            self.recorded_order.load(Ordering::SeqCst)
720        }
721    }
722
723    #[async_trait]
724    impl EnhancedPlugin for OrderTrackingPlugin {
725        fn name(&self) -> &str {
726            &self.name
727        }
728
729        fn priority(&self) -> i32 {
730            self.priority
731        }
732
733        async fn before_tool_call(
734            &self,
735            _tool: Arc<dyn Tool>,
736            args: Value,
737            _ctx: Arc<dyn CallbackContext>,
738            _plugin_ctx: &PluginContext,
739        ) -> Result<BeforeToolCallResult> {
740            let order = self.order_counter.fetch_add(1, Ordering::SeqCst);
741            self.recorded_order.store(order, Ordering::SeqCst);
742            Ok(BeforeToolCallResult::Continue(args))
743        }
744    }
745
746    // --- Mock Tool and CallbackContext ---
747
748    struct MockTool;
749
750    #[async_trait]
751    impl Tool for MockTool {
752        fn name(&self) -> &str {
753            "mock_tool"
754        }
755
756        fn description(&self) -> &str {
757            "A mock tool for testing"
758        }
759
760        async fn execute(
761            &self,
762            _ctx: Arc<dyn adk_core::ToolContext>,
763            _args: Value,
764        ) -> Result<Value> {
765            Ok(json!({"result": "mock"}))
766        }
767    }
768
769    struct MockCallbackContext {
770        content: AdkContent,
771    }
772
773    impl MockCallbackContext {
774        fn new() -> Self {
775            Self { content: AdkContent::new("user") }
776        }
777    }
778
779    impl adk_core::ReadonlyContext for MockCallbackContext {
780        fn invocation_id(&self) -> &str {
781            "test-invocation"
782        }
783
784        fn agent_name(&self) -> &str {
785            "test-agent"
786        }
787
788        fn user_id(&self) -> &str {
789            "test-user"
790        }
791
792        fn app_name(&self) -> &str {
793            "test-app"
794        }
795
796        fn session_id(&self) -> &str {
797            "test-session"
798        }
799
800        fn branch(&self) -> &str {
801            ""
802        }
803
804        fn user_content(&self) -> &AdkContent {
805            &self.content
806        }
807    }
808
809    #[async_trait]
810    impl CallbackContext for MockCallbackContext {
811        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
812            None
813        }
814
815        fn tool_name(&self) -> Option<&str> {
816            Some("mock_tool")
817        }
818    }
819
820    fn mock_tool() -> Arc<dyn Tool> {
821        Arc::new(MockTool)
822    }
823
824    fn mock_ctx() -> Arc<dyn CallbackContext> {
825        Arc::new(MockCallbackContext::new())
826    }
827
828    fn mock_request() -> LlmRequest {
829        LlmRequest::new("test-model", vec![])
830    }
831
832    // --- Tests ---
833
834    #[test]
835    fn test_new_sorts_by_priority() {
836        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
837            Arc::new(NoOpPlugin::new("c", 100)),
838            Arc::new(NoOpPlugin::new("a", 10)),
839            Arc::new(NoOpPlugin::new("b", 50)),
840        ];
841
842        let manager = EnhancedPluginManager::new(plugins);
843        assert_eq!(manager.plugin_names(), vec!["a", "b", "c"]);
844    }
845
846    #[test]
847    fn test_stable_sort_preserves_registration_order() {
848        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
849            Arc::new(NoOpPlugin::new("first", 100)),
850            Arc::new(NoOpPlugin::new("second", 100)),
851            Arc::new(NoOpPlugin::new("third", 100)),
852        ];
853
854        let manager = EnhancedPluginManager::new(plugins);
855        assert_eq!(manager.plugin_names(), vec!["first", "second", "third"]);
856    }
857
858    #[test]
859    fn test_add_plugin_resorts() {
860        let plugins: Vec<Arc<dyn EnhancedPlugin>> =
861            vec![Arc::new(NoOpPlugin::new("b", 50)), Arc::new(NoOpPlugin::new("c", 100))];
862
863        let mut manager = EnhancedPluginManager::new(plugins);
864        manager.add_plugin(Arc::new(NoOpPlugin::new("a", 10)));
865
866        assert_eq!(manager.plugin_names(), vec!["a", "b", "c"]);
867        assert_eq!(manager.plugin_count(), 3);
868    }
869
870    #[test]
871    fn test_context_accessor() {
872        let manager = EnhancedPluginManager::new(vec![]);
873        let ctx = manager.context();
874        // Just verify we can access it without panic
875        assert!(Arc::strong_count(ctx) >= 1);
876    }
877
878    /// A context for invocation `n` of one session.
879    struct Invocation(String, AdkContent);
880
881    impl adk_core::ReadonlyContext for Invocation {
882        fn invocation_id(&self) -> &str {
883            &self.0
884        }
885        fn agent_name(&self) -> &str {
886            "test-agent"
887        }
888        fn user_id(&self) -> &str {
889            "test-user"
890        }
891        fn app_name(&self) -> &str {
892            "test-app"
893        }
894        fn session_id(&self) -> &str {
895            "test-session"
896        }
897        fn branch(&self) -> &str {
898            ""
899        }
900        fn user_content(&self) -> &AdkContent {
901            &self.1
902        }
903    }
904
905    fn invocation(n: usize) -> Invocation {
906        Invocation(format!("inv-{n}"), AdkContent::new("user"))
907    }
908
909    #[test]
910    fn the_least_recently_used_invocation_context_is_dropped() {
911        let manager = EnhancedPluginManager::new(vec![]);
912        let first = manager.invocation_context(&invocation(0));
913        let second = manager.invocation_context(&invocation(1));
914        for n in 2..MAX_INVOCATION_CONTEXTS {
915            manager.invocation_context(&invocation(n));
916        }
917        // Using the first keeps it; the second is now the least recently used.
918        assert!(Arc::ptr_eq(&first, &manager.invocation_context(&invocation(0))));
919
920        manager.invocation_context(&invocation(MAX_INVOCATION_CONTEXTS));
921        let invocations = manager.invocations.lock().unwrap();
922        assert_eq!(invocations.by_invocation.len(), MAX_INVOCATION_CONTEXTS);
923        drop(invocations);
924        assert!(Arc::ptr_eq(&first, &manager.invocation_context(&invocation(0))));
925        assert!(!Arc::ptr_eq(&second, &manager.invocation_context(&invocation(1))));
926    }
927
928    #[test]
929    fn test_empty_manager() {
930        let manager = EnhancedPluginManager::new(vec![]);
931        assert_eq!(manager.plugin_count(), 0);
932        assert!(manager.plugin_names().is_empty());
933    }
934
935    #[tokio::test]
936    async fn test_before_tool_call_pipeline_propagation() {
937        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
938            Arc::new(ArgModifierPlugin {
939                name: "plugin1".to_string(),
940                priority: 10,
941                key: "added_by_1".to_string(),
942                value: json!(true),
943            }),
944            Arc::new(ArgModifierPlugin {
945                name: "plugin2".to_string(),
946                priority: 20,
947                key: "added_by_2".to_string(),
948                value: json!("hello"),
949            }),
950        ];
951
952        let manager = EnhancedPluginManager::new(plugins);
953        let result = manager
954            .run_before_tool_call(mock_tool(), json!({"original": "value"}), mock_ctx())
955            .await
956            .unwrap();
957
958        match result {
959            BeforeToolCallResult::Continue(args) => {
960                assert_eq!(args["original"], "value");
961                assert_eq!(args["added_by_1"], true);
962                assert_eq!(args["added_by_2"], "hello");
963            }
964            BeforeToolCallResult::ShortCircuit(_) => panic!("expected Continue"),
965        }
966    }
967
968    #[tokio::test]
969    async fn test_before_tool_call_short_circuit() {
970        let tracking = Arc::new(TrackingPlugin::new("after_short_circuit", 50));
971        let tracking_clone = tracking.clone();
972
973        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
974            Arc::new(ShortCircuitPlugin {
975                name: "short_circuit".to_string(),
976                priority: 10,
977                result: json!({"cached": true}),
978            }),
979            tracking_clone,
980        ];
981
982        let manager = EnhancedPluginManager::new(plugins);
983        let result =
984            manager.run_before_tool_call(mock_tool(), json!({}), mock_ctx()).await.unwrap();
985
986        match result {
987            BeforeToolCallResult::ShortCircuit(value) => {
988                assert_eq!(value, json!({"cached": true}));
989            }
990            BeforeToolCallResult::Continue(_) => panic!("expected ShortCircuit"),
991        }
992
993        // The tracking plugin should NOT have been called
994        assert!(!tracking.before_tool_called.load(Ordering::SeqCst));
995    }
996
997    #[tokio::test]
998    async fn test_before_tool_call_error_propagation() {
999        let tracking = Arc::new(TrackingPlugin::new("after_error", 50));
1000        let tracking_clone = tracking.clone();
1001
1002        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1003            Arc::new(ErrorPlugin { name: "error_plugin".to_string(), priority: 10 }),
1004            tracking_clone,
1005        ];
1006
1007        let manager = EnhancedPluginManager::new(plugins);
1008        let result = manager.run_before_tool_call(mock_tool(), json!({}), mock_ctx()).await;
1009
1010        assert!(result.is_err());
1011        // The tracking plugin should NOT have been called
1012        assert!(!tracking.before_tool_called.load(Ordering::SeqCst));
1013    }
1014
1015    /// A plugin whose before_tool_call panics.
1016    struct PanickingPlugin;
1017
1018    #[async_trait]
1019    impl EnhancedPlugin for PanickingPlugin {
1020        fn name(&self) -> &str {
1021            "panicking"
1022        }
1023
1024        // Runs before the tracking plugin, so the test shows the panic stops the pipeline.
1025        fn priority(&self) -> i32 {
1026            10
1027        }
1028
1029        async fn before_tool_call(
1030            &self,
1031            _tool: Arc<dyn Tool>,
1032            _args: Value,
1033            _ctx: Arc<dyn CallbackContext>,
1034            _plugin_ctx: &PluginContext,
1035        ) -> Result<BeforeToolCallResult> {
1036            panic!("the policy client crashed")
1037        }
1038    }
1039
1040    #[tokio::test]
1041    async fn a_panicking_before_tool_call_plugin_blocks_the_call() {
1042        let tracking = Arc::new(TrackingPlugin::new("after_panic", 50));
1043        let plugins: Vec<Arc<dyn EnhancedPlugin>> =
1044            vec![Arc::new(PanickingPlugin), tracking.clone()];
1045
1046        let manager = EnhancedPluginManager::new(plugins);
1047        let error =
1048            manager.run_before_tool_call(mock_tool(), json!({}), mock_ctx()).await.unwrap_err();
1049
1050        assert_eq!(error.code, adk_core::CALLBACK_PANICKED_CODE);
1051        assert!(error.message.contains("the policy client crashed"), "{}", error.message);
1052        assert!(!tracking.before_tool_called.load(Ordering::SeqCst));
1053    }
1054
1055    #[tokio::test]
1056    async fn test_after_tool_call_pipeline_propagation() {
1057        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1058            Arc::new(ResultModifierPlugin {
1059                name: "plugin1".to_string(),
1060                priority: 10,
1061                key: "enriched_by_1".to_string(),
1062                value: json!(true),
1063            }),
1064            Arc::new(ResultModifierPlugin {
1065                name: "plugin2".to_string(),
1066                priority: 20,
1067                key: "enriched_by_2".to_string(),
1068                value: json!(42),
1069            }),
1070        ];
1071
1072        let manager = EnhancedPluginManager::new(plugins);
1073        let args = json!({"tool_arg": "test"});
1074        let result = manager
1075            .run_after_tool_call(mock_tool(), &args, json!({"status": "ok"}), mock_ctx())
1076            .await
1077            .unwrap();
1078
1079        match result {
1080            AfterToolCallResult::Continue(value) => {
1081                assert_eq!(value["status"], "ok");
1082                assert_eq!(value["enriched_by_1"], true);
1083                assert_eq!(value["enriched_by_2"], 42);
1084            }
1085        }
1086    }
1087
1088    #[tokio::test]
1089    async fn test_after_tool_call_error_propagation() {
1090        let tracking = Arc::new(TrackingPlugin::new("after_error", 50));
1091        let tracking_clone = tracking.clone();
1092
1093        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1094            Arc::new(ErrorPlugin { name: "error_plugin".to_string(), priority: 10 }),
1095            tracking_clone,
1096        ];
1097
1098        let manager = EnhancedPluginManager::new(plugins);
1099        let result =
1100            manager.run_after_tool_call(mock_tool(), &json!({}), json!({}), mock_ctx()).await;
1101
1102        assert!(result.is_err());
1103        assert!(!tracking.after_tool_called.load(Ordering::SeqCst));
1104    }
1105
1106    #[tokio::test]
1107    async fn test_before_model_call_pipeline_propagation() {
1108        // Use no-op plugins to verify the request passes through
1109        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1110            Arc::new(NoOpPlugin::new("plugin1", 10)),
1111            Arc::new(NoOpPlugin::new("plugin2", 20)),
1112        ];
1113
1114        let manager = EnhancedPluginManager::new(plugins);
1115        let request = mock_request();
1116        let result = manager.run_before_model_call(request, mock_ctx()).await.unwrap();
1117
1118        match result {
1119            BeforeModelCallResult::Continue(_) => { /* pass */ }
1120            BeforeModelCallResult::ShortCircuit(_) => panic!("expected Continue"),
1121        }
1122    }
1123
1124    #[tokio::test]
1125    async fn test_before_model_call_short_circuit() {
1126        let tracking = Arc::new(TrackingPlugin::new("after_short_circuit", 50));
1127        let tracking_clone = tracking.clone();
1128
1129        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1130            Arc::new(ModelShortCircuitPlugin {
1131                name: "model_short_circuit".to_string(),
1132                priority: 10,
1133            }),
1134            tracking_clone,
1135        ];
1136
1137        let manager = EnhancedPluginManager::new(plugins);
1138        let result = manager.run_before_model_call(mock_request(), mock_ctx()).await.unwrap();
1139
1140        match result {
1141            BeforeModelCallResult::ShortCircuit(_) => { /* pass */ }
1142            BeforeModelCallResult::Continue(_) => panic!("expected ShortCircuit"),
1143        }
1144
1145        assert!(!tracking.before_model_called.load(Ordering::SeqCst));
1146    }
1147
1148    #[tokio::test]
1149    async fn test_before_model_call_error_propagation() {
1150        let tracking = Arc::new(TrackingPlugin::new("after_error", 50));
1151        let tracking_clone = tracking.clone();
1152
1153        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1154            Arc::new(ErrorPlugin { name: "error_plugin".to_string(), priority: 10 }),
1155            tracking_clone,
1156        ];
1157
1158        let manager = EnhancedPluginManager::new(plugins);
1159        let result = manager.run_before_model_call(mock_request(), mock_ctx()).await;
1160
1161        assert!(result.is_err());
1162        assert!(!tracking.before_model_called.load(Ordering::SeqCst));
1163    }
1164
1165    #[tokio::test]
1166    async fn test_after_model_call_pipeline_propagation() {
1167        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1168            Arc::new(NoOpPlugin::new("plugin1", 10)),
1169            Arc::new(NoOpPlugin::new("plugin2", 20)),
1170        ];
1171
1172        let manager = EnhancedPluginManager::new(plugins);
1173        let result =
1174            manager.run_after_model_call(LlmResponse::default(), mock_ctx()).await.unwrap();
1175
1176        match result {
1177            AfterModelCallResult::Continue(_) => { /* pass */ }
1178        }
1179    }
1180
1181    #[tokio::test]
1182    async fn test_after_model_call_error_propagation() {
1183        let tracking = Arc::new(TrackingPlugin::new("after_error", 50));
1184        let tracking_clone = tracking.clone();
1185
1186        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1187            Arc::new(ErrorPlugin { name: "error_plugin".to_string(), priority: 10 }),
1188            tracking_clone,
1189        ];
1190
1191        let manager = EnhancedPluginManager::new(plugins);
1192        let result = manager.run_after_model_call(LlmResponse::default(), mock_ctx()).await;
1193
1194        assert!(result.is_err());
1195        assert!(!tracking.after_model_called.load(Ordering::SeqCst));
1196    }
1197
1198    #[tokio::test]
1199    async fn test_empty_plugin_list_before_tool_call() {
1200        let manager = EnhancedPluginManager::new(vec![]);
1201        let result = manager
1202            .run_before_tool_call(mock_tool(), json!({"key": "value"}), mock_ctx())
1203            .await
1204            .unwrap();
1205
1206        match result {
1207            BeforeToolCallResult::Continue(args) => {
1208                assert_eq!(args, json!({"key": "value"}));
1209            }
1210            BeforeToolCallResult::ShortCircuit(_) => panic!("expected Continue"),
1211        }
1212    }
1213
1214    #[tokio::test]
1215    async fn test_empty_plugin_list_after_tool_call() {
1216        let manager = EnhancedPluginManager::new(vec![]);
1217        let result = manager
1218            .run_after_tool_call(mock_tool(), &json!({}), json!({"result": 42}), mock_ctx())
1219            .await
1220            .unwrap();
1221
1222        match result {
1223            AfterToolCallResult::Continue(value) => {
1224                assert_eq!(value, json!({"result": 42}));
1225            }
1226        }
1227    }
1228
1229    #[tokio::test]
1230    async fn test_empty_plugin_list_before_model_call() {
1231        let manager = EnhancedPluginManager::new(vec![]);
1232        let request = mock_request();
1233        let result = manager.run_before_model_call(request, mock_ctx()).await.unwrap();
1234
1235        match result {
1236            BeforeModelCallResult::Continue(_) => { /* pass */ }
1237            BeforeModelCallResult::ShortCircuit(_) => panic!("expected Continue"),
1238        }
1239    }
1240
1241    #[tokio::test]
1242    async fn test_empty_plugin_list_after_model_call() {
1243        let manager = EnhancedPluginManager::new(vec![]);
1244        let result =
1245            manager.run_after_model_call(LlmResponse::default(), mock_ctx()).await.unwrap();
1246
1247        match result {
1248            AfterModelCallResult::Continue(_) => { /* pass */ }
1249        }
1250    }
1251
1252    #[tokio::test]
1253    async fn test_priority_ordering_execution() {
1254        let counter = Arc::new(AtomicUsize::new(0));
1255
1256        let p1 = Arc::new(OrderTrackingPlugin::new("high_priority", 10, counter.clone()));
1257        let p2 = Arc::new(OrderTrackingPlugin::new("medium_priority", 50, counter.clone()));
1258        let p3 = Arc::new(OrderTrackingPlugin::new("low_priority", 100, counter.clone()));
1259
1260        let p1_clone = p1.clone();
1261        let p2_clone = p2.clone();
1262        let p3_clone = p3.clone();
1263
1264        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![p3_clone, p1_clone, p2_clone];
1265
1266        let manager = EnhancedPluginManager::new(plugins);
1267        manager.run_before_tool_call(mock_tool(), json!({}), mock_ctx()).await.unwrap();
1268
1269        // Verify execution order: high (0), medium (1), low (2)
1270        assert_eq!(p1.execution_order(), 0);
1271        assert_eq!(p2.execution_order(), 1);
1272        assert_eq!(p3.execution_order(), 2);
1273    }
1274
1275    #[tokio::test]
1276    async fn test_close_calls_all_plugins() {
1277        let closed = Arc::new(AtomicUsize::new(0));
1278
1279        struct CloseTrackingPlugin {
1280            name: String,
1281            closed: Arc<AtomicUsize>,
1282        }
1283
1284        #[async_trait]
1285        impl EnhancedPlugin for CloseTrackingPlugin {
1286            fn name(&self) -> &str {
1287                &self.name
1288            }
1289
1290            async fn close(&self) {
1291                self.closed.fetch_add(1, Ordering::SeqCst);
1292            }
1293        }
1294
1295        let plugins: Vec<Arc<dyn EnhancedPlugin>> = vec![
1296            Arc::new(CloseTrackingPlugin { name: "p1".to_string(), closed: closed.clone() }),
1297            Arc::new(CloseTrackingPlugin { name: "p2".to_string(), closed: closed.clone() }),
1298            Arc::new(CloseTrackingPlugin { name: "p3".to_string(), closed: closed.clone() }),
1299        ];
1300
1301        let manager = EnhancedPluginManager::new(plugins);
1302        manager.close().await;
1303
1304        assert_eq!(closed.load(Ordering::SeqCst), 3);
1305    }
1306
1307    #[tokio::test]
1308    async fn test_debug_impl() {
1309        let plugins: Vec<Arc<dyn EnhancedPlugin>> =
1310            vec![Arc::new(NoOpPlugin::new("alpha", 10)), Arc::new(NoOpPlugin::new("beta", 20))];
1311
1312        let manager = EnhancedPluginManager::new(plugins);
1313        let debug_str = format!("{manager:?}");
1314        assert!(debug_str.contains("EnhancedPluginManager"));
1315        assert!(debug_str.contains("plugin_count: 2"));
1316    }
1317}