Skip to main content

adk_surface/genui/
catalog.rs

1//! The `forms` 1.0 catalog (spec 3.3 §6.1 `genui`): the A2UI v0.9.1 basic catalog without
2//! the components that can fake a decision or cover the home, embedded and never fetched.
3//! `catalogs/README.md` records its source, its upstream copyright and what changed.
4//!
5//! An **extension catalog** is `forms` 1.0 plus components another crate defines
6//! ([`Catalog::extend`]). A2UI gives a surface one catalog, so an extension is always a
7//! superset of `forms` under its own id, and it can never loosen what `forms` refuses: its
8//! components only show (no actions, no fields), every string in them and every data model
9//! value they bind is checked by rule 5, and each one says what the home and the terminal
10//! show for it ([`ExtensionComponent::home`]) in forms components and the home's own
11//! elements only: charts, 3D scenes and depth effects.
12
13use std::collections::BTreeMap;
14use std::sync::{Arc, LazyLock};
15
16use serde_json::{Map, Value, json};
17
18use super::drawn::DrawnChart;
19use super::scene::{DrawnDepth, DrawnScene};
20
21/// The id of the `forms` 1.0 catalog.
22pub const FORMS_CATALOG_ID: &str = "https://adk-rust.com/a2ui/catalogs/forms/1.0/catalog.json";
23
24/// The upstream basic catalog's components `forms` 1.0 leaves out, which no extension may
25/// bring back under the same name.
26pub(crate) const LEFT_OUT: &[&str] = &["Image", "Icon", "Modal", "Video", "AudioPlayer"];
27
28/// Properties an extension component's schema may not declare: a component that only shows
29/// has no action to dispatch, no event to send and no field to check.
30const FORBIDDEN_PROPERTIES: &[&str] = &["action", "event", "checks"];
31
32/// String formats an extension component's schema may not declare: a drawing has no links.
33const FORBIDDEN_FORMATS: &[&str] = &["uri", "uri-reference", "iri", "iri-reference", "url"];
34
35/// A property of an extension component that holds other components of the drawing, by id
36/// (spec 3.3 §6.1 `genui`, extension catalogs). The validator follows these slots for depth,
37/// loops and every limit, so a container can never hide a component from a check.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum ChildSlot {
40    /// The property is one component id.
41    One(&'static str),
42    /// The property is a list of component ids.
43    Many(&'static str),
44    /// The property `array` is a list of objects, each naming one component id at `child`,
45    /// such as an app's `pages: [{ "title": "Overview", "child": "overview" }]`.
46    EachOf {
47        /// The list.
48        array: &'static str,
49        /// The id's key in each of its objects.
50        child: &'static str,
51    },
52}
53
54/// An extension component as its projection reads it (spec 3.3 §7.4 rule 5): every property
55/// with its bindings, `formatString` and `pluralize` already resolved on the server, and
56/// every string already checked.
57#[derive(Debug, Clone, Copy)]
58pub struct ResolvedComponent<'a> {
59    /// Its id.
60    pub id: &'a str,
61    /// Its type, such as `Metric`.
62    pub component: &'a str,
63    /// Its properties, resolved.
64    pub props: &'a Value,
65    /// How many components its slots hold, in slot order: [`HomeNode::Child`] names them by
66    /// index.
67    pub children: usize,
68}
69
70impl ResolvedComponent<'_> {
71    /// The resolved string property `name`.
72    pub fn str(&self, name: &str) -> Option<&str> {
73        self.props.get(name).and_then(Value::as_str)
74    }
75
76    /// The resolved property `name`.
77    pub fn get(&self, name: &str) -> Option<&Value> {
78        self.props.get(name)
79    }
80}
81
82/// The text style of a [`HomeNode::Text`], one of the `forms` `Text` variants.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum HomeText {
85    /// A level 1 heading.
86    H1,
87    /// A level 2 heading.
88    H2,
89    /// A level 3 heading.
90    H3,
91    /// A level 4 heading.
92    H4,
93    /// A level 5 heading.
94    H5,
95    /// Small, muted text.
96    Caption,
97    /// Body text.
98    #[default]
99    Body,
100}
101
102impl HomeText {
103    /// The `forms` `Text` variant it is drawn with.
104    pub fn variant(self) -> &'static str {
105        match self {
106            Self::H1 => "h1",
107            Self::H2 => "h2",
108            Self::H3 => "h3",
109            Self::H4 => "h4",
110            Self::H5 => "h5",
111            Self::Caption => "caption",
112            Self::Body => "body",
113        }
114    }
115}
116
117/// What the home and the terminal show for an extension component: forms components, charts,
118/// 3D scenes and depth effects, never a button or a field, so a projection only shows (spec
119/// 3.3 §7.4 rule 5). Every string in it is checked again, and every child the component's
120/// slots hold must appear exactly once, as [`HomeNode::Child`].
121///
122/// A scene's panels and a wall or stage's children hold only what shows: no button or field
123/// anywhere inside them. A scene's text view holds no child. Scenes and depth effects don't
124/// nest in each other.
125#[derive(Debug, Clone, PartialEq)]
126#[non_exhaustive]
127pub enum HomeNode {
128    /// Text.
129    Text {
130        /// What it reads.
131        text: String,
132        /// How it is styled.
133        variant: HomeText,
134    },
135    /// Side by side.
136    Row(Vec<HomeNode>),
137    /// One above another.
138    Column(Vec<HomeNode>),
139    /// On a card.
140    Card(Vec<HomeNode>),
141    /// Tabs, each a title and what it shows.
142    Tabs(Vec<(String, HomeNode)>),
143    /// A rule.
144    Divider,
145    /// The component's child at this index, drawn as the home draws it.
146    Child(usize),
147    /// A chart the home draws natively.
148    Chart(DrawnChart),
149    /// A 3D scene the home draws natively, with its panels and its text view.
150    Scene(Box<HomeScene>),
151    /// Children the home presents in depth, with CSS 3D.
152    Depth {
153        /// How.
154        depth: DrawnDepth,
155        /// What it presents.
156        children: Vec<HomeNode>,
157    },
158}
159
160/// A 3D scene in a home view.
161#[derive(Debug, Clone, PartialEq)]
162pub struct HomeScene {
163    /// The scene; the server writes its summary, its panels' keys and its text view's key.
164    pub scene: DrawnScene,
165    /// Held components shown beside its objects.
166    pub panels: Vec<HomePanel>,
167    /// What it shows, in words: a table or a list, holding no child. It is shown by "Show as
168    /// text", where WebGL is missing, and in the terminal; without one, they list the
169    /// labelled objects.
170    pub text: Option<HomeNode>,
171}
172
173impl HomeScene {
174    /// `scene`, with no panels and no text view.
175    pub fn new(scene: DrawnScene) -> Self {
176        Self { scene, panels: Vec::new(), text: None }
177    }
178}
179
180/// A held component shown beside a scene's object.
181#[derive(Debug, Clone, PartialEq)]
182pub struct HomePanel {
183    /// The object's id.
184    pub anchor: String,
185    /// What it shows: usually a [`HomeNode::Child`].
186    pub content: HomeNode,
187}
188
189impl HomeNode {
190    /// Body text.
191    pub fn text(text: impl Into<String>) -> Self {
192        Self::Text { text: text.into(), variant: HomeText::Body }
193    }
194
195    /// Small, muted text.
196    pub fn caption(text: impl Into<String>) -> Self {
197        Self::Text { text: text.into(), variant: HomeText::Caption }
198    }
199
200    /// A heading, level 1 to 5.
201    pub fn heading(level: u8, text: impl Into<String>) -> Self {
202        let variant = match level {
203            0 | 1 => HomeText::H1,
204            2 => HomeText::H2,
205            3 => HomeText::H3,
206            4 => HomeText::H4,
207            _ => HomeText::H5,
208        };
209        Self::Text { text: text.into(), variant }
210    }
211}
212
213/// A component an extension catalog adds to `forms` 1.0 (spec 3.3 §6.1 `genui`, extension
214/// catalogs).
215///
216/// A component only shows: its schema may not declare `action`, `event` or `checks`, and an
217/// instance that carries any of them is refused. [`home`](Self::home) says what the web home
218/// and the terminal show for it; a host that registers a renderer for the component (the
219/// React `DrawnView`'s `renderers`) may draw its resolved properties instead.
220///
221/// # Example
222///
223/// ```rust
224/// use adk_surface::genui::{ExtensionComponent, HomeNode, ResolvedComponent};
225/// use serde_json::{Value, json};
226///
227/// struct Metric;
228///
229/// impl ExtensionComponent for Metric {
230///     fn name(&self) -> &'static str {
231///         "Metric"
232///     }
233///     fn schema(&self) -> Value {
234///         json!({
235///             "type": "object",
236///             "properties": {
237///                 "id": { "type": "string" },
238///                 "component": { "const": "Metric" },
239///                 "label": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/DynamicString" },
240///                 "value": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/DynamicValue" }
241///             },
242///             "required": ["id", "component", "label", "value"],
243///             "additionalProperties": false
244///         })
245///     }
246///     fn usage(&self) -> &'static str {
247///         "Metric: one number with its label, such as {label: \"Open incidents\", value: 3}"
248///     }
249///     fn home(&self, metric: &ResolvedComponent<'_>) -> Result<HomeNode, String> {
250///         let value = metric.get("value").map(Value::to_string).unwrap_or_default();
251///         Ok(HomeNode::Row(vec![
252///             HomeNode::caption(metric.str("label").unwrap_or_default()),
253///             HomeNode::heading(3, value.trim_matches('"')),
254///         ]))
255///     }
256/// }
257/// ```
258pub trait ExtensionComponent: Send + Sync + 'static {
259    /// The component's type, unique in the catalog and not one of `forms`' or of the
260    /// components `forms` leaves out.
261    fn name(&self) -> &'static str;
262
263    /// Its A2UI component schema (JSON Schema). It may `$ref` the A2UI common types and the
264    /// catalog's `#/$defs/CatalogComponentCommon`, and declares no `$defs`, `functions`,
265    /// `action`, `event`, `checks` or URI formats.
266    fn schema(&self) -> Value;
267
268    /// The properties that hold other components, by id; none for a component that holds
269    /// nothing.
270    fn children(&self) -> &'static [ChildSlot] {
271        &[]
272    }
273
274    /// One line the render tools tell the model about it: what it shows and its shape.
275    fn usage(&self) -> &'static str;
276
277    /// The component types that may hold it (A2UI 1.0 `allowedParents`, `"Surface"` for the
278    /// top level); empty for any.
279    fn allowed_parents(&self) -> &'static [&'static str] {
280        &[]
281    }
282
283    /// The component types it may hold (A2UI 1.0 `allowedChildren`); empty for any.
284    fn allowed_children(&self) -> &'static [&'static str] {
285        &[]
286    }
287
288    /// What the home and the terminal show for it, from its resolved properties. It must be
289    /// pure: the same component always projects the same way.
290    ///
291    /// # Errors
292    ///
293    /// Returns why the component cannot be shown; the drawing is refused with that reason.
294    fn home(&self, component: &ResolvedComponent<'_>) -> Result<HomeNode, String>;
295}
296
297/// An extension catalog: its id, name, version and the components it adds to `forms` 1.0.
298pub struct ExtensionSpec {
299    /// Its id, which every surface drawn in it carries. A schema change takes a new id.
300    pub id: &'static str,
301    /// Its name, such as `insight`.
302    pub name: &'static str,
303    /// Its version, such as `1.0`.
304    pub version: &'static str,
305    /// The components it adds.
306    pub components: Vec<Arc<dyn ExtensionComponent>>,
307}
308
309impl std::fmt::Debug for ExtensionSpec {
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        f.debug_struct("ExtensionSpec")
312            .field("id", &self.id)
313            .field("components", &self.components.iter().map(|c| c.name()).collect::<Vec<_>>())
314            .finish_non_exhaustive()
315    }
316}
317
318/// Why an extension catalog was refused.
319#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
320#[error("extension catalog {catalog}: {detail}")]
321pub struct CatalogError {
322    /// The catalog's id.
323    pub catalog: String,
324    /// What is wrong.
325    pub detail: String,
326}
327
328/// The id the A2UI v0.9.1 common types carry.
329const COMMON_TYPES_ID: &str = "https://a2ui.org/specification/v0_9/common_types.json";
330
331/// Where the common types look for the catalog's functions: `catalog.json`, relative to
332/// their own id.
333const COMMON_TYPES_CATALOG: &str = "https://a2ui.org/specification/v0_9/catalog.json";
334
335const FORMS_DOCUMENT: &str = include_str!("catalogs/forms-1.0.json");
336/// The `forms` 1.0 catalog as an A2UI 1.0 catalog document, derived from the 1.0 basic catalog.
337const FORMS_DOCUMENT_V1_0: &str = include_str!("catalogs/forms-1.0.a2ui-1.0.json");
338/// The A2UI 1.0 common types and catalog meta-schema, for checking 1.0 catalog documents.
339#[cfg(test)]
340pub(crate) const COMMON_TYPES_V1_0: &str = include_str!("catalogs/common_types-1.0.json");
341#[cfg(test)]
342pub(crate) const CATALOG_DEFINITION_V1_0: &str =
343    include_str!("catalogs/catalog_definition-1.0.json");
344const COMMON_TYPES_DOCUMENT: &str = include_str!("catalogs/common_types-0.9.1.json");
345
346/// An A2UI catalog this home renders: the components and functions a drawing may use, each
347/// component checked against the catalog's JSON Schema (spec 3.3 §6.1 `genui`).
348///
349/// # Example
350///
351/// ```rust
352/// use adk_surface::genui::{Catalog, FORMS_CATALOG_ID};
353///
354/// let forms = Catalog::forms();
355/// assert_eq!(forms.id(), FORMS_CATALOG_ID);
356/// assert_eq!(forms.label(), "forms 1.0");
357/// assert!(forms.has_component("TextField"));
358/// assert!(!forms.has_component("Image"));
359/// assert!(!forms.functions().any(|name| name == "openUrl"));
360/// ```
361pub struct Catalog {
362    id: &'static str,
363    name: &'static str,
364    version: &'static str,
365    instructions: Option<String>,
366    document: Value,
367    components: BTreeMap<String, jsonschema::Validator>,
368    extensions: BTreeMap<String, Arc<dyn ExtensionComponent>>,
369}
370
371impl std::fmt::Debug for Catalog {
372    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        f.debug_struct("Catalog")
374            .field("id", &self.id)
375            .field("components", &self.components.keys().collect::<Vec<_>>())
376            .field("extensions", &self.extensions.keys().collect::<Vec<_>>())
377            .finish_non_exhaustive()
378    }
379}
380
381static FORMS: LazyLock<Catalog> = LazyLock::new(|| {
382    Catalog::compile(FORMS_CATALOG_ID, "forms", "1.0", FORMS_DOCUMENT)
383        .unwrap_or_else(|error| panic!("the embedded forms 1.0 catalog does not compile: {error}"))
384});
385
386impl Catalog {
387    /// The `forms` 1.0 catalog.
388    pub fn forms() -> &'static Catalog {
389        &FORMS
390    }
391
392    /// An extension catalog: `forms` 1.0 and `spec`'s components, under `spec`'s id (spec 3.3
393    /// §6.1 `genui`, extension catalogs). Keep it in a `static`
394    /// ([`LazyLock`](std::sync::LazyLock)) and register it with the toolset that draws in it
395    /// ([`DrawToolset::new`](super::DrawToolset::new)), the engine that shows it
396    /// (`SurfaceEngineBuilder::with_catalog`) and, where set, `GenuiAgUi::with_catalog`.
397    ///
398    /// # Errors
399    ///
400    /// Refuses a catalog whose id is `forms`', that adds no component, or one of whose
401    /// components reuses a name of `forms` or of what `forms` leaves out (`Image`, `Icon`,
402    /// `Modal`, `Video`, `AudioPlayer`), repeats a name, or declares `$defs`, `functions`,
403    /// `action`, `event`, `checks` or a URI format in its schema; and one whose schemas do
404    /// not compile.
405    pub fn extend(spec: ExtensionSpec) -> Result<Catalog, CatalogError> {
406        let refuse = |detail: String| CatalogError { catalog: spec.id.to_string(), detail };
407        if spec.id == FORMS_CATALOG_ID {
408            return Err(refuse("its id is the forms catalog's".to_string()));
409        }
410        if spec.id.trim().is_empty()
411            || spec.name.trim().is_empty()
412            || spec.version.trim().is_empty()
413        {
414            return Err(refuse("it needs an id, a name and a version".to_string()));
415        }
416        if spec.components.is_empty() {
417            return Err(refuse("it adds no components".to_string()));
418        }
419        let forms = Catalog::forms();
420        let mut document = forms.document.clone();
421        document["$id"] = json!(spec.id);
422        document["catalogId"] = json!(spec.id);
423        document["title"] = json!(format!("{} {}", spec.name, spec.version));
424        document["description"] = json!(format!(
425            "The forms 1.0 catalog and the components of {} {}",
426            spec.name, spec.version
427        ));
428        let mut extensions: BTreeMap<String, Arc<dyn ExtensionComponent>> = BTreeMap::new();
429        for component in &spec.components {
430            let name = component.name();
431            if name.is_empty() || !name.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
432                return Err(refuse(format!(
433                    "'{name}' is not a component name of letters and digits"
434                )));
435            }
436            if forms.has_component(name) {
437                return Err(refuse(format!("{name} is a forms component")));
438            }
439            if LEFT_OUT.contains(&name) {
440                return Err(refuse(format!("{name} is one of the components forms leaves out")));
441            }
442            if extensions.contains_key(name) {
443                return Err(refuse(format!("{name} is added twice")));
444            }
445            let schema = component.schema();
446            if let Some(why) = forbidden(&schema) {
447                return Err(refuse(format!("{name}'s schema {why}")));
448            }
449            document["components"][name] = schema;
450            if let Some(any) = document["$defs"]["anyComponent"]["oneOf"].as_array_mut() {
451                any.push(json!({ "$ref": format!("#/components/{name}") }));
452            }
453            extensions.insert(name.to_string(), Arc::clone(component));
454        }
455        let mut catalog = Catalog::compile_document(spec.id, spec.name, spec.version, document)
456            .map_err(refuse)?;
457        catalog.extensions = extensions;
458        Ok(catalog)
459    }
460
461    fn compile(
462        id: &'static str,
463        name: &'static str,
464        version: &'static str,
465        document: &str,
466    ) -> Result<Self, String> {
467        let document: Value = serde_json::from_str(document).map_err(|error| error.to_string())?;
468        Self::compile_document(id, name, version, document)
469    }
470
471    fn compile_document(
472        id: &'static str,
473        name: &'static str,
474        version: &'static str,
475        document: Value,
476    ) -> Result<Self, String> {
477        let common: Value =
478            serde_json::from_str(COMMON_TYPES_DOCUMENT).map_err(|error| error.to_string())?;
479        let registry = jsonschema::Registry::new()
480            .add(id, document.clone())
481            .and_then(|registry| registry.add(COMMON_TYPES_CATALOG, document.clone()))
482            .and_then(|registry| registry.add(COMMON_TYPES_ID, common))
483            .and_then(jsonschema::RegistryBuilder::prepare)
484            .map_err(|error| error.to_string())?;
485        let names: Vec<String> = document["components"]
486            .as_object()
487            .map(|components| components.keys().cloned().collect())
488            .unwrap_or_default();
489        let mut components = BTreeMap::new();
490        for component in names {
491            let schema = json!({ "$ref": format!("{id}#/components/{component}") });
492            let validator = jsonschema::options()
493                .with_registry(&registry)
494                .build(&schema)
495                .map_err(|error| format!("{component}: {error}"))?;
496            components.insert(component, validator);
497        }
498        Ok(Self {
499            id,
500            name,
501            version,
502            instructions: None,
503            document,
504            components,
505            extensions: BTreeMap::new(),
506        })
507    }
508
509    /// The catalog's id.
510    pub fn id(&self) -> &str {
511        self.id
512    }
513
514    /// The catalog's name and version as the developer panel shows them, `forms 1.0`.
515    pub fn label(&self) -> String {
516        format!("{} {}", self.name, self.version)
517    }
518
519    /// The catalog's JSON Schema document, in the internal (A2UI v0.9.1) form: `forms` and
520    /// every component an extension adds, under the catalog's id.
521    pub fn document(&self) -> &Value {
522        &self.document
523    }
524
525    /// Design guidance for a model drawing in this catalog, carried in its A2UI 1.0 document
526    /// (`instructions`) after each extension component's usage line.
527    #[must_use]
528    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
529        self.instructions = Some(instructions.into());
530        self
531    }
532
533    /// The catalog as a document of A2UI `version` (spec 3.3 §6.1 `genui`). For v0.9.1, the
534    /// internal document. For 1.0: `forms` as an A2UI 1.0 catalog (derived from the 1.0 basic
535    /// catalog); an extension catalog as a 1.0 catalog of only the components it adds, which a
536    /// surface mixes with `forms` (each one names its catalog with `@catalogId`), with
537    /// `protocolVersion`, `instructions` and each component's `allowedParents` and
538    /// `allowedChildren`.
539    ///
540    /// # Example
541    ///
542    /// ```rust
543    /// use adk_surface::genui::{A2uiVersion, Catalog, FORMS_CATALOG_ID};
544    ///
545    /// let forms = Catalog::forms().document_for(A2uiVersion::V1_0);
546    /// assert_eq!(forms["protocolVersion"], "1.0");
547    /// assert_eq!(forms["catalogId"], FORMS_CATALOG_ID);
548    /// assert!(forms["components"]["TextField"].is_object());
549    /// ```
550    pub fn document_for(&self, version: super::wire::A2uiVersion) -> Value {
551        if version == super::wire::A2uiVersion::V0_9_1 {
552            return self.document.clone();
553        }
554        if !self.is_extension() {
555            return serde_json::from_str(FORMS_DOCUMENT_V1_0).unwrap_or_default();
556        }
557        let mut components = Map::new();
558        for (name, extension) in &self.extensions {
559            let mut schema = schema_v1_0(&extension.schema());
560            if let Value::Object(map) = &mut schema {
561                let parents = extension.allowed_parents();
562                if !parents.is_empty() {
563                    map.insert("allowedParents".to_string(), json!(parents));
564                }
565                let children = extension.allowed_children();
566                if !children.is_empty() {
567                    map.insert("allowedChildren".to_string(), json!(children));
568                }
569            }
570            components.insert(name.clone(), schema);
571        }
572        let mut instructions: Vec<String> = self.usage().into_iter().map(str::to_string).collect();
573        if let Some(extra) = &self.instructions {
574            instructions.push(extra.clone());
575        }
576        json!({
577            "$schema": "https://json-schema.org/draft/2020-12/schema",
578            "$id": self.id,
579            "protocolVersion": "1.0",
580            "title": self.label(),
581            "description": format!(
582                "The components {} adds to {FORMS_CATALOG_ID}, which a surface mixes with it",
583                self.label()
584            ),
585            "catalogId": self.id,
586            "instructions": instructions.join("\n"),
587            "components": components,
588        })
589    }
590
591    /// The component types it renders.
592    pub fn components(&self) -> impl Iterator<Item = &str> {
593        self.components.keys().map(String::as_str)
594    }
595
596    /// The functions a drawing may call.
597    pub fn functions(&self) -> impl Iterator<Item = &str> {
598        self.document["functions"]
599            .as_object()
600            .into_iter()
601            .flat_map(|functions| functions.keys().map(String::as_str))
602    }
603
604    /// Whether it renders `component`.
605    pub fn has_component(&self, component: &str) -> bool {
606        self.components.contains_key(component)
607    }
608
609    /// The components an extension catalog adds to `forms`; none for `forms` itself.
610    pub fn extensions(&self) -> impl Iterator<Item = &str> {
611        self.extensions.keys().map(String::as_str)
612    }
613
614    /// Whether it is an extension catalog ([`Catalog::extend`]).
615    pub fn is_extension(&self) -> bool {
616        !self.extensions.is_empty()
617    }
618
619    /// The extension component `component`, if this catalog adds it.
620    pub(crate) fn extension(&self, component: &str) -> Option<&dyn ExtensionComponent> {
621        self.extensions.get(component).map(|extension| extension.as_ref())
622    }
623
624    /// What the render tools tell the model about the catalog's extension components, one
625    /// line each.
626    pub(crate) fn usage(&self) -> Vec<&'static str> {
627        self.extensions.values().map(|extension| extension.usage()).collect()
628    }
629
630    /// Checks `value` against the schema of its component type, `component`: `None` when it
631    /// conforms, else where and why it does not.
632    pub(crate) fn schema_error(&self, component: &str, value: &Value) -> Option<String> {
633        let validator = self.components.get(component)?;
634        validator.iter_errors(value).next().map(|error| {
635            let error = error.to_owned();
636            let error = specific(&error);
637            let at = error.instance_path().as_str();
638            let why = shortened(&error.to_string());
639            if at.is_empty() { why } else { format!("{at}: {why}") }
640        })
641    }
642}
643
644/// An extension component's schema as an A2UI 1.0 catalog component: references to the
645/// v0.9 common types become the relative `common_types.json`, the component envelope (`id`,
646/// `ComponentCommon`, `CatalogComponentCommon`) is left to the 1.0 envelope, which composes it,
647/// and so is closing the object (`additionalProperties: false`; the envelope's
648/// `unevaluatedProperties` closes it with its `@` keys).
649fn schema_v1_0(schema: &Value) -> Value {
650    fn refs(value: &Value) -> Value {
651        match value {
652            Value::Object(map) => Value::Object(
653                map.iter()
654                    .map(|(key, value)| match (key.as_str(), value) {
655                        ("$ref", Value::String(target)) => {
656                            let relative = target
657                                .split_once("common_types.json#")
658                                .map(|(_, pointer)| format!("common_types.json#{pointer}"))
659                                .unwrap_or_else(|| target.clone());
660                            (key.clone(), Value::String(relative))
661                        }
662                        _ => (key.clone(), refs(value)),
663                    })
664                    .collect(),
665            ),
666            Value::Array(items) => Value::Array(items.iter().map(refs).collect()),
667            other => other.clone(),
668        }
669    }
670    let mut out = refs(schema);
671    if let Value::Object(map) = &mut out {
672        if let Some(Value::Object(properties)) = map.get_mut("properties") {
673            properties.remove("id");
674        }
675        if let Some(Value::Array(required)) = map.get_mut("required") {
676            required.retain(|name| name != "id");
677        }
678        if map.get("additionalProperties") == Some(&Value::Bool(false)) {
679            map.remove("additionalProperties");
680        }
681        if let Some(Value::Array(all)) = map.get_mut("allOf") {
682            all.retain(|part| {
683                let target = part.get("$ref").and_then(Value::as_str).unwrap_or_default();
684                !target.ends_with("/ComponentCommon")
685                    && !target.ends_with("/CatalogComponentCommon")
686            });
687            if all.is_empty() {
688                map.remove("allOf");
689            }
690        }
691    }
692    out
693}
694
695/// The most specific cause of `error`. A `oneOf` or `anyOf` that no branch matched, such as a
696/// property that is a binding or a literal list, names the deepest failure among its branches,
697/// so the agent reads which value broke which rule rather than the whole value.
698fn specific<'e>(
699    error: &'e jsonschema::ValidationError<'static>,
700) -> &'e jsonschema::ValidationError<'static> {
701    let context = match error.kind() {
702        jsonschema::error::ValidationErrorKind::OneOfNotValid { context }
703        | jsonschema::error::ValidationErrorKind::AnyOf { context } => context,
704        _ => return error,
705    };
706    let deepest = context
707        .iter()
708        .flatten()
709        .map(specific)
710        .max_by_key(|cause| cause.instance_path().as_str().matches('/').count());
711    match deepest {
712        Some(cause)
713            if cause.instance_path().as_str().len() > error.instance_path().as_str().len() =>
714        {
715            cause
716        }
717        _ => error,
718    }
719}
720
721/// The most of a schema error's text a reason carries; a value it quotes can be long.
722const MAX_SCHEMA_ERROR_CHARS: usize = 300;
723
724fn shortened(text: &str) -> String {
725    if text.chars().count() <= MAX_SCHEMA_ERROR_CHARS {
726        return text.to_string();
727    }
728    let kept: String = text.chars().take(MAX_SCHEMA_ERROR_CHARS).collect();
729    format!("{kept}…")
730}
731
732/// What an extension component's schema declares that a component that only shows may not.
733fn forbidden(schema: &Value) -> Option<String> {
734    match schema {
735        Value::Object(map) => {
736            for key in ["$defs", "definitions", "functions"] {
737                if map.contains_key(key) {
738                    return Some(format!("declares {key}"));
739                }
740            }
741            if let Some(properties) = map.get("properties").and_then(Value::as_object)
742                && let Some(property) =
743                    FORBIDDEN_PROPERTIES.iter().find(|name| properties.contains_key(**name))
744            {
745                return Some(format!("declares the property '{property}'"));
746            }
747            if let Some(format) = map.get("format").and_then(Value::as_str)
748                && FORBIDDEN_FORMATS.contains(&format)
749            {
750                return Some(format!("declares the string format '{format}'"));
751            }
752            map.values().find_map(forbidden)
753        }
754        Value::Array(items) => items.iter().find_map(forbidden),
755        _ => None,
756    }
757}
758
759/// The catalogs a home shows, by id (spec 3.3 §6.1 `genui`): `forms` 1.0 always, and every
760/// extension catalog a host registers. A drawing is checked again against its own catalog;
761/// one in a catalog that is not here is refused ("this home does not render the catalog …").
762///
763/// # Example
764///
765/// ```rust
766/// use adk_surface::genui::{Catalogs, FORMS_CATALOG_ID};
767///
768/// let catalogs = Catalogs::forms();
769/// assert!(catalogs.get(FORMS_CATALOG_ID).is_some());
770/// assert!(catalogs.get("https://example.com/other.json").is_none());
771/// ```
772#[derive(Clone)]
773pub struct Catalogs(Arc<Vec<&'static Catalog>>);
774
775impl Catalogs {
776    /// `forms` 1.0 alone.
777    pub fn forms() -> Self {
778        Self(Arc::new(vec![Catalog::forms()]))
779    }
780
781    /// These catalogs and `catalog`. A catalog whose id is here already is not added again.
782    #[must_use]
783    pub fn with(self, catalog: &'static Catalog) -> Self {
784        if self.get(catalog.id()).is_some() {
785            return self;
786        }
787        let mut catalogs = (*self.0).clone();
788        catalogs.push(catalog);
789        Self(Arc::new(catalogs))
790    }
791
792    /// The catalog whose id is `id`.
793    pub fn get(&self, id: &str) -> Option<&'static Catalog> {
794        self.0.iter().copied().find(|catalog| catalog.id() == id)
795    }
796
797    /// Every catalog, `forms` first.
798    pub fn iter(&self) -> impl Iterator<Item = &'static Catalog> + '_ {
799        self.0.iter().copied()
800    }
801}
802
803impl Default for Catalogs {
804    fn default() -> Self {
805        Self::forms()
806    }
807}
808
809impl std::fmt::Debug for Catalogs {
810    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
811        f.debug_list().entries(self.0.iter().map(|catalog| catalog.id())).finish()
812    }
813}
814
815#[cfg(test)]
816mod tests {
817    use super::*;
818    use crate::genui::A2uiVersion;
819
820    /// A validator of A2UI 1.0 catalog documents: the pinned 1.0 meta-schema, with the 1.0
821    /// common types it and the documents refer to.
822    fn v1_0_meta() -> jsonschema::Validator {
823        let meta: Value = serde_json::from_str(CATALOG_DEFINITION_V1_0).unwrap();
824        let common: Value = serde_json::from_str(COMMON_TYPES_V1_0).unwrap();
825        // The common types refer to `catalog.json` for the components a surface may hold;
826        // checking a catalog document needs only that it exists.
827        let catalog = json!({ "$defs": { "anyComponent": {}, "anyFunction": {} } });
828        let registry = jsonschema::Registry::new()
829            .add("https://a2ui.org/specification/v1_0/common_types.json", common)
830            .and_then(|registry| {
831                registry.add("https://a2ui.org/specification/v1_0/catalog.json", catalog)
832            })
833            .and_then(jsonschema::RegistryBuilder::prepare)
834            .unwrap();
835        jsonschema::options().with_registry(&registry).build(&meta).unwrap()
836    }
837
838    struct Gauge;
839
840    impl ExtensionComponent for Gauge {
841        fn name(&self) -> &'static str {
842            "Gauge"
843        }
844        fn schema(&self) -> Value {
845            json!({
846                "type": "object",
847                "allOf": [{ "$ref": "#/$defs/CatalogComponentCommon" }],
848                "properties": {
849                    "id": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/ComponentId" },
850                    "component": { "const": "Gauge" },
851                    "label": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/DynamicString" },
852                    "value": { "type": "number" }
853                },
854                "required": ["id", "component", "label", "value"],
855                "additionalProperties": false
856            })
857        }
858        fn usage(&self) -> &'static str {
859            "Gauge: {label, value} one number on a dial"
860        }
861        fn allowed_parents(&self) -> &'static [&'static str] {
862            &["Card", "Column"]
863        }
864        fn home(&self, _gauge: &ResolvedComponent<'_>) -> Result<HomeNode, String> {
865            Ok(HomeNode::text("gauge"))
866        }
867    }
868
869    #[test]
870    fn catalogs_are_published_as_a2ui_1_0_documents_that_pass_the_1_0_meta_schema() {
871        let meta = v1_0_meta();
872        let forms = Catalog::forms().document_for(A2uiVersion::V1_0);
873        if let Some(error) = meta.iter_errors(&forms).next() {
874            panic!("forms 1.0 document: {error} at {}", error.instance_path());
875        }
876        assert_eq!(forms["functions"].as_object().unwrap().len(), 10);
877        assert!(forms["components"].get("Image").is_none());
878        assert!(forms["functions"].get("openUrl").is_none());
879        assert_eq!(forms["components"]["Text"]["properties"]["variant"]["enum"][2], "h3");
880        assert!(!forms["components"]["TextField"].to_string().contains("obscured"));
881
882        let gauges = Catalog::extend(ExtensionSpec {
883            id: "https://example.com/a2ui/catalogs/gauges/1.0/catalog.json",
884            name: "gauges",
885            version: "1.0",
886            components: vec![Arc::new(Gauge) as Arc<dyn ExtensionComponent>],
887        })
888        .unwrap()
889        .with_instructions("Use a gauge for one number against a known range.");
890        let document = gauges.document_for(A2uiVersion::V1_0);
891        if let Some(error) = meta.iter_errors(&document).next() {
892            panic!("extension 1.0 document: {error} at {}", error.instance_path());
893        }
894        assert_eq!(document["protocolVersion"], "1.0");
895        let gauge = &document["components"]["Gauge"];
896        assert!(document["components"].get("Text").is_none(), "only what the extension adds");
897        assert!(gauge["properties"].get("id").is_none());
898        assert_eq!(gauge["required"], json!(["component", "label", "value"]));
899        assert!(gauge.get("additionalProperties").is_none());
900        assert_eq!(gauge["properties"]["label"]["$ref"], "common_types.json#/$defs/DynamicString");
901        assert!(gauge.get("allOf").is_none(), "the envelope composes ComponentCommon");
902        assert_eq!(gauge["allowedParents"], json!(["Card", "Column"]));
903        assert!(document["instructions"].as_str().unwrap().contains("Gauge: {label, value}"));
904        assert!(document["instructions"].as_str().unwrap().contains("known range"));
905        // v0.9.1 keeps the superset document.
906        assert!(gauges.document_for(A2uiVersion::V0_9_1)["components"]["Text"].is_object());
907    }
908
909    #[test]
910    fn the_forms_catalog_is_the_basic_catalog_without_what_can_fake_a_decision() {
911        let forms = Catalog::forms();
912        assert_eq!(
913            forms.components().collect::<Vec<_>>(),
914            vec![
915                "Button",
916                "Card",
917                "CheckBox",
918                "ChoicePicker",
919                "Column",
920                "DateTimeInput",
921                "Divider",
922                "List",
923                "Row",
924                "Slider",
925                "Tabs",
926                "Text",
927                "TextField"
928            ]
929        );
930        assert_eq!(
931            forms.functions().collect::<Vec<_>>(),
932            vec![
933                "and",
934                "email",
935                "formatString",
936                "length",
937                "not",
938                "numeric",
939                "or",
940                "pluralize",
941                "regex",
942                "required"
943            ]
944        );
945        assert_eq!(forms.document()["catalogId"], FORMS_CATALOG_ID);
946    }
947
948    #[test]
949    fn components_are_checked_against_their_schema() {
950        let forms = Catalog::forms();
951        let text = json!({ "id": "t", "component": "Text", "text": "Invoice INV-10" });
952        assert_eq!(forms.schema_error("Text", &text), None);
953        let bound = json!({ "id": "t", "component": "Text", "text": { "path": "/title" } });
954        assert_eq!(forms.schema_error("Text", &bound), None);
955        let extra = json!({ "id": "t", "component": "Text", "text": "x", "onClick": "y" });
956        assert!(forms.schema_error("Text", &extra).is_some());
957        let obscured = json!({
958            "id": "p", "component": "TextField", "label": "Password", "variant": "obscured"
959        });
960        assert!(forms.schema_error("TextField", &obscured).is_some());
961        let open = json!({
962            "id": "b", "component": "Button", "child": "t",
963            "action": { "functionCall": { "call": "openUrl", "args": { "url": "https://x.test" } } }
964        });
965        assert!(forms.schema_error("Button", &open).is_some(), "openUrl is not in the catalog");
966    }
967
968    #[test]
969    fn a_value_that_may_be_a_binding_or_a_list_names_what_broke_in_the_list() {
970        let forms = Catalog::forms();
971        let picker = json!({
972            "id": "c", "component": "ChoicePicker", "label": "Dock",
973            "options": [{ "label": "Dock 1", "value": "dock-1" }],
974            "value": ["dock-1", 5]
975        });
976        let error = forms.schema_error("ChoicePicker", &picker).expect("a number among strings");
977        assert!(error.starts_with("/value/1: "), "{error}");
978        assert!(!error.contains("oneOf"), "{error}");
979    }
980
981    #[test]
982    fn a_schema_error_quoting_a_long_value_is_shortened() {
983        let forms = Catalog::forms();
984        let long = json!({ "id": "t", "component": "Text", "text": vec![1; 400] });
985        let error = forms.schema_error("Text", &long).expect("a list is not text");
986        assert!(error.chars().count() <= MAX_SCHEMA_ERROR_CHARS + "/text: …".len(), "{error}");
987        assert!(error.ends_with('…'), "{error}");
988    }
989}