1use 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#[derive(Debug)]
39pub struct PluginManager {
40 plugins: Vec<Plugin>,
41 close_timeout: Duration,
42}
43
44impl PluginManager {
45 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 pub fn has_plugins(&self) -> bool {
66 !self.plugins.is_empty()
67 }
68
69 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 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 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 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 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 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 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 tracing::error!(exception.message = msg.as_str(), "exception");
169 }
170 }
171 }
172
173 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 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 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 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 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 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 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
335fn 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}