Skip to main content

agent86_ui/
schema.rs

1//! The A2UI 1.0 JSON Schemas, vendored from the specification (`spec/`), and the
2//! compiled validators built from them.
3//!
4//! A2UI's envelope schema is catalog-agnostic: a component is checked against
5//! `catalog.json#/$defs/anyComponent`, and `catalog.json` is a placeholder the
6//! validator maps to whichever catalog is in use (the specification's "Swappable
7//! Catalogs & Validation"). [`SchemaSet::for_catalog`] does that mapping, the same
8//! way the specification's own test runner does: the catalog document is served
9//! under the placeholder's URI with its `$id` rewritten to match, so its relative
10//! `common_types.json` references resolve to the protocol's common types.
11//!
12//! Nothing is fetched. Every document a reference can reach is served from memory
13//! by [`MemoryDocs`]; a reference to anything else fails to compile.
14
15use crate::catalog::Catalog;
16use serde_json::Value;
17use std::collections::{BTreeSet, HashMap};
18use std::sync::OnceLock;
19
20/// The base URI the 1.0 schemas' `$id`s share.
21pub const SPEC_BASE: &str = "https://a2ui.org/specification/v1_0/";
22
23const COMMON_TYPES: &str = include_str!("../spec/v1_0/json/common_types.json");
24const AGENT_TO_RENDERER: &str = include_str!("../spec/v1_0/json/agent_to_renderer.json");
25const RENDERER_TO_AGENT: &str = include_str!("../spec/v1_0/json/renderer_to_agent.json");
26const CATALOG_DEFINITION: &str = include_str!("../spec/v1_0/json/catalog_definition.json");
27const AGENT_CAPABILITIES: &str = include_str!("../spec/v1_0/json/agent_capabilities.json");
28const RENDERER_CAPABILITIES: &str = include_str!("../spec/v1_0/json/renderer_capabilities.json");
29const RENDERER_DATA_MODEL: &str = include_str!("../spec/v1_0/json/renderer_data_model.json");
30
31/// One failure from a schema check: where in the checked value, and why.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct SchemaError {
34    /// A JSON Pointer into the checked value (`""` for the value itself).
35    pub path: String,
36    /// The validator's description of the failure.
37    pub message: String,
38}
39
40impl std::fmt::Display for SchemaError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        if self.path.is_empty() {
43            f.write_str(&self.message)
44        } else {
45            write!(f, "{}: {}", self.path, self.message)
46        }
47    }
48}
49
50/// Why a schema could not be compiled: a catalog that refers outside the
51/// documents served, or that is not a valid schema.
52#[derive(Debug, Clone, thiserror::Error)]
53#[error("schema does not compile: {0}")]
54pub struct CompileError(pub String);
55
56fn parse(text: &str) -> Value {
57    // The vendored schemas are checked by this crate's tests; a parse failure is a
58    // packaging fault, not an input error.
59    serde_json::from_str(text).expect("vendored A2UI schema is valid JSON")
60}
61
62/// The vendored schema documents, parsed once.
63struct Docs {
64    common_types: Value,
65    agent_to_renderer: Value,
66    renderer_to_agent: Value,
67    catalog_definition: Value,
68    agent_capabilities: Value,
69    renderer_capabilities: Value,
70    renderer_data_model: Value,
71}
72
73fn docs() -> &'static Docs {
74    static DOCS: OnceLock<Docs> = OnceLock::new();
75    DOCS.get_or_init(|| Docs {
76        common_types: parse(COMMON_TYPES),
77        agent_to_renderer: parse(AGENT_TO_RENDERER),
78        renderer_to_agent: parse(RENDERER_TO_AGENT),
79        catalog_definition: parse(CATALOG_DEFINITION),
80        agent_capabilities: parse(AGENT_CAPABILITIES),
81        renderer_capabilities: parse(RENDERER_CAPABILITIES),
82        renderer_data_model: parse(RENDERER_DATA_MODEL),
83    })
84}
85
86/// Serves schema documents from memory, by URI. The only retriever the
87/// validators ever get, so a reference outside these documents cannot reach the
88/// network or the file system.
89struct MemoryDocs(HashMap<String, Value>);
90
91impl jsonschema::Retrieve for MemoryDocs {
92    fn retrieve(
93        &self,
94        uri: &jsonschema::Uri<String>,
95    ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
96        let key = uri.as_str();
97        let key = key.split('#').next().unwrap_or(key);
98        self.0
99            .get(key)
100            .cloned()
101            .ok_or_else(|| format!("no A2UI schema is served at {key}").into())
102    }
103}
104
105fn uri(name: &str) -> String {
106    format!("{SPEC_BASE}{name}")
107}
108
109/// The documents a validator may reach: the common types, the message schemas,
110/// the catalog definition, and `catalog.json`. `common_types.json` itself refers
111/// to `catalog.json` (a `FunctionCall` is checked against the catalog's
112/// `anyFunction`), so the schemas that take no catalog (the catalog definition,
113/// the capabilities) are given a stand-in that matches nothing; they never reach
114/// it, since none of them checks a function call.
115fn memory(catalog: Option<&Value>) -> MemoryDocs {
116    let d = docs();
117    let catalog = catalog.cloned().unwrap_or_else(|| {
118        serde_json::json!({
119            "$schema": "https://json-schema.org/draft/2020-12/schema",
120            "$id": uri("catalog.json"),
121            "$defs": {"anyComponent": false, "anyFunction": false}
122        })
123    });
124    MemoryDocs(HashMap::from([
125        (uri("common_types.json"), d.common_types.clone()),
126        (uri("agent_to_renderer.json"), d.agent_to_renderer.clone()),
127        (uri("renderer_to_agent.json"), d.renderer_to_agent.clone()),
128        (uri("catalog_definition.json"), d.catalog_definition.clone()),
129        (uri("catalog.json"), catalog),
130    ]))
131}
132
133fn compile(schema: &Value, catalog: Option<&Value>) -> Result<jsonschema::Validator, CompileError> {
134    jsonschema::options()
135        .with_draft(jsonschema::Draft::Draft202012)
136        // The specification's runner validates with ajv-formats, so `format`
137        // (the action's `date-time` timestamp) is asserted, not just annotated.
138        .should_validate_formats(true)
139        .with_retriever(memory(catalog))
140        .build(schema)
141        .map_err(|error| CompileError(error.to_string()))
142}
143
144fn errors(validator: &jsonschema::Validator, value: &Value) -> Result<(), Vec<SchemaError>> {
145    let mut found = Vec::new();
146    let mut unevaluated = Vec::new();
147    for error in validator.iter_errors(value) {
148        if matches!(
149            error.kind(),
150            jsonschema::error::ValidationErrorKind::UnevaluatedProperties { .. }
151        ) {
152            unevaluated.push(SchemaError {
153                path: error.instance_path().to_string(),
154                message: render(&error),
155            });
156        } else {
157            describe(&error, &mut found);
158        }
159    }
160    // When part of an object fails, the properties that part would have
161    // evaluated are reported as unexpected too, valid or not ("label" and
162    // "value" of a TextField whose check is wrong). That complaint only stands
163    // when nothing else failed inside the same object.
164    for error in unevaluated {
165        let inside = |other: &SchemaError| {
166            other.path == error.path || other.path.starts_with(&format!("{}/", error.path))
167        };
168        if !found.iter().any(inside) {
169            found.push(error);
170        }
171    }
172    let mut seen = std::collections::HashSet::new();
173    found.retain(|error| seen.insert((error.path.clone(), error.message.clone())));
174    if found.is_empty() {
175        Ok(())
176    } else {
177        Err(found)
178    }
179}
180
181/// The longest instance a message quotes; a longer one is written as `value`.
182const QUOTE_LIMIT: usize = 60;
183
184fn render(error: &jsonschema::ValidationError<'_>) -> String {
185    use jsonschema::error::ValidationErrorKind;
186    let short = error.instance().to_string().chars().count() <= QUOTE_LIMIT;
187    let text = if short {
188        error.to_string()
189    } else {
190        error.masked().to_string()
191    };
192    // The field a value sits in, when the path ends in a property name, so
193    // the message says which one is wrong.
194    let path = error.instance_path().to_string();
195    let field = path
196        .rsplit('/')
197        .next()
198        .filter(|segment| !segment.is_empty() && segment.parse::<usize>().is_err());
199    match (error.kind(), field) {
200        (ValidationErrorKind::Type { .. }, Some(field)) => {
201            match text.split_once(" is not of type ") {
202                Some((value, expected)) => {
203                    let expected = expected.trim_matches('"');
204                    let article = if expected.starts_with(['a', 'e', 'i', 'o', 'u']) {
205                        "an"
206                    } else {
207                        "a"
208                    };
209                    format!("{field} must be {article} {expected}, not {value}")
210                }
211                None => format!("{field}: {text}"),
212            }
213        }
214        (ValidationErrorKind::Enum { .. }, Some(field)) => format!("{field}: {text}"),
215        // A component missing a property: name its type.
216        (ValidationErrorKind::Required { .. }, _) => {
217            match error.instance().get("component").and_then(Value::as_str) {
218                Some(component) => format!("{text} of {component}"),
219                None => text,
220            }
221        }
222        _ => text,
223    }
224}
225
226/// Whether an error shows a value plainly is not a `oneOf` branch's form:
227/// - a discriminator mismatch, the `const` on a component's `component` or a
228///   function call's `@call` (how a `oneOf` over a catalog's components or
229///   functions rules out the other types);
230/// - at the `oneOf`'s own location, a type mismatch (an object is not the
231///   literal-string branch), a missing `@` key (a `{"@call": ...}` is not the
232///   `{"@path": ...}` branch), or a missing `event` or `functionCall` (an
233///   action's two forms).
234fn rules_out(error: &jsonschema::ValidationError<'_>, at: &str) -> bool {
235    use jsonschema::error::ValidationErrorKind;
236    let path = error.instance_path().to_string();
237    match error.kind() {
238        ValidationErrorKind::Constant { .. } => {
239            path.ends_with("/component") || path.ends_with("/@call")
240        }
241        ValidationErrorKind::Type { .. } => path == at,
242        ValidationErrorKind::Required { property } => {
243            path == at
244                && property
245                    .as_str()
246                    .is_some_and(|name| name.starts_with('@') || ACTION_FORMS.contains(&name))
247        }
248        _ => false,
249    }
250}
251
252/// The keys that tell an action's two forms apart.
253const ACTION_FORMS: &[&str] = &["event", "functionCall"];
254
255/// A value whose discriminator (`component`, `@call`) names no branch of a
256/// `oneOf`: the name it gave, and the names the catalog defines, so the model
257/// can pick one.
258fn unknown_type(context: &[Vec<jsonschema::ValidationError<'static>>]) -> String {
259    use jsonschema::error::ValidationErrorKind;
260    let mut given = None;
261    let mut key = "component";
262    let mut known = BTreeSet::new();
263    for inner in context.iter().flatten() {
264        if let ValidationErrorKind::Constant { expected_value } = inner.kind() {
265            let path = inner.instance_path().to_string();
266            if path.ends_with("/@call") {
267                key = "@call";
268            }
269            given.get_or_insert_with(|| inner.instance().to_string());
270            if let Some(name) = expected_value.as_str() {
271                known.insert(name.to_string());
272            }
273        }
274    }
275    let given = given.unwrap_or_default();
276    let given = given.trim_matches('"');
277    let known = known.into_iter().collect::<Vec<_>>().join(", ");
278    if key == "@call" {
279        format!("Unrecognized function '{given}': the catalog defines no such function; use one of: {known}")
280    } else {
281        format!("Unknown component type '{given}': the catalog defines no such component; use one of: {known}")
282    }
283}
284
285/// Turn a validator error into what a model can act on. A failed `oneOf` or
286/// `anyOf` says only that nothing matched, quoting the whole value. When every
287/// branch but one is plainly not the value's form ([`rules_out`]: a Text checked
288/// against Button's schema, a function call against the binding form), the one
289/// left is what the value meant to be, so its errors are reported instead.
290/// Otherwise the error lists each candidate branch's first complaint, which
291/// names the forms the field allows.
292fn describe(error: &jsonschema::ValidationError<'_>, out: &mut Vec<SchemaError>) {
293    use jsonschema::error::ValidationErrorKind;
294    let path = error.instance_path().to_string();
295    match error.kind() {
296        ValidationErrorKind::OneOfNotValid { context } | ValidationErrorKind::AnyOf { context } => {
297            let mut meant: Vec<&Vec<jsonschema::ValidationError<'static>>> = context
298                .iter()
299                .filter(|branch| !branch.iter().any(|inner| rules_out(inner, &path)))
300                .collect();
301            if let [branch] = meant.as_slice() {
302                // As at the top level: the branch's "unevaluated" complaint stands
303                // only when nothing else in it failed at or inside that place.
304                let unevaluated = |e: &jsonschema::ValidationError<'_>| {
305                    matches!(e.kind(), ValidationErrorKind::UnevaluatedProperties { .. })
306                };
307                for inner in branch.iter() {
308                    if unevaluated(inner) {
309                        let at = inner.instance_path().to_string();
310                        let shadowed = branch.iter().any(|other| {
311                            let path = other.instance_path().to_string();
312                            !unevaluated(other)
313                                && (path == at || path.starts_with(&format!("{at}/")))
314                        });
315                        if shadowed {
316                            continue;
317                        }
318                    }
319                    describe(inner, out);
320                }
321                return;
322            }
323            if meant.is_empty() {
324                if context.iter().all(|branch| {
325                    branch.iter().any(|inner| {
326                        matches!(inner.kind(), ValidationErrorKind::Constant { .. })
327                            && rules_out(inner, &path)
328                    })
329                }) {
330                    out.push(SchemaError {
331                        path,
332                        message: unknown_type(context),
333                    });
334                    return;
335                }
336                meant = context.iter().collect();
337            }
338            let mut forms: Vec<String> = Vec::new();
339            for inner in meant.iter().filter_map(|branch| branch.first()) {
340                let form = inner.masked().to_string();
341                if !forms.contains(&form) {
342                    forms.push(form);
343                }
344            }
345            // Every branch failing the same way (a component with no
346            // `component`) is one problem, said once.
347            let message = match forms.as_slice() {
348                [only] => only.clone(),
349                _ => format!(
350                    "matches none of the forms allowed here ({})",
351                    forms.join("; ")
352                ),
353            };
354            out.push(SchemaError { path, message });
355        }
356        _ => out.push(SchemaError {
357            path,
358            message: render(error),
359        }),
360    }
361}
362
363/// A catalog document as the envelope schema expects to find it: its `$id`
364/// set to the `catalog.json` placeholder, so the references inside it
365/// (`common_types.json#/...` and its own `#/components/...`) resolve.
366pub(crate) fn aliased(catalog: &Value) -> Value {
367    let mut catalog = catalog.clone();
368    if let Some(object) = catalog.as_object_mut() {
369        object.insert("$id".into(), Value::String(uri("catalog.json")));
370    }
371    catalog
372}
373
374/// The agent-to-renderer message kinds and their definitions in
375/// `agent_to_renderer.json`.
376const MESSAGE_DEFS: &[(&str, &str)] = &[
377    ("createSurface", "CreateSurfaceMessage"),
378    ("updateComponents", "UpdateComponentsMessage"),
379    ("updateDataModel", "UpdateDataModelMessage"),
380    ("deleteSurface", "DeleteSurfaceMessage"),
381    ("callRendererFunction", "CallRendererFunctionMessage"),
382    ("agentFunctionResponse", "AgentFunctionResponseMessage"),
383];
384
385/// The message schemas compiled against one catalog.
386pub struct SchemaSet {
387    agent_to_renderer: jsonschema::Validator,
388    renderer_to_agent: jsonschema::Validator,
389    /// One validator per message kind: the same definitions the envelope's
390    /// `oneOf` chooses between, so a message checked against its own kind's
391    /// gets that kind's errors rather than "matches none of the kinds".
392    kinds: Vec<(&'static str, jsonschema::Validator)>,
393    /// A function call against the catalog's `anyFunction`.
394    function_call: jsonschema::Validator,
395}
396
397impl std::fmt::Debug for SchemaSet {
398    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
399        f.debug_struct("SchemaSet").finish_non_exhaustive()
400    }
401}
402
403impl SchemaSet {
404    /// Compile `agent_to_renderer.json` and `renderer_to_agent.json` with
405    /// `catalog.json` mapped to `catalog`.
406    pub fn for_catalog(catalog: &Catalog) -> Result<Self, CompileError> {
407        Self::for_document(catalog.document())
408    }
409
410    /// As [`SchemaSet::for_catalog`], from a catalog's JSON document as it is,
411    /// unchecked. For the specification's tests, which pair messages with
412    /// catalogs; use [`SchemaSet::for_catalog`] otherwise.
413    pub fn for_document(catalog: &Value) -> Result<Self, CompileError> {
414        let catalog = aliased(catalog);
415        let d = docs();
416        let kinds = MESSAGE_DEFS
417            .iter()
418            .map(|(kind, def)| {
419                let schema = serde_json::json!({
420                    "$ref": format!("{}#/$defs/{def}", uri("agent_to_renderer.json"))
421                });
422                Ok((*kind, compile(&schema, Some(&catalog))?))
423            })
424            .collect::<Result<_, CompileError>>()?;
425        let any_function = serde_json::json!({
426            "$ref": format!("{}#/$defs/anyFunction", uri("catalog.json"))
427        });
428        Ok(Self {
429            agent_to_renderer: compile(&d.agent_to_renderer, Some(&catalog))?,
430            renderer_to_agent: compile(&d.renderer_to_agent, Some(&catalog))?,
431            kinds,
432            function_call: compile(&any_function, Some(&catalog))?,
433        })
434    }
435
436    /// Check a message against one kind's definition (`"createSurface"`, ...).
437    /// Valid exactly when [`SchemaSet::check_agent_message`] is for a message
438    /// holding that kind's key, with errors about that kind only.
439    pub fn check_agent_message_as(
440        &self,
441        kind: &str,
442        message: &Value,
443    ) -> Result<(), Vec<SchemaError>> {
444        match self.kinds.iter().find(|(name, _)| *name == kind) {
445            Some((_, validator)) => errors(validator, message),
446            None => self.check_agent_message(message),
447        }
448    }
449
450    /// Check one agent-to-renderer message against the envelope schema and the
451    /// catalog. This is the schema half of validation only: whether a surface
452    /// exists, whether `root` is there, and the composition rules are checked by
453    /// [`crate::Validator`].
454    pub fn check_agent_message(&self, message: &Value) -> Result<(), Vec<SchemaError>> {
455        errors(&self.agent_to_renderer, message)
456    }
457
458    /// Check one function call (`{"@call": ..., "args": ...}`) against this
459    /// catalog's functions: that it names one, and its arguments.
460    pub fn check_function_call(&self, call: &Value) -> Result<(), Vec<SchemaError>> {
461        errors(&self.function_call, call)
462    }
463
464    /// Check one renderer-to-agent message (an action, a function call or
465    /// response, an error).
466    pub fn check_renderer_message(&self, message: &Value) -> Result<(), Vec<SchemaError>> {
467        errors(&self.renderer_to_agent, message)
468    }
469}
470
471/// The schemas that need no catalog, compiled once.
472struct Fixed {
473    catalog_definition: jsonschema::Validator,
474    agent_capabilities: jsonschema::Validator,
475    renderer_capabilities: jsonschema::Validator,
476    renderer_data_model: jsonschema::Validator,
477}
478
479fn fixed() -> &'static Fixed {
480    static FIXED: OnceLock<Fixed> = OnceLock::new();
481    FIXED.get_or_init(|| {
482        let d = docs();
483        let build = |schema: &Value| compile(schema, None).expect("vendored A2UI schema compiles");
484        Fixed {
485            catalog_definition: build(&d.catalog_definition),
486            agent_capabilities: build(&d.agent_capabilities),
487            renderer_capabilities: build(&d.renderer_capabilities),
488            renderer_data_model: build(&d.renderer_data_model),
489        }
490    })
491}
492
493/// Check a catalog document against `catalog_definition.json`.
494pub fn check_catalog_definition(catalog: &Value) -> Result<(), Vec<SchemaError>> {
495    errors(&fixed().catalog_definition, catalog)
496}
497
498/// Check an agent capabilities object (`{"1.0": {...}}`).
499pub fn check_agent_capabilities(value: &Value) -> Result<(), Vec<SchemaError>> {
500    errors(&fixed().agent_capabilities, value)
501}
502
503/// Check a renderer capabilities object (`{"1.0": {"supportedCatalogIds": [...]}}`).
504pub fn check_renderer_capabilities(value: &Value) -> Result<(), Vec<SchemaError>> {
505    errors(&fixed().renderer_capabilities, value)
506}
507
508/// Check a renderer data model message (`{"version": "1.0", "surfaces": {...}}`).
509pub fn check_renderer_data_model(value: &Value) -> Result<(), Vec<SchemaError>> {
510    errors(&fixed().renderer_data_model, value)
511}