adk-surface 3.0.0

Agent surfaces for ADK-Rust: one engine that turns a kernel's sessions, decisions and activity into plain words for every surface, and the surfaces that show them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! The render tools (spec 3.3 §6.1 `genui`, §7.4 rule 5): what an agent draws with, each
//! drawing checked whole by the [`Validator`] and recorded under [`DRAWN_STATE_KEY`].

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};

/// The reserved session state key every drawing writes, `{ surfaceId, version, digest }`:
/// the proof that a drawing tool result came from these tools, checked against the digest of
/// the result's `drawn` record (spec 3.3 §6.1 `genui`).
pub const DRAWN_STATE_KEY: &str = "adk.surface.drawn";

/// The reserved session state key a refused drawing writes, its [`DrawRefusal`]: the proof
/// that a render tool's error came from these tools, so the thread shows the refusal's plain
/// notice and an MCP server's tool of the same name stays an ordinary failed result
/// (spec 3.3 §7.4 rule 5).
pub const REFUSED_STATE_KEY: &str = "adk.surface.refused";

/// The prefix of the session state keys holding the latest version of each surface a
/// session drew, `adk.surface.versions.<surface id>`, so versions keep rising after a
/// restart or a compaction.
const VERSIONS_STATE_KEY: &str = "adk.surface.versions";

/// How many times `patch_surface` may change one surface in a minute. A live view updated
/// every two seconds fits; a model patching in a loop is told to batch its changes, so the
/// person's view (and every approval card over it) is not redrawn faster than it can be read.
pub const MAX_PATCHES_PER_MINUTE: usize = 30;

/// A surface in one session: app, user, session and surface ids.
type SurfaceKey = (String, String, String, String);

/// What [`DRAWN_STATE_KEY`] holds: the latest drawing of the session.
///
/// # Example
///
/// ```rust
/// use adk_surface::genui::DrawnRecord;
///
/// let record = DrawnRecord { surface_id: "invoice-10".into(), version: 2, digest: "ab".into() };
/// assert_eq!(serde_json::to_value(&record).unwrap()["surfaceId"], "invoice-10");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DrawnRecord {
    /// The surface drawn.
    pub surface_id: String,
    /// Its version.
    pub version: u64,
    /// The SHA-256 of the drawing's [`DrawnEnvelope`], hex.
    pub digest: String,
}

/// One drawing as a drawing tool's result records it, under `drawn`: the A2UI messages that
/// rebuild the whole surface, and the actions its buttons ask for (spec 3.3 §6.1 `genui`).
///
/// # Example
///
/// ```rust
/// use adk_surface::genui::{A2uiMessage, DrawnEnvelope, DrawnKind, FORMS_CATALOG_ID};
///
/// let envelope = DrawnEnvelope {
///     surface_id: "s".into(),
///     version: 1,
///     kind: DrawnKind::Card,
///     catalog_id: FORMS_CATALOG_ID.into(),
///     title: None,
///     messages: vec![A2uiMessage::create_surface("s")],
///     actions: Vec::new(),
///     deleted: false,
/// };
/// assert_eq!(envelope.digest(), envelope.clone().digest());
/// assert_eq!(envelope.digest().len(), 64);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DrawnEnvelope {
    /// The surface.
    pub surface_id: String,
    /// Its version: one more than any earlier drawing of the surface in the session.
    pub version: u64,
    /// What it is.
    pub kind: DrawnKind,
    /// The catalog it was checked against.
    pub catalog_id: String,
    /// The title above it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// The A2UI messages that draw it: `createSurface`, `updateComponents` and
    /// `updateDataModel`, or `deleteSurface`.
    pub messages: Vec<A2uiMessage>,
    /// The actions its buttons ask for.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actions: Vec<DrawnAction>,
    /// Whether this version removes the surface.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub deleted: bool,
}

