use super::{failure, success, Tool, ToolContext, ToolError};
use crate::agent86ui::{policy, sanitize, MESSAGES_KEY, RENDER_UI, TRACE_KEY, WAIT_KEY};
use crate::types::ToolResult;
use serde_json::{json, Map, Value};
pub struct RenderUiTool;
impl Tool for RenderUiTool {
fn name(&self) -> &str {
RENDER_UI
}
fn description(&self) -> &str {
"Show the user interactive UI (a form, a choice, a confirmation, a small \
dashboard) by sending A2UI 1.0 messages, which their screen draws natively. \
The result says whether the messages were valid; if not, nothing was drawn, \
and it lists what to fix. A button the user presses comes back later as a \
user message starting `[ui action]`. See the agent86UI section of the system \
prompt for the messages and the catalogs' components."
}
fn parallel_safe(&self) -> bool {
false
}
fn parameters(&self) -> Value {
json!({
"properties": {
"messages": {
"description": "A2UI 1.0 agent-to-renderer messages, applied in order, all or nothing: each {\"version\": \"1.0\"} plus one of createSurface, updateComponents, updateDataModel, deleteSurface.",
"items": {"type": "object"},
"title": "Messages",
"type": "array",
},
"wait": {
"default": false,
"description": "Wait for the user's first action on the surface and get it as this call's result, for a form in the middle of a task. Without it the turn goes on, and an action comes later as a user message.",
"title": "Wait",
"type": "boolean",
},
},
"required": ["messages"],
"type": "object",
})
}
fn execute(
&self,
args: &Map<String, Value>,
ctx: &ToolContext,
) -> Result<ToolResult, ToolError> {
let messages = match args.get("messages") {
Some(Value::Array(items)) if items.iter().all(Value::is_object) => items,
Some(Value::Array(_)) => {
return Err(ToolError::InvalidArguments(vec![
"messages: each item should be a valid dictionary".into(),
]))
}
Some(_) => {
return Err(ToolError::InvalidArguments(vec![
"messages: Input should be a valid list".into(),
]))
}
None => {
return Err(ToolError::InvalidArguments(vec![
"messages: Field required".into(),
]))
}
};
let wait = match args.get("wait") {
None | Some(Value::Null) => false,
Some(Value::Bool(wait)) => *wait,
Some(_) => {
return Err(ToolError::InvalidArguments(vec![
"wait: Input should be a valid boolean".into(),
]))
}
};
if let Some(extra) = args.keys().find(|key| *key != "messages" && *key != "wait") {
return Err(ToolError::InvalidArguments(vec![format!(
"{extra}: Extra inputs are not permitted"
)]));
}
let Some(ui) = ctx.ui.as_deref() else {
return Ok(failure(
self.name(),
"No screen that can draw UI is attached here, so nothing was drawn. \
Ask the user in plain text instead."
.into(),
));
};
if wait && !ui.can_wait() {
return Ok(failure(
self.name(),
"This screen cannot answer while the turn waits, so nothing was drawn. Send \
the messages again without wait; an action on the surface comes as a later \
user message."
.into(),
));
}
if messages.is_empty() {
return Ok(failure(
self.name(),
"messages is empty, so there was nothing to draw.".into(),
));
}
let messages: Vec<Value> = messages
.iter()
.map(|message| sanitize(message, &ctx.secrets, ui.egress()))
.collect();
let components = component_count(&messages);
let refusals = policy(&messages, &ctx.policy, ui.remote_media());
if !refusals.is_empty() {
let codes = vec!["REFUSED"; refusals.len()];
let mut result = failure(
self.name(),
format!(
"agent86 does not allow some of these messages, so nothing was drawn. Change \
these and send the messages again (paths point into `messages`):\n{}",
bullets(&refusals)
),
);
result.metadata.insert(
TRACE_KEY.into(),
trace(&messages, components, "refused", &codes),
);
return Ok(result);
}
let report = ui.apply(&messages);
if !report.is_ok() {
let codes: Vec<&str> = report.errors.iter().map(|p| p.code.as_str()).collect();
let mut result = failure(
self.name(),
format!(
"The messages are not valid A2UI, so nothing was drawn. Fix these and \
send the corrected messages again (paths point into `messages`):\n{}",
bullets(&report.errors)
),
);
result.metadata.insert(
TRACE_KEY.into(),
trace(&messages, components, "invalid", &codes),
);
return Ok(result);
}
let mut lines = Vec::new();
let mut surfaces: Vec<&str> = Vec::new();
for message in &report.messages {
if let Some(id) = message.surface_id() {
if !surfaces.contains(&id) {
surfaces.push(id);
}
}
}
let live = ui.surface_ids();
for id in &surfaces {
if live.iter().any(|s| s == id) {
lines.push(format!("Rendered surface {id}."));
} else {
lines.push(format!("Deleted surface {id}."));
}
}
if lines.is_empty() {
lines.push("Applied.".into());
}
for warning in &report.warnings {
lines.push(format!("Warning: {warning}"));
}
let mut result = success(self.name(), lines.join("\n"));
let typed: Vec<Value> = report
.messages
.iter()
.filter_map(|message| serde_json::to_value(message).ok())
.collect();
result
.metadata
.insert(MESSAGES_KEY.into(), Value::Array(typed));
result.metadata.insert(
TRACE_KEY.into(),
trace(&messages, components, "rendered", &[]),
);
if wait {
let waited: Vec<Value> = surfaces
.iter()
.filter(|id| live.iter().any(|s| s == *id))
.map(|id| Value::from(*id))
.collect();
result
.metadata
.insert(WAIT_KEY.into(), Value::Array(waited));
}
Ok(result)
}
}
fn bullets<T: std::fmt::Display>(items: &[T]) -> String {
items
.iter()
.map(|item| format!("- {item}"))
.collect::<Vec<_>>()
.join("\n")
}
fn component_count(messages: &[Value]) -> usize {
messages
.iter()
.flat_map(|message| {
["createSurface", "updateComponents"]
.into_iter()
.filter_map(move |kind| message.get(kind)?.get("components")?.as_array())
})
.map(Vec::len)
.sum()
}
fn trace(messages: &[Value], components: usize, verdict: &str, codes: &[&str]) -> Value {
let mut surfaces: Vec<&str> = Vec::new();
for message in messages {
let id = message
.as_object()
.into_iter()
.flat_map(|object| object.values())
.find_map(|body| body.get("surfaceId").and_then(Value::as_str));
if let Some(id) = id {
if !surfaces.contains(&id) {
surfaces.push(id);
}
}
}
json!({
"surfaces": surfaces,
"components": components,
"verdict": verdict,
"problems": codes,
})
}