1use crate::Plugin;
6use adk_core::{
7 BeforeModelResult, CallbackContext, Content, Event, InvocationContext, InvocationHooks,
8 LlmRequest, LlmResponse, Result, Tool, async_trait,
9};
10use std::sync::Arc;
11use std::time::Duration;
12use tracing::{debug, warn};
13
14#[derive(Clone)]
16pub struct PluginManagerConfig {
17 pub close_timeout: Duration,
19}
20
21impl Default for PluginManagerConfig {
22 fn default() -> Self {
23 Self { close_timeout: Duration::from_secs(5) }
24 }
25}
26
27pub struct PluginManager {
61 plugins: Vec<Plugin>,
62 config: PluginManagerConfig,
63}
64
65impl PluginManager {
66 pub fn new(plugins: Vec<Plugin>) -> Self {
68 Self::with_config(plugins, PluginManagerConfig::default())
69 }
70
71 pub fn with_config(plugins: Vec<Plugin>, config: PluginManagerConfig) -> Self {
73 Self { plugins, config }
74 }
75
76 pub fn plugin_count(&self) -> usize {
78 self.plugins.len()
79 }
80
81 pub fn plugin_names(&self) -> Vec<&str> {
83 self.plugins.iter().map(|p| p.name()).collect()
84 }
85
86 pub async fn run_on_user_message(
90 &self,
91 ctx: Arc<dyn InvocationContext>,
92 content: Content,
93 ) -> Result<Option<Content>> {
94 let mut current_content = content;
95 let mut was_modified = false;
96
97 for plugin in &self.plugins {
98 if let Some(callback) = plugin.on_user_message() {
99 debug!(plugin = plugin.name(), "Running on_user_message callback");
100 match callback(ctx.clone(), current_content.clone()).await {
101 Ok(Some(modified)) => {
102 debug!(plugin = plugin.name(), "Content modified by plugin");
103 was_modified = true;
104 current_content = modified;
105 }
106 Ok(None) => {
107 }
109 Err(e) => {
110 warn!(plugin = plugin.name(), error = %e, "on_user_message callback failed");
111 return Err(e);
112 }
113 }
114 }
115 }
116
117 Ok(if was_modified { Some(current_content) } else { None })
118 }
119
120 pub async fn run_on_event(
124 &self,
125 ctx: Arc<dyn InvocationContext>,
126 event: Event,
127 ) -> Result<Option<Event>> {
128 let mut current_event = event;
129 let mut was_modified = false;
130
131 for plugin in &self.plugins {
132 if let Some(callback) = plugin.on_event() {
133 debug!(plugin = plugin.name(), event_id = %current_event.id, "Running on_event callback");
134 match callback(ctx.clone(), current_event.clone()).await {
135 Ok(Some(modified)) => {
136 debug!(plugin = plugin.name(), "Event modified by plugin");
137 was_modified = true;
138 current_event = modified;
139 }
140 Ok(None) => {
141 }
143 Err(e) => {
144 warn!(plugin = plugin.name(), error = %e, "on_event callback failed");
145 return Err(e);
146 }
147 }
148 }
149 }
150
151 Ok(if was_modified { Some(current_event) } else { None })
152 }
153
154 pub async fn run_before_run(&self, ctx: Arc<dyn InvocationContext>) -> Result<Option<Content>> {
158 for plugin in &self.plugins {
159 if let Some(callback) = plugin.before_run() {
160 debug!(plugin = plugin.name(), "Running before_run callback");
161 match callback(ctx.clone()).await {
162 Ok(Some(content)) => {
163 debug!(plugin = plugin.name(), "before_run returned early exit content");
164 return Ok(Some(content));
165 }
166 Ok(None) => {
167 }
169 Err(e) => {
170 warn!(plugin = plugin.name(), error = %e, "before_run callback failed");
171 return Err(e);
172 }
173 }
174 }
175 }
176
177 Ok(None)
178 }
179
180 pub async fn run_after_run(&self, ctx: Arc<dyn InvocationContext>) {
184 for plugin in &self.plugins {
185 if let Some(callback) = plugin.after_run() {
186 debug!(plugin = plugin.name(), "Running after_run callback");
187 callback(ctx.clone()).await;
188 }
189 }
190 }
191
192 pub async fn run_before_agent(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
196 for plugin in &self.plugins {
197 if let Some(callback) = plugin.before_agent() {
198 debug!(plugin = plugin.name(), "Running before_agent callback");
199 match callback(ctx.clone()).await {
200 Ok(Some(content)) => {
201 debug!(plugin = plugin.name(), "before_agent returned early exit content");
202 return Ok(Some(content));
203 }
204 Ok(None) => {
205 }
207 Err(e) => {
208 warn!(plugin = plugin.name(), error = %e, "before_agent callback failed");
209 return Err(e);
210 }
211 }
212 }
213 }
214
215 Ok(None)
216 }
217
218 pub async fn run_after_agent(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
220 for plugin in &self.plugins {
221 if let Some(callback) = plugin.after_agent() {
222 debug!(plugin = plugin.name(), "Running after_agent callback");
223 match callback(ctx.clone()).await {
224 Ok(Some(content)) => {
225 debug!(plugin = plugin.name(), "after_agent returned content");
226 return Ok(Some(content));
227 }
228 Ok(None) => {
229 }
231 Err(e) => {
232 warn!(plugin = plugin.name(), error = %e, "after_agent callback failed");
233 return Err(e);
234 }
235 }
236 }
237 }
238
239 Ok(None)
240 }
241
242 pub async fn run_before_model(
246 &self,
247 ctx: Arc<dyn CallbackContext>,
248 request: LlmRequest,
249 ) -> Result<BeforeModelResult> {
250 let mut current_request = request;
251
252 for plugin in &self.plugins {
254 if let Some(callback) = plugin.before_model() {
255 debug!(plugin = plugin.name(), "Running before_model callback");
256 match callback(ctx.clone(), current_request).await {
257 Ok(BeforeModelResult::Continue(modified)) => {
258 current_request = modified;
259 }
260 Ok(BeforeModelResult::Skip(response)) => {
261 debug!(plugin = plugin.name(), "before_model skipped model call");
262 return Ok(BeforeModelResult::Skip(response));
263 }
264 Err(e) => {
265 warn!(plugin = plugin.name(), error = %e, "before_model callback failed");
266 return Err(e);
267 }
268 }
269 }
270 }
271
272 Ok(BeforeModelResult::Continue(current_request))
273 }
274
275 pub async fn run_after_model(
277 &self,
278 ctx: Arc<dyn CallbackContext>,
279 response: LlmResponse,
280 ) -> Result<Option<LlmResponse>> {
281 let mut current_response = response;
282 let mut was_modified = false;
283
284 for plugin in &self.plugins {
285 if let Some(callback) = plugin.after_model() {
286 debug!(plugin = plugin.name(), "Running after_model callback");
287 match callback(ctx.clone(), current_response.clone()).await {
288 Ok(Some(modified)) => {
289 was_modified = true;
290 current_response = modified;
291 }
292 Ok(None) => {
293 }
295 Err(e) => {
296 warn!(plugin = plugin.name(), error = %e, "after_model callback failed");
297 return Err(e);
298 }
299 }
300 }
301 }
302
303 Ok(if was_modified { Some(current_response) } else { None })
304 }
305
306 pub async fn run_on_model_error(
311 &self,
312 ctx: Arc<dyn CallbackContext>,
313 request: LlmRequest,
314 error: String,
315 ) -> Result<Option<LlmResponse>> {
316 for plugin in &self.plugins {
317 if let Some(callback) = plugin.on_model_error() {
318 debug!(plugin = plugin.name(), "Running on_model_error callback");
319 match callback(ctx.clone(), request.clone(), error.clone()).await {
320 Ok(Some(response)) => {
321 debug!(plugin = plugin.name(), "on_model_error provided fallback response");
322 return Ok(Some(response));
323 }
324 Ok(None) => {
325 }
327 Err(e) => {
328 warn!(plugin = plugin.name(), error = %e, "on_model_error callback failed");
329 return Err(e);
330 }
331 }
332 }
333 }
334
335 Ok(None)
336 }
337
338 pub async fn run_before_tool(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
340 for plugin in &self.plugins {
341 if let Some(callback) = plugin.before_tool() {
342 debug!(plugin = plugin.name(), "Running before_tool callback");
343 match callback(ctx.clone()).await {
344 Ok(Some(content)) => {
345 debug!(plugin = plugin.name(), "before_tool returned early exit content");
346 return Ok(Some(content));
347 }
348 Ok(None) => {
349 }
351 Err(e) => {
352 warn!(plugin = plugin.name(), error = %e, "before_tool callback failed");
353 return Err(e);
354 }
355 }
356 }
357 }
358
359 Ok(None)
360 }
361
362 pub async fn run_after_tool(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
364 for plugin in &self.plugins {
365 if let Some(callback) = plugin.after_tool() {
366 debug!(plugin = plugin.name(), "Running after_tool callback");
367 match callback(ctx.clone()).await {
368 Ok(Some(content)) => {
369 debug!(plugin = plugin.name(), "after_tool returned content");
370 return Ok(Some(content));
371 }
372 Ok(None) => {
373 }
375 Err(e) => {
376 warn!(plugin = plugin.name(), error = %e, "after_tool callback failed");
377 return Err(e);
378 }
379 }
380 }
381 }
382
383 Ok(None)
384 }
385
386 pub async fn run_on_tool_error(
388 &self,
389 ctx: Arc<dyn CallbackContext>,
390 tool: Arc<dyn Tool>,
391 args: serde_json::Value,
392 error: String,
393 ) -> Result<Option<serde_json::Value>> {
394 for plugin in &self.plugins {
395 if let Some(callback) = plugin.on_tool_error() {
396 debug!(
397 plugin = plugin.name(),
398 tool = tool.name(),
399 "Running on_tool_error callback"
400 );
401 match callback(ctx.clone(), tool.clone(), args.clone(), error.clone()).await {
402 Ok(Some(result)) => {
403 debug!(plugin = plugin.name(), "on_tool_error provided fallback result");
404 return Ok(Some(result));
405 }
406 Ok(None) => {
407 }
409 Err(e) => {
410 warn!(plugin = plugin.name(), error = %e, "on_tool_error callback failed");
411 return Err(e);
412 }
413 }
414 }
415 }
416
417 Ok(None)
418 }
419
420 pub async fn close(&self) {
422 debug!("Closing {} plugins", self.plugins.len());
423
424 for plugin in &self.plugins {
425 let close_future = plugin.close();
426 match tokio::time::timeout(self.config.close_timeout, close_future).await {
427 Ok(()) => {
428 debug!(plugin = plugin.name(), "Plugin closed successfully");
429 }
430 Err(_) => {
431 warn!(plugin = plugin.name(), "Plugin close timed out");
432 }
433 }
434 }
435 }
436}
437
438#[async_trait]
439impl InvocationHooks for PluginManager {
440 async fn before_agent(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
441 self.run_before_agent(ctx).await
442 }
443
444 async fn after_agent(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
445 self.run_after_agent(ctx).await
446 }
447
448 async fn before_model(
449 &self,
450 ctx: Arc<dyn CallbackContext>,
451 request: LlmRequest,
452 ) -> Result<BeforeModelResult> {
453 self.run_before_model(ctx, request).await
454 }
455
456 async fn after_model(
457 &self,
458 ctx: Arc<dyn CallbackContext>,
459 response: LlmResponse,
460 ) -> Result<Option<LlmResponse>> {
461 self.run_after_model(ctx, response).await
462 }
463
464 async fn on_model_error(
465 &self,
466 ctx: Arc<dyn CallbackContext>,
467 request: LlmRequest,
468 error: &adk_core::AdkError,
469 ) -> Result<Option<LlmResponse>> {
470 self.run_on_model_error(ctx, request, error.to_string()).await
471 }
472
473 fn handles_model_errors(&self) -> bool {
474 self.plugins.iter().any(|plugin| plugin.on_model_error().is_some())
475 }
476
477 async fn before_tool(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
478 self.run_before_tool(ctx).await
479 }
480
481 async fn after_tool(&self, ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
482 self.run_after_tool(ctx).await
483 }
484
485 async fn on_tool_error(
486 &self,
487 ctx: Arc<dyn CallbackContext>,
488 tool: Arc<dyn Tool>,
489 args: serde_json::Value,
490 error: String,
491 ) -> Result<Option<serde_json::Value>> {
492 self.run_on_tool_error(ctx, tool, args, error).await
493 }
494}
495
496impl std::fmt::Debug for PluginManager {
497 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
498 f.debug_struct("PluginManager")
499 .field("plugin_count", &self.plugins.len())
500 .field("plugin_names", &self.plugin_names())
501 .field("close_timeout", &self.config.close_timeout)
502 .finish()
503 }
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509 use crate::PluginConfig;
510
511 #[test]
512 fn test_plugin_manager_creation() {
513 let plugins = vec![
514 Plugin::new(PluginConfig { name: "test1".to_string(), ..Default::default() }),
515 Plugin::new(PluginConfig { name: "test2".to_string(), ..Default::default() }),
516 ];
517
518 let manager = PluginManager::new(plugins);
519 assert_eq!(manager.plugin_count(), 2);
520 assert_eq!(manager.plugin_names(), vec!["test1", "test2"]);
521 }
522
523 #[test]
524 fn handles_model_errors_only_with_an_on_model_error_plugin() {
525 let observer = || {
526 crate::PluginBuilder::new("observer")
527 .before_model(Box::new(|_ctx, request| {
528 Box::pin(async move { Ok(BeforeModelResult::Continue(request)) })
529 }))
530 .build()
531 };
532 let fallback = crate::PluginBuilder::new("fallback")
533 .on_model_error(Box::new(|_ctx, _request, _error| Box::pin(async { Ok(None) })))
534 .build();
535
536 let without = PluginManager::new(vec![observer()]);
537 let with = PluginManager::new(vec![observer(), fallback]);
538 assert_eq!(
539 (
540 InvocationHooks::handles_model_errors(&without),
541 InvocationHooks::handles_model_errors(&with)
542 ),
543 (false, true)
544 );
545 }
546}