impl DrawnEnvelope {
    /// The SHA-256 of the envelope's canonical JSON (keys sorted), hex.
    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
        })
    }

    /// The drawing its messages describe, or `None` for a removal.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_surface::genui::{A2uiMessage, DrawnEnvelope, DrawnKind, FORMS_CATALOG_ID};
    /// use serde_json::json;
    ///
    /// let envelope = DrawnEnvelope {
    ///     surface_id: "s".into(),
    ///     version: 1,
    ///     kind: DrawnKind::Card,
    ///     catalog_id: FORMS_CATALOG_ID.into(),
    ///     title: None,
    ///     messages: vec![
    ///         A2uiMessage::create_surface("s"),
    ///         A2uiMessage::update_components(
    ///             "s",
    ///             vec![json!({ "id": "root", "component": "Text", "text": { "path": "/t" } })],
    ///         ),
    ///         A2uiMessage::update_data_model("s", None, Some(json!({ "t": "Hello" }))),
    ///     ],
    ///     actions: Vec::new(),
    ///     deleted: false,
    /// };
    /// assert_eq!(envelope.draft().unwrap().data_model, json!({ "t": "Hello" }));
    /// ```
    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(),
        })
    }

    /// The envelope a drawing tool's `response` records under `drawn`, if any.
    pub fn from_response(response: &Value) -> Option<Self> {
        serde_json::from_value(response.get("drawn")?.clone()).ok()
    }

    /// The A2UI messages that turn a renderer showing `previous` into one showing this
    /// version: one `updateComponents` with the components that are new or changed, then an
    /// `updateDataModel` for each data path that changed (no value where one was removed).
    /// Empty when nothing changed. An envelope keeps the whole drawing, so its digest and
    /// what a person approves stay whole; a transport that knows which version a renderer
    /// holds (a socket, an A2A task) sends this instead of the whole drawing.
    ///
    /// A2UI has no message that removes a component: a component dropped from the drawing is
    /// no longer referenced by its changed parent, so the renderer stops drawing it.
    ///
    /// `None` when there is no sound base: either is a removal, they are different surfaces
    /// or catalogs, or `previous` is not older.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_surface::genui::{A2uiBody, A2uiMessage, DrawnEnvelope, DrawnKind, FORMS_CATALOG_ID};
    /// use serde_json::json;
    ///
    /// let version = |n: u64, total: i64| DrawnEnvelope {
    ///     surface_id: "s".into(), version: n, kind: DrawnKind::Screen,
    ///     catalog_id: FORMS_CATALOG_ID.into(), title: None,
    ///     messages: vec![
    ///         A2uiMessage::create_surface("s"),
    ///         A2uiMessage::update_components("s", vec![
    ///             json!({ "id": "root", "component": "Text", "text": { "path": "/total" } })]),
    ///         A2uiMessage::update_data_model("s", None, Some(json!({ "total": total, "currency": "USD" }))),
    ///     ],
    ///     actions: Vec::new(), deleted: false,
    /// };
    /// let delta = version(2, 12).delta_from(&version(1, 10)).unwrap();
    /// assert_eq!(delta.len(), 1);
    /// let A2uiBody::UpdateDataModel(update) = &delta[0].body else { panic!() };
    /// assert_eq!(update.path.as_deref(), Some("/total"));
    /// assert_eq!(update.value, Some(json!(12)));
    /// ```
    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)
    }

    /// The envelope of `draft`, at `version`.
    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,
        }
    }
}

/// The data changes that turn `before` into `now`, as (JSON pointer, new value) in order: an
/// object is compared key by key, anything else is replaced whole, and a removed key has no
/// value. The empty pointer is the whole model.
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()))),
    }
}

/// Writes `value` as JSON with every object's keys sorted.
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()),
    }
}

