use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::time::Duration;
use gadk_genai::Content;
use gadk_model::{LlmRequest, LlmResponse, ModelError};
use gadk_session::Event;
use serde_json::{Map, Value};
use crate::agent::Agent;
use crate::context::{Context, InvocationContext};
use crate::error::{AgentError, ToolError};
use crate::go_fmt::go_quote;
use crate::plugin::Plugin;
use crate::tool::Tool;
#[derive(Debug)]
pub struct PluginManager {
plugins: Vec<Plugin>,
close_timeout: Duration,
}
impl PluginManager {
pub fn new(plugins: Vec<Plugin>, close_timeout: Duration) -> Result<Self, AgentError> {
let mut out: Vec<Plugin> = Vec::with_capacity(plugins.len());
for p in plugins {
if out.iter().any(|q| q.name() == p.name()) {
return Err(AgentError::Config(format!(
"plugin with name '{}' already registered",
p.name()
)));
}
out.push(p);
}
Ok(Self {
plugins: out,
close_timeout,
})
}
pub fn has_plugins(&self) -> bool {
!self.plugins.is_empty()
}
pub async fn run_on_user_message(
&self,
ctx: InvocationContext,
msg: Content,
) -> Result<Option<Content>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.on_user_message_callback()
&& let Some(c) = cb(ctx.clone(), msg.clone()).await?
{
return Ok(Some(c));
}
}
Ok(None)
}
pub async fn run_before_run(
&self,
ctx: InvocationContext,
) -> Result<Option<Content>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.before_run_callback()
&& let Some(c) = cb(ctx.clone()).await?
{
return Ok(Some(c));
}
}
Ok(None)
}
pub async fn run_after_run(&self, ctx: InvocationContext) {
for p in &self.plugins {
if let Some(cb) = p.after_run_callback() {
cb(ctx.clone()).await;
}
}
}
pub async fn run_on_event(
&self,
ctx: InvocationContext,
event: Event,
) -> Result<Option<Event>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.on_event_callback()
&& let Some(e) = cb(ctx.clone(), event.clone()).await?
{
return Ok(Some(e));
}
}
Ok(None)
}
pub async fn run_before_agent(&self, ctx: Context) -> Result<Option<Content>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.before_agent_callback()
&& let Some(c) = cb(ctx.clone()).await?
{
return Ok(Some(c));
}
}
Ok(None)
}
pub async fn run_after_agent(&self, ctx: Context) -> Result<Option<Content>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.after_agent_callback()
&& let Some(c) = cb(ctx.clone()).await?
{
return Ok(Some(c));
}
}
Ok(None)
}
pub fn run_on_agent_error(&self, ctx: Context, agent: Arc<dyn Agent>, err: &AgentError) {
for p in &self.plugins {
let Some(cb) = p.on_agent_error_callback() else {
continue;
};
let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
cb(ctx.clone(), agent.clone(), err);
}));
if let Err(payload) = res {
let msg = format!(
"plugin {} OnAgentErrorCallback panicked: {}",
go_quote(p.name()),
panic_text(&*payload)
);
tracing::error!(exception.message = msg.as_str(), "exception");
}
}
}
pub async fn run_before_model(
&self,
ctx: Context,
mut req: LlmRequest,
) -> (LlmRequest, Result<Option<LlmResponse>, AgentError>) {
for p in &self.plugins {
if let Some(cb) = p.before_model_callback() {
let (r, res) = cb(ctx.clone(), req).await;
req = r;
match res {
Err(e) => return (req, Err(e)),
Ok(Some(resp)) => return (req, Ok(Some(resp))),
Ok(None) => {}
}
}
}
(req, Ok(None))
}
pub async fn run_after_model(
&self,
ctx: Context,
mut resp: LlmResponse,
err: Option<Arc<ModelError>>,
) -> (LlmResponse, Result<Option<LlmResponse>, AgentError>) {
for p in &self.plugins {
if let Some(cb) = p.after_model_callback() {
let (r, res) = cb(ctx.clone(), resp, err.clone()).await;
resp = r;
match res {
Err(e) => return (resp, Err(e)),
Ok(Some(new_resp)) => return (resp, Ok(Some(new_resp))),
Ok(None) => {}
}
}
}
(resp, Ok(None))
}
pub async fn run_on_model_error(
&self,
ctx: Context,
req: LlmRequest,
err: Arc<ModelError>,
) -> Result<Option<LlmResponse>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.on_model_error_callback()
&& let Some(r) = cb(ctx.clone(), req.clone(), err.clone()).await?
{
return Ok(Some(r));
}
}
Ok(None)
}
pub async fn run_before_tool(
&self,
ctx: Context,
tool: Arc<dyn Tool>,
mut args: Map<String, Value>,
) -> (
Map<String, Value>,
Result<Option<Map<String, Value>>, AgentError>,
) {
for p in &self.plugins {
if let Some(cb) = p.before_tool_callback() {
let (a, res) = cb(ctx.clone(), tool.clone(), args).await;
args = a;
match res {
Err(e) => return (args, Err(e)),
Ok(Some(r)) => return (args, Ok(Some(r))),
Ok(None) => {}
}
}
}
(args, Ok(None))
}
pub async fn run_after_tool(
&self,
ctx: Context,
tool: Arc<dyn Tool>,
args: Map<String, Value>,
result: Map<String, Value>,
err: Option<Arc<ToolError>>,
) -> Result<Option<Map<String, Value>>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.after_tool_callback()
&& let Some(r) = cb(
ctx.clone(),
tool.clone(),
args.clone(),
result.clone(),
err.clone(),
)
.await?
{
return Ok(Some(r));
}
}
Ok(None)
}
pub async fn run_on_tool_error(
&self,
ctx: Context,
tool: Arc<dyn Tool>,
args: Map<String, Value>,
err: Arc<ToolError>,
) -> Result<Option<Map<String, Value>>, AgentError> {
for p in &self.plugins {
if let Some(cb) = p.on_tool_error_callback()
&& let Some(r) = cb(ctx.clone(), tool.clone(), args.clone(), err.clone()).await?
{
return Ok(Some(r));
}
}
Ok(None)
}
pub async fn close(&self) -> Result<(), AgentError> {
let mut errors: Vec<String> = Vec::new();
for p in &self.plugins {
let Some(close) = p.close() else { continue };
let res = if self.close_timeout.is_zero() {
close().await
} else {
match tokio::time::timeout(self.close_timeout, close()).await {
Ok(r) => r,
Err(_) => Err(AgentError::other(format!(
"close timed out after {:?}",
self.close_timeout
))),
}
};
if let Err(e) = res {
errors.push(format!("error closing plugin '{}': {e}", p.name()));
}
}
if errors.is_empty() {
return Ok(());
}
Err(AgentError::other(format!(
"failed to close plugins: [{}]",
errors.join(" ")
)))
}
}
fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
return (*s).to_owned();
}
if let Some(s) = payload.downcast_ref::<String>() {
return s.clone();
}
"<non-string panic>".to_owned()
}