1use std::collections::{HashMap, VecDeque};
5use std::fmt::Write as _;
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, Instant};
8
9use adk_core::{
10 AdkError, DRAW_TOOL_NAMES, ErrorCategory, ErrorComponent, ReadonlyContext, Result,
11 TOOL_INVALID_ARGUMENTS_CODE, Tool, ToolContext, ToolEffect, Toolset,
12};
13use async_trait::async_trait;
14use schemars::JsonSchema;
15use serde::de::DeserializeOwned;
16use serde::{Deserialize, Serialize};
17use serde_json::{Value, json};
18use sha2::{Digest, Sha256};
19
20use super::a2ui::{A2uiBody, A2uiMessage, DataModel};
21use super::catalog::{Catalog, FORMS_CATALOG_ID};
22use super::drawn::DrawnKind;
23use super::validate::{DrawRefusal, DrawnAction, SurfaceDraft, Validator};
24
25pub const DRAWN_STATE_KEY: &str = "adk.surface.drawn";
29
30pub const REFUSED_STATE_KEY: &str = "adk.surface.refused";
35
36const VERSIONS_STATE_KEY: &str = "adk.surface.versions";
40
41pub const MAX_PATCHES_PER_MINUTE: usize = 30;
45
46type SurfaceKey = (String, String, String, String);
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
60#[serde(rename_all = "camelCase")]
61pub struct DrawnRecord {
62 pub surface_id: String,
64 pub version: u64,
66 pub digest: String,
68}
69
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
92#[serde(rename_all = "camelCase")]
93pub struct DrawnEnvelope {
94 pub surface_id: String,
96 pub version: u64,
98 pub kind: DrawnKind,
100 pub catalog_id: String,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub title: Option<String>,
105 pub messages: Vec<A2uiMessage>,
108 #[serde(default, skip_serializing_if = "Vec::is_empty")]
110 pub actions: Vec<DrawnAction>,
111 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
113 pub deleted: bool,
114}
115
116impl DrawnEnvelope {
117 pub fn digest(&self) -> String {
119 let mut canonical = String::new();
120 write_canonical(&serde_json::to_value(self).unwrap_or_default(), &mut canonical);
121 let hash = Sha256::digest(canonical.as_bytes());
122 hash.iter().fold(String::with_capacity(64), |mut hex, byte| {
123 let _ = write!(hex, "{byte:02x}");
124 hex
125 })
126 }
127
128 pub fn draft(&self) -> Option<SurfaceDraft> {
156 if self.deleted {
157 return None;
158 }
159 let mut components = Vec::new();
160 let mut model = DataModel::default();
161 for message in
162 self.messages.iter().filter(|message| message.surface_id() == self.surface_id)
163 {
164 match &message.body {
165 A2uiBody::CreateSurface(_) => {}
166 A2uiBody::UpdateComponents(update) => components.clone_from(&update.components),
167 A2uiBody::UpdateDataModel(update) => {
168 model.apply(update.path.as_deref(), update.value.clone()).ok()?;
169 }
170 A2uiBody::DeleteSurface(_) => return None,
171 }
172 }
173 Some(SurfaceDraft {
174 surface_id: self.surface_id.clone(),
175 kind: self.kind,
176 title: self.title.clone(),
177 components,
178 data_model: model.value().clone(),
179 actions: self.actions.clone(),
180 })
181 }
182
183 pub fn from_response(response: &Value) -> Option<Self> {
185 serde_json::from_value(response.get("drawn")?.clone()).ok()
186 }
187
188 pub fn delta_from(&self, previous: &DrawnEnvelope) -> Option<Vec<A2uiMessage>> {
225 if self.surface_id != previous.surface_id
226 || self.catalog_id != previous.catalog_id
227 || self.version <= previous.version
228 {
229 return None;
230 }
231 let (now, before) = (self.draft()?, previous.draft()?);
232 let mut messages = Vec::new();
233 let changed: Vec<Value> = now
234 .components
235 .iter()
236 .filter(|component| !before.components.contains(component))
237 .cloned()
238 .collect();
239 if !changed.is_empty() {
240 messages.push(A2uiMessage::update_components(self.surface_id.clone(), changed));
241 }
242 let mut paths = Vec::new();
243 data_delta(&before.data_model, &now.data_model, String::new(), &mut paths);
244 for (path, value) in paths {
245 let path = if path.is_empty() { None } else { Some(path) };
246 messages.push(A2uiMessage::update_data_model(self.surface_id.clone(), path, value));
247 }
248 Some(messages)
249 }
250
251 fn of(draft: &SurfaceDraft, version: u64, catalog_id: &str) -> Self {
253 let surface = draft.surface_id.clone();
254 let data_model = (!draft.data_model.is_null()).then(|| draft.data_model.clone());
255 let mut create = A2uiMessage::create_surface(surface.clone());
256 if let A2uiBody::CreateSurface(body) = &mut create.body {
257 body.catalog_id = catalog_id.to_string();
258 }
259 Self {
260 surface_id: surface.clone(),
261 version,
262 kind: draft.kind,
263 catalog_id: catalog_id.to_string(),
264 title: draft.title.clone(),
265 messages: vec![
266 create,
267 A2uiMessage::update_components(surface.clone(), draft.components.clone()),
268 A2uiMessage::update_data_model(surface, None, data_model),
269 ],
270 actions: draft.actions.clone(),
271 deleted: false,
272 }
273 }
274}
275
276fn data_delta(before: &Value, now: &Value, at: String, out: &mut Vec<(String, Option<Value>)>) {
280 if before == now {
281 return;
282 }
283 match (before, now) {
284 (Value::Object(before), Value::Object(now)) => {
285 for (key, old) in before {
286 let path = format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"));
287 match now.get(key) {
288 Some(new) => data_delta(old, new, path, out),
289 None => out.push((path, None)),
290 }
291 }
292 for (key, new) in now.iter().filter(|(key, _)| !before.contains_key(*key)) {
293 let path = format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"));
294 out.push((path, Some(new.clone())));
295 }
296 }
297 (_, Value::Null) => out.push((at, None)),
298 _ => out.push((at, Some(now.clone()))),
299 }
300}
301
302fn write_canonical(value: &Value, out: &mut String) {
304 match value {
305 Value::Object(map) => {
306 out.push('{');
307 let mut keys: Vec<&String> = map.keys().collect();
308 keys.sort();
309 for (index, key) in keys.into_iter().enumerate() {
310 if index > 0 {
311 out.push(',');
312 }
313 out.push_str(&Value::String(key.clone()).to_string());
314 out.push(':');
315 write_canonical(&map[key], out);
316 }
317 out.push('}');
318 }
319 Value::Array(items) => {
320 out.push('[');
321 for (index, item) in items.iter().enumerate() {
322 if index > 0 {
323 out.push(',');
324 }
325 write_canonical(item, out);
326 }
327 out.push(']');
328 }
329 scalar => out.push_str(&scalar.to_string()),
330 }
331}
332
333#[derive(Debug, Clone)]
354pub struct DrawToolset {
355 shared: Arc<Shared>,
356}
357
358#[derive(Debug)]
359struct Shared {
360 validator: Validator,
361 issued: Mutex<HashMap<SurfaceKey, u64>>,
364 patched: Mutex<HashMap<SurfaceKey, VecDeque<Instant>>>,
366 screen_description: String,
369 screen_schema: Value,
371}
372
373impl DrawToolset {
374 pub fn new(validator: Validator) -> Self {
379 let catalog = validator.catalog();
380 Self {
381 shared: Arc::new(Shared {
382 screen_description: screen_description(catalog),
383 screen_schema: screen_schema(catalog),
384 validator,
385 issued: Mutex::new(HashMap::new()),
386 patched: Mutex::new(HashMap::new()),
387 }),
388 }
389 }
390
391 pub fn forms() -> Self {
393 Self::new(Validator::forms())
394 }
395
396 pub fn catalog(&self) -> &'static Catalog {
399 self.shared.validator.catalog()
400 }
401
402 pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
404 [Op::Form, Op::Card, Op::Table, Op::Screen, Op::Patch, Op::Delete]
405 .into_iter()
406 .map(|op| Arc::new(DrawTool { op, shared: Arc::clone(&self.shared) }) as Arc<dyn Tool>)
407 .collect()
408 }
409}
410
411#[async_trait]
412impl Toolset for DrawToolset {
413 fn name(&self) -> &str {
414 "genui"
415 }
416
417 async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
418 Ok(DrawToolset::tools(self))
419 }
420}
421
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423enum Op {
424 Form,
425 Card,
426 Table,
427 Screen,
428 Patch,
429 Delete,
430}
431
432impl Op {
433 fn name(self) -> &'static str {
435 match self {
436 Self::Form => "render_form",
437 Self::Card => "render_card",
438 Self::Table => "render_table",
439 Self::Screen => "render_screen",
440 Self::Patch => "patch_surface",
441 Self::Delete => "delete_surface",
442 }
443 }
444}
445
446struct DrawTool {
447 op: Op,
448 shared: Arc<Shared>,
449}
450
451#[derive(Debug, Clone, Deserialize, JsonSchema)]
453#[serde(rename_all = "camelCase", deny_unknown_fields)]
454struct FormField {
455 name: String,
457 label: String,
459 #[serde(rename = "type", default)]
461 field_type: FieldType,
462 #[serde(default)]
464 value: Option<Value>,
465 #[serde(default)]
467 required: bool,
468 #[serde(default)]
470 options: Vec<ChoiceOption>,
471}
472
473#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, JsonSchema)]
474#[serde(rename_all = "camelCase")]
475enum FieldType {
476 #[default]
477 Text,
478 LongText,
479 Number,
480 Email,
481 Date,
482 Checkbox,
483 Choice,
484}
485
486#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
488#[serde(deny_unknown_fields)]
489struct ChoiceOption {
490 label: String,
492 value: String,
494}
495
496#[derive(Debug, Clone, Deserialize, JsonSchema)]
498#[serde(rename_all = "camelCase", deny_unknown_fields)]
499struct FormParams {
500 #[serde(default)]
502 surface_id: Option<String>,
503 title: String,
505 #[serde(default)]
507 description: Option<String>,
508 fields: Vec<FormField>,
510 actions: Vec<DrawnAction>,
513}
514
515#[derive(Debug, Clone, Deserialize, JsonSchema)]
517#[serde(deny_unknown_fields)]
518struct CardRow {
519 label: String,
521 value: Value,
523}
524
525#[derive(Debug, Clone, Deserialize, JsonSchema)]
527#[serde(rename_all = "camelCase", deny_unknown_fields)]
528struct CardParams {
529 #[serde(default)]
531 surface_id: Option<String>,
532 title: String,
534 rows: Vec<CardRow>,
536 #[serde(default)]
538 note: Option<String>,
539}
540
541#[derive(Debug, Clone, Deserialize, JsonSchema)]
543#[serde(rename_all = "camelCase", deny_unknown_fields)]
544struct TableParams {
545 #[serde(default)]
547 surface_id: Option<String>,
548 title: String,
550 columns: Vec<String>,
552 rows: Vec<Vec<Value>>,
554}
555
556#[derive(Debug, Clone, Deserialize, JsonSchema)]
558#[serde(rename_all = "camelCase", deny_unknown_fields)]
559struct ScreenParams {
560 surface_id: String,
562 #[serde(default)]
564 title: Option<String>,
565 components: Vec<Value>,
568 #[serde(default)]
570 data_model: Option<Value>,
571 #[serde(default)]
573 actions: Vec<DrawnAction>,
574}
575
576#[derive(Debug, Clone, Deserialize, JsonSchema)]
578#[serde(deny_unknown_fields)]
579struct DataChange {
580 path: String,
582 #[serde(default)]
584 value: Option<Value>,
585}
586
587#[derive(Debug, Clone, Deserialize, JsonSchema)]
589#[serde(rename_all = "camelCase", deny_unknown_fields)]
590struct PatchParams {
591 surface_id: String,
593 #[serde(default)]
595 data: Vec<DataChange>,
596 #[serde(default)]
598 components: Vec<Value>,
599 #[serde(default)]
601 remove: Vec<String>,
602}
603
604#[derive(Debug, Clone, Deserialize, JsonSchema)]
606#[serde(rename_all = "camelCase", deny_unknown_fields)]
607struct DeleteParams {
608 surface_id: String,
610}
611
612const FORMS_SCREEN_DESCRIPTION: &str = "Show the person a screen of A2UI 1.0 (or v0.9.1) components from \
614 the forms catalog (Text, Row, Column, List, Card, Tabs, Divider, Button, TextField, \
615 CheckBox, ChoicePicker, Slider, DateTimeInput), one with id root. Buttons dispatch only \
616 declared actions, which ask the person before a tool runs.";
617
618fn screen_description(catalog: &Catalog) -> String {
620 if !catalog.is_extension() {
621 return FORMS_SCREEN_DESCRIPTION.to_string();
622 }
623 let added: Vec<&str> = catalog.extensions().collect();
624 let mut out = format!(
625 "Show the person a screen of A2UI 1.0 (or v0.9.1) components from the {} catalog, one with id \
626 root: the forms components (Text, Row, Column, List, Card, Tabs, Divider, Button, \
627 TextField, CheckBox, ChoicePicker, Slider, DateTimeInput) and {}. Bind data with \
628 {{\"@path\": \"/...\"}} (or v0.9.1's {{\"path\": \"/...\"}}) into dataModel.",
629 catalog.label(),
630 added.join(", ")
631 );
632 for usage in catalog.usage() {
633 let _ = write!(out, " {usage}");
634 }
635 out.push_str(
636 " Only buttons dispatch declared actions, which ask the person before a tool runs; the \
637 other components only show.",
638 );
639 out
640}
641
642fn screen_schema(catalog: &Catalog) -> Value {
644 let mut schema = schema_of::<ScreenParams>();
645 if catalog.is_extension()
646 && let Some(components) = schema.pointer_mut("/properties/components")
647 {
648 components["description"] = json!(format!(
649 "A2UI components of the {} catalog, one with id `root`, in 1.0's syntax or v0.9.1's.",
650 catalog.label()
651 ));
652 }
653 schema
654}
655
656fn schema_of<T: JsonSchema>() -> Value {
657 let mut schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
658 if let Some(map) = schema.as_object_mut() {
659 map.remove("$schema");
660 map.remove("title");
661 }
662 schema
663}
664
665fn invalid(tool: &str, error: impl std::fmt::Display) -> AdkError {
666 AdkError::new(
667 ErrorComponent::Tool,
668 ErrorCategory::InvalidInput,
669 TOOL_INVALID_ARGUMENTS_CODE,
670 format!("invalid arguments for '{tool}': {error}. Correct them and call it again."),
671 )
672}
673
674fn refused(refusal: &DrawRefusal) -> AdkError {
677 let result = serde_json::to_string(&refusal.validation_result()).unwrap_or_default();
678 AdkError::new(
679 ErrorComponent::Tool,
680 ErrorCategory::Forbidden,
681 refusal.code(),
682 format!("{}\nvalidationResult: {result}", refusal.message()),
683 )
684}
685
686fn params<T: DeserializeOwned>(tool: &str, args: Value) -> Result<T> {
687 serde_json::from_value(args).map_err(|error| invalid(tool, error))
688}
689
690fn surface_id_from(kind: &str, title: &str) -> String {
692 let mut slug = String::new();
693 for c in title.chars().flat_map(char::to_lowercase) {
694 if c.is_ascii_alphanumeric() {
695 slug.push(c);
696 } else if !slug.ends_with('-') && !slug.is_empty() {
697 slug.push('-');
698 }
699 }
700 let slug: String = slug.trim_end_matches('-').chars().take(48).collect();
701 if slug.is_empty() { kind.to_string() } else { format!("{kind}-{slug}") }
702}
703
704fn form(params: FormParams) -> Result<SurfaceDraft> {
706 let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("form", ¶ms.title));
707 let mut components = vec![
708 json!({ "id": "root", "component": "Card", "child": "body" }),
709 json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
710 ];
711 let mut body = vec![json!("title")];
712 if let Some(description) = params.description {
713 components.push(json!({ "id": "description", "component": "Text", "text": description }));
714 body.push(json!("description"));
715 }
716 let mut model = serde_json::Map::new();
717 for field in params.fields {
718 let name = &field.name;
719 if name.is_empty()
720 || name.len() > 48
721 || !name.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
722 {
723 return Err(invalid(
724 Op::Form.name(),
725 format!("field name '{name}' is not 1 to 48 letters, digits, '_' or '-'"),
726 ));
727 }
728 let id = format!("field-{name}");
729 let path = format!("/{name}");
730 let binding = json!({ "path": path });
731 let mut checks = Vec::new();
732 if field.required {
733 checks.push(json!({
734 "condition": { "call": "required", "args": { "value": binding } },
735 "message": "Fill this in"
736 }));
737 }
738 let (component, initial) = match field.field_type {
739 FieldType::Text | FieldType::Email | FieldType::Number | FieldType::LongText => {
740 let variant = match field.field_type {
741 FieldType::LongText => "longText",
742 FieldType::Number => "number",
743 _ => "shortText",
744 };
745 if field.field_type == FieldType::Email {
746 checks.push(json!({
747 "condition": { "call": "email", "args": { "value": binding } },
748 "message": "Enter an email address"
749 }));
750 }
751 (
752 json!({
753 "id": id, "component": "TextField", "label": field.label,
754 "value": binding, "variant": variant
755 }),
756 json!(""),
757 )
758 }
759 FieldType::Date => (
760 json!({
761 "id": id, "component": "DateTimeInput", "label": field.label,
762 "value": binding, "enableDate": true
763 }),
764 json!(""),
765 ),
766 FieldType::Checkbox => (
767 json!({
768 "id": id, "component": "CheckBox", "label": field.label, "value": binding
769 }),
770 json!(false),
771 ),
772 FieldType::Choice => (
773 json!({
774 "id": id, "component": "ChoicePicker", "label": field.label, "value": binding,
775 "options": field.options, "variant": "mutuallyExclusive"
776 }),
777 json!([]),
778 ),
779 };
780 let mut component = component;
781 if !checks.is_empty() {
782 component["checks"] = Value::Array(checks);
783 }
784 model.insert(name.clone(), field.value.unwrap_or(initial));
785 components.push(component);
786 body.push(json!(id));
787 }
788 let mut buttons = Vec::new();
789 for (index, action) in params.actions.iter().enumerate() {
790 let button = format!("action-{}", action.id);
791 let label = format!("action-{}-label", action.id);
792 components.push(json!({ "id": label, "component": "Text", "text": action.label }));
793 components.push(json!({
794 "id": button, "component": "Button", "child": label,
795 "variant": if index == 0 { "primary" } else { "default" },
796 "action": { "event": { "name": action.id } }
797 }));
798 buttons.push(json!(button));
799 }
800 if !buttons.is_empty() {
801 components.push(json!({ "id": "actions", "component": "Row", "children": buttons }));
802 body.push(json!("actions"));
803 }
804 components.push(json!({ "id": "body", "component": "Column", "children": body }));
805 Ok(SurfaceDraft {
806 surface_id,
807 kind: DrawnKind::Form,
808 title: Some(params.title),
809 components,
810 data_model: Value::Object(model),
811 actions: params.actions,
812 })
813}
814
815fn card(params: CardParams) -> SurfaceDraft {
817 let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("card", ¶ms.title));
818 let mut components = vec![
819 json!({ "id": "root", "component": "Card", "child": "body" }),
820 json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
821 ];
822 let mut body = vec![json!("title")];
823 for (index, row) in params.rows.into_iter().enumerate() {
824 let value = match row.value {
825 Value::String(text) => text,
826 other => other.to_string(),
827 };
828 components.push(json!({
829 "id": format!("row-{index}-label"), "component": "Text", "text": row.label,
830 "variant": "caption"
831 }));
832 components.push(
833 json!({ "id": format!("row-{index}-value"), "component": "Text", "text": value }),
834 );
835 components.push(json!({
836 "id": format!("row-{index}"), "component": "Row", "justify": "spaceBetween",
837 "children": [format!("row-{index}-label"), format!("row-{index}-value")]
838 }));
839 body.push(json!(format!("row-{index}")));
840 }
841 if let Some(note) = params.note {
842 components
843 .push(json!({ "id": "note", "component": "Text", "text": note, "variant": "caption" }));
844 body.push(json!("note"));
845 }
846 components.push(json!({ "id": "body", "component": "Column", "children": body }));
847 SurfaceDraft {
848 surface_id,
849 kind: DrawnKind::Card,
850 title: Some(params.title),
851 components,
852 data_model: json!({}),
853 actions: Vec::new(),
854 }
855}
856
857fn table(params: TableParams) -> SurfaceDraft {
860 let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("table", ¶ms.title));
861 let mut components = vec![
862 json!({ "id": "root", "component": "Card", "child": "body" }),
863 json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
864 ];
865 let mut header = Vec::new();
866 let mut cells = Vec::new();
867 for (index, column) in params.columns.iter().enumerate() {
868 components.push(json!({
869 "id": format!("head-{index}"), "component": "Text", "text": column,
870 "variant": "caption"
871 }));
872 components.push(json!({
873 "id": format!("cell-{index}"), "component": "Text",
874 "text": { "path": index.to_string() }
875 }));
876 header.push(json!(format!("head-{index}")));
877 cells.push(json!(format!("cell-{index}")));
878 }
879 let rows: Vec<Value> = params
880 .rows
881 .into_iter()
882 .map(|row| {
883 Value::Array(
884 row.into_iter()
885 .map(|cell| match cell {
886 Value::String(text) => Value::String(text),
887 other => Value::String(other.to_string()),
888 })
889 .collect(),
890 )
891 })
892 .collect();
893 components.push(json!({ "id": "header", "component": "Row", "children": header }));
894 components.push(json!({ "id": "row", "component": "Row", "children": cells }));
895 components.push(json!({
896 "id": "rows", "component": "List",
897 "children": { "componentId": "row", "path": "/rows" }
898 }));
899 components.push(
900 json!({ "id": "body", "component": "Column", "children": ["title", "header", "rows"] }),
901 );
902 SurfaceDraft {
903 surface_id,
904 kind: DrawnKind::Table,
905 title: Some(params.title),
906 components,
907 data_model: json!({ "rows": rows }),
908 actions: Vec::new(),
909 }
910}
911
912impl DrawTool {
913 fn description(&self) -> &str {
914 match self.op {
915 Op::Form => {
916 "Show the person a form in this thread. Each field's value is at the data path \
917 /<name>. Each action is a button that asks to run one of your tools with \
918 constants and field values; pressing it never runs the tool: it asks the \
919 person first, on the home's own card. Never draw decision words or controls \
920 (Allow once, Deny, Approve...), links, or password fields."
921 }
922 Op::Card => {
923 "Show the person a card in this thread: a title and label and value rows. Plain \
924 text only; no buttons, links or decision words."
925 }
926 Op::Table => {
927 "Show the person a table in this thread: a title, column headings and rows of \
928 text or numbers. No buttons, links or decision words."
929 }
930 Op::Screen => &self.shared.screen_description,
931 Op::Patch => {
932 "Change a surface you drew in this session: set or remove data model values, \
933 add or replace components by id, or remove components. The whole surface is \
934 checked again."
935 }
936 Op::Delete => "Remove a surface you drew in this session from the person's thread.",
937 }
938 }
939
940 fn latest(&self, ctx: &dyn ToolContext, surface_id: &str) -> Option<DrawnEnvelope> {
942 let history = ctx.session()?.conversation_history();
943 history
944 .iter()
945 .flat_map(|content| &content.parts)
946 .filter_map(|part| match part {
947 adk_core::Part::FunctionResponse { function_response, .. }
948 if DRAW_TOOL_NAMES.contains(&function_response.name.as_str()) =>
949 {
950 DrawnEnvelope::from_response(&function_response.response)
951 }
952 _ => None,
953 })
954 .filter(|envelope| envelope.surface_id == surface_id)
955 .max_by_key(|envelope| envelope.version)
956 }
957
958 fn next_version(
961 &self,
962 ctx: &dyn ToolContext,
963 surface_id: &str,
964 latest: Option<&DrawnEnvelope>,
965 ) -> u64 {
966 let stored = ctx
967 .session()
968 .and_then(|session| session.state().get(&format!("{VERSIONS_STATE_KEY}.{surface_id}")))
969 .and_then(|version| version.as_u64())
970 .unwrap_or(0);
971 let seen = latest.map_or(0, |envelope| envelope.version);
972 let key = (
973 ctx.app_name().to_string(),
974 ctx.user_id().to_string(),
975 ctx.session_id().to_string(),
976 surface_id.to_string(),
977 );
978 let mut issued =
979 self.shared.issued.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
980 let version =
981 stored.max(seen).max(issued.get(&key).copied().unwrap_or(0)).saturating_add(1);
982 issued.insert(key, version);
983 version
984 }
985
986 fn shown(&self, ctx: &dyn ToolContext, envelope: DrawnEnvelope) -> Value {
988 let record = DrawnRecord {
989 surface_id: envelope.surface_id.clone(),
990 version: envelope.version,
991 digest: envelope.digest(),
992 };
993 let mut actions = ctx.actions();
994 actions.state_delta.insert(DRAWN_STATE_KEY.to_string(), json!(record));
995 actions.state_delta.insert(
997 format!("{VERSIONS_STATE_KEY}.{}", envelope.surface_id),
998 json!(envelope.version),
999 );
1000 ctx.set_actions(actions);
1001 tracing::info!(
1002 surface.id = %envelope.surface_id,
1003 surface.version = envelope.version,
1004 surface.deleted = envelope.deleted,
1005 "drawing recorded"
1006 );
1007 let message = if envelope.deleted {
1008 format!("Removed '{}' from the person's thread.", envelope.surface_id)
1009 } else if envelope.actions.is_empty() {
1010 format!(
1011 "Shown to the person as version {} of '{}'.",
1012 envelope.version, envelope.surface_id
1013 )
1014 } else {
1015 format!(
1016 "Shown to the person as version {} of '{}'. Sending asks them first; you are told \
1017 when they decide.",
1018 envelope.version, envelope.surface_id
1019 )
1020 };
1021 json!({
1022 "status": if envelope.deleted { "removed" } else { "shown" },
1023 "message": message,
1024 "drawn": envelope,
1025 })
1026 }
1027
1028 fn draw(&self, ctx: &dyn ToolContext, draft: SurfaceDraft) -> Result<Value> {
1030 let own_tools = ctx
1033 .agent_tool_names()
1034 .map(|tools| self.shared.validator.clone().with_bindable_tools(tools));
1035 let validator = own_tools.as_ref().unwrap_or(&self.shared.validator);
1036 let validated = match validator.validate(&draft) {
1037 Ok(validated) => validated,
1038 Err(refusal) => {
1039 tracing::info!(
1040 surface.id = %draft.surface_id,
1041 refusal.code = refusal.code(),
1042 refusal.reason = %refusal.technical(),
1043 "drawing refused"
1044 );
1045 let mut actions = ctx.actions();
1046 actions.state_delta.insert(REFUSED_STATE_KEY.to_string(), json!(refusal));
1047 ctx.set_actions(actions);
1048 return Err(refused(&refusal));
1049 }
1050 };
1051 let latest = self.latest(ctx, &draft.surface_id);
1052 let version = self.next_version(ctx, &draft.surface_id, latest.as_ref());
1053 let mut result =
1054 self.shown(ctx, DrawnEnvelope::of(&draft, version, validator.catalog().id()));
1055 if !validated.warnings.is_empty() {
1057 tracing::info!(
1058 surface.id = %draft.surface_id,
1059 warnings = validated.warnings.len(),
1060 "drawing shown with warnings"
1061 );
1062 let said: Vec<String> =
1063 validated.warnings.iter().filter_map(|warning| warning.message.clone()).collect();
1064 if let Some(message) = result.get("message").and_then(Value::as_str) {
1065 result["message"] = json!(format!("{message} Change it: {}", said.join(" ")));
1066 }
1067 result["warnings"] = json!(validated.warnings);
1068 }
1069 Ok(result)
1070 }
1071
1072 fn patch(&self, ctx: &dyn ToolContext, params: PatchParams) -> Result<Value> {
1073 let tool = Op::Patch.name();
1074 let latest = self.latest(ctx, ¶ms.surface_id);
1075 let own = self.shared.validator.catalog().id();
1078 if let Some(previous) = latest.as_ref()
1079 && previous.catalog_id != own
1080 && previous.catalog_id != FORMS_CATALOG_ID
1081 {
1082 return Err(invalid(
1083 tool,
1084 format!(
1085 "surface '{}' was drawn in the catalog {}, which these tools do not draw in; \
1086 draw it again instead",
1087 params.surface_id, previous.catalog_id
1088 ),
1089 ));
1090 }
1091 let Some(mut draft) = latest.as_ref().and_then(DrawnEnvelope::draft) else {
1092 return Err(invalid(
1093 tool,
1094 format!(
1095 "no surface '{}' is shown in this session; draw it first",
1096 params.surface_id
1097 ),
1098 ));
1099 };
1100 self.within_patch_budget(ctx, ¶ms.surface_id)?;
1101 let mut model = DataModel::new(draft.data_model.clone());
1102 for change in params.data {
1103 model.apply(Some(&change.path), change.value).map_err(|error| invalid(tool, error))?;
1104 }
1105 draft.data_model = model.value().clone();
1106 draft.components.retain(|component| {
1107 let id = component.get("id").and_then(Value::as_str).unwrap_or_default();
1108 !params.remove.iter().any(|removed| removed == id)
1109 });
1110 let components =
1111 super::wire::components_in(params.components, self.shared.validator.catalog())
1112 .map_err(|error| invalid(tool, format!("components{error}")))?;
1113 for component in components {
1114 let id = component.get("id").and_then(Value::as_str).unwrap_or_default().to_string();
1115 match draft
1116 .components
1117 .iter_mut()
1118 .find(|existing| existing.get("id").and_then(Value::as_str) == Some(id.as_str()))
1119 {
1120 Some(existing) => *existing = component,
1121 None => draft.components.push(component),
1122 }
1123 }
1124 let mut result = self.draw(ctx, draft)?;
1125 if let (Some(previous), Some(now)) =
1127 (latest.as_ref(), DrawnEnvelope::from_response(&result))
1128 && let Some(delta) = now.delta_from(previous)
1129 {
1130 let mut components = Vec::new();
1131 let mut data = Vec::new();
1132 for message in &delta {
1133 match &message.body {
1134 A2uiBody::UpdateComponents(update) => components
1135 .extend(update.components.iter().filter_map(|c| c.get("id").cloned())),
1136 A2uiBody::UpdateDataModel(update) => {
1137 data.push(json!(update.path.as_deref().unwrap_or("/")));
1138 }
1139 _ => {}
1140 }
1141 }
1142 result["changed"] = json!({ "components": components, "data": data });
1143 }
1144 Ok(result)
1145 }
1146
1147 fn within_patch_budget(&self, ctx: &dyn ToolContext, surface_id: &str) -> Result<()> {
1149 let key = (
1150 ctx.app_name().to_string(),
1151 ctx.user_id().to_string(),
1152 ctx.session_id().to_string(),
1153 surface_id.to_string(),
1154 );
1155 let now = Instant::now();
1156 let mut patched =
1157 self.shared.patched.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
1158 let times = patched.entry(key).or_default();
1159 while times.front().is_some_and(|at| now.duration_since(*at) >= Duration::from_secs(60)) {
1160 times.pop_front();
1161 }
1162 if times.len() >= MAX_PATCHES_PER_MINUTE {
1163 return Err(invalid(
1164 Op::Patch.name(),
1165 format!(
1166 "surface '{surface_id}' was changed {MAX_PATCHES_PER_MINUTE} times in the last \
1167 minute; put changes together in one patch (it takes many data changes and \
1168 components) and patch less often"
1169 ),
1170 ));
1171 }
1172 times.push_back(now);
1173 Ok(())
1174 }
1175
1176 fn delete(&self, ctx: &dyn ToolContext, params: DeleteParams) -> Result<Value> {
1177 let latest = self.latest(ctx, ¶ms.surface_id);
1178 let Some(previous) = latest.as_ref().filter(|envelope| !envelope.deleted) else {
1179 return Err(invalid(
1180 Op::Delete.name(),
1181 format!("no surface '{}' is shown in this session", params.surface_id),
1182 ));
1183 };
1184 let version = self.next_version(ctx, ¶ms.surface_id, latest.as_ref());
1185 let envelope = DrawnEnvelope {
1186 surface_id: params.surface_id.clone(),
1187 version,
1188 kind: previous.kind,
1189 catalog_id: previous.catalog_id.clone(),
1190 title: None,
1191 messages: vec![A2uiMessage::delete_surface(params.surface_id)],
1192 actions: Vec::new(),
1193 deleted: true,
1194 };
1195 Ok(self.shown(ctx, envelope))
1196 }
1197}
1198
1199#[async_trait]
1200impl Tool for DrawTool {
1201 fn name(&self) -> &str {
1202 self.op.name()
1203 }
1204
1205 fn description(&self) -> &str {
1206 DrawTool::description(self)
1207 }
1208
1209 fn parameters_schema(&self) -> Option<Value> {
1210 Some(match self.op {
1211 Op::Form => schema_of::<FormParams>(),
1212 Op::Card => schema_of::<CardParams>(),
1213 Op::Table => schema_of::<TableParams>(),
1214 Op::Screen => self.shared.screen_schema.clone(),
1215 Op::Patch => schema_of::<PatchParams>(),
1216 Op::Delete => schema_of::<DeleteParams>(),
1217 })
1218 }
1219
1220 fn is_read_only(&self) -> bool {
1221 true
1222 }
1223
1224 fn effect(&self) -> ToolEffect {
1225 ToolEffect::ReadOnly
1226 }
1227
1228 fn is_concurrency_safe(&self) -> bool {
1229 true
1230 }
1231
1232 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
1233 let tool = self.op.name();
1234 let ctx = ctx.as_ref();
1235 match self.op {
1236 Op::Form => self.draw(ctx, form(params(tool, args)?)?),
1237 Op::Card => self.draw(ctx, card(params(tool, args)?)),
1238 Op::Table => self.draw(ctx, table(params(tool, args)?)),
1239 Op::Screen => {
1240 let screen: ScreenParams = params(tool, args)?;
1241 let components =
1243 super::wire::components_in(screen.components, self.shared.validator.catalog())
1244 .map_err(|error| invalid(tool, format!("components{error}")))?;
1245 self.draw(
1246 ctx,
1247 SurfaceDraft {
1248 surface_id: screen.surface_id,
1249 kind: DrawnKind::Screen,
1250 title: screen.title,
1251 components,
1252 data_model: screen.data_model.unwrap_or_else(|| json!({})),
1253 actions: screen.actions,
1254 },
1255 )
1256 }
1257 Op::Patch => self.patch(ctx, params(tool, args)?),
1258 Op::Delete => self.delete(ctx, params(tool, args)?),
1259 }
1260 }
1261}
1262
1263#[cfg(test)]
1264mod tests {
1265 use super::*;
1266
1267 #[test]
1268 fn a_data_delta_names_each_changed_path() {
1269 let before = json!({ "a": 1, "b": { "c": 2, "d": 3 }, "rows": [1, 2], "gone": true });
1270 let now = json!({ "a": 1, "b": { "c": 5, "d": 3 }, "rows": [1, 2, 3], "x/y": "new" });
1271 let mut out = Vec::new();
1272 data_delta(&before, &now, String::new(), &mut out);
1273 assert_eq!(
1274 out,
1275 vec![
1276 ("/b/c".to_string(), Some(json!(5))),
1277 ("/gone".to_string(), None),
1278 ("/rows".to_string(), Some(json!([1, 2, 3]))),
1279 ("/x~1y".to_string(), Some(json!("new"))),
1280 ]
1281 );
1282 let mut whole = Vec::new();
1283 data_delta(&Value::Null, &json!({ "a": 1 }), String::new(), &mut whole);
1284 assert_eq!(whole, vec![(String::new(), Some(json!({ "a": 1 })))]);
1285 }
1286}