use crate::catalog::Catalog;
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
use std::sync::OnceLock;
pub const SPEC_BASE: &str = "https://a2ui.org/specification/v1_0/";
const COMMON_TYPES: &str = include_str!("../spec/v1_0/json/common_types.json");
const AGENT_TO_RENDERER: &str = include_str!("../spec/v1_0/json/agent_to_renderer.json");
const RENDERER_TO_AGENT: &str = include_str!("../spec/v1_0/json/renderer_to_agent.json");
const CATALOG_DEFINITION: &str = include_str!("../spec/v1_0/json/catalog_definition.json");
const AGENT_CAPABILITIES: &str = include_str!("../spec/v1_0/json/agent_capabilities.json");
const RENDERER_CAPABILITIES: &str = include_str!("../spec/v1_0/json/renderer_capabilities.json");
const RENDERER_DATA_MODEL: &str = include_str!("../spec/v1_0/json/renderer_data_model.json");
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaError {
pub path: String,
pub message: String,
}
impl std::fmt::Display for SchemaError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.path.is_empty() {
f.write_str(&self.message)
} else {
write!(f, "{}: {}", self.path, self.message)
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
#[error("schema does not compile: {0}")]
pub struct CompileError(pub String);
fn parse(text: &str) -> Value {
serde_json::from_str(text).expect("vendored A2UI schema is valid JSON")
}
struct Docs {
common_types: Value,
agent_to_renderer: Value,
renderer_to_agent: Value,
catalog_definition: Value,
agent_capabilities: Value,
renderer_capabilities: Value,
renderer_data_model: Value,
}
fn docs() -> &'static Docs {
static DOCS: OnceLock<Docs> = OnceLock::new();
DOCS.get_or_init(|| Docs {
common_types: parse(COMMON_TYPES),
agent_to_renderer: parse(AGENT_TO_RENDERER),
renderer_to_agent: parse(RENDERER_TO_AGENT),
catalog_definition: parse(CATALOG_DEFINITION),
agent_capabilities: parse(AGENT_CAPABILITIES),
renderer_capabilities: parse(RENDERER_CAPABILITIES),
renderer_data_model: parse(RENDERER_DATA_MODEL),
})
}
struct MemoryDocs(HashMap<String, Value>);
impl jsonschema::Retrieve for MemoryDocs {
fn retrieve(
&self,
uri: &jsonschema::Uri<String>,
) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
let key = uri.as_str();
let key = key.split('#').next().unwrap_or(key);
self.0
.get(key)
.cloned()
.ok_or_else(|| format!("no A2UI schema is served at {key}").into())
}
}
fn uri(name: &str) -> String {
format!("{SPEC_BASE}{name}")
}
fn memory(catalog: Option<&Value>) -> MemoryDocs {
let d = docs();
let catalog = catalog.cloned().unwrap_or_else(|| {
serde_json::json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": uri("catalog.json"),
"$defs": {"anyComponent": false, "anyFunction": false}
})
});
MemoryDocs(HashMap::from([
(uri("common_types.json"), d.common_types.clone()),
(uri("agent_to_renderer.json"), d.agent_to_renderer.clone()),
(uri("renderer_to_agent.json"), d.renderer_to_agent.clone()),
(uri("catalog_definition.json"), d.catalog_definition.clone()),
(uri("catalog.json"), catalog),
]))
}
fn compile(schema: &Value, catalog: Option<&Value>) -> Result<jsonschema::Validator, CompileError> {
jsonschema::options()
.with_draft(jsonschema::Draft::Draft202012)
.should_validate_formats(true)
.with_retriever(memory(catalog))
.build(schema)
.map_err(|error| CompileError(error.to_string()))
}
fn errors(validator: &jsonschema::Validator, value: &Value) -> Result<(), Vec<SchemaError>> {
let mut found = Vec::new();
let mut unevaluated = Vec::new();
for error in validator.iter_errors(value) {
if matches!(
error.kind(),
jsonschema::error::ValidationErrorKind::UnevaluatedProperties { .. }
) {
unevaluated.push(SchemaError {
path: error.instance_path().to_string(),
message: render(&error),
});
} else {
describe(&error, &mut found);
}
}
for error in unevaluated {
let inside = |other: &SchemaError| {
other.path == error.path || other.path.starts_with(&format!("{}/", error.path))
};
if !found.iter().any(inside) {
found.push(error);
}
}
let mut seen = std::collections::HashSet::new();
found.retain(|error| seen.insert((error.path.clone(), error.message.clone())));
if found.is_empty() {
Ok(())
} else {
Err(found)
}
}
const QUOTE_LIMIT: usize = 60;
fn render(error: &jsonschema::ValidationError<'_>) -> String {
use jsonschema::error::ValidationErrorKind;
let short = error.instance().to_string().chars().count() <= QUOTE_LIMIT;
let text = if short {
error.to_string()
} else {
error.masked().to_string()
};
let path = error.instance_path().to_string();
let field = path
.rsplit('/')
.next()
.filter(|segment| !segment.is_empty() && segment.parse::<usize>().is_err());
match (error.kind(), field) {
(ValidationErrorKind::Type { .. }, Some(field)) => {
match text.split_once(" is not of type ") {
Some((value, expected)) => {
let expected = expected.trim_matches('"');
let article = if expected.starts_with(['a', 'e', 'i', 'o', 'u']) {
"an"
} else {
"a"
};
format!("{field} must be {article} {expected}, not {value}")
}
None => format!("{field}: {text}"),
}
}
(ValidationErrorKind::Enum { .. }, Some(field)) => format!("{field}: {text}"),
(ValidationErrorKind::Required { .. }, _) => {
match error.instance().get("component").and_then(Value::as_str) {
Some(component) => format!("{text} of {component}"),
None => text,
}
}
_ => text,
}
}
fn rules_out(error: &jsonschema::ValidationError<'_>, at: &str) -> bool {
use jsonschema::error::ValidationErrorKind;
let path = error.instance_path().to_string();
match error.kind() {
ValidationErrorKind::Constant { .. } => {
path.ends_with("/component") || path.ends_with("/@call")
}
ValidationErrorKind::Type { .. } => path == at,
ValidationErrorKind::Required { property } => {
path == at
&& property
.as_str()
.is_some_and(|name| name.starts_with('@') || ACTION_FORMS.contains(&name))
}
_ => false,
}
}
const ACTION_FORMS: &[&str] = &["event", "functionCall"];
fn unknown_type(context: &[Vec<jsonschema::ValidationError<'static>>]) -> String {
use jsonschema::error::ValidationErrorKind;
let mut given = None;
let mut key = "component";
let mut known = BTreeSet::new();
for inner in context.iter().flatten() {
if let ValidationErrorKind::Constant { expected_value } = inner.kind() {
let path = inner.instance_path().to_string();
if path.ends_with("/@call") {
key = "@call";
}
given.get_or_insert_with(|| inner.instance().to_string());
if let Some(name) = expected_value.as_str() {
known.insert(name.to_string());
}
}
}
let given = given.unwrap_or_default();
let given = given.trim_matches('"');
let known = known.into_iter().collect::<Vec<_>>().join(", ");
if key == "@call" {
format!("Unrecognized function '{given}': the catalog defines no such function; use one of: {known}")
} else {
format!("Unknown component type '{given}': the catalog defines no such component; use one of: {known}")
}
}
fn describe(error: &jsonschema::ValidationError<'_>, out: &mut Vec<SchemaError>) {
use jsonschema::error::ValidationErrorKind;
let path = error.instance_path().to_string();
match error.kind() {
ValidationErrorKind::OneOfNotValid { context } | ValidationErrorKind::AnyOf { context } => {
let mut meant: Vec<&Vec<jsonschema::ValidationError<'static>>> = context
.iter()
.filter(|branch| !branch.iter().any(|inner| rules_out(inner, &path)))
.collect();
if let [branch] = meant.as_slice() {
let unevaluated = |e: &jsonschema::ValidationError<'_>| {
matches!(e.kind(), ValidationErrorKind::UnevaluatedProperties { .. })
};
for inner in branch.iter() {
if unevaluated(inner) {
let at = inner.instance_path().to_string();
let shadowed = branch.iter().any(|other| {
let path = other.instance_path().to_string();
!unevaluated(other)
&& (path == at || path.starts_with(&format!("{at}/")))
});
if shadowed {
continue;
}
}
describe(inner, out);
}
return;
}
if meant.is_empty() {
if context.iter().all(|branch| {
branch.iter().any(|inner| {
matches!(inner.kind(), ValidationErrorKind::Constant { .. })
&& rules_out(inner, &path)
})
}) {
out.push(SchemaError {
path,
message: unknown_type(context),
});
return;
}
meant = context.iter().collect();
}
let mut forms: Vec<String> = Vec::new();
for inner in meant.iter().filter_map(|branch| branch.first()) {
let form = inner.masked().to_string();
if !forms.contains(&form) {
forms.push(form);
}
}
let message = match forms.as_slice() {
[only] => only.clone(),
_ => format!(
"matches none of the forms allowed here ({})",
forms.join("; ")
),
};
out.push(SchemaError { path, message });
}
_ => out.push(SchemaError {
path,
message: render(error),
}),
}
}
pub(crate) fn aliased(catalog: &Value) -> Value {
let mut catalog = catalog.clone();
if let Some(object) = catalog.as_object_mut() {
object.insert("$id".into(), Value::String(uri("catalog.json")));
}
catalog
}
const MESSAGE_DEFS: &[(&str, &str)] = &[
("createSurface", "CreateSurfaceMessage"),
("updateComponents", "UpdateComponentsMessage"),
("updateDataModel", "UpdateDataModelMessage"),
("deleteSurface", "DeleteSurfaceMessage"),
("callRendererFunction", "CallRendererFunctionMessage"),
("agentFunctionResponse", "AgentFunctionResponseMessage"),
];
pub struct SchemaSet {
agent_to_renderer: jsonschema::Validator,
renderer_to_agent: jsonschema::Validator,
kinds: Vec<(&'static str, jsonschema::Validator)>,
function_call: jsonschema::Validator,
}
impl std::fmt::Debug for SchemaSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SchemaSet").finish_non_exhaustive()
}
}
impl SchemaSet {
pub fn for_catalog(catalog: &Catalog) -> Result<Self, CompileError> {
Self::for_document(catalog.document())
}
pub fn for_document(catalog: &Value) -> Result<Self, CompileError> {
let catalog = aliased(catalog);
let d = docs();
let kinds = MESSAGE_DEFS
.iter()
.map(|(kind, def)| {
let schema = serde_json::json!({
"$ref": format!("{}#/$defs/{def}", uri("agent_to_renderer.json"))
});
Ok((*kind, compile(&schema, Some(&catalog))?))
})
.collect::<Result<_, CompileError>>()?;
let any_function = serde_json::json!({
"$ref": format!("{}#/$defs/anyFunction", uri("catalog.json"))
});
Ok(Self {
agent_to_renderer: compile(&d.agent_to_renderer, Some(&catalog))?,
renderer_to_agent: compile(&d.renderer_to_agent, Some(&catalog))?,
kinds,
function_call: compile(&any_function, Some(&catalog))?,
})
}
pub fn check_agent_message_as(
&self,
kind: &str,
message: &Value,
) -> Result<(), Vec<SchemaError>> {
match self.kinds.iter().find(|(name, _)| *name == kind) {
Some((_, validator)) => errors(validator, message),
None => self.check_agent_message(message),
}
}
pub fn check_agent_message(&self, message: &Value) -> Result<(), Vec<SchemaError>> {
errors(&self.agent_to_renderer, message)
}
pub fn check_function_call(&self, call: &Value) -> Result<(), Vec<SchemaError>> {
errors(&self.function_call, call)
}
pub fn check_renderer_message(&self, message: &Value) -> Result<(), Vec<SchemaError>> {
errors(&self.renderer_to_agent, message)
}
}
struct Fixed {
catalog_definition: jsonschema::Validator,
agent_capabilities: jsonschema::Validator,
renderer_capabilities: jsonschema::Validator,
renderer_data_model: jsonschema::Validator,
}
fn fixed() -> &'static Fixed {
static FIXED: OnceLock<Fixed> = OnceLock::new();
FIXED.get_or_init(|| {
let d = docs();
let build = |schema: &Value| compile(schema, None).expect("vendored A2UI schema compiles");
Fixed {
catalog_definition: build(&d.catalog_definition),
agent_capabilities: build(&d.agent_capabilities),
renderer_capabilities: build(&d.renderer_capabilities),
renderer_data_model: build(&d.renderer_data_model),
}
})
}
pub fn check_catalog_definition(catalog: &Value) -> Result<(), Vec<SchemaError>> {
errors(&fixed().catalog_definition, catalog)
}
pub fn check_agent_capabilities(value: &Value) -> Result<(), Vec<SchemaError>> {
errors(&fixed().agent_capabilities, value)
}
pub fn check_renderer_capabilities(value: &Value) -> Result<(), Vec<SchemaError>> {
errors(&fixed().renderer_capabilities, value)
}
pub fn check_renderer_data_model(value: &Value) -> Result<(), Vec<SchemaError>> {
errors(&fixed().renderer_data_model, value)
}