Skip to main content

gadk_agent/
plugin_manager.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//! The plugin manager: runs plugin callbacks around invocations, agents, models and tools.
17//!
18//! Every `run_*` method visits the plugins in registration order. The first callback error is
19//! returned unchanged (no plugin name), and the first `Some` result short-circuits.
20
21use std::panic::AssertUnwindSafe;
22use std::sync::Arc;
23use std::time::Duration;
24
25use gadk_genai::Content;
26use gadk_model::{LlmRequest, LlmResponse, ModelError};
27use gadk_session::Event;
28use serde_json::{Map, Value};
29
30use crate::agent::Agent;
31use crate::context::{Context, InvocationContext};
32use crate::error::{AgentError, ToolError};
33use crate::go_fmt::go_quote;
34use crate::plugin::Plugin;
35use crate::tool::Tool;
36
37/// The registered plugins and the bound on closing them.
38#[derive(Debug)]
39pub struct PluginManager {
40    plugins: Vec<Plugin>,
41    close_timeout: Duration,
42}
43
44impl PluginManager {
45    /// Registers `plugins` in order; fails only on a duplicate plugin name.
46    pub fn new(plugins: Vec<Plugin>, close_timeout: Duration) -> Result<Self, AgentError> {
47        let mut out: Vec<Plugin> = Vec::with_capacity(plugins.len());
48        for p in plugins {
49            if out.iter().any(|q| q.name() == p.name()) {
50                return Err(AgentError::Config(format!(
51                    "plugin with name '{}' already registered",
52                    p.name()
53                )));
54            }
55            out.push(p);
56        }
57        Ok(Self {
58            plugins: out,
59            close_timeout,
60        })
61    }
62
63    /// Whether any plugin is registered. A missing manager is `None` at the call
64    /// site (`pm.is_some_and(|m| m.has_plugins())`).
65    pub fn has_plugins(&self) -> bool {
66        !self.plugins.is_empty()
67    }
68
69    /// Runs the on-user-message callbacks; the first `Some` content replaces the user message.
70    pub async fn run_on_user_message(
71        &self,
72        ctx: InvocationContext,
73        msg: Content,
74    ) -> Result<Option<Content>, AgentError> {
75        for p in &self.plugins {
76            if let Some(cb) = p.on_user_message_callback()
77                && let Some(c) = cb(ctx.clone(), msg.clone()).await?
78            {
79                return Ok(Some(c));
80            }
81        }
82        Ok(None)
83    }
84
85    /// Runs the before-run callbacks; the first `Some` content ends the run early.
86    pub async fn run_before_run(
87        &self,
88        ctx: InvocationContext,
89    ) -> Result<Option<Content>, AgentError> {
90        for p in &self.plugins {
91            if let Some(cb) = p.before_run_callback()
92                && let Some(c) = cb(ctx.clone()).await?
93            {
94                return Ok(Some(c));
95            }
96        }
97        Ok(None)
98    }
99
100    /// Runs the after-run callbacks: every plugin's callback, in order.
101    pub async fn run_after_run(&self, ctx: InvocationContext) {
102        for p in &self.plugins {
103            if let Some(cb) = p.after_run_callback() {
104                cb(ctx.clone()).await;
105            }
106        }
107    }
108
109    /// Runs the on-event callbacks; the first `Some` event replaces the event.
110    pub async fn run_on_event(
111        &self,
112        ctx: InvocationContext,
113        event: Event,
114    ) -> Result<Option<Event>, AgentError> {
115        for p in &self.plugins {
116            if let Some(cb) = p.on_event_callback()
117                && let Some(e) = cb(ctx.clone(), event.clone()).await?
118            {
119                return Ok(Some(e));
120            }
121        }
122        Ok(None)
123    }
124
125    /// Runs the before-agent callbacks; the first `Some` content skips the agent run.
126    pub async fn run_before_agent(&self, ctx: Context) -> Result<Option<Content>, AgentError> {
127        for p in &self.plugins {
128            if let Some(cb) = p.before_agent_callback()
129                && let Some(c) = cb(ctx.clone()).await?
130            {
131                return Ok(Some(c));
132            }
133        }
134        Ok(None)
135    }
136
137    /// Runs the after-agent callbacks; the first `Some` content is returned as the agent's output.
138    pub async fn run_after_agent(&self, ctx: Context) -> Result<Option<Content>, AgentError> {
139        for p in &self.plugins {
140            if let Some(cb) = p.after_agent_callback()
141                && let Some(c) = cb(ctx.clone()).await?
142            {
143                return Ok(Some(c));
144            }
145        }
146        Ok(None)
147    }
148
149    /// Notifies every plugin, in registration order, that `err`
150    /// escaped `agent`'s run. Best-effort notification: no plugin can suppress the error. A panic
151    /// from one callback is caught (and recorded on the current span as `plugin "<name>"
152    /// OnAgentErrorCallback panicked: <panic>`), so the remaining callbacks still run.
153    pub fn run_on_agent_error(&self, ctx: Context, agent: Arc<dyn Agent>, err: &AgentError) {
154        for p in &self.plugins {
155            let Some(cb) = p.on_agent_error_callback() else {
156                continue;
157            };
158            let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
159                cb(ctx.clone(), agent.clone(), err);
160            }));
161            if let Err(payload) = res {
162                let msg = format!(
163                    "plugin {} OnAgentErrorCallback panicked: {}",
164                    go_quote(p.name()),
165                    panic_text(&*payload)
166                );
167                // An `exception` event on the current span.
168                tracing::error!(exception.message = msg.as_str(), "exception");
169            }
170        }
171    }
172
173    /// Runs the before-model callbacks: the request is threaded through every callback and always
174    /// handed back.
175    pub async fn run_before_model(
176        &self,
177        ctx: Context,
178        mut req: LlmRequest,
179    ) -> (LlmRequest, Result<Option<LlmResponse>, AgentError>) {
180        for p in &self.plugins {
181            if let Some(cb) = p.before_model_callback() {
182                let (r, res) = cb(ctx.clone(), req).await;
183                req = r;
184                match res {
185                    Err(e) => return (req, Err(e)),
186                    Ok(Some(resp)) => return (req, Ok(Some(resp))),
187                    Ok(None) => {}
188                }
189            }
190        }
191        (req, Ok(None))
192    }
193
194    /// Runs the after-model callbacks: the response is threaded through every callback (each sees
195    /// the previous callback's response) and always handed back.
196    pub async fn run_after_model(
197        &self,
198        ctx: Context,
199        mut resp: LlmResponse,
200        err: Option<Arc<ModelError>>,
201    ) -> (LlmResponse, Result<Option<LlmResponse>, AgentError>) {
202        for p in &self.plugins {
203            if let Some(cb) = p.after_model_callback() {
204                let (r, res) = cb(ctx.clone(), resp, err.clone()).await;
205                resp = r;
206                match res {
207                    Err(e) => return (resp, Err(e)),
208                    Ok(Some(new_resp)) => return (resp, Ok(Some(new_resp))),
209                    Ok(None) => {}
210                }
211            }
212        }
213        (resp, Ok(None))
214    }
215
216    /// Runs the on-model-error callbacks; the first `Some` response replaces the failed call.
217    pub async fn run_on_model_error(
218        &self,
219        ctx: Context,
220        req: LlmRequest,
221        err: Arc<ModelError>,
222    ) -> Result<Option<LlmResponse>, AgentError> {
223        for p in &self.plugins {
224            if let Some(cb) = p.on_model_error_callback()
225                && let Some(r) = cb(ctx.clone(), req.clone(), err.clone()).await?
226            {
227                return Ok(Some(r));
228            }
229        }
230        Ok(None)
231    }
232
233    /// Runs the before-tool callbacks: the arguments are threaded through every callback (each
234    /// sees the previous callback's arguments) and always handed back.
235    pub async fn run_before_tool(
236        &self,
237        ctx: Context,
238        tool: Arc<dyn Tool>,
239        mut args: Map<String, Value>,
240    ) -> (
241        Map<String, Value>,
242        Result<Option<Map<String, Value>>, AgentError>,
243    ) {
244        for p in &self.plugins {
245            if let Some(cb) = p.before_tool_callback() {
246                let (a, res) = cb(ctx.clone(), tool.clone(), args).await;
247                args = a;
248                match res {
249                    Err(e) => return (args, Err(e)),
250                    Ok(Some(r)) => return (args, Ok(Some(r))),
251                    Ok(None) => {}
252                }
253            }
254        }
255        (args, Ok(None))
256    }
257
258    /// Runs the after-tool callbacks; the first `Some` result replaces the tool's result.
259    pub async fn run_after_tool(
260        &self,
261        ctx: Context,
262        tool: Arc<dyn Tool>,
263        args: Map<String, Value>,
264        result: Map<String, Value>,
265        err: Option<Arc<ToolError>>,
266    ) -> Result<Option<Map<String, Value>>, AgentError> {
267        for p in &self.plugins {
268            if let Some(cb) = p.after_tool_callback()
269                && let Some(r) = cb(
270                    ctx.clone(),
271                    tool.clone(),
272                    args.clone(),
273                    result.clone(),
274                    err.clone(),
275                )
276                .await?
277            {
278                return Ok(Some(r));
279            }
280        }
281        Ok(None)
282    }
283
284    /// Runs the on-tool-error callbacks; the first `Some` result replaces the failed call.
285    pub async fn run_on_tool_error(
286        &self,
287        ctx: Context,
288        tool: Arc<dyn Tool>,
289        args: Map<String, Value>,
290        err: Arc<ToolError>,
291    ) -> Result<Option<Map<String, Value>>, AgentError> {
292        for p in &self.plugins {
293            if let Some(cb) = p.on_tool_error_callback()
294                && let Some(r) = cb(ctx.clone(), tool.clone(), args.clone(), err.clone()).await?
295            {
296                return Ok(Some(r));
297            }
298        }
299        Ok(None)
300    }
301
302    /// Closes every plugin, collecting `error closing plugin '<name>': <err>`, and
303    /// returns `failed to close plugins: [e1 e2 …]`. A `close_timeout` above
304    /// zero bounds each close function (an elapsed one records `close timed out after
305    /// {close_timeout:?}`); zero means no bound.
306    pub async fn close(&self) -> Result<(), AgentError> {
307        let mut errors: Vec<String> = Vec::new();
308        for p in &self.plugins {
309            let Some(close) = p.close() else { continue };
310            let res = if self.close_timeout.is_zero() {
311                close().await
312            } else {
313                match tokio::time::timeout(self.close_timeout, close()).await {
314                    Ok(r) => r,
315                    Err(_) => Err(AgentError::other(format!(
316                        "close timed out after {:?}",
317                        self.close_timeout
318                    ))),
319                }
320            };
321            if let Err(e) = res {
322                errors.push(format!("error closing plugin '{}': {e}", p.name()));
323            }
324        }
325        if errors.is_empty() {
326            return Ok(());
327        }
328        Err(AgentError::other(format!(
329            "failed to close plugins: [{}]",
330            errors.join(" ")
331        )))
332    }
333}
334
335/// The `&str` / `String` payload of a recovered panic, else a placeholder.
336fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
337    if let Some(s) = payload.downcast_ref::<&str>() {
338        return (*s).to_owned();
339    }
340    if let Some(s) = payload.downcast_ref::<String>() {
341        return s.clone();
342    }
343    "<non-string panic>".to_owned()
344}