Skip to main content

adk_plugin/
plugin.rs

1//! Plugin definition
2//!
3//! A Plugin bundles related callbacks together for a specific purpose.
4
5use crate::callbacks::*;
6use adk_core::{
7    AfterAgentCallback, AfterModelCallback, AfterToolCallback, BeforeAgentCallback,
8    BeforeModelCallback, BeforeToolCallback,
9};
10use std::future::Future;
11use std::pin::Pin;
12
13/// Type alias for async cleanup functions.
14pub type CloseFn = Box<dyn Fn() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
15
16/// Configuration for creating a Plugin.
17///
18/// All callbacks are optional - only set the ones you need.
19///
20/// # Example
21///
22/// ```rust,ignore
23/// let config = PluginConfig {
24///     name: "my-plugin".to_string(),
25///     on_user_message: Some(Box::new(|ctx, content| {
26///         Box::pin(async move {
27///             // Process user message
28///             Ok(None)
29///         })
30///     })),
31///     ..Default::default()
32/// };
33/// ```
34pub struct PluginConfig {
35    /// Unique name for this plugin
36    pub name: String,
37
38    // Run lifecycle callbacks
39    /// Called when a user message is received (can modify)
40    pub on_user_message: Option<OnUserMessageCallback>,
41    /// Called for each event (can modify)
42    pub on_event: Option<OnEventCallback>,
43    /// Called before the run starts (can skip run)
44    pub before_run: Option<BeforeRunCallback>,
45    /// Called after the run completes (cleanup)
46    pub after_run: Option<AfterRunCallback>,
47
48    // Agent callbacks
49    /// Called before agent execution
50    pub before_agent: Option<BeforeAgentCallback>,
51    /// Called after agent execution
52    pub after_agent: Option<AfterAgentCallback>,
53
54    // Model callbacks
55    /// Called before LLM call (can modify request or skip)
56    pub before_model: Option<BeforeModelCallback>,
57    /// Called after LLM call (can modify response)
58    pub after_model: Option<AfterModelCallback>,
59    /// Called when a model call or its response stream fails, before the agent fails the
60    /// turn; a returned response answers the turn instead.
61    pub on_model_error: Option<OnModelErrorCallback>,
62
63    // Tool callbacks
64    /// Called before tool execution
65    pub before_tool: Option<BeforeToolCallback>,
66    /// Called after tool execution
67    pub after_tool: Option<AfterToolCallback>,
68    /// Called when tool returns an error
69    pub on_tool_error: Option<OnToolErrorCallback>,
70
71    /// Cleanup function called when plugin is closed
72    pub close_fn: Option<CloseFn>,
73}
74
75impl Default for PluginConfig {
76    fn default() -> Self {
77        Self {
78            name: "unnamed".to_string(),
79            on_user_message: None,
80            on_event: None,
81            before_run: None,
82            after_run: None,
83            before_agent: None,
84            after_agent: None,
85            before_model: None,
86            after_model: None,
87            on_model_error: None,
88            before_tool: None,
89            after_tool: None,
90            on_tool_error: None,
91            close_fn: None,
92        }
93    }
94}
95
96/// A Plugin bundles related callbacks for extending agent behavior.
97///
98/// Plugins are registered with a PluginManager which coordinates
99/// callback execution across all registered plugins.
100///
101/// # Example
102///
103/// ```rust,ignore
104/// use adk_plugin::{Plugin, PluginConfig};
105///
106/// // Create a caching plugin
107/// let cache_plugin = Plugin::new(PluginConfig {
108///     name: "cache".to_string(),
109///     before_model: Some(Box::new(|ctx, request| {
110///         Box::pin(async move {
111///             // Check cache for this request
112///             if let Some(cached) = check_cache(&request).await {
113///                 return Ok(BeforeModelResult::Skip(cached));
114///             }
115///             Ok(BeforeModelResult::Continue(request))
116///         })
117///     })),
118///     after_model: Some(Box::new(|ctx, response| {
119///         Box::pin(async move {
120///             // Store response in cache
121///             store_in_cache(&response).await;
122///             Ok(None)
123///         })
124///     })),
125///     ..Default::default()
126/// });
127/// ```
128pub struct Plugin {
129    config: PluginConfig,
130}
131
132impl Plugin {
133    /// Create a new plugin from configuration.
134    pub fn new(config: PluginConfig) -> Self {
135        Self { config }
136    }
137
138    /// Get the plugin name.
139    pub fn name(&self) -> &str {
140        &self.config.name
141    }
142
143    /// Get the on_user_message callback if set.
144    pub fn on_user_message(&self) -> Option<&OnUserMessageCallback> {
145        self.config.on_user_message.as_ref()
146    }
147
148    /// Get the on_event callback if set.
149    pub fn on_event(&self) -> Option<&OnEventCallback> {
150        self.config.on_event.as_ref()
151    }
152
153    /// Get the before_run callback if set.
154    pub fn before_run(&self) -> Option<&BeforeRunCallback> {
155        self.config.before_run.as_ref()
156    }
157
158    /// Get the after_run callback if set.
159    pub fn after_run(&self) -> Option<&AfterRunCallback> {
160        self.config.after_run.as_ref()
161    }
162
163    /// Get the before_agent callback if set.
164    pub fn before_agent(&self) -> Option<&BeforeAgentCallback> {
165        self.config.before_agent.as_ref()
166    }
167
168    /// Get the after_agent callback if set.
169    pub fn after_agent(&self) -> Option<&AfterAgentCallback> {
170        self.config.after_agent.as_ref()
171    }
172
173    /// Get the before_model callback if set.
174    pub fn before_model(&self) -> Option<&BeforeModelCallback> {
175        self.config.before_model.as_ref()
176    }
177
178    /// Get the after_model callback if set.
179    pub fn after_model(&self) -> Option<&AfterModelCallback> {
180        self.config.after_model.as_ref()
181    }
182
183    /// Get the on_model_error callback if set.
184    pub fn on_model_error(&self) -> Option<&OnModelErrorCallback> {
185        self.config.on_model_error.as_ref()
186    }
187
188    /// Get the before_tool callback if set.
189    pub fn before_tool(&self) -> Option<&BeforeToolCallback> {
190        self.config.before_tool.as_ref()
191    }
192
193    /// Get the after_tool callback if set.
194    pub fn after_tool(&self) -> Option<&AfterToolCallback> {
195        self.config.after_tool.as_ref()
196    }
197
198    /// Get the on_tool_error callback if set.
199    pub fn on_tool_error(&self) -> Option<&OnToolErrorCallback> {
200        self.config.on_tool_error.as_ref()
201    }
202
203    /// Close the plugin, running cleanup if configured.
204    pub async fn close(&self) {
205        if let Some(ref close_fn) = self.config.close_fn {
206            close_fn().await;
207        }
208    }
209}
210
211impl std::fmt::Debug for Plugin {
212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213        f.debug_struct("Plugin")
214            .field("name", &self.config.name)
215            .field("has_on_user_message", &self.config.on_user_message.is_some())
216            .field("has_on_event", &self.config.on_event.is_some())
217            .field("has_before_run", &self.config.before_run.is_some())
218            .field("has_after_run", &self.config.after_run.is_some())
219            .field("has_before_agent", &self.config.before_agent.is_some())
220            .field("has_after_agent", &self.config.after_agent.is_some())
221            .field("has_before_model", &self.config.before_model.is_some())
222            .field("has_after_model", &self.config.after_model.is_some())
223            .field("has_before_tool", &self.config.before_tool.is_some())
224            .field("has_after_tool", &self.config.after_tool.is_some())
225            .finish()
226    }
227}
228
229/// Builder for creating plugins with a fluent API.
230///
231/// `PluginBuilder` provides a chainable interface for constructing [`Plugin`] instances
232/// without manually filling out a [`PluginConfig`] struct. Each method configures a
233/// single lifecycle callback, and [`build`](Self::build) produces the final `Plugin`.
234///
235/// # End-to-End Example
236///
237/// ```rust,ignore
238/// use adk_plugin::PluginBuilder;
239/// use std::sync::Arc;
240///
241/// let plugin = PluginBuilder::new("audit-trail")
242///     .before_agent(Box::new(|ctx| {
243///         Box::pin(async move {
244///             tracing::info!("agent starting");
245///             Ok(())
246///         })
247///     }))
248///     .after_agent(Box::new(|ctx| {
249///         Box::pin(async move {
250///             tracing::info!("agent finished");
251///             Ok(())
252///         })
253///     }))
254///     .before_tool(Box::new(|ctx| {
255///         Box::pin(async move {
256///             if let Some(name) = ctx.tool_name() {
257///                 tracing::info!(tool = name, "tool invoked");
258///             }
259///             Ok(())
260///         })
261///     }))
262///     .after_tool(Box::new(|ctx| {
263///         Box::pin(async move {
264///             tracing::info!("tool completed");
265///             Ok(())
266///         })
267///     }))
268///     .before_model(Box::new(|ctx, request| {
269///         Box::pin(async move {
270///             tracing::debug!(model = ?request.model, "sending request to model");
271///             Ok(request)
272///         })
273///     }))
274///     .after_model(Box::new(|ctx, response| {
275///         Box::pin(async move {
276///             tracing::debug!("model responded");
277///             Ok(None)
278///         })
279///     }))
280///     .close_fn(|| Box::pin(async { tracing::info!("plugin closed") }))
281///     .build();
282///
283/// assert_eq!(plugin.name(), "audit-trail");
284/// ```
285pub struct PluginBuilder {
286    config: PluginConfig,
287}
288
289impl PluginBuilder {
290    /// Create a new plugin builder with the given name.
291    ///
292    /// The name uniquely identifies this plugin within a [`PluginManager`](crate::PluginManager).
293    ///
294    /// ```rust,ignore
295    /// let builder = PluginBuilder::new("my-plugin");
296    /// ```
297    pub fn new(name: impl Into<String>) -> Self {
298        Self { config: PluginConfig { name: name.into(), ..Default::default() } }
299    }
300
301    /// Set the callback invoked when a user message is received.
302    ///
303    /// The callback can inspect or modify the incoming [`Content`](adk_core::Content).
304    /// Return `Ok(Some(content))` to replace the message, or `Ok(None)` to keep the original.
305    ///
306    /// ```rust,ignore
307    /// builder.on_user_message(Box::new(|ctx, content| {
308    ///     Box::pin(async move {
309    ///         tracing::info!(role = %content.role, "user message received");
310    ///         Ok(None) // pass through unchanged
311    ///     })
312    /// }))
313    /// ```
314    pub fn on_user_message(mut self, callback: OnUserMessageCallback) -> Self {
315        self.config.on_user_message = Some(callback);
316        self
317    }
318
319    /// Set the callback invoked for each event generated by the agent.
320    ///
321    /// The callback can inspect or modify [`Event`](adk_core::Event) objects before they
322    /// are yielded to the caller. Return `Ok(Some(event))` to replace the event, or
323    /// `Ok(None)` to keep the original.
324    ///
325    /// ```rust,ignore
326    /// builder.on_event(Box::new(|ctx, event| {
327    ///     Box::pin(async move {
328    ///         tracing::debug!(id = %event.id, "event emitted");
329    ///         Ok(None)
330    ///     })
331    /// }))
332    /// ```
333    pub fn on_event(mut self, callback: OnEventCallback) -> Self {
334        self.config.on_event = Some(callback);
335        self
336    }
337
338    /// Set the callback invoked before the agent run starts.
339    ///
340    /// Use this for setup, validation, or early exit. Return `Ok(Some(content))` to
341    /// skip the run entirely and return that content, or `Ok(None)` to proceed normally.
342    ///
343    /// ```rust,ignore
344    /// builder.before_run(Box::new(|ctx| {
345    ///     Box::pin(async move {
346    ///         tracing::info!("run starting");
347    ///         Ok(None) // continue with the run
348    ///     })
349    /// }))
350    /// ```
351    pub fn before_run(mut self, callback: BeforeRunCallback) -> Self {
352        self.config.before_run = Some(callback);
353        self
354    }
355
356    /// Set the callback invoked after the agent run completes.
357    ///
358    /// Use this for cleanup, logging, or metrics collection. This callback is for
359    /// side effects only and does not emit events.
360    ///
361    /// ```rust,ignore
362    /// builder.after_run(Box::new(|ctx| {
363    ///     Box::pin(async move {
364    ///         tracing::info!("run completed");
365    ///     })
366    /// }))
367    /// ```
368    pub fn after_run(mut self, callback: AfterRunCallback) -> Self {
369        self.config.after_run = Some(callback);
370        self
371    }
372
373    /// Set the callback invoked before agent execution.
374    ///
375    /// Runs each time an agent is about to execute. Useful for tracing, permission
376    /// checks, or injecting state.
377    ///
378    /// ```rust,ignore
379    /// builder.before_agent(Box::new(|ctx| {
380    ///     Box::pin(async move {
381    ///         tracing::info!("agent starting");
382    ///         Ok(())
383    ///     })
384    /// }))
385    /// ```
386    pub fn before_agent(mut self, callback: BeforeAgentCallback) -> Self {
387        self.config.before_agent = Some(callback);
388        self
389    }
390
391    /// Set the callback invoked after agent execution.
392    ///
393    /// Runs each time an agent finishes. Useful for logging duration, collecting
394    /// metrics, or post-processing results.
395    ///
396    /// ```rust,ignore
397    /// builder.after_agent(Box::new(|ctx| {
398    ///     Box::pin(async move {
399    ///         tracing::info!("agent finished");
400    ///         Ok(())
401    ///     })
402    /// }))
403    /// ```
404    pub fn after_agent(mut self, callback: AfterAgentCallback) -> Self {
405        self.config.after_agent = Some(callback);
406        self
407    }
408
409    /// Set the callback invoked before an LLM call.
410    ///
411    /// The callback receives the [`LlmRequest`](adk_core::LlmRequest) and can modify it
412    /// or skip the call entirely by returning a pre-built response.
413    ///
414    /// ```rust,ignore
415    /// builder.before_model(Box::new(|ctx, request| {
416    ///     Box::pin(async move {
417    ///         tracing::debug!(model = ?request.model, "calling model");
418    ///         Ok(request) // pass through unchanged
419    ///     })
420    /// }))
421    /// ```
422    pub fn before_model(mut self, callback: BeforeModelCallback) -> Self {
423        self.config.before_model = Some(callback);
424        self
425    }
426
427    /// Set the callback invoked after an LLM call.
428    ///
429    /// The callback receives the [`LlmResponse`](adk_core::LlmResponse) and can modify
430    /// or replace it. Return `Ok(Some(response))` to replace, or `Ok(None)` to keep
431    /// the original.
432    ///
433    /// ```rust,ignore
434    /// builder.after_model(Box::new(|ctx, response| {
435    ///     Box::pin(async move {
436    ///         tracing::debug!("model responded");
437    ///         Ok(None) // keep original response
438    ///     })
439    /// }))
440    /// ```
441    pub fn after_model(mut self, callback: AfterModelCallback) -> Self {
442        self.config.after_model = Some(callback);
443        self
444    }
445
446    /// Set the callback invoked when a model call or its response stream fails.
447    ///
448    /// `LlmAgent` calls it before it fails the turn, with the [`LlmRequest`](adk_core::LlmRequest)
449    /// the model was sent and the error message. Return `Ok(Some(response))` to answer the
450    /// turn with a fallback response, which the agent processes as the model's response, or
451    /// `Ok(None)` to propagate the error. A refusal by the run's budget or spend ledger is not
452    /// reported.
453    ///
454    /// ```rust,ignore
455    /// builder.on_model_error(Box::new(|ctx, request, error| {
456    ///     Box::pin(async move {
457    ///         tracing::warn!(error = %error, "model error, no fallback");
458    ///         Ok(None) // propagate the error
459    ///     })
460    /// }))
461    /// ```
462    pub fn on_model_error(mut self, callback: OnModelErrorCallback) -> Self {
463        self.config.on_model_error = Some(callback);
464        self
465    }
466
467    /// Set the callback invoked before tool execution.
468    ///
469    /// Runs each time a tool is about to execute. The [`CallbackContext`](adk_core::CallbackContext)
470    /// provides `tool_name()` and `tool_input()` for tool-specific logic.
471    ///
472    /// ```rust,ignore
473    /// builder.before_tool(Box::new(|ctx| {
474    ///     Box::pin(async move {
475    ///         if let Some(name) = ctx.tool_name() {
476    ///             tracing::info!(tool = name, "tool starting");
477    ///         }
478    ///         Ok(())
479    ///     })
480    /// }))
481    /// ```
482    pub fn before_tool(mut self, callback: BeforeToolCallback) -> Self {
483        self.config.before_tool = Some(callback);
484        self
485    }
486
487    /// Set the callback invoked after tool execution.
488    ///
489    /// Runs each time a tool finishes. Useful for logging results, collecting metrics,
490    /// or auditing tool usage.
491    ///
492    /// ```rust,ignore
493    /// builder.after_tool(Box::new(|ctx| {
494    ///     Box::pin(async move {
495    ///         tracing::info!("tool completed");
496    ///         Ok(())
497    ///     })
498    /// }))
499    /// ```
500    pub fn after_tool(mut self, callback: AfterToolCallback) -> Self {
501        self.config.after_tool = Some(callback);
502        self
503    }
504
505    /// Set the callback invoked when a tool returns an error.
506    ///
507    /// The callback receives the tool name, the error, and the
508    /// [`CallbackContext`](adk_core::CallbackContext). Use this to log failures or
509    /// provide fallback values.
510    ///
511    /// ```rust,ignore
512    /// builder.on_tool_error(Box::new(|ctx, tool_name, error| {
513    ///     Box::pin(async move {
514    ///         tracing::warn!(tool = %tool_name, error = %error, "tool failed");
515    ///         Ok(None) // propagate the error
516    ///     })
517    /// }))
518    /// ```
519    pub fn on_tool_error(mut self, callback: OnToolErrorCallback) -> Self {
520        self.config.on_tool_error = Some(callback);
521        self
522    }
523
524    /// Set the async cleanup function called when the plugin is closed.
525    ///
526    /// Use this to release resources, flush buffers, or perform final cleanup.
527    ///
528    /// ```rust,ignore
529    /// builder.close_fn(|| Box::pin(async {
530    ///     tracing::info!("plugin shutting down");
531    /// }))
532    /// ```
533    pub fn close_fn(
534        mut self,
535        f: impl Fn() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync + 'static,
536    ) -> Self {
537        self.config.close_fn = Some(Box::new(f));
538        self
539    }
540
541    /// Consume the builder and produce a [`Plugin`].
542    ///
543    /// Only callbacks that were explicitly set will be active; all others remain `None`.
544    pub fn build(self) -> Plugin {
545        Plugin::new(self.config)
546    }
547}