1use crate::catalog::Catalog;
16use serde_json::Value;
17use std::collections::{BTreeSet, HashMap};
18use std::sync::OnceLock;
19
20pub 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#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct SchemaError {
34 pub path: String,
36 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#[derive(Debug, Clone, thiserror::Error)]
53#[error("schema does not compile: {0}")]
54pub struct CompileError(pub String);
55
56fn parse(text: &str) -> Value {
57 serde_json::from_str(text).expect("vendored A2UI schema is valid JSON")
60}
61
62struct 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
86struct 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
109fn 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 .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 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
181const 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 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 (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
226fn 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
252const ACTION_FORMS: &[&str] = &["event", "functionCall"];
254
255fn 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
285fn 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 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 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
363pub(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
374const MESSAGE_DEFS: &[(&str, &str)] = &[
377 ("createSurface", "CreateSurfaceMessage"),
378 ("updateComponents", "UpdateComponentsMessage"),
379 ("updateDataModel", "UpdateDataModelMessage"),
380 ("deleteSurface", "DeleteSurfaceMessage"),
381 ("callRendererFunction", "CallRendererFunctionMessage"),
382 ("agentFunctionResponse", "AgentFunctionResponseMessage"),
383];
384
385pub struct SchemaSet {
387 agent_to_renderer: jsonschema::Validator,
388 renderer_to_agent: jsonschema::Validator,
389 kinds: Vec<(&'static str, jsonschema::Validator)>,
393 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 pub fn for_catalog(catalog: &Catalog) -> Result<Self, CompileError> {
407 Self::for_document(catalog.document())
408 }
409
410 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 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 pub fn check_agent_message(&self, message: &Value) -> Result<(), Vec<SchemaError>> {
455 errors(&self.agent_to_renderer, message)
456 }
457
458 pub fn check_function_call(&self, call: &Value) -> Result<(), Vec<SchemaError>> {
461 errors(&self.function_call, call)
462 }
463
464 pub fn check_renderer_message(&self, message: &Value) -> Result<(), Vec<SchemaError>> {
467 errors(&self.renderer_to_agent, message)
468 }
469}
470
471struct 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
493pub fn check_catalog_definition(catalog: &Value) -> Result<(), Vec<SchemaError>> {
495 errors(&fixed().catalog_definition, catalog)
496}
497
498pub fn check_agent_capabilities(value: &Value) -> Result<(), Vec<SchemaError>> {
500 errors(&fixed().agent_capabilities, value)
501}
502
503pub fn check_renderer_capabilities(value: &Value) -> Result<(), Vec<SchemaError>> {
505 errors(&fixed().renderer_capabilities, value)
506}
507
508pub fn check_renderer_data_model(value: &Value) -> Result<(), Vec<SchemaError>> {
510 errors(&fixed().renderer_data_model, value)
511}