use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use adk_core::{
AdkError, DRAW_TOOL_NAMES, ErrorCategory, ErrorComponent, ReadonlyContext, Result,
TOOL_INVALID_ARGUMENTS_CODE, Tool, ToolContext, ToolEffect, Toolset,
};
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use super::a2ui::{A2uiBody, A2uiMessage, DataModel};
use super::catalog::{Catalog, FORMS_CATALOG_ID};
use super::drawn::DrawnKind;
use super::validate::{DrawRefusal, DrawnAction, SurfaceDraft, Validator};
pub const DRAWN_STATE_KEY: &str = "adk.surface.drawn";
pub const REFUSED_STATE_KEY: &str = "adk.surface.refused";
const VERSIONS_STATE_KEY: &str = "adk.surface.versions";
pub const MAX_PATCHES_PER_MINUTE: usize = 30;
type SurfaceKey = (String, String, String, String);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DrawnRecord {
pub surface_id: String,
pub version: u64,
pub digest: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DrawnEnvelope {
pub surface_id: String,
pub version: u64,
pub kind: DrawnKind,
pub catalog_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub messages: Vec<A2uiMessage>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub actions: Vec<DrawnAction>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl DrawnEnvelope {
pub fn digest(&self) -> String {
let mut canonical = String::new();
write_canonical(&serde_json::to_value(self).unwrap_or_default(), &mut canonical);
let hash = Sha256::digest(canonical.as_bytes());
hash.iter().fold(String::with_capacity(64), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
})
}
pub fn draft(&self) -> Option<SurfaceDraft> {
if self.deleted {
return None;
}
let mut components = Vec::new();
let mut model = DataModel::default();
for message in
self.messages.iter().filter(|message| message.surface_id() == self.surface_id)
{
match &message.body {
A2uiBody::CreateSurface(_) => {}
A2uiBody::UpdateComponents(update) => components.clone_from(&update.components),
A2uiBody::UpdateDataModel(update) => {
model.apply(update.path.as_deref(), update.value.clone()).ok()?;
}
A2uiBody::DeleteSurface(_) => return None,
}
}
Some(SurfaceDraft {
surface_id: self.surface_id.clone(),
kind: self.kind,
title: self.title.clone(),
components,
data_model: model.value().clone(),
actions: self.actions.clone(),
})
}
pub fn from_response(response: &Value) -> Option<Self> {
serde_json::from_value(response.get("drawn")?.clone()).ok()
}
pub fn delta_from(&self, previous: &DrawnEnvelope) -> Option<Vec<A2uiMessage>> {
if self.surface_id != previous.surface_id
|| self.catalog_id != previous.catalog_id
|| self.version <= previous.version
{
return None;
}
let (now, before) = (self.draft()?, previous.draft()?);
let mut messages = Vec::new();
let changed: Vec<Value> = now
.components
.iter()
.filter(|component| !before.components.contains(component))
.cloned()
.collect();
if !changed.is_empty() {
messages.push(A2uiMessage::update_components(self.surface_id.clone(), changed));
}
let mut paths = Vec::new();
data_delta(&before.data_model, &now.data_model, String::new(), &mut paths);
for (path, value) in paths {
let path = if path.is_empty() { None } else { Some(path) };
messages.push(A2uiMessage::update_data_model(self.surface_id.clone(), path, value));
}
Some(messages)
}
fn of(draft: &SurfaceDraft, version: u64, catalog_id: &str) -> Self {
let surface = draft.surface_id.clone();
let data_model = (!draft.data_model.is_null()).then(|| draft.data_model.clone());
let mut create = A2uiMessage::create_surface(surface.clone());
if let A2uiBody::CreateSurface(body) = &mut create.body {
body.catalog_id = catalog_id.to_string();
}
Self {
surface_id: surface.clone(),
version,
kind: draft.kind,
catalog_id: catalog_id.to_string(),
title: draft.title.clone(),
messages: vec![
create,
A2uiMessage::update_components(surface.clone(), draft.components.clone()),
A2uiMessage::update_data_model(surface, None, data_model),
],
actions: draft.actions.clone(),
deleted: false,
}
}
}
fn data_delta(before: &Value, now: &Value, at: String, out: &mut Vec<(String, Option<Value>)>) {
if before == now {
return;
}
match (before, now) {
(Value::Object(before), Value::Object(now)) => {
for (key, old) in before {
let path = format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"));
match now.get(key) {
Some(new) => data_delta(old, new, path, out),
None => out.push((path, None)),
}
}
for (key, new) in now.iter().filter(|(key, _)| !before.contains_key(*key)) {
let path = format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"));
out.push((path, Some(new.clone())));
}
}
(_, Value::Null) => out.push((at, None)),
_ => out.push((at, Some(now.clone()))),
}
}
fn write_canonical(value: &Value, out: &mut String) {
match value {
Value::Object(map) => {
out.push('{');
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
for (index, key) in keys.into_iter().enumerate() {
if index > 0 {
out.push(',');
}
out.push_str(&Value::String(key.clone()).to_string());
out.push(':');
write_canonical(&map[key], out);
}
out.push('}');
}
Value::Array(items) => {
out.push('[');
for (index, item) in items.iter().enumerate() {
if index > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
scalar => out.push_str(&scalar.to_string()),
}
}
#[derive(Debug, Clone)]
pub struct DrawToolset {
shared: Arc<Shared>,
}
#[derive(Debug)]
struct Shared {
validator: Validator,
issued: Mutex<HashMap<SurfaceKey, u64>>,
patched: Mutex<HashMap<SurfaceKey, VecDeque<Instant>>>,
screen_description: String,
screen_schema: Value,
}
impl DrawToolset {
pub fn new(validator: Validator) -> Self {
let catalog = validator.catalog();
Self {
shared: Arc::new(Shared {
screen_description: screen_description(catalog),
screen_schema: screen_schema(catalog),
validator,
issued: Mutex::new(HashMap::new()),
patched: Mutex::new(HashMap::new()),
}),
}
}
pub fn forms() -> Self {
Self::new(Validator::forms())
}
pub fn catalog(&self) -> &'static Catalog {
self.shared.validator.catalog()
}
pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
[Op::Form, Op::Card, Op::Table, Op::Screen, Op::Patch, Op::Delete]
.into_iter()
.map(|op| Arc::new(DrawTool { op, shared: Arc::clone(&self.shared) }) as Arc<dyn Tool>)
.collect()
}
}
#[async_trait]
impl Toolset for DrawToolset {
fn name(&self) -> &str {
"genui"
}
async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
Ok(DrawToolset::tools(self))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
Form,
Card,
Table,
Screen,
Patch,
Delete,
}
impl Op {
fn name(self) -> &'static str {
match self {
Self::Form => "render_form",
Self::Card => "render_card",
Self::Table => "render_table",
Self::Screen => "render_screen",
Self::Patch => "patch_surface",
Self::Delete => "delete_surface",
}
}
}
struct DrawTool {
op: Op,
shared: Arc<Shared>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct FormField {
name: String,
label: String,
#[serde(rename = "type", default)]
field_type: FieldType,
#[serde(default)]
value: Option<Value>,
#[serde(default)]
required: bool,
#[serde(default)]
options: Vec<ChoiceOption>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
enum FieldType {
#[default]
Text,
LongText,
Number,
Email,
Date,
Checkbox,
Choice,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ChoiceOption {
label: String,
value: String,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct FormParams {
#[serde(default)]
surface_id: Option<String>,
title: String,
#[serde(default)]
description: Option<String>,
fields: Vec<FormField>,
actions: Vec<DrawnAction>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct CardRow {
label: String,
value: Value,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CardParams {
#[serde(default)]
surface_id: Option<String>,
title: String,
rows: Vec<CardRow>,
#[serde(default)]
note: Option<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct TableParams {
#[serde(default)]
surface_id: Option<String>,
title: String,
columns: Vec<String>,
rows: Vec<Vec<Value>>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ScreenParams {
surface_id: String,
#[serde(default)]
title: Option<String>,
components: Vec<Value>,
#[serde(default)]
data_model: Option<Value>,
#[serde(default)]
actions: Vec<DrawnAction>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct DataChange {
path: String,
#[serde(default)]
value: Option<Value>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct PatchParams {
surface_id: String,
#[serde(default)]
data: Vec<DataChange>,
#[serde(default)]
components: Vec<Value>,
#[serde(default)]
remove: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct DeleteParams {
surface_id: String,
}
const FORMS_SCREEN_DESCRIPTION: &str = "Show the person a screen of A2UI 1.0 (or v0.9.1) components from \
the forms catalog (Text, Row, Column, List, Card, Tabs, Divider, Button, TextField, \
CheckBox, ChoicePicker, Slider, DateTimeInput), one with id root. Buttons dispatch only \
declared actions, which ask the person before a tool runs.";
fn screen_description(catalog: &Catalog) -> String {
if !catalog.is_extension() {
return FORMS_SCREEN_DESCRIPTION.to_string();
}
let added: Vec<&str> = catalog.extensions().collect();
let mut out = format!(
"Show the person a screen of A2UI 1.0 (or v0.9.1) components from the {} catalog, one with id \
root: the forms components (Text, Row, Column, List, Card, Tabs, Divider, Button, \
TextField, CheckBox, ChoicePicker, Slider, DateTimeInput) and {}. Bind data with \
{{\"@path\": \"/...\"}} (or v0.9.1's {{\"path\": \"/...\"}}) into dataModel.",
catalog.label(),
added.join(", ")
);
for usage in catalog.usage() {
let _ = write!(out, " {usage}");
}
out.push_str(
" Only buttons dispatch declared actions, which ask the person before a tool runs; the \
other components only show.",
);
out
}
fn screen_schema(catalog: &Catalog) -> Value {
let mut schema = schema_of::<ScreenParams>();
if catalog.is_extension()
&& let Some(components) = schema.pointer_mut("/properties/components")
{
components["description"] = json!(format!(
"A2UI components of the {} catalog, one with id `root`, in 1.0's syntax or v0.9.1's.",
catalog.label()
));
}
schema
}
fn schema_of<T: JsonSchema>() -> Value {
let mut schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
if let Some(map) = schema.as_object_mut() {
map.remove("$schema");
map.remove("title");
}
schema
}
fn invalid(tool: &str, error: impl std::fmt::Display) -> AdkError {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
TOOL_INVALID_ARGUMENTS_CODE,
format!("invalid arguments for '{tool}': {error}. Correct them and call it again."),
)
}
fn refused(refusal: &DrawRefusal) -> AdkError {
let result = serde_json::to_string(&refusal.validation_result()).unwrap_or_default();
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Forbidden,
refusal.code(),
format!("{}\nvalidationResult: {result}", refusal.message()),
)
}
fn params<T: DeserializeOwned>(tool: &str, args: Value) -> Result<T> {
serde_json::from_value(args).map_err(|error| invalid(tool, error))
}
fn surface_id_from(kind: &str, title: &str) -> String {
let mut slug = String::new();
for c in title.chars().flat_map(char::to_lowercase) {
if c.is_ascii_alphanumeric() {
slug.push(c);
} else if !slug.ends_with('-') && !slug.is_empty() {
slug.push('-');
}
}
let slug: String = slug.trim_end_matches('-').chars().take(48).collect();
if slug.is_empty() { kind.to_string() } else { format!("{kind}-{slug}") }
}
fn form(params: FormParams) -> Result<SurfaceDraft> {
let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("form", ¶ms.title));
let mut components = vec![
json!({ "id": "root", "component": "Card", "child": "body" }),
json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
];
let mut body = vec![json!("title")];
if let Some(description) = params.description {
components.push(json!({ "id": "description", "component": "Text", "text": description }));
body.push(json!("description"));
}
let mut model = serde_json::Map::new();
for field in params.fields {
let name = &field.name;
if name.is_empty()
|| name.len() > 48
|| !name.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
return Err(invalid(
Op::Form.name(),
format!("field name '{name}' is not 1 to 48 letters, digits, '_' or '-'"),
));
}
let id = format!("field-{name}");
let path = format!("/{name}");
let binding = json!({ "path": path });
let mut checks = Vec::new();
if field.required {
checks.push(json!({
"condition": { "call": "required", "args": { "value": binding } },
"message": "Fill this in"
}));
}
let (component, initial) = match field.field_type {
FieldType::Text | FieldType::Email | FieldType::Number | FieldType::LongText => {
let variant = match field.field_type {
FieldType::LongText => "longText",
FieldType::Number => "number",
_ => "shortText",
};
if field.field_type == FieldType::Email {
checks.push(json!({
"condition": { "call": "email", "args": { "value": binding } },
"message": "Enter an email address"
}));
}
(
json!({
"id": id, "component": "TextField", "label": field.label,
"value": binding, "variant": variant
}),
json!(""),
)
}
FieldType::Date => (
json!({
"id": id, "component": "DateTimeInput", "label": field.label,
"value": binding, "enableDate": true
}),
json!(""),
),
FieldType::Checkbox => (
json!({
"id": id, "component": "CheckBox", "label": field.label, "value": binding
}),
json!(false),
),
FieldType::Choice => (
json!({
"id": id, "component": "ChoicePicker", "label": field.label, "value": binding,
"options": field.options, "variant": "mutuallyExclusive"
}),
json!([]),
),
};
let mut component = component;
if !checks.is_empty() {
component["checks"] = Value::Array(checks);
}
model.insert(name.clone(), field.value.unwrap_or(initial));
components.push(component);
body.push(json!(id));
}
let mut buttons = Vec::new();
for (index, action) in params.actions.iter().enumerate() {
let button = format!("action-{}", action.id);
let label = format!("action-{}-label", action.id);
components.push(json!({ "id": label, "component": "Text", "text": action.label }));
components.push(json!({
"id": button, "component": "Button", "child": label,
"variant": if index == 0 { "primary" } else { "default" },
"action": { "event": { "name": action.id } }
}));
buttons.push(json!(button));
}
if !buttons.is_empty() {
components.push(json!({ "id": "actions", "component": "Row", "children": buttons }));
body.push(json!("actions"));
}
components.push(json!({ "id": "body", "component": "Column", "children": body }));
Ok(SurfaceDraft {
surface_id,
kind: DrawnKind::Form,
title: Some(params.title),
components,
data_model: Value::Object(model),
actions: params.actions,
})
}
fn card(params: CardParams) -> SurfaceDraft {
let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("card", ¶ms.title));
let mut components = vec![
json!({ "id": "root", "component": "Card", "child": "body" }),
json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
];
let mut body = vec![json!("title")];
for (index, row) in params.rows.into_iter().enumerate() {
let value = match row.value {
Value::String(text) => text,
other => other.to_string(),
};
components.push(json!({
"id": format!("row-{index}-label"), "component": "Text", "text": row.label,
"variant": "caption"
}));
components.push(
json!({ "id": format!("row-{index}-value"), "component": "Text", "text": value }),
);
components.push(json!({
"id": format!("row-{index}"), "component": "Row", "justify": "spaceBetween",
"children": [format!("row-{index}-label"), format!("row-{index}-value")]
}));
body.push(json!(format!("row-{index}")));
}
if let Some(note) = params.note {
components
.push(json!({ "id": "note", "component": "Text", "text": note, "variant": "caption" }));
body.push(json!("note"));
}
components.push(json!({ "id": "body", "component": "Column", "children": body }));
SurfaceDraft {
surface_id,
kind: DrawnKind::Card,
title: Some(params.title),
components,
data_model: json!({}),
actions: Vec::new(),
}
}
fn table(params: TableParams) -> SurfaceDraft {
let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("table", ¶ms.title));
let mut components = vec![
json!({ "id": "root", "component": "Card", "child": "body" }),
json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
];
let mut header = Vec::new();
let mut cells = Vec::new();
for (index, column) in params.columns.iter().enumerate() {
components.push(json!({
"id": format!("head-{index}"), "component": "Text", "text": column,
"variant": "caption"
}));
components.push(json!({
"id": format!("cell-{index}"), "component": "Text",
"text": { "path": index.to_string() }
}));
header.push(json!(format!("head-{index}")));
cells.push(json!(format!("cell-{index}")));
}
let rows: Vec<Value> = params
.rows
.into_iter()
.map(|row| {
Value::Array(
row.into_iter()
.map(|cell| match cell {
Value::String(text) => Value::String(text),
other => Value::String(other.to_string()),
})
.collect(),
)
})
.collect();
components.push(json!({ "id": "header", "component": "Row", "children": header }));
components.push(json!({ "id": "row", "component": "Row", "children": cells }));
components.push(json!({
"id": "rows", "component": "List",
"children": { "componentId": "row", "path": "/rows" }
}));
components.push(
json!({ "id": "body", "component": "Column", "children": ["title", "header", "rows"] }),
);
SurfaceDraft {
surface_id,
kind: DrawnKind::Table,
title: Some(params.title),
components,
data_model: json!({ "rows": rows }),
actions: Vec::new(),
}
}
impl DrawTool {
fn description(&self) -> &str {
match self.op {
Op::Form => {
"Show the person a form in this thread. Each field's value is at the data path \
/<name>. Each action is a button that asks to run one of your tools with \
constants and field values; pressing it never runs the tool: it asks the \
person first, on the home's own card. Never draw decision words or controls \
(Allow once, Deny, Approve...), links, or password fields."
}
Op::Card => {
"Show the person a card in this thread: a title and label and value rows. Plain \
text only; no buttons, links or decision words."
}
Op::Table => {
"Show the person a table in this thread: a title, column headings and rows of \
text or numbers. No buttons, links or decision words."
}
Op::Screen => &self.shared.screen_description,
Op::Patch => {
"Change a surface you drew in this session: set or remove data model values, \
add or replace components by id, or remove components. The whole surface is \
checked again."
}
Op::Delete => "Remove a surface you drew in this session from the person's thread.",
}
}
fn latest(&self, ctx: &dyn ToolContext, surface_id: &str) -> Option<DrawnEnvelope> {
let history = ctx.session()?.conversation_history();
history
.iter()
.flat_map(|content| &content.parts)
.filter_map(|part| match part {
adk_core::Part::FunctionResponse { function_response, .. }
if DRAW_TOOL_NAMES.contains(&function_response.name.as_str()) =>
{
DrawnEnvelope::from_response(&function_response.response)
}
_ => None,
})
.filter(|envelope| envelope.surface_id == surface_id)
.max_by_key(|envelope| envelope.version)
}
fn next_version(
&self,
ctx: &dyn ToolContext,
surface_id: &str,
latest: Option<&DrawnEnvelope>,
) -> u64 {
let stored = ctx
.session()
.and_then(|session| session.state().get(&format!("{VERSIONS_STATE_KEY}.{surface_id}")))
.and_then(|version| version.as_u64())
.unwrap_or(0);
let seen = latest.map_or(0, |envelope| envelope.version);
let key = (
ctx.app_name().to_string(),
ctx.user_id().to_string(),
ctx.session_id().to_string(),
surface_id.to_string(),
);
let mut issued =
self.shared.issued.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let version =
stored.max(seen).max(issued.get(&key).copied().unwrap_or(0)).saturating_add(1);
issued.insert(key, version);
version
}
fn shown(&self, ctx: &dyn ToolContext, envelope: DrawnEnvelope) -> Value {
let record = DrawnRecord {
surface_id: envelope.surface_id.clone(),
version: envelope.version,
digest: envelope.digest(),
};
let mut actions = ctx.actions();
actions.state_delta.insert(DRAWN_STATE_KEY.to_string(), json!(record));
actions.state_delta.insert(
format!("{VERSIONS_STATE_KEY}.{}", envelope.surface_id),
json!(envelope.version),
);
ctx.set_actions(actions);
tracing::info!(
surface.id = %envelope.surface_id,
surface.version = envelope.version,
surface.deleted = envelope.deleted,
"drawing recorded"
);
let message = if envelope.deleted {
format!("Removed '{}' from the person's thread.", envelope.surface_id)
} else if envelope.actions.is_empty() {
format!(
"Shown to the person as version {} of '{}'.",
envelope.version, envelope.surface_id
)
} else {
format!(
"Shown to the person as version {} of '{}'. Sending asks them first; you are told \
when they decide.",
envelope.version, envelope.surface_id
)
};
json!({
"status": if envelope.deleted { "removed" } else { "shown" },
"message": message,
"drawn": envelope,
})
}
fn draw(&self, ctx: &dyn ToolContext, draft: SurfaceDraft) -> Result<Value> {
let own_tools = ctx
.agent_tool_names()
.map(|tools| self.shared.validator.clone().with_bindable_tools(tools));
let validator = own_tools.as_ref().unwrap_or(&self.shared.validator);
let validated = match validator.validate(&draft) {
Ok(validated) => validated,
Err(refusal) => {
tracing::info!(
surface.id = %draft.surface_id,
refusal.code = refusal.code(),
refusal.reason = %refusal.technical(),
"drawing refused"
);
let mut actions = ctx.actions();
actions.state_delta.insert(REFUSED_STATE_KEY.to_string(), json!(refusal));
ctx.set_actions(actions);
return Err(refused(&refusal));
}
};
let latest = self.latest(ctx, &draft.surface_id);
let version = self.next_version(ctx, &draft.surface_id, latest.as_ref());
let mut result =
self.shown(ctx, DrawnEnvelope::of(&draft, version, validator.catalog().id()));
if !validated.warnings.is_empty() {
tracing::info!(
surface.id = %draft.surface_id,
warnings = validated.warnings.len(),
"drawing shown with warnings"
);
let said: Vec<String> =
validated.warnings.iter().filter_map(|warning| warning.message.clone()).collect();
if let Some(message) = result.get("message").and_then(Value::as_str) {
result["message"] = json!(format!("{message} Change it: {}", said.join(" ")));
}
result["warnings"] = json!(validated.warnings);
}
Ok(result)
}
fn patch(&self, ctx: &dyn ToolContext, params: PatchParams) -> Result<Value> {
let tool = Op::Patch.name();
let latest = self.latest(ctx, ¶ms.surface_id);
let own = self.shared.validator.catalog().id();
if let Some(previous) = latest.as_ref()
&& previous.catalog_id != own
&& previous.catalog_id != FORMS_CATALOG_ID
{
return Err(invalid(
tool,
format!(
"surface '{}' was drawn in the catalog {}, which these tools do not draw in; \
draw it again instead",
params.surface_id, previous.catalog_id
),
));
}
let Some(mut draft) = latest.as_ref().and_then(DrawnEnvelope::draft) else {
return Err(invalid(
tool,
format!(
"no surface '{}' is shown in this session; draw it first",
params.surface_id
),
));
};
self.within_patch_budget(ctx, ¶ms.surface_id)?;
let mut model = DataModel::new(draft.data_model.clone());
for change in params.data {
model.apply(Some(&change.path), change.value).map_err(|error| invalid(tool, error))?;
}
draft.data_model = model.value().clone();
draft.components.retain(|component| {
let id = component.get("id").and_then(Value::as_str).unwrap_or_default();
!params.remove.iter().any(|removed| removed == id)
});
let components =
super::wire::components_in(params.components, self.shared.validator.catalog())
.map_err(|error| invalid(tool, format!("components{error}")))?;
for component in components {
let id = component.get("id").and_then(Value::as_str).unwrap_or_default().to_string();
match draft
.components
.iter_mut()
.find(|existing| existing.get("id").and_then(Value::as_str) == Some(id.as_str()))
{
Some(existing) => *existing = component,
None => draft.components.push(component),
}
}
let mut result = self.draw(ctx, draft)?;
if let (Some(previous), Some(now)) =
(latest.as_ref(), DrawnEnvelope::from_response(&result))
&& let Some(delta) = now.delta_from(previous)
{
let mut components = Vec::new();
let mut data = Vec::new();
for message in &delta {
match &message.body {
A2uiBody::UpdateComponents(update) => components
.extend(update.components.iter().filter_map(|c| c.get("id").cloned())),
A2uiBody::UpdateDataModel(update) => {
data.push(json!(update.path.as_deref().unwrap_or("/")));
}
_ => {}
}
}
result["changed"] = json!({ "components": components, "data": data });
}
Ok(result)
}
fn within_patch_budget(&self, ctx: &dyn ToolContext, surface_id: &str) -> Result<()> {
let key = (
ctx.app_name().to_string(),
ctx.user_id().to_string(),
ctx.session_id().to_string(),
surface_id.to_string(),
);
let now = Instant::now();
let mut patched =
self.shared.patched.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let times = patched.entry(key).or_default();
while times.front().is_some_and(|at| now.duration_since(*at) >= Duration::from_secs(60)) {
times.pop_front();
}
if times.len() >= MAX_PATCHES_PER_MINUTE {
return Err(invalid(
Op::Patch.name(),
format!(
"surface '{surface_id}' was changed {MAX_PATCHES_PER_MINUTE} times in the last \
minute; put changes together in one patch (it takes many data changes and \
components) and patch less often"
),
));
}
times.push_back(now);
Ok(())
}
fn delete(&self, ctx: &dyn ToolContext, params: DeleteParams) -> Result<Value> {
let latest = self.latest(ctx, ¶ms.surface_id);
let Some(previous) = latest.as_ref().filter(|envelope| !envelope.deleted) else {
return Err(invalid(
Op::Delete.name(),
format!("no surface '{}' is shown in this session", params.surface_id),
));
};
let version = self.next_version(ctx, ¶ms.surface_id, latest.as_ref());
let envelope = DrawnEnvelope {
surface_id: params.surface_id.clone(),
version,
kind: previous.kind,
catalog_id: previous.catalog_id.clone(),
title: None,
messages: vec![A2uiMessage::delete_surface(params.surface_id)],
actions: Vec::new(),
deleted: true,
};
Ok(self.shown(ctx, envelope))
}
}
#[async_trait]
impl Tool for DrawTool {
fn name(&self) -> &str {
self.op.name()
}
fn description(&self) -> &str {
DrawTool::description(self)
}
fn parameters_schema(&self) -> Option<Value> {
Some(match self.op {
Op::Form => schema_of::<FormParams>(),
Op::Card => schema_of::<CardParams>(),
Op::Table => schema_of::<TableParams>(),
Op::Screen => self.shared.screen_schema.clone(),
Op::Patch => schema_of::<PatchParams>(),
Op::Delete => schema_of::<DeleteParams>(),
})
}
fn is_read_only(&self) -> bool {
true
}
fn effect(&self) -> ToolEffect {
ToolEffect::ReadOnly
}
fn is_concurrency_safe(&self) -> bool {
true
}
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
let tool = self.op.name();
let ctx = ctx.as_ref();
match self.op {
Op::Form => self.draw(ctx, form(params(tool, args)?)?),
Op::Card => self.draw(ctx, card(params(tool, args)?)),
Op::Table => self.draw(ctx, table(params(tool, args)?)),
Op::Screen => {
let screen: ScreenParams = params(tool, args)?;
let components =
super::wire::components_in(screen.components, self.shared.validator.catalog())
.map_err(|error| invalid(tool, format!("components{error}")))?;
self.draw(
ctx,
SurfaceDraft {
surface_id: screen.surface_id,
kind: DrawnKind::Screen,
title: screen.title,
components,
data_model: screen.data_model.unwrap_or_else(|| json!({})),
actions: screen.actions,
},
)
}
Op::Patch => self.patch(ctx, params(tool, args)?),
Op::Delete => self.delete(ctx, params(tool, args)?),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_data_delta_names_each_changed_path() {
let before = json!({ "a": 1, "b": { "c": 2, "d": 3 }, "rows": [1, 2], "gone": true });
let now = json!({ "a": 1, "b": { "c": 5, "d": 3 }, "rows": [1, 2, 3], "x/y": "new" });
let mut out = Vec::new();
data_delta(&before, &now, String::new(), &mut out);
assert_eq!(
out,
vec![
("/b/c".to_string(), Some(json!(5))),
("/gone".to_string(), None),
("/rows".to_string(), Some(json!([1, 2, 3]))),
("/x~1y".to_string(), Some(json!("new"))),
]
);
let mut whole = Vec::new();
data_delta(&Value::Null, &json!({ "a": 1 }), String::new(), &mut whole);
assert_eq!(whole, vec![(String::new(), Some(json!({ "a": 1 })))]);
}
}