/// The render tools, bound to one catalog through their [`Validator`] (spec 3.3 §6.1
/// `genui`): `render_form`, `render_card`, `render_table`, `render_screen`, `patch_surface`
/// and `delete_surface`.
///
/// Every tool is read-only and safe to run beside others: drawing changes nothing but what
/// the person's threads show, and a form's Send asks the person before anything runs. Each
/// result records the drawing under `drawn` and writes [`DRAWN_STATE_KEY`]; a refused
/// drawing is a tool error whose message says why in plain words.
///
/// # Example
///
/// ```rust
/// use adk_core::Tool;
/// use adk_surface::genui::DrawToolset;
///
/// let tools = DrawToolset::forms().tools();
/// let names: Vec<&str> = tools.iter().map(|tool| tool.name()).collect();
/// assert_eq!(names, adk_core::DRAW_TOOL_NAMES);
/// assert!(tools.iter().all(|tool| tool.is_read_only() && tool.is_concurrency_safe()));
/// ```
#[derive(Debug, Clone)]
pub struct DrawToolset {
    shared: Arc<Shared>,
}

#[derive(Debug)]
struct Shared {
    validator: Validator,
    /// Versions given out in this process, by app, user, session and surface, so drawings
    /// made side by side in one turn get their own.
    issued: Mutex<HashMap<SurfaceKey, u64>>,
    /// When each surface was patched in the last minute, by app, user, session and surface.
    patched: Mutex<HashMap<SurfaceKey, VecDeque<Instant>>>,
    /// What `render_screen` tells the model: the catalog's components, and each extension
    /// component's usage.
    screen_description: String,
    /// `render_screen`'s parameters, its components described by the catalog.
    screen_schema: Value,
}

impl DrawToolset {
    /// Render tools that check every drawing with `validator`, in its catalog: `forms`, or an
    /// extension catalog ([`Catalog::extend`]), whose components `render_screen` draws and
    /// describes to the model. The tools keep their names in every catalog, so give an agent
    /// one `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()),
            }),
        }
    }

    /// Render tools on the `forms` 1.0 catalog.
    pub fn forms() -> Self {
        Self::new(Validator::forms())
    }

    /// The catalog these tools draw in: register it with the engine that shows the drawings
    /// (`SurfaceEngineBuilder::with_catalog`).
    pub fn catalog(&self) -> &'static Catalog {
        self.shared.validator.catalog()
    }

    /// The tools.
    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 {
    /// The tool's name, one of [`DRAW_TOOL_NAMES`].
    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>,
}

/// A field of a form.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct FormField {
    /// The field's name: letters, digits, `_` or `-`. Its value is at the data path `/<name>`.
    name: String,
    /// What the person reads beside it.
    label: String,
    /// `text` (default), `longText`, `number`, `email`, `date`, `checkbox` or `choice`.
    #[serde(rename = "type", default)]
    field_type: FieldType,
    /// The value it starts with.
    #[serde(default)]
    value: Option<Value>,
    /// Whether the person must fill it in.
    #[serde(default)]
    required: bool,
    /// The choices of a `choice` field.
    #[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,
}

/// One choice of a `choice` field.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ChoiceOption {
    /// What the person reads.
    label: String,
    /// The value sent.
    value: String,
}

/// `render_form`: fields and the actions their buttons ask for.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct FormParams {
    /// The surface to draw; drawing it again makes a new version. Defaults to one from the title.
    #[serde(default)]
    surface_id: Option<String>,
    /// The form's title.
    title: String,
    /// A line under the title.
    #[serde(default)]
    description: Option<String>,
    /// The fields, in order.
    fields: Vec<FormField>,
    /// What the buttons ask for: `{ id, label, tool, args }`, each argument a constant or
    /// `{ "path": "/<field name>" }`. Sending asks the person before the tool runs.
    actions: Vec<DrawnAction>,
}

/// One row of a card.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct CardRow {
    /// The row's label.
    label: String,
    /// Its value: text or a number.
    value: Value,
}

/// `render_card`: label and value rows to read.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CardParams {
    /// The surface to draw. Defaults to one from the title.
    #[serde(default)]
    surface_id: Option<String>,
    /// The card's title.
    title: String,
    /// The rows, in order.
    rows: Vec<CardRow>,
    /// A line under the rows.
    #[serde(default)]
    note: Option<String>,
}

