use std::any::Any;
use std::sync::Arc;
use futures::StreamExt;
use gadk_agent::{Agent, AgentError, Context, ContextDelta, EventStream, Mode};
use gadk_genai::{Content, Schema};
use gadk_session::{Event, EventActions, NodeInfo};
use serde_json::{Map, Value, json};
use crate::error::{WorkflowError, WorkflowErrorKind};
use crate::llm::mode::{resolve_mode, with_bound_mode};
use crate::llm::node_wrapper::run_llm_agent_as_node;
use crate::llm::output_schema_binding::with_bound_output_schema;
use crate::llm::processors::go_json_marshal;
use crate::llm::state::reveal;
use crate::workflow::base_node::compile_schema;
use crate::workflow::model_output_schema::model_output_schema;
use crate::workflow::route::go_quote;
use crate::workflow::scheduler::message_text;
use crate::workflow::{BaseNode, Node, NodeConfig};
pub struct AgentNode {
pub(crate) base: BaseNode,
pub(crate) agent: Arc<dyn Agent>,
pub(crate) model_output_schema: Option<Schema>,
}
impl AgentNode {
pub fn new(agent: Arc<dyn Agent>, cfg: NodeConfig) -> Result<Arc<AgentNode>, WorkflowError> {
Self::with_schemas(agent, None, None, cfg)
}
pub fn with_schemas(
agent: Arc<dyn Agent>,
input: Option<Value>,
output: Option<Value>,
mut cfg: NodeConfig,
) -> Result<Arc<AgentNode>, WorkflowError> {
let input = compile_schema(Some(input.unwrap_or_else(|| json!({})))).map_err(|e| {
WorkflowError::new(
WorkflowErrorKind::Other,
format!(
"resolving input schema for agent {}: {e}",
go_quote(agent.name())
),
)
})?;
let output = output.unwrap_or_else(|| json!({}));
let model_output_schema = model_output_schema(Some(&output));
let output = compile_schema(Some(output)).map_err(|e| {
WorkflowError::new(
WorkflowErrorKind::Other,
format!(
"resolving output schema for agent {}: {e}",
go_quote(agent.name())
),
)
})?;
cfg.emits_own_span = true;
let base = BaseNode::from_compiled(agent.name(), agent.description(), cfg, input, output);
Ok(Arc::new(AgentNode {
base,
agent,
model_output_schema,
}))
}
pub fn agent(&self) -> &Arc<dyn Agent> {
&self.agent
}
}
impl Node for AgentNode {
fn name(&self) -> &str {
self.base.name()
}
fn description(&self) -> &str {
self.base.description()
}
fn config(&self) -> &NodeConfig {
self.base.config()
}
fn input_schema(&self) -> Option<&Value> {
self.base.input_schema()
}
fn output_schema(&self) -> Option<&Value> {
self.base.output_schema()
}
fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
self.base.validate_input(v)
}
fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
self.base.validate_output(v)
}
fn run(&self, ctx: Context, input: Value) -> EventStream {
let agent = Arc::clone(self.agent());
let model_output_schema = self.model_output_schema.clone();
Box::pin(async_stream::stream! {
let user_content = match node_input_to_content(&input) {
Ok(c) => c,
Err(e) => {
yield Err(e);
return;
}
};
let declared_mode: Option<Mode> = reveal(agent.as_ref()).map(|s| s.cfg.mode);
let mut delta = ContextDelta {
agent: Some(Arc::clone(&agent)),
user_content: Some(user_content),
path: Some(String::new()),
run_id: Some(String::new()),
sub_scheduler: Some(None),
output_for_ancestors: Some(Vec::new()),
resumed_inputs: Some(Arc::new(Map::new())),
tool_confirmation: Some(None),
actions: Some(Arc::new(parking_lot::Mutex::new(EventActions::default()))),
fresh_end_flag: true,
..ContextDelta::default()
};
if let Some(declared) = declared_mode {
let mode = resolve_mode(declared, Mode::SingleTurn);
let bound = with_bound_mode(ctx.as_invocation(), agent.name(), agent.agent_state(), mode);
let bound = with_bound_output_schema(
&bound,
agent.name(),
agent.agent_state(),
model_output_schema.clone(),
);
delta.bound_modes = Some(bound.bound_modes().clone());
}
let ex_ctx = ctx.with_delta(delta);
let mut events = if declared_mode.is_some() {
run_llm_agent_as_node(ex_ctx, Arc::clone(&agent), input)
} else {
agent.run(ex_ctx.as_invocation().clone())
};
let synthesize = declared_mode != Some(Mode::Task);
let scope = ctx.isolation_scope();
while let Some(item) = events.next().await {
let mut ev = match item {
Ok(ev) => ev,
Err(e) => {
yield Err(e);
return;
}
};
if synthesize && is_own_agent_event(&ev, agent.name()) {
synthesize_agent_output(&mut ev);
}
if !scope.is_empty() && ev.isolation_scope.is_empty() {
ev.isolation_scope = scope.clone();
}
yield Ok(ev);
}
})
}
fn as_any(&self) -> &dyn Any {
self
}
}
pub(crate) fn synthesize_agent_output(ev: &mut Event) {
if ev.output.is_some() || !ev.is_final_response() || !ev.long_running_tool_ids.is_empty() {
return;
}
if let Some(text) = message_text(ev) {
ev.output = Some(Value::String(text));
ev.node_info
.get_or_insert_with(NodeInfo::default)
.message_as_output = true;
}
}
pub(crate) fn is_own_agent_event(ev: &Event, node_agent_name: &str) -> bool {
ev.author.is_empty() || ev.author == node_agent_name
}
pub(crate) fn node_input_to_content(input: &Value) -> Result<Option<Content>, AgentError> {
match input {
Value::Null => Ok(None),
Value::String(s) => Ok(Some(Content::from_text(s.clone(), "user"))),
other => Ok(Some(Content::from_text(go_json_marshal(other), "user"))),
}
}