Skip to main content

adk_plugin/
adapted_plugin.rs

1//! Adapter wrapping a legacy closure-based [`Plugin`] as an [`EnhancedPlugin`].
2//!
3//! The [`AdaptedPlugin`] struct bridges the existing closure-based plugin system
4//! to the new trait-based [`EnhancedPlugin`] interface, enabling legacy plugins
5//! to participate in the enhanced pipeline without modification.
6//!
7//! # Overview
8//!
9//! Legacy plugins use callbacks that receive only a [`CallbackContext`] for tool hooks,
10//! and `(CallbackContext, LlmRequest)` / `(CallbackContext, LlmResponse)` for model hooks.
11//! They cannot modify tool arguments or results directly. The adapter:
12//!
13//! - Delegates `name()` to the inner [`Plugin::name()`]
14//! - Uses a configurable priority (default 100)
15//! - Invokes legacy `before_tool` / `after_tool` callbacks with a context that
16//!   carries the tool name and arguments. A `before_tool` callback that returns
17//!   content refuses the call: the adapter short-circuits with that content as the
18//!   tool's result, exactly as an agent's own before-tool callback does. Arguments
19//!   and `after_tool` results pass through unchanged
20//! - Maps legacy [`BeforeModelResult`] to [`BeforeModelCallResult`]
21//! - Maps legacy `AfterModelCallback` results to [`AfterModelCallResult`]
22//! - Delegates `close()` to the inner [`Plugin::close()`]
23//!
24//! # Example
25//!
26//! ```rust,ignore
27//! use adk_plugin::{AdaptedPlugin, Plugin, PluginConfig};
28//!
29//! let legacy_plugin = Plugin::new(PluginConfig {
30//!     name: "my-legacy-plugin".to_string(),
31//!     before_tool: Some(Box::new(|ctx| {
32//!         Box::pin(async move {
33//!             tracing::info!("tool starting");
34//!             Ok(None)
35//!         })
36//!     })),
37//!     ..Default::default()
38//! });
39//!
40//! // Wrap with default priority (100)
41//! let adapted = AdaptedPlugin::new(legacy_plugin, 100);
42//! ```
43
44use std::sync::Arc;
45
46use adk_core::{
47    BeforeModelResult, CallbackContext, Content, LlmRequest, LlmResponse, Part, Result, Tool,
48    ToolCallbackContext, async_trait,
49};
50use serde_json::Value;
51
52use crate::context::PluginContext;
53use crate::enhanced_plugin::EnhancedPlugin;
54use crate::hook_result::{
55    AfterModelCallResult, AfterToolCallResult, BeforeModelCallResult, BeforeToolCallResult,
56};
57use crate::plugin::Plugin;
58
59/// Wraps a legacy closure-based [`Plugin`] as an [`EnhancedPlugin`].
60///
61/// This adapter enables existing plugins to participate in the enhanced
62/// pipeline without modification. A legacy `before_tool` callback that returns
63/// content refuses the call, as it does when registered on an agent; the adapter
64/// never modifies tool arguments or results.
65///
66/// For model hooks, the adapter maps between the legacy [`BeforeModelResult`]
67/// and the new [`BeforeModelCallResult`], preserving short-circuit semantics.
68pub struct AdaptedPlugin {
69    inner: Plugin,
70    priority: i32,
71}
72
73impl AdaptedPlugin {
74    /// Create a new adapter wrapping a legacy plugin with the given priority.
75    ///
76    /// # Arguments
77    ///
78    /// * `plugin` - The legacy [`Plugin`] to wrap
79    /// * `priority` - Execution priority (lower values execute first, default: 100)
80    ///
81    /// # Example
82    ///
83    /// ```rust,ignore
84    /// use adk_plugin::{AdaptedPlugin, Plugin, PluginConfig};
85    ///
86    /// let plugin = Plugin::new(PluginConfig {
87    ///     name: "logger".to_string(),
88    ///     ..Default::default()
89    /// });
90    ///
91    /// let adapted = AdaptedPlugin::new(plugin, 50);
92    /// assert_eq!(adapted.priority(), 50);
93    /// ```
94    pub fn new(plugin: Plugin, priority: i32) -> Self {
95        Self { inner: plugin, priority }
96    }
97}
98
99#[async_trait]
100impl EnhancedPlugin for AdaptedPlugin {
101    fn name(&self) -> &str {
102        self.inner.name()
103    }
104
105    fn priority(&self) -> i32 {
106        self.priority
107    }
108
109    async fn before_tool_call(
110        &self,
111        tool: Arc<dyn Tool>,
112        args: Value,
113        ctx: Arc<dyn CallbackContext>,
114        _plugin_ctx: &PluginContext,
115    ) -> Result<BeforeToolCallResult> {
116        // A legacy callback returns `Ok(Some(content))` to skip the tool. Dropping that
117        // return let a denying plugin report a refusal while the tool ran anyway.
118        if let Some(callback) = self.inner.before_tool() {
119            let tool_ctx: Arc<dyn CallbackContext> =
120                Arc::new(ToolCallbackContext::new(ctx, tool.name().to_string(), args.clone()));
121            if let Some(content) = callback(tool_ctx).await? {
122                return Ok(BeforeToolCallResult::ShortCircuit(refusal_result(&content)));
123            }
124        }
125        Ok(BeforeToolCallResult::Continue(args))
126    }
127
128    async fn after_tool_call(
129        &self,
130        tool: Arc<dyn Tool>,
131        args: &Value,
132        result: Value,
133        ctx: Arc<dyn CallbackContext>,
134        _plugin_ctx: &PluginContext,
135    ) -> Result<AfterToolCallResult> {
136        // Legacy after_tool callbacks only receive CallbackContext and return
137        // Ok(None) to continue or Ok(Some(content)). They cannot modify tool results.
138        // We invoke for side effects and always return Continue with unchanged result.
139        if let Some(callback) = self.inner.after_tool() {
140            let tool_ctx: Arc<dyn CallbackContext> =
141                Arc::new(ToolCallbackContext::new(ctx, tool.name().to_string(), args.clone()));
142            let _ = callback(tool_ctx).await?;
143        }
144        Ok(AfterToolCallResult::Continue(result))
145    }
146
147    async fn before_model_call(
148        &self,
149        request: LlmRequest,
150        ctx: Arc<dyn CallbackContext>,
151        _plugin_ctx: &PluginContext,
152    ) -> Result<BeforeModelCallResult> {
153        // Legacy before_model callbacks receive (CallbackContext, LlmRequest) and return
154        // BeforeModelResult::Continue(request) or BeforeModelResult::Skip(response).
155        // We map these to the new BeforeModelCallResult variants.
156        if let Some(callback) = self.inner.before_model() {
157            let legacy_result = callback(ctx, request).await?;
158            match legacy_result {
159                BeforeModelResult::Continue(req) => Ok(BeforeModelCallResult::Continue(req)),
160                BeforeModelResult::Skip(response) => {
161                    Ok(BeforeModelCallResult::ShortCircuit(response))
162                }
163            }
164        } else {
165            Ok(BeforeModelCallResult::Continue(request))
166        }
167    }
168
169    async fn after_model_call(
170        &self,
171        response: LlmResponse,
172        ctx: Arc<dyn CallbackContext>,
173        _plugin_ctx: &PluginContext,
174    ) -> Result<AfterModelCallResult> {
175        // Legacy after_model callbacks receive (CallbackContext, LlmResponse) and return
176        // Ok(Some(response)) to replace or Ok(None) to keep original.
177        if let Some(callback) = self.inner.after_model() {
178            let result = callback(ctx, response.clone()).await?;
179            match result {
180                Some(modified_response) => Ok(AfterModelCallResult::Continue(modified_response)),
181                None => Ok(AfterModelCallResult::Continue(response)),
182            }
183        } else {
184            Ok(AfterModelCallResult::Continue(response))
185        }
186    }
187
188    async fn close(&self) {
189        self.inner.close().await;
190    }
191}
192
193/// The tool result for a legacy before-tool callback's refusal.
194///
195/// A function response part is used as-is; text is reported as the call's error,
196/// matching how an agent answers a call its own before-tool callback skipped.
197fn refusal_result(content: &Content) -> Value {
198    for part in &content.parts {
199        if let Part::FunctionResponse { function_response, .. } = part {
200            return function_response.response.clone();
201        }
202    }
203    let text: String = content.parts.iter().filter_map(Part::text).collect();
204    serde_json::json!({ "error": text })
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use crate::{PluginConfig, plugin::Plugin};
211    use adk_core::{BeforeModelResult, Content, LlmRequest, LlmResponse, Part};
212    use std::sync::atomic::{AtomicBool, Ordering};
213
214    /// Mock CallbackContext for testing
215    struct MockCallbackContext;
216
217    impl adk_core::ReadonlyContext for MockCallbackContext {
218        fn invocation_id(&self) -> &str {
219            "test-invocation"
220        }
221
222        fn agent_name(&self) -> &str {
223            "test-agent"
224        }
225
226        fn user_id(&self) -> &str {
227            "test-user"
228        }
229
230        fn app_name(&self) -> &str {
231            "test-app"
232        }
233
234        fn session_id(&self) -> &str {
235            "test-session"
236        }
237
238        fn branch(&self) -> &str {
239            "main"
240        }
241
242        fn user_content(&self) -> &Content {
243            static CONTENT: std::sync::OnceLock<Content> = std::sync::OnceLock::new();
244            CONTENT.get_or_init(|| Content::new("user"))
245        }
246    }
247
248    #[async_trait]
249    impl CallbackContext for MockCallbackContext {
250        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
251            None
252        }
253    }
254
255    /// Mock Tool for testing
256    struct MockTool;
257
258    #[async_trait]
259    impl Tool for MockTool {
260        fn name(&self) -> &str {
261            "mock-tool"
262        }
263
264        fn description(&self) -> &str {
265            "A mock tool for testing"
266        }
267
268        async fn execute(
269            &self,
270            _ctx: Arc<dyn adk_core::ToolContext>,
271            _args: Value,
272        ) -> adk_core::Result<Value> {
273            Ok(Value::Null)
274        }
275    }
276
277    #[tokio::test]
278    async fn test_name_delegates_to_inner() {
279        let plugin = Plugin::new(PluginConfig {
280            name: "my-legacy-plugin".to_string(),
281            ..Default::default()
282        });
283        let adapted = AdaptedPlugin::new(plugin, 100);
284        assert_eq!(adapted.name(), "my-legacy-plugin");
285    }
286
287    #[tokio::test]
288    async fn test_priority_uses_configured_value() {
289        let plugin = Plugin::new(PluginConfig { name: "test".to_string(), ..Default::default() });
290        let adapted = AdaptedPlugin::new(plugin, 42);
291        assert_eq!(adapted.priority(), 42);
292    }
293
294    #[tokio::test]
295    async fn test_before_tool_call_invokes_legacy_callback() {
296        let called = Arc::new(AtomicBool::new(false));
297        let called_clone = called.clone();
298
299        let plugin = Plugin::new(PluginConfig {
300            name: "test".to_string(),
301            before_tool: Some(Box::new(move |_ctx| {
302                let flag = called_clone.clone();
303                Box::pin(async move {
304                    flag.store(true, Ordering::SeqCst);
305                    Ok(None)
306                })
307            })),
308            ..Default::default()
309        });
310
311        let adapted = AdaptedPlugin::new(plugin, 100);
312        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
313        let plugin_ctx = PluginContext::new();
314        let tool: Arc<dyn Tool> = Arc::new(MockTool);
315        let args = serde_json::json!({"key": "value"});
316
317        let result = adapted.before_tool_call(tool, args.clone(), ctx, &plugin_ctx).await.unwrap();
318
319        assert!(called.load(Ordering::SeqCst));
320        match result {
321            BeforeToolCallResult::Continue(returned_args) => {
322                assert_eq!(returned_args, args);
323            }
324            _ => panic!("expected Continue"),
325        }
326    }
327
328    #[tokio::test]
329    async fn test_after_tool_call_invokes_legacy_callback() {
330        let called = Arc::new(AtomicBool::new(false));
331        let called_clone = called.clone();
332
333        let plugin = Plugin::new(PluginConfig {
334            name: "test".to_string(),
335            after_tool: Some(Box::new(move |_ctx| {
336                let flag = called_clone.clone();
337                Box::pin(async move {
338                    flag.store(true, Ordering::SeqCst);
339                    Ok(None)
340                })
341            })),
342            ..Default::default()
343        });
344
345        let adapted = AdaptedPlugin::new(plugin, 100);
346        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
347        let plugin_ctx = PluginContext::new();
348        let tool: Arc<dyn Tool> = Arc::new(MockTool);
349        let args = serde_json::json!({"input": "test"});
350        let result_val = serde_json::json!({"output": "done"});
351
352        let result = adapted
353            .after_tool_call(tool, &args, result_val.clone(), ctx, &plugin_ctx)
354            .await
355            .unwrap();
356
357        assert!(called.load(Ordering::SeqCst));
358        match result {
359            AfterToolCallResult::Continue(returned_result) => {
360                assert_eq!(returned_result, result_val);
361            }
362        }
363    }
364
365    #[tokio::test]
366    async fn test_before_model_call_maps_continue() {
367        let plugin = Plugin::new(PluginConfig {
368            name: "test".to_string(),
369            before_model: Some(Box::new(|_ctx, request| {
370                Box::pin(async move { Ok(BeforeModelResult::Continue(request)) })
371            })),
372            ..Default::default()
373        });
374
375        let adapted = AdaptedPlugin::new(plugin, 100);
376        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
377        let plugin_ctx = PluginContext::new();
378        let request = LlmRequest::new("test-model", vec![]);
379
380        let result = adapted.before_model_call(request, ctx, &plugin_ctx).await.unwrap();
381
382        match result {
383            BeforeModelCallResult::Continue(req) => {
384                assert_eq!(req.model, "test-model");
385            }
386            _ => panic!("expected Continue"),
387        }
388    }
389
390    #[tokio::test]
391    async fn test_before_model_call_maps_skip_to_short_circuit() {
392        let plugin = Plugin::new(PluginConfig {
393            name: "test".to_string(),
394            before_model: Some(Box::new(|_ctx, _request| {
395                Box::pin(async move {
396                    let response = LlmResponse {
397                        content: Some(Content::new("model").with_text("cached")),
398                        ..Default::default()
399                    };
400                    Ok(BeforeModelResult::Skip(response))
401                })
402            })),
403            ..Default::default()
404        });
405
406        let adapted = AdaptedPlugin::new(plugin, 100);
407        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
408        let plugin_ctx = PluginContext::new();
409        let request = LlmRequest::new("model", vec![]);
410
411        let result = adapted.before_model_call(request, ctx, &plugin_ctx).await.unwrap();
412
413        match result {
414            BeforeModelCallResult::ShortCircuit(resp) => {
415                assert!(resp.content.is_some());
416            }
417            _ => panic!("expected ShortCircuit"),
418        }
419    }
420
421    #[tokio::test]
422    async fn test_after_model_call_maps_some_to_continue_modified() {
423        let plugin = Plugin::new(PluginConfig {
424            name: "test".to_string(),
425            after_model: Some(Box::new(|_ctx, _response| {
426                Box::pin(async move {
427                    let modified = LlmResponse {
428                        content: Some(Content::new("model").with_text("modified")),
429                        ..Default::default()
430                    };
431                    Ok(Some(modified))
432                })
433            })),
434            ..Default::default()
435        });
436
437        let adapted = AdaptedPlugin::new(plugin, 100);
438        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
439        let plugin_ctx = PluginContext::new();
440        let response = LlmResponse::default();
441
442        let result = adapted.after_model_call(response, ctx, &plugin_ctx).await.unwrap();
443
444        match result {
445            AfterModelCallResult::Continue(resp) => {
446                let content = resp.content.unwrap();
447                assert!(
448                    content
449                        .parts
450                        .iter()
451                        .any(|p| matches!(p, Part::Text { text } if text == "modified"))
452                );
453            }
454        }
455    }
456
457    #[tokio::test]
458    async fn test_after_model_call_maps_none_to_continue_unchanged() {
459        let plugin = Plugin::new(PluginConfig {
460            name: "test".to_string(),
461            after_model: Some(Box::new(|_ctx, _response| Box::pin(async move { Ok(None) }))),
462            ..Default::default()
463        });
464
465        let adapted = AdaptedPlugin::new(plugin, 100);
466        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
467        let plugin_ctx = PluginContext::new();
468        let response = LlmResponse {
469            content: Some(Content::new("model").with_text("original")),
470            ..Default::default()
471        };
472
473        let result = adapted.after_model_call(response, ctx, &plugin_ctx).await.unwrap();
474
475        match result {
476            AfterModelCallResult::Continue(resp) => {
477                let content = resp.content.unwrap();
478                assert!(
479                    content
480                        .parts
481                        .iter()
482                        .any(|p| matches!(p, Part::Text { text } if text == "original"))
483                );
484            }
485        }
486    }
487
488    #[tokio::test]
489    async fn test_close_delegates_to_inner() {
490        let closed = Arc::new(AtomicBool::new(false));
491        let closed_clone = closed.clone();
492
493        let plugin = Plugin::new(PluginConfig {
494            name: "test".to_string(),
495            close_fn: Some(Box::new(move || {
496                let flag = closed_clone.clone();
497                Box::pin(async move {
498                    flag.store(true, Ordering::SeqCst);
499                })
500            })),
501            ..Default::default()
502        });
503
504        let adapted = AdaptedPlugin::new(plugin, 100);
505        adapted.close().await;
506
507        assert!(closed.load(Ordering::SeqCst));
508    }
509
510    #[tokio::test]
511    async fn test_no_callbacks_returns_continue_unchanged() {
512        let plugin = Plugin::new(PluginConfig { name: "empty".to_string(), ..Default::default() });
513
514        let adapted = AdaptedPlugin::new(plugin, 100);
515        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
516        let plugin_ctx = PluginContext::new();
517        let tool: Arc<dyn Tool> = Arc::new(MockTool);
518
519        // before_tool_call with no callback
520        let args = serde_json::json!({"x": 1});
521        let result = adapted
522            .before_tool_call(tool.clone(), args.clone(), ctx.clone(), &plugin_ctx)
523            .await
524            .unwrap();
525        match result {
526            BeforeToolCallResult::Continue(v) => assert_eq!(v, args),
527            _ => panic!("expected Continue"),
528        }
529
530        // after_tool_call with no callback
531        let res_val = serde_json::json!({"y": 2});
532        let result = adapted
533            .after_tool_call(tool.clone(), &args, res_val.clone(), ctx.clone(), &plugin_ctx)
534            .await
535            .unwrap();
536        match result {
537            AfterToolCallResult::Continue(v) => assert_eq!(v, res_val),
538        }
539
540        // before_model_call with no callback
541        let request = LlmRequest::new("m", vec![]);
542        let result = adapted.before_model_call(request, ctx.clone(), &plugin_ctx).await.unwrap();
543        match result {
544            BeforeModelCallResult::Continue(req) => assert_eq!(req.model, "m"),
545            _ => panic!("expected Continue"),
546        }
547
548        // after_model_call with no callback
549        let response = LlmResponse {
550            content: Some(Content::new("model").with_text("hi")),
551            ..Default::default()
552        };
553        let result = adapted.after_model_call(response, ctx, &plugin_ctx).await.unwrap();
554        match result {
555            AfterModelCallResult::Continue(resp) => {
556                assert!(resp.content.is_some());
557            }
558        }
559    }
560
561    #[tokio::test]
562    async fn a_legacy_before_tool_refusal_short_circuits_the_call() {
563        let seen_tool = Arc::new(std::sync::Mutex::new(None));
564        let seen = seen_tool.clone();
565        let plugin = Plugin::new(PluginConfig {
566            name: "deny".to_string(),
567            before_tool: Some(Box::new(move |ctx| {
568                let seen = seen.clone();
569                Box::pin(async move {
570                    *seen.lock().unwrap() =
571                        Some((ctx.tool_name().map(str::to_string), ctx.tool_input().cloned()));
572                    Ok(Some(Content::new("function").with_text("blocked by policy")))
573                })
574            })),
575            ..Default::default()
576        });
577
578        let adapted = AdaptedPlugin::new(plugin, 100);
579        let ctx: Arc<dyn CallbackContext> = Arc::new(MockCallbackContext);
580        let tool: Arc<dyn Tool> = Arc::new(MockTool);
581        let args = serde_json::json!({ "key": "value" });
582
583        let result =
584            adapted.before_tool_call(tool, args.clone(), ctx, &PluginContext::new()).await.unwrap();
585
586        match result {
587            BeforeToolCallResult::ShortCircuit(value) => {
588                assert_eq!(value, serde_json::json!({ "error": "blocked by policy" }));
589            }
590            BeforeToolCallResult::Continue(_) => panic!("a refusal must not continue the call"),
591        }
592        assert_eq!(
593            *seen_tool.lock().unwrap(),
594            Some((Some("mock-tool".to_string()), Some(args))),
595            "the callback must see the tool it is deciding"
596        );
597    }
598}