/// `render_table`: columns and rows to read.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct TableParams {
    /// The surface to draw. Defaults to one from the title.
    #[serde(default)]
    surface_id: Option<String>,
    /// The table's title.
    title: String,
    /// The column headings.
    columns: Vec<String>,
    /// The rows, each a list of cells: text or numbers.
    rows: Vec<Vec<Value>>,
}

/// `render_screen`: A2UI components of the catalog.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ScreenParams {
    /// The surface to draw.
    surface_id: String,
    /// The title above it.
    #[serde(default)]
    title: Option<String>,
    /// A2UI components of the forms catalog, one with id `root`, in 1.0's syntax
    /// (`{"@path": "/x"}`) or v0.9.1's (`{"path": "/x"}`).
    components: Vec<Value>,
    /// The data model the components bind to.
    #[serde(default)]
    data_model: Option<Value>,
    /// What its buttons ask for, as in `render_form`.
    #[serde(default)]
    actions: Vec<DrawnAction>,
}

/// A change to a drawn surface's data model.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct DataChange {
    /// Where, as a data path such as `/total`.
    path: String,
    /// The new value; absent or `null` removes it.
    #[serde(default)]
    value: Option<Value>,
}

/// `patch_surface`: changes to a surface drawn earlier, which make its next version.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct PatchParams {
    /// The surface to change.
    surface_id: String,
    /// Data model changes, in order.
    #[serde(default)]
    data: Vec<DataChange>,
    /// Components to add, or to replace by id.
    #[serde(default)]
    components: Vec<Value>,
    /// Ids of components to remove.
    #[serde(default)]
    remove: Vec<String>,
}

/// `delete_surface`: removes a surface drawn earlier.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct DeleteParams {
    /// The surface to remove.
    surface_id: String,
}

/// The forms catalog's `render_screen` description, unchanged for a `forms` toolset.
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.";

/// What `render_screen` tells the model about `catalog`.
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
}

/// `render_screen`'s parameters, its components described by `catalog`.
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."),
    )
}

/// A refusal as the tool's error: its message, then the same in A2UI 1.0's `ValidationResult`
/// shape so an agent can act on its code.
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))
}

/// A surface id from `title`: `<kind>-` and the title's letters and digits, lowercased.
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}") }
}

/// The components of a form.
fn form(params: FormParams) -> Result<SurfaceDraft> {
    let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("form", &params.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,
    })
}

/// The components of a card.
fn card(params: CardParams) -> SurfaceDraft {
    let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("card", &params.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(),
    }
}

/// The components of a table: a header row, then one row per item of `/rows`, rendered by a
/// template.
fn table(params: TableParams) -> SurfaceDraft {
    let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("table", &params.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.",
        }
    }

    /// The latest drawing of `surface_id` in the session, from earlier tool results.
    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)
    }

    /// The next version of `surface_id`: one more than any version the session state, the
    /// session's earlier results or this process gave it.
    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
    }

    /// Records `envelope` as the session's latest drawing and answers the call.
    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));
        // One key per surface: drawings made side by side in one turn each keep theirs.
        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,
        })
    }

    /// Checks `draft` and records it as the next version of its surface.
    fn draw(&self, ctx: &dyn ToolContext, draft: SurfaceDraft) -> Result<Value> {
        // An action names one of the drawing agent's own tools, so "Sending runs …" under its
        // button is true from the start (spec 3.3 §7.4 rule 5).
        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()));
        // Shown, and the agent is told what pressures the person, to draw it plainly next time.
        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, &params.surface_id);
        // A change is checked in these tools' catalog: a drawing in another catalog cannot be
        // checked here, except one in forms, which every extension catalog holds whole.
        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, &params.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)?;
        // What changed, so the agent can tell an empty patch from a real one.
        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)
    }

    /// Refuses a patch past [`MAX_PATCHES_PER_MINUTE`] for `surface_id` in this session.
    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, &params.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, &params.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)?;
                // Components in A2UI 1.0's syntax are read into the internal form first.
                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 })))]);
    }
}