Skip to main content

gadk_agent/
plugin.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Plugins: a plugin's name, callbacks and close function.
17
18use std::any::Any;
19use std::sync::Arc;
20
21use futures::FutureExt;
22
23use crate::callback::{
24    AfterAgentCallback, AfterModelCallback, AfterRunCallback, AfterToolCallback,
25    BeforeAgentCallback, BeforeModelCallback, BeforeRunCallback, BeforeToolCallback, CloseFn,
26    OnAgentErrorCallback, OnEventCallback, OnModelErrorCallback, OnToolErrorCallback,
27    OnUserMessageCallback,
28};
29
30/// A plugin's name and callbacks.
31#[derive(Clone, Default)]
32pub struct PluginConfig {
33    /// The plugin's name, unique among the registered plugins.
34    pub name: String,
35    /// See [`OnUserMessageCallback`].
36    pub on_user_message_callback: Option<OnUserMessageCallback>,
37    /// See [`OnEventCallback`].
38    pub on_event_callback: Option<OnEventCallback>,
39    /// See [`BeforeRunCallback`].
40    pub before_run_callback: Option<BeforeRunCallback>,
41    /// See [`AfterRunCallback`].
42    pub after_run_callback: Option<AfterRunCallback>,
43    /// See [`BeforeAgentCallback`].
44    pub before_agent_callback: Option<BeforeAgentCallback>,
45    /// See [`AfterAgentCallback`].
46    pub after_agent_callback: Option<AfterAgentCallback>,
47    /// See [`OnAgentErrorCallback`].
48    pub on_agent_error_callback: Option<OnAgentErrorCallback>,
49    /// See [`BeforeModelCallback`].
50    pub before_model_callback: Option<BeforeModelCallback>,
51    /// See [`AfterModelCallback`].
52    pub after_model_callback: Option<AfterModelCallback>,
53    /// See [`OnModelErrorCallback`].
54    pub on_model_error_callback: Option<OnModelErrorCallback>,
55    /// See [`BeforeToolCallback`].
56    pub before_tool_callback: Option<BeforeToolCallback>,
57    /// See [`AfterToolCallback`].
58    pub after_tool_callback: Option<AfterToolCallback>,
59    /// See [`OnToolErrorCallback`].
60    pub on_tool_error_callback: Option<OnToolErrorCallback>,
61    /// Called when the plugin manager closes.
62    pub close: Option<CloseFn>,
63    /// Typed plugin state, read back with [`Plugin::state`] (e.g. the agent-analytics plugin
64    /// keeps its handle here).
65    pub state: Option<Arc<dyn Any + Send + Sync>>,
66}
67
68/// A plugin: its name, callbacks and typed state.
69#[derive(Clone)]
70pub struct Plugin {
71    cfg: Arc<PluginConfig>,
72}
73
74impl Plugin {
75    /// Builds a plugin (never fails): a missing close function becomes a no-op, so `close()`
76    /// is always `Some`.
77    pub fn new(mut cfg: PluginConfig) -> Plugin {
78        if cfg.close.is_none() {
79            let noop: CloseFn = Arc::new(|| async { Ok(()) }.boxed());
80            cfg.close = Some(noop);
81        }
82        Plugin { cfg: Arc::new(cfg) }
83    }
84
85    /// The plugin's name.
86    pub fn name(&self) -> &str {
87        &self.cfg.name
88    }
89
90    /// The plugin's on-user-message callback.
91    pub fn on_user_message_callback(&self) -> Option<OnUserMessageCallback> {
92        self.cfg.on_user_message_callback.clone()
93    }
94
95    /// The plugin's on-event callback.
96    pub fn on_event_callback(&self) -> Option<OnEventCallback> {
97        self.cfg.on_event_callback.clone()
98    }
99
100    /// The plugin's before-run callback.
101    pub fn before_run_callback(&self) -> Option<BeforeRunCallback> {
102        self.cfg.before_run_callback.clone()
103    }
104
105    /// The plugin's after-run callback.
106    pub fn after_run_callback(&self) -> Option<AfterRunCallback> {
107        self.cfg.after_run_callback.clone()
108    }
109
110    /// The plugin's before-agent callback.
111    pub fn before_agent_callback(&self) -> Option<BeforeAgentCallback> {
112        self.cfg.before_agent_callback.clone()
113    }
114
115    /// The plugin's after-agent callback.
116    pub fn after_agent_callback(&self) -> Option<AfterAgentCallback> {
117        self.cfg.after_agent_callback.clone()
118    }
119
120    /// The plugin's on-agent-error callback.
121    pub fn on_agent_error_callback(&self) -> Option<OnAgentErrorCallback> {
122        self.cfg.on_agent_error_callback.clone()
123    }
124
125    /// The plugin's before-model callback.
126    pub fn before_model_callback(&self) -> Option<BeforeModelCallback> {
127        self.cfg.before_model_callback.clone()
128    }
129
130    /// The plugin's after-model callback.
131    pub fn after_model_callback(&self) -> Option<AfterModelCallback> {
132        self.cfg.after_model_callback.clone()
133    }
134
135    /// The plugin's on-model-error callback.
136    pub fn on_model_error_callback(&self) -> Option<OnModelErrorCallback> {
137        self.cfg.on_model_error_callback.clone()
138    }
139
140    /// The plugin's before-tool callback.
141    pub fn before_tool_callback(&self) -> Option<BeforeToolCallback> {
142        self.cfg.before_tool_callback.clone()
143    }
144
145    /// The plugin's after-tool callback.
146    pub fn after_tool_callback(&self) -> Option<AfterToolCallback> {
147        self.cfg.after_tool_callback.clone()
148    }
149
150    /// The plugin's on-tool-error callback.
151    pub fn on_tool_error_callback(&self) -> Option<OnToolErrorCallback> {
152        self.cfg.on_tool_error_callback.clone()
153    }
154
155    /// The plugin's close function; always `Some`.
156    pub fn close(&self) -> Option<CloseFn> {
157        self.cfg.close.clone()
158    }
159
160    /// The plugin's [`PluginConfig::state`] when it is a `T`; `None` without state or for another
161    /// type.
162    pub fn state<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
163        self.cfg.state.clone()?.downcast::<T>().ok()
164    }
165}
166
167impl std::fmt::Debug for Plugin {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        f.debug_struct("Plugin")
170            .field("name", &self.cfg.name)
171            .finish_non_exhaustive()
172    }
173}
174
175#[cfg(test)]
176#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
177mod tests {
178    use std::sync::Arc;
179
180    use super::{Plugin, PluginConfig};
181
182    #[derive(Debug, PartialEq)]
183    struct Stats(u32);
184
185    #[test]
186    fn state_downcasts_to_its_own_type_only() {
187        let stats = Arc::new(Stats(7));
188        let p = Plugin::new(PluginConfig {
189            name: "p".into(),
190            state: Some(stats.clone()),
191            ..Default::default()
192        });
193        let got = p.state::<Stats>().expect("typed state");
194        assert!(Arc::ptr_eq(&got, &stats));
195        assert_eq!(p.clone().state::<Stats>(), Some(stats));
196        assert!(p.state::<String>().is_none(), "another type");
197    }
198
199    #[test]
200    fn no_state_is_none() {
201        let p = Plugin::new(PluginConfig::default());
202        assert!(p.state::<Stats>().is_none());
203    }
204}