use crate::message::Context;
use crate::runtime::{emit_input, Result};
use serde_json::{json, Value};
use std::collections::HashMap;
pub fn is_tool_request(ctx: &Context) -> bool {
ctx.get("__message_type__")
.and_then(|v| v.as_str().map(|s| s == "tool_request"))
.unwrap_or(false)
}
pub async fn tool_response(
ctx: &Context,
status: &str,
data: Option<HashMap<String, Value>>,
error_msg: &str,
) -> Result<()> {
if !is_tool_request(ctx) {
return Ok(());
}
let caller_id = ctx.get("__tool_caller_id__");
let agent_node_id = ctx.get("__agent_node_id__");
let response_ctx = Context::new(b"{}");
if let Some(msg_id) = ctx.get("id") {
response_ctx.set("id", msg_id)?;
}
if let Some(session_id) = ctx.get("session_id") {
response_ctx.set("session_id", session_id)?;
}
if let Some(query) = ctx.get("query") {
response_ctx.set("query", query)?;
}
response_ctx.set("__message_type__", "tool_response")?;
if let Some(caller) = caller_id {
response_ctx.set("__tool_caller_id__", caller)?;
}
response_ctx.set("__tool_status__", status)?;
if !error_msg.is_empty() {
response_ctx.set("__tool_error__", error_msg)?;
}
if let Some(d) = data {
response_ctx.set("__tool_data__", json!(d))?;
}
if let Some(agent_id) = agent_node_id {
if let Some(agent_id_str) = agent_id.as_str() {
let response_data = response_ctx.get_raw()?;
emit_input(agent_id_str, &response_data).await?;
}
}
ctx.set_raw(None)?;
Ok(())
}
pub async fn tool_success(ctx: &Context, data: HashMap<String, Value>) -> Result<()> {
tool_response(ctx, "success", Some(data), "").await
}
pub async fn tool_error(ctx: &Context, error_msg: &str) -> Result<()> {
tool_response(ctx, "error", None, error_msg).await
}