Skip to main content

agent86_ui/
validate.rs

1//! Validation of what an agent sends, as the agent's side of A2UI's
2//! "prompt, generate, validate" loop: the schema check, then the rules a schema
3//! cannot express, against the surfaces earlier messages created.
4//!
5//! [`Validator::check`] takes a batch of messages (one model tool call, say) and
6//! reports every problem it finds; [`Validator::apply`] does the same and, when
7//! there are no errors, records the batch's effect on the surfaces, so the next
8//! batch is checked against them. A batch is all or nothing.
9//!
10//! Errors use the specification's codes and paths, so they can go back to the
11//! model as the standard validation error format. Warnings are things a renderer
12//! tolerates (a child not defined yet renders as a placeholder) but a model
13//! probably did not mean.
14
15use crate::catalog::{Callers, Catalog, ChildRef, ComponentDef};
16use crate::ident::is_identifier;
17use crate::message::AgentMessage;
18use crate::schema::{CompileError, SchemaError, SchemaSet};
19use serde_json::{Map, Value};
20use std::collections::{BTreeMap, BTreeSet};
21
22/// The specification's error codes that agent-side validation reports.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum Code {
26    /// The message or a component does not match the schema or a rule.
27    ValidationFailed,
28    /// A component sits under a parent its `allowedParents` does not name.
29    UnallowedParent,
30    /// A container holds a child its `allowedChildren` does not name.
31    UnallowedChild,
32    /// The message does not fit the surfaces' state (a surface created twice,
33    /// or one updated before it exists).
34    IntegrityError,
35    /// A `callRendererFunction` the renderer would refuse.
36    InvalidFunctionCall,
37    /// A dynamic value cannot be evaluated: a template that does not parse,
38    /// `@index` outside a list template, a function that cannot be resolved
39    /// (found by [`crate::runtime::Runtime`], which evaluates the surface).
40    ExpressionError,
41    /// An `updateDataModel` write the path does not allow (through a string,
42    /// a non-numeric segment on an array). Sent on the wire as
43    /// `VALIDATION_FAILED`, the code for a message field that fails.
44    DataError,
45    /// A limit the reference SDKs share was passed: values nested more than
46    /// [`MAX_DEPTH`] deep, components more than [`MAX_DEPTH`] below `root`,
47    /// function calls nested more than [`MAX_CALL_DEPTH`] deep, or components
48    /// that refer to each other in a cycle. Sent as `RECURSION_LIMIT_EXCEEDED`,
49    /// the reference SDKs' code; the specification leaves codes other than its
50    /// three validation ones open.
51    RecursionLimitExceeded,
52    /// A component or a function call resolves to no catalog this renderer
53    /// has: the one it names is not supported, or it names none and its surface
54    /// has no default. Sent as `CATALOG_NOT_FOUND`, the reference SDKs' code.
55    CatalogNotFound,
56}
57
58/// How deep values may nest in a message, and components below `root`, as in
59/// the reference SDKs.
60pub const MAX_DEPTH: usize = 50;
61
62/// How deep function calls may nest, as in the reference SDKs.
63pub const MAX_CALL_DEPTH: usize = 5;
64
65impl Code {
66    /// The code as the specification writes it.
67    pub fn as_str(self) -> &'static str {
68        match self {
69            Code::ValidationFailed => "VALIDATION_FAILED",
70            Code::UnallowedParent => "UNALLOWED_PARENT",
71            Code::UnallowedChild => "UNALLOWED_CHILD",
72            Code::IntegrityError => "INTEGRITY_ERROR",
73            Code::InvalidFunctionCall => "INVALID_FUNCTION_CALL",
74            Code::ExpressionError => "EXPRESSION_ERROR",
75            Code::DataError => "VALIDATION_FAILED",
76            Code::RecursionLimitExceeded => "RECURSION_LIMIT_EXCEEDED",
77            Code::CatalogNotFound => "CATALOG_NOT_FOUND",
78        }
79    }
80}
81
82impl std::fmt::Display for Code {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.write_str(self.as_str())
85    }
86}
87
88/// One problem found in a batch.
89#[derive(Debug, Clone, PartialEq, Eq)]
90#[non_exhaustive]
91pub struct Problem {
92    /// The specification's code.
93    pub code: Code,
94    /// The surface it concerns, when there is one.
95    pub surface_id: Option<String>,
96    /// A JSON Pointer into the batch (`/0/createSurface/components/2/text`),
97    /// or `""` for a problem with no single location.
98    pub path: String,
99    /// One sentence on what is wrong.
100    pub message: String,
101}
102
103impl std::fmt::Display for Problem {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        write!(f, "{}", self.code)?;
106        if !self.path.is_empty() {
107            write!(f, " at {}", self.path)?;
108        }
109        write!(f, ": {}", self.message)
110    }
111}
112
113/// What [`Validator::check`] found.
114#[derive(Debug, Clone, Default, PartialEq)]
115#[non_exhaustive]
116pub struct Report {
117    /// Problems that make the batch invalid.
118    pub errors: Vec<Problem>,
119    /// Problems a renderer tolerates.
120    pub warnings: Vec<Problem>,
121    /// The batch as typed messages, when it has no errors.
122    pub messages: Vec<AgentMessage>,
123}
124
125impl Report {
126    /// Whether the batch is valid.
127    pub fn is_ok(&self) -> bool {
128        self.errors.is_empty()
129    }
130}
131
132/// How strictly a surface's component tree must be complete once a batch is
133/// applied: the reference SDKs' `ValidationConfig`, without its version and
134/// message filters.
135///
136/// [`Rules::STRICT`] (the default, as in the reference SDKs) makes each problem
137/// an error, which suits a batch that is meant to be whole (one tool call).
138/// [`Rules::RELAXED`] makes each a warning, for a renderer drawing a stream that
139/// is completed later. A cycle or a broken composition rule is an error either
140/// way.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub struct Rules {
144    /// A surface with components but none with id `root` is accepted.
145    pub allow_missing_root: bool,
146    /// A component may refer to a child that is not defined.
147    pub allow_dangling_references: bool,
148    /// A component nothing reachable from `root` shows is accepted.
149    pub allow_orphans: bool,
150}
151
152impl Rules {
153    /// Every problem is an error.
154    pub const STRICT: Rules = Rules {
155        allow_missing_root: false,
156        allow_dangling_references: false,
157        allow_orphans: false,
158    };
159    /// Every problem is a warning.
160    pub const RELAXED: Rules = Rules {
161        allow_missing_root: true,
162        allow_dangling_references: true,
163        allow_orphans: true,
164    };
165    /// These rules with a missing root allowed or not.
166    pub const fn allowing_missing_root(mut self, allow: bool) -> Self {
167        self.allow_missing_root = allow;
168        self
169    }
170
171    /// These rules with dangling references allowed or not.
172    pub const fn allowing_dangling_references(mut self, allow: bool) -> Self {
173        self.allow_dangling_references = allow;
174        self
175    }
176
177    /// These rules with orphans allowed or not.
178    pub const fn allowing_orphans(mut self, allow: bool) -> Self {
179        self.allow_orphans = allow;
180        self
181    }
182}
183
184impl Default for Rules {
185    fn default() -> Self {
186        Rules::STRICT
187    }
188}
189
190/// What the validator remembers about a surface.
191#[derive(Debug, Clone, Default)]
192struct Surface {
193    catalog_id: Option<String>,
194    components: BTreeMap<String, Value>,
195}
196
197struct Entry {
198    catalog: Catalog,
199    schemas: SchemaSet,
200}
201
202/// The agent's view of a renderer: the catalogs it supports and the surfaces
203/// sent to it so far.
204pub struct Validator {
205    catalogs: Vec<Entry>,
206    surfaces: BTreeMap<String, Surface>,
207    rules: Rules,
208}
209
210impl std::fmt::Debug for Validator {
211    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        f.debug_struct("Validator")
213            .field("catalogs", &self.supported_catalog_ids())
214            .field("surfaces", &self.surfaces.keys().collect::<Vec<_>>())
215            .finish()
216    }
217}
218
219/// Message kinds of A2UI 0.8 and 0.9 that 1.0 renamed or dropped, named in
220/// the error so a model trained on them sees why.
221const LEGACY_KINDS: &[&str] = &[
222    "beginRendering",
223    "surfaceUpdate",
224    "dataModelUpdate",
225    "updateSurface",
226];
227
228const KINDS: &[&str] = &[
229    "createSurface",
230    "updateComponents",
231    "updateDataModel",
232    "deleteSurface",
233    "callRendererFunction",
234    "agentFunctionResponse",
235];
236
237pub(crate) fn problem(
238    code: Code,
239    surface: Option<&str>,
240    path: String,
241    message: impl Into<String>,
242) -> Problem {
243    Problem {
244        code,
245        surface_id: surface.map(String::from),
246        path,
247        message: message.into(),
248    }
249}
250
251/// Escape one JSON Pointer segment.
252fn segment(key: &str) -> String {
253    key.replace('~', "~0").replace('/', "~1")
254}
255
256impl Validator {
257    /// A validator for a renderer that supports `catalogs`. The first is used
258    /// to check messages that name no catalog (a function response).
259    pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Result<Self, CompileError> {
260        let catalogs = catalogs
261            .into_iter()
262            .map(|catalog| {
263                let schemas = SchemaSet::for_catalog(&catalog)?;
264                Ok(Entry { catalog, schemas })
265            })
266            .collect::<Result<Vec<_>, CompileError>>()?;
267        Ok(Self {
268            catalogs,
269            surfaces: BTreeMap::new(),
270            rules: Rules::default(),
271        })
272    }
273
274    /// The completeness rules batches are checked under from now on.
275    pub fn set_rules(&mut self, rules: Rules) {
276        self.rules = rules;
277    }
278
279    /// The completeness rules in force.
280    pub fn rules(&self) -> Rules {
281        self.rules
282    }
283
284    /// A validator for a renderer that supports the basic catalog only.
285    pub fn basic() -> Self {
286        Self::new([Catalog::basic().clone()]).expect("the basic catalog compiles")
287    }
288
289    /// The ids of the catalogs this renderer supports, in the order given.
290    pub fn supported_catalog_ids(&self) -> Vec<&str> {
291        self.catalogs
292            .iter()
293            .map(|entry| entry.catalog.id())
294            .collect()
295    }
296
297    /// The catalogs this renderer supports.
298    pub fn catalogs(&self) -> impl Iterator<Item = &Catalog> {
299        self.catalogs.iter().map(|entry| &entry.catalog)
300    }
301
302    /// The surfaces created and not deleted, as of the last applied batch.
303    pub fn surface_ids(&self) -> impl Iterator<Item = &str> {
304        self.surfaces.keys().map(String::as_str)
305    }
306
307    /// Forget every surface (the renderer was reset).
308    pub fn clear(&mut self) {
309        self.surfaces.clear();
310    }
311
312    fn entry(&self, id: &str) -> Option<&Entry> {
313        self.catalogs.iter().find(|entry| entry.catalog.id() == id)
314    }
315
316    /// Check a batch without recording it.
317    pub fn check(&self, messages: &[Value]) -> Report {
318        self.run(messages).0
319    }
320
321    /// [`Validator::check`], with the batch as checked: each component's
322    /// legacy envelope keys (`catalogId`, `metadata`, `accessibility`, `checks`
323    /// where its schema does not declare them) moved to their `@` spellings.
324    pub(crate) fn check_normalized(&self, messages: &[Value]) -> (Report, Vec<Value>) {
325        let (report, _, normalized) = self.run(messages);
326        (report, normalized)
327    }
328
329    /// Check a batch and, when it has no errors, record its effect on the
330    /// surfaces.
331    pub fn apply(&mut self, messages: &[Value]) -> Report {
332        let (report, surfaces, _) = self.run(messages);
333        if report.is_ok() {
334            self.surfaces = surfaces;
335        }
336        report
337    }
338
339    fn run(&self, messages: &[Value]) -> (Report, BTreeMap<String, Surface>, Vec<Value>) {
340        let mut state = self.surfaces.clone();
341        let mut report = Report::default();
342        // Where each component of a touched surface was last defined in this
343        // batch, so tree problems can point at it.
344        let mut origins: BTreeMap<(String, String), String> = BTreeMap::new();
345        let mut touched = BTreeSet::new();
346        let mut normalized = Vec::with_capacity(messages.len());
347
348        for (index, raw) in messages.iter().enumerate() {
349            let prefix = format!("/{index}");
350            let before = report.errors.len();
351            // Limits and path syntax first, over the raw message: a value nested
352            // too deep is not worth a schema check.
353            if let Err(problem) = limits_and_paths(raw, &prefix, 1, 0) {
354                report.errors.push(problem);
355                normalized.push(raw.clone());
356                continue;
357            }
358            let message = self.normalize(raw, &prefix, &state, &mut report);
359            let raw = &message;
360            self.check_message(
361                raw,
362                &prefix,
363                &mut state,
364                &mut report,
365                &mut origins,
366                &mut touched,
367            );
368            if report.errors.len() == before {
369                match serde_json::from_value::<AgentMessage>(raw.clone()) {
370                    Ok(message) => report.messages.push(message),
371                    Err(error) => report.errors.push(problem(
372                        Code::ValidationFailed,
373                        None,
374                        prefix,
375                        format!("message does not parse: {error}"),
376                    )),
377                }
378            }
379            normalized.push(message);
380        }
381
382        for surface_id in &touched {
383            if let Some(surface) = state.get(surface_id) {
384                self.check_tree(surface_id, surface, &origins, &mut report);
385            }
386        }
387        if !report.is_ok() {
388            report.messages.clear();
389        }
390        (report, state, normalized)
391    }
392
393    /// A message with each component's legacy envelope keys moved to their `@`
394    /// spellings, as renderers accept them during the 1.0 transition (the
395    /// specification's evolution guide): a bare `catalogId` the component's
396    /// schema in the surface's default catalog does not declare routes it like
397    /// `@catalogId`, and a bare `metadata`, `accessibility`, or `checks` its
398    /// schema in the catalog it resolves to does not declare is that `@` key. A
399    /// component carrying both spellings of one is refused. A declared property
400    /// is the component's own and stays as it is.
401    fn normalize(
402        &self,
403        raw: &Value,
404        prefix: &str,
405        state: &BTreeMap<String, Surface>,
406        report: &mut Report,
407    ) -> Value {
408        let mut message = raw.clone();
409        for kind in ["createSurface", "updateComponents"] {
410            let Some(body) = message.get_mut(kind) else {
411                continue;
412            };
413            let default = match kind {
414                "createSurface" => body
415                    .get("catalogId")
416                    .and_then(Value::as_str)
417                    .map(String::from),
418                _ => body
419                    .get("surfaceId")
420                    .and_then(Value::as_str)
421                    .and_then(|id| state.get(id))
422                    .and_then(|surface| surface.catalog_id.clone()),
423            };
424            let surface = body
425                .get("surfaceId")
426                .and_then(Value::as_str)
427                .map(String::from);
428            let Some(components) = body.get_mut("components").and_then(Value::as_array_mut) else {
429                continue;
430            };
431            for (index, component) in components.iter_mut().enumerate() {
432                let Some(object) = component.as_object_mut() else {
433                    continue;
434                };
435                let at = format!("{prefix}/{kind}/components/{index}");
436                let type_name = object
437                    .get("component")
438                    .and_then(Value::as_str)
439                    .unwrap_or_default()
440                    .to_string();
441                let declares = |catalog: Option<&str>, key: &str| {
442                    catalog
443                        .and_then(|id| self.entry(id))
444                        .is_some_and(|entry| entry.catalog.declares_own(&type_name, key))
445                };
446                let legacy = |object: &mut Map<String, Value>,
447                              key: &str,
448                              declared: bool,
449                              report: &mut Report| {
450                    if declared || !object.contains_key(key) {
451                        return;
452                    }
453                    let prefixed = format!("@{key}");
454                    if object.contains_key(&prefixed) {
455                        report.errors.push(problem(
456                            Code::ValidationFailed,
457                            surface.as_deref(),
458                            format!("{at}/{key}"),
459                            format!(
460                                "this component has both {key} and {prefixed}; write only {prefixed}"
461                            ),
462                        ));
463                        // Said once: the bare key's schema complaint would only
464                        // repeat it.
465                        object.remove(key);
466                    } else if let Some(value) = object.remove(key) {
467                        object.insert(prefixed, value);
468                    }
469                };
470                let declared = declares(default.as_deref(), "catalogId");
471                legacy(object, "catalogId", declared, report);
472                let resolved = object
473                    .get("@catalogId")
474                    .and_then(Value::as_str)
475                    .map(String::from)
476                    .or_else(|| default.clone());
477                for key in ["metadata", "accessibility", "checks"] {
478                    let declared = declares(resolved.as_deref(), key);
479                    legacy(object, key, declared, report);
480                }
481            }
482        }
483        message
484    }
485
486    #[allow(clippy::too_many_arguments)]
487    fn check_message(
488        &self,
489        raw: &Value,
490        prefix: &str,
491        state: &mut BTreeMap<String, Surface>,
492        report: &mut Report,
493        origins: &mut BTreeMap<(String, String), String>,
494        touched: &mut BTreeSet<String>,
495    ) {
496        // The version first: a message for another protocol version is not
497        // worth reading further, and this check needs no catalog.
498        match raw.get("version") {
499            Some(Value::String(version)) if version == crate::PROTOCOL_VERSION => {}
500            None => {
501                report.errors.push(problem(
502                    Code::ValidationFailed,
503                    None,
504                    prefix.to_string(),
505                    "Missing required version field: every message needs \"version\": \"1.0\"",
506                ));
507                return;
508            }
509            Some(version) => {
510                let shown = version
511                    .as_str()
512                    .map_or_else(|| version.to_string(), String::from);
513                report.errors.push(problem(
514                    Code::ValidationFailed,
515                    None,
516                    format!("{prefix}/version"),
517                    format!(
518                        "Unsupported protocol version '{shown}': this renderer speaks A2UI 1.0, so set \"version\": \"1.0\""
519                    ),
520                ));
521                return;
522            }
523        }
524        let present: Vec<&str> = KINDS
525            .iter()
526            .copied()
527            .filter(|kind| raw.get(*kind).is_some())
528            .collect();
529        let [kind] = present.as_slice() else {
530            let message = if let Some(old) = LEGACY_KINDS.iter().find(|k| raw.get(**k).is_some()) {
531                format!(
532                    "action '{old}' is not supported in protocol version 1.0 (it is from A2UI 0.8 or 0.9); use one of {}",
533                    KINDS.join(", ")
534                )
535            } else if present.is_empty() {
536                format!("a message must hold exactly one of {}", KINDS.join(", "))
537            } else {
538                format!(
539                    "Message contains multiple conflicting update actions ({}); send each in a message of its own",
540                    present.join(" and ")
541                )
542            };
543            report.errors.push(problem(
544                Code::ValidationFailed,
545                None,
546                prefix.to_string(),
547                message,
548            ));
549            return;
550        };
551        let body = &raw[*kind];
552        let surface_id = body.get("surfaceId").and_then(Value::as_str);
553        let before = report.errors.len();
554
555        match *kind {
556            "createSurface" => {
557                let catalog_id = body.get("catalogId").and_then(Value::as_str);
558                if let Some(id) = surface_id {
559                    if state.contains_key(id) {
560                        report.errors.push(problem(
561                            Code::IntegrityError,
562                            Some(id),
563                            format!("{prefix}/createSurface/surfaceId"),
564                            format!(
565                                "surface {id:?} already exists; delete it first or use a new surfaceId"
566                            ),
567                        ));
568                    }
569                }
570                if let Some(id) = catalog_id {
571                    if self.entry(id).is_none() {
572                        report.errors.push(problem(
573                            Code::CatalogNotFound,
574                            surface_id,
575                            format!("{prefix}/createSurface/catalogId"),
576                            self.not_found(id),
577                        ));
578                    }
579                }
580                self.check_components(raw, kind, catalog_id, prefix, surface_id, report);
581                if report.errors.len() == before {
582                    if let Some(id) = surface_id {
583                        let mut surface = Surface {
584                            catalog_id: catalog_id.map(String::from),
585                            ..Surface::default()
586                        };
587                        record(&mut surface, body, id, kind, prefix, origins);
588                        state.insert(id.to_string(), surface);
589                        touched.insert(id.to_string());
590                    }
591                }
592            }
593            // Deleting a surface that does not exist changes nothing, as in the
594            // reference SDKs; the model hears about it as a warning.
595            "deleteSurface"
596                if surface_id.is_some_and(|id| !state.contains_key(id))
597                    && body.as_object().is_some_and(|b| b.len() == 1) =>
598            {
599                let id = surface_id.unwrap_or_default();
600                report.warnings.push(problem(
601                    Code::IntegrityError,
602                    Some(id),
603                    format!("{prefix}/deleteSurface/surfaceId"),
604                    format!("surface {id:?} does not exist, so there was nothing to delete"),
605                ));
606            }
607            "updateComponents" | "updateDataModel" | "deleteSurface" => {
608                let known = surface_id.and_then(|id| state.get(id));
609                if let (Some(id), None) = (surface_id, known) {
610                    report.errors.push(problem(
611                        Code::IntegrityError,
612                        Some(id),
613                        format!("{prefix}/{kind}/surfaceId"),
614                        format!(
615                            "surface {id:?} does not exist; create it with createSurface first"
616                        ),
617                    ));
618                }
619                let default = known.and_then(|surface| surface.catalog_id.clone());
620                if surface_id.is_some() && known.is_none() {
621                    // Nothing to resolve the catalog against: the integrity error says it.
622                } else if *kind == "updateComponents" {
623                    self.check_components(
624                        raw,
625                        kind,
626                        default.as_deref(),
627                        prefix,
628                        surface_id,
629                        report,
630                    );
631                } else {
632                    let entry = default
633                        .as_deref()
634                        .and_then(|id| self.entry(id))
635                        .or(self.catalogs.first());
636                    if let Some(entry) = entry {
637                        push_schema(
638                            report,
639                            surface_id,
640                            prefix,
641                            entry.schemas.check_agent_message_as(kind, raw),
642                        );
643                    }
644                }
645                if *kind == "updateDataModel" {
646                    if let Some(path) = body.get("path").and_then(Value::as_str) {
647                        if !path.is_empty() && !path.starts_with('/') {
648                            report.errors.push(problem(
649                                Code::ValidationFailed,
650                                surface_id,
651                                format!("{prefix}/updateDataModel/path"),
652                                format!(
653                                    "path {path:?} is not a JSON Pointer; it must start with \"/\""
654                                ),
655                            ));
656                        }
657                    }
658                }
659                if report.errors.len() == before {
660                    if let Some(id) = surface_id {
661                        match *kind {
662                            "updateComponents" => {
663                                if let Some(surface) = state.get_mut(id) {
664                                    record(surface, body, id, kind, prefix, origins);
665                                }
666                                touched.insert(id.to_string());
667                            }
668                            "deleteSurface" => {
669                                state.remove(id);
670                                touched.remove(id);
671                            }
672                            _ => {}
673                        }
674                    }
675                }
676            }
677            "callRendererFunction" => self.check_call(raw, prefix, state, report),
678            _ => {
679                if let Some(entry) = self.catalogs.first() {
680                    push_schema(
681                        report,
682                        None,
683                        prefix,
684                        entry.schemas.check_agent_message_as(kind, raw),
685                    );
686                }
687            }
688        }
689    }
690
691    /// Schema-check a message that carries components, one catalog at a time:
692    /// each component against the catalog it resolves to (its `@catalogId`,
693    /// else the surface's default), so a surface can mix catalogs.
694    fn check_components(
695        &self,
696        raw: &Value,
697        kind: &str,
698        default: Option<&str>,
699        prefix: &str,
700        surface: Option<&str>,
701        report: &mut Report,
702    ) {
703        let components = raw[kind].get("components").and_then(Value::as_array);
704        let Some(components) = components else {
705            let entry = default
706                .and_then(|id| self.entry(id))
707                .or(self.catalogs.first());
708            if let Some(entry) = entry {
709                push_schema(
710                    report,
711                    surface,
712                    prefix,
713                    entry.schemas.check_agent_message_as(kind, raw),
714                );
715            }
716            return;
717        };
718
719        let mut groups: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
720        let mut ids = BTreeMap::new();
721        for (index, component) in components.iter().enumerate() {
722            let at = format!("{prefix}/{kind}/components/{index}");
723            let own = component.get("@catalogId").and_then(Value::as_str);
724            match own.or(default) {
725                None => report.errors.push(problem(
726                    Code::CatalogNotFound,
727                    surface,
728                    at.clone(),
729                    format!(
730                        "this component has no catalog: surface {:?} has no default catalogId, so set @catalogId on the component or catalogId on createSurface",
731                        surface.unwrap_or_default()
732                    ),
733                )),
734                Some(id) if self.entry(id).is_none() => {
735                    // An unsupported surface default is reported once, on the surface.
736                    if own.is_some() {
737                        report.errors.push(problem(
738                            Code::CatalogNotFound,
739                            surface,
740                            format!("{at}/@catalogId"),
741                            self.not_found(id),
742                        ));
743                    }
744                }
745                Some(id) => groups.entry(id).or_default().push(index),
746            }
747            if let Some(id) = component.get("id").and_then(Value::as_str) {
748                if !is_identifier(id) {
749                    report.errors.push(problem(
750                        Code::ValidationFailed,
751                        surface,
752                        format!("{at}/id"),
753                        format!(
754                            "Component id '{id}' must be a valid UAX #31 identifier: start with a letter or _, then letters, digits, or _"
755                        ),
756                    ));
757                }
758                if let Some(first) = ids.insert(id.to_string(), index) {
759                    report.errors.push(problem(
760                        Code::IntegrityError,
761                        surface,
762                        format!("{at}/id"),
763                        format!("Duplicate component ID '{id}': it is used twice in this message (also at index {first}); give each component its own id"),
764                    ));
765                }
766            }
767            self.check_functions(component, default, &at, surface, report);
768        }
769        // A call resolves to its own catalogId, else the surface's default, which
770        // need not be its component's catalog. The component's schema knows only
771        // its own catalog's functions, so such a call is checked against the
772        // catalog it resolves to, and a binding stands in for it in the
773        // component's check.
774        let mut checked: Vec<Value> = Vec::with_capacity(components.len());
775        let mut detached = Vec::new();
776        for (index, component) in components.iter().enumerate() {
777            let at = format!("{prefix}/{kind}/components/{index}");
778            let own = component
779                .get("@catalogId")
780                .and_then(Value::as_str)
781                .or(default);
782            checked.push(match own.filter(|id| self.entry(id).is_some()) {
783                Some(context) => self.detach(
784                    component,
785                    context,
786                    default,
787                    &at,
788                    None,
789                    surface,
790                    report,
791                    &mut detached,
792                ),
793                None => component.clone(),
794            });
795        }
796        let mut seen = BTreeSet::new();
797        for (catalog_id, indices) in groups {
798            let entry = self
799                .entry(catalog_id)
800                .expect("grouped by supported catalogs");
801            let mut part = raw.clone();
802            part[kind]["components"] =
803                Value::Array(indices.iter().map(|&i| checked[i].clone()).collect());
804            if let Err(errors) = entry.schemas.check_agent_message_as(kind, &part) {
805                for error in errors {
806                    let path = remap(&error.path, kind, &indices);
807                    if seen.insert((path.clone(), error.message.clone())) {
808                        report.errors.push(problem(
809                            Code::ValidationFailed,
810                            surface,
811                            format!("{prefix}{path}"),
812                            error.message,
813                        ));
814                    }
815                }
816            }
817        }
818        // Then every call against the catalog it resolves to, as the reference
819        // SDKs check a call wherever it sits (a component's schema need not
820        // type the place, a list of objects say). What the component's check
821        // already said about a call is not said twice.
822        for (path, call, catalog_id) in detached {
823            let Some(entry) = self.entry(&catalog_id) else {
824                continue;
825            };
826            let covers = |p: &Problem| {
827                p.path.starts_with(&path) || (!p.path.is_empty() && path.starts_with(&p.path))
828            };
829            // A generic "matches none of the forms" over the call (with the
830            // unevaluated `args` a failed `oneOf` leaves behind) says less than
831            // the call's own check, which then replaces it.
832            let generic = |p: &Problem| {
833                p.message.starts_with("matches none of the forms")
834                    || p.message
835                        .starts_with("value is not valid under any of the schemas")
836                    || p.message
837                        .starts_with("Unevaluated properties are not allowed ('args'")
838            };
839            let covering: Vec<&Problem> = report.errors.iter().filter(|p| covers(p)).collect();
840            if !covering.is_empty() && !covering.iter().all(|p| generic(p)) {
841                continue;
842            }
843            let mut call = call;
844            if let Some(object) = call.as_object_mut() {
845                object.remove("catalogId");
846            }
847            if let Err(errors) = entry.schemas.check_function_call(&call) {
848                report.errors.retain(|p| !(covers(p) && generic(p)));
849                for error in errors {
850                    report.errors.push(problem(
851                        Code::ValidationFailed,
852                        surface,
853                        format!("{path}{}", error.path),
854                        error.message,
855                    ));
856                }
857            }
858        }
859    }
860
861    /// "Catalog not found", with the catalogs this renderer has.
862    fn not_found(&self, id: &str) -> String {
863        format!(
864            "Catalog not found: {id}; this renderer supports: {}",
865            self.supported_catalog_ids().join(", ")
866        )
867    }
868
869    /// `value` with each function call that resolves to a catalog other than
870    /// `context` (its own `catalogId`, else the surface's `default`) replaced
871    /// by a binding, which every dynamic value accepts, and the call pushed to
872    /// `out` with its path and catalog, its own arguments treated the same way
873    /// against that catalog. A call that resolves to no catalog the renderer
874    /// has is reported here. System functions (`@index`) belong to no catalog,
875    /// and an action's `functionCall`, where a binding cannot stand, is left to
876    /// the component's check.
877    #[allow(clippy::too_many_arguments)]
878    fn detach(
879        &self,
880        value: &Value,
881        context: &str,
882        default: Option<&str>,
883        at: &str,
884        parent: Option<&str>,
885        surface: Option<&str>,
886        report: &mut Report,
887        out: &mut Vec<(String, Value, String)>,
888    ) -> Value {
889        let descend = |value: &Value,
890                       context: &str,
891                       report: &mut Report,
892                       out: &mut Vec<(String, Value, String)>|
893         -> Value {
894            match value {
895                Value::Object(map) => Value::Object(
896                    map.iter()
897                        .map(|(key, item)| {
898                            let path = format!("{at}/{}", segment(key));
899                            let item = self.detach(
900                                item,
901                                context,
902                                default,
903                                &path,
904                                Some(key),
905                                surface,
906                                report,
907                                out,
908                            );
909                            (key.clone(), item)
910                        })
911                        .collect(),
912                ),
913                Value::Array(items) => Value::Array(
914                    items
915                        .iter()
916                        .enumerate()
917                        .map(|(index, item)| {
918                            let path = format!("{at}/{index}");
919                            self.detach(item, context, default, &path, parent, surface, report, out)
920                        })
921                        .collect(),
922                ),
923                other => other.clone(),
924            }
925        };
926        let Some(name) = value.get("@call").and_then(Value::as_str) else {
927            return descend(value, context, report, out);
928        };
929        if name.starts_with('@') || parent == Some("functionCall") {
930            return descend(value, context, report, out);
931        }
932        let placeholder = serde_json::json!({"@path": "/"});
933        let named = value.get("catalogId").and_then(Value::as_str);
934        match named.or(default) {
935            None => {
936                report.errors.push(problem(
937                    Code::CatalogNotFound,
938                    surface,
939                    at.to_string(),
940                    format!(
941                        "{name} is called with no catalogId, and surface {:?} has no default catalogId; give the call a catalogId",
942                        surface.unwrap_or_default()
943                    ),
944                ));
945                placeholder
946            }
947            Some(id) if self.entry(id).is_none() => {
948                report.errors.push(problem(
949                    Code::CatalogNotFound,
950                    surface,
951                    format!("{at}/catalogId"),
952                    self.not_found(id),
953                ));
954                placeholder
955            }
956            Some(id) if id == context => {
957                let call = descend(value, context, report, out);
958                out.push((at.to_string(), call.clone(), id.to_string()));
959                call
960            }
961            Some(id) => {
962                let call = descend(value, id, report, out);
963                out.push((at.to_string(), call, id.to_string()));
964                placeholder
965            }
966        }
967    }
968
969    /// Function calls inside a component: one that needs a user gesture may
970    /// only be an action's `functionCall`, and an `agentOnly` function cannot be
971    /// used by a component at all (the specification's "Security Boundaries").
972    /// Unknown functions are the schema's to report.
973    fn check_functions(
974        &self,
975        component: &Value,
976        catalog: Option<&str>,
977        at: &str,
978        surface: Option<&str>,
979        report: &mut Report,
980    ) {
981        let mut calls = Vec::new();
982        find_calls(component, at.to_string(), None, &mut calls);
983        for (path, parent_key, call) in calls {
984            let name = call
985                .get("@call")
986                .and_then(Value::as_str)
987                .unwrap_or_default();
988            // System functions (`@index`) are named by the specification.
989            if !name.starts_with('@') && !is_identifier(name) {
990                report.errors.push(problem(
991                    Code::ValidationFailed,
992                    surface,
993                    format!("{path}/@call"),
994                    format!(
995                        "Function name '{name}' must be a valid UAX #31 identifier: start with a letter or _, then letters, digits, or _"
996                    ),
997                ));
998                continue;
999            }
1000            let catalog_id = call.get("catalogId").and_then(Value::as_str).or(catalog);
1001            let Some(def) = catalog_id
1002                .and_then(|id| self.entry(id))
1003                .and_then(|entry| entry.catalog.function(name))
1004            else {
1005                continue;
1006            };
1007            if def.requires_user_activation && parent_key.as_deref() != Some("functionCall") {
1008                report.errors.push(problem(
1009                    Code::ValidationFailed,
1010                    surface,
1011                    path.clone(),
1012                    format!(
1013                        "{name} needs a user gesture, so it can only be an action's functionCall, not a binding or a check"
1014                    ),
1015                ));
1016            }
1017            if def.callers == Callers::AgentOnly {
1018                report.errors.push(problem(
1019                    Code::ValidationFailed,
1020                    surface,
1021                    path,
1022                    format!("{name} is agentOnly: only the agent can call it, never a component"),
1023                ));
1024            }
1025        }
1026    }
1027
1028    fn check_call(
1029        &self,
1030        raw: &Value,
1031        prefix: &str,
1032        state: &BTreeMap<String, Surface>,
1033        report: &mut Report,
1034    ) {
1035        let body = &raw["callRendererFunction"];
1036        let call = &body["callFunction"];
1037        let name = call
1038            .get("@call")
1039            .and_then(Value::as_str)
1040            .unwrap_or_default();
1041        let catalog_id = call.get("catalogId").and_then(Value::as_str);
1042        let entry = catalog_id.and_then(|id| self.entry(id));
1043        match (catalog_id, entry) {
1044            (Some(id), None) => report.errors.push(problem(
1045                Code::InvalidFunctionCall,
1046                None,
1047                format!("{prefix}/callRendererFunction/callFunction/catalogId"),
1048                format!("catalog {id:?} is not supported here"),
1049            )),
1050            _ => {
1051                let entry = entry.or(self.catalogs.first());
1052                if let Some(entry) = entry {
1053                    push_schema(
1054                        report,
1055                        None,
1056                        prefix,
1057                        entry
1058                            .schemas
1059                            .check_agent_message_as("callRendererFunction", raw),
1060                    );
1061                }
1062            }
1063        }
1064        if let Some(def) = entry.and_then(|entry| entry.catalog.function(name)) {
1065            if def.callers == Callers::RendererOnly {
1066                report.errors.push(problem(
1067                    Code::InvalidFunctionCall,
1068                    None,
1069                    format!("{prefix}/callRendererFunction/callFunction/@call"),
1070                    format!(
1071                        "{name} cannot be called by the agent (allowedCallers is rendererOnly)"
1072                    ),
1073                ));
1074            }
1075        }
1076        if let Some(id) = body.get("surfaceId").and_then(Value::as_str) {
1077            if !state.contains_key(id) {
1078                report.errors.push(problem(
1079                    Code::InvalidFunctionCall,
1080                    Some(id),
1081                    format!("{prefix}/callRendererFunction/surfaceId"),
1082                    format!("surface {id:?} does not exist"),
1083                ));
1084            }
1085        }
1086    }
1087
1088    /// The rules over a surface's whole component tree, after the batch:
1089    /// composition constraints, cycles, and, as errors or warnings by
1090    /// [`Rules`], missing children, a missing root, and components nothing
1091    /// shows.
1092    fn check_tree(
1093        &self,
1094        surface_id: &str,
1095        surface: &Surface,
1096        origins: &BTreeMap<(String, String), String>,
1097        report: &mut Report,
1098    ) {
1099        let at = |id: &str| {
1100            origins
1101                .get(&(surface_id.to_string(), id.to_string()))
1102                .cloned()
1103                .unwrap_or_default()
1104        };
1105        let def_of = |component: &Value| -> Option<&ComponentDef> {
1106            let type_name = component.get("component")?.as_str()?;
1107            let catalog = component
1108                .get("@catalogId")
1109                .and_then(Value::as_str)
1110                .or(surface.catalog_id.as_deref())?;
1111            self.entry(catalog)?.catalog.component(type_name)
1112        };
1113
1114        let mut edges: BTreeMap<&str, Vec<String>> = BTreeMap::new();
1115        for (id, component) in &surface.components {
1116            let Some(def) = def_of(component) else {
1117                continue;
1118            };
1119            let children = child_ids(component, def);
1120            for (child, field) in &children {
1121                match surface.components.get(child) {
1122                    None if self.rules.allow_dangling_references => report.warnings.push(problem(
1123                        Code::ValidationFailed,
1124                        Some(surface_id),
1125                        at(id),
1126                        format!(
1127                            "Dangling reference: {id} references component '{child}' in field '{field}', which is not defined yet; it shows as a placeholder until it is"
1128                        ),
1129                    )),
1130                    None => report.errors.push(problem(
1131                        Code::ValidationFailed,
1132                        Some(surface_id),
1133                        at(id),
1134                        format!(
1135                            "Dangling reference: {id} references non-existent component '{child}' in field '{field}'; define it in the same call or remove the reference"
1136                        ),
1137                    )),
1138                    Some(child_component) => {
1139                        if let Some(allowed) = &def.allowed_children {
1140                            if !allowed.iter().any(|t| t == type_of(child_component)) {
1141                                report.errors.push(problem(
1142                                    Code::UnallowedChild,
1143                                    Some(surface_id),
1144                                    at(id),
1145                                    format!(
1146                                        "{} {id} may only contain {}, not {} {child}",
1147                                        type_of(component),
1148                                        allowed.join(", "),
1149                                        type_of(child_component)
1150                                    ),
1151                                ));
1152                            }
1153                        }
1154                        if let Some(allowed) = def_of(child_component).and_then(|d| d.allowed_parents.as_ref()) {
1155                            if !allowed.iter().any(|t| t == type_of(component)) {
1156                                report.errors.push(problem(
1157                                    Code::UnallowedParent,
1158                                    Some(surface_id),
1159                                    at(child),
1160                                    format!(
1161                                        "{} {child} may only be placed under {}, not {} {id}",
1162                                        type_of(child_component),
1163                                        allowed.join(", "),
1164                                        type_of(component)
1165                                    ),
1166                                ));
1167                            }
1168                        }
1169                    }
1170                }
1171            }
1172            edges.insert(
1173                id.as_str(),
1174                children.into_iter().map(|(child, _)| child).collect(),
1175            );
1176        }
1177
1178        if let Some(cycle) = find_cycle(&edges) {
1179            let message = if cycle.len() == 2 {
1180                format!("Self-reference detected: {} references itself", cycle[0])
1181            } else {
1182                format!("Circular reference detected: {}", cycle.join(" -> "))
1183            };
1184            report.errors.push(problem(
1185                Code::RecursionLimitExceeded,
1186                Some(surface_id),
1187                at(&cycle[0]),
1188                message,
1189            ));
1190            return;
1191        }
1192        let Some(root) = surface.components.get("root") else {
1193            if !surface.components.is_empty() {
1194                let (list, verdict) = if self.rules.allow_missing_root {
1195                    (&mut report.warnings, "so nothing is shown yet")
1196                } else {
1197                    (&mut report.errors, "so nothing can be shown; add one")
1198                };
1199                list.push(problem(
1200                    Code::ValidationFailed,
1201                    Some(surface_id),
1202                    String::new(),
1203                    format!(
1204                        "Missing root component: surface {surface_id:?} has components but none with id \"root\", {verdict}"
1205                    ),
1206                ));
1207            }
1208            return;
1209        };
1210        if let Some(allowed) = def_of(root).and_then(|d| d.allowed_parents.as_ref()) {
1211            if !allowed.iter().any(|t| t == "Surface") {
1212                report.errors.push(problem(
1213                    Code::UnallowedParent,
1214                    Some(surface_id),
1215                    at("root"),
1216                    format!(
1217                        "{} cannot be the root: it may only be placed under {}",
1218                        type_of(root),
1219                        allowed.join(", ")
1220                    ),
1221                ));
1222            }
1223        }
1224        let depth = longest_chain(&edges, "root", &mut BTreeMap::new());
1225        if depth > MAX_DEPTH {
1226            report.errors.push(problem(
1227                Code::RecursionLimitExceeded,
1228                Some(surface_id),
1229                String::new(),
1230                format!(
1231                    "Global recursion limit exceeded: logical depth > {MAX_DEPTH} (components nest {depth} deep below root); flatten the layout"
1232                ),
1233            ));
1234            return;
1235        }
1236        let reachable = reach(&edges, "root");
1237        for id in surface
1238            .components
1239            .keys()
1240            .filter(|id| !reachable.contains(id.as_str()))
1241        {
1242            if self.rules.allow_orphans {
1243                report.warnings.push(problem(
1244                    Code::ValidationFailed,
1245                    Some(surface_id),
1246                    at(id),
1247                    format!("Component '{id}' is not reachable from 'root', so it is not shown"),
1248                ));
1249            } else {
1250                report.errors.push(problem(
1251                    Code::ValidationFailed,
1252                    Some(surface_id),
1253                    at(id),
1254                    format!(
1255                        "Component '{id}' is not reachable from 'root', so it would never be shown; make it a child of a shown component or remove it"
1256                    ),
1257                ));
1258            }
1259        }
1260    }
1261}
1262
1263/// A component's type name (`""` when it has none).
1264fn type_of(component: &Value) -> &str {
1265    component
1266        .get("component")
1267        .and_then(Value::as_str)
1268        .unwrap_or("")
1269}
1270
1271/// Add a message's components to a surface, noting where each came from.
1272fn record(
1273    surface: &mut Surface,
1274    body: &Value,
1275    surface_id: &str,
1276    kind: &str,
1277    prefix: &str,
1278    origins: &mut BTreeMap<(String, String), String>,
1279) {
1280    if let Some(components) = body.get("components").and_then(Value::as_array) {
1281        for (index, component) in components.iter().enumerate() {
1282            if let Some(id) = component.get("id").and_then(Value::as_str) {
1283                surface.components.insert(id.to_string(), component.clone());
1284                origins.insert(
1285                    (surface_id.to_string(), id.to_string()),
1286                    format!("{prefix}/{kind}/components/{index}"),
1287                );
1288            }
1289        }
1290    }
1291}
1292
1293fn push_schema(
1294    report: &mut Report,
1295    surface: Option<&str>,
1296    prefix: &str,
1297    result: Result<(), Vec<SchemaError>>,
1298) {
1299    if let Err(errors) = result {
1300        for error in errors {
1301            report.errors.push(problem(
1302                Code::ValidationFailed,
1303                surface,
1304                format!("{prefix}{}", error.path),
1305                error.message,
1306            ));
1307        }
1308    }
1309}
1310
1311/// Map a path into a partial message's components back to the full message's.
1312fn remap(path: &str, kind: &str, indices: &[usize]) -> String {
1313    let head = format!("/{kind}/components/");
1314    let Some(rest) = path.strip_prefix(&head) else {
1315        return path.to_string();
1316    };
1317    let (number, tail) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
1318    match number.parse::<usize>().ok().and_then(|n| indices.get(n)) {
1319        Some(original) => format!("{head}{original}{tail}"),
1320        None => path.to_string(),
1321    }
1322}
1323
1324/// The ids a component refers to through its child-reference properties.
1325/// A template's `componentId` counts as a child.
1326/// A component's child references, each with the field it is in, written
1327/// as the reference SDKs write it (`children[1]`, `tabs[0].child`,
1328/// `children.componentId` for a template).
1329fn child_ids(component: &Value, def: &ComponentDef) -> Vec<(String, String)> {
1330    let mut ids = Vec::new();
1331    for (property, kind) in &def.children {
1332        let Some(value) = component.get(property) else {
1333            continue;
1334        };
1335        match (kind, value) {
1336            (ChildRef::Single, Value::String(id)) => ids.push((id.clone(), property.clone())),
1337            (ChildRef::List, Value::Array(items)) => {
1338                for (index, item) in items.iter().enumerate() {
1339                    if let Some(id) = item.as_str() {
1340                        ids.push((id.to_string(), format!("{property}[{index}]")));
1341                    }
1342                }
1343            }
1344            (ChildRef::List, Value::Object(template)) => {
1345                if let Some(id) = template.get("componentId").and_then(Value::as_str) {
1346                    ids.push((id.to_string(), format!("{property}.componentId")));
1347                }
1348            }
1349            (ChildRef::Items(field), Value::Array(items)) => {
1350                for (index, item) in items.iter().enumerate() {
1351                    if let Some(id) = item.get(field).and_then(Value::as_str) {
1352                        ids.push((id.to_string(), format!("{property}[{index}].{field}")));
1353                    }
1354                }
1355            }
1356            _ => {}
1357        }
1358    }
1359    ids
1360}
1361
1362/// Every function call (an object with a string `@call`) inside a value, with
1363/// its path and the key it sits under.
1364fn find_calls<'a>(
1365    value: &'a Value,
1366    path: String,
1367    key: Option<String>,
1368    calls: &mut Vec<(String, Option<String>, &'a Map<String, Value>)>,
1369) {
1370    match value {
1371        Value::Object(object) => {
1372            if object.get("@call").is_some_and(Value::is_string) {
1373                calls.push((path.clone(), key, object));
1374            }
1375            for (name, child) in object {
1376                find_calls(
1377                    child,
1378                    format!("{path}/{}", segment(name)),
1379                    Some(name.clone()),
1380                    calls,
1381                );
1382            }
1383        }
1384        Value::Array(items) => {
1385            for (index, item) in items.iter().enumerate() {
1386                find_calls(item, format!("{path}/{index}"), key.clone(), calls);
1387            }
1388        }
1389        _ => {}
1390    }
1391}
1392
1393fn find_cycle(edges: &BTreeMap<&str, Vec<String>>) -> Option<Vec<String>> {
1394    #[derive(Clone, Copy, PartialEq)]
1395    enum Mark {
1396        Open,
1397        Done,
1398    }
1399    fn visit(
1400        node: &str,
1401        edges: &BTreeMap<&str, Vec<String>>,
1402        marks: &mut BTreeMap<String, Mark>,
1403        stack: &mut Vec<String>,
1404    ) -> Option<Vec<String>> {
1405        match marks.get(node) {
1406            Some(Mark::Done) => return None,
1407            Some(Mark::Open) => {
1408                let start = stack.iter().position(|n| n == node).unwrap_or(0);
1409                let mut cycle = stack[start..].to_vec();
1410                cycle.push(node.to_string());
1411                return Some(cycle);
1412            }
1413            None => {}
1414        }
1415        marks.insert(node.to_string(), Mark::Open);
1416        stack.push(node.to_string());
1417        for child in edges.get(node).into_iter().flatten() {
1418            if let Some(cycle) = visit(child, edges, marks, stack) {
1419                return Some(cycle);
1420            }
1421        }
1422        stack.pop();
1423        marks.insert(node.to_string(), Mark::Done);
1424        None
1425    }
1426    let mut marks = BTreeMap::new();
1427    for node in edges.keys() {
1428        if let Some(cycle) = visit(node, edges, &mut marks, &mut Vec::new()) {
1429            return Some(cycle);
1430        }
1431    }
1432    None
1433}
1434
1435/// How many levels of children lie below `node` at most (0 for a leaf),
1436/// memoized; the graph has no cycles by the time this runs.
1437fn longest_chain(
1438    edges: &BTreeMap<&str, Vec<String>>,
1439    node: &str,
1440    memo: &mut BTreeMap<String, usize>,
1441) -> usize {
1442    if let Some(depth) = memo.get(node) {
1443        return *depth;
1444    }
1445    let depth = edges
1446        .get(node)
1447        .into_iter()
1448        .flatten()
1449        .filter(|child| edges.contains_key(child.as_str()))
1450        .map(|child| 1 + longest_chain(edges, child, memo))
1451        .max()
1452        .unwrap_or(0);
1453    memo.insert(node.to_string(), depth);
1454    depth
1455}
1456
1457/// The reference SDKs' limits and path syntax over a raw message: values
1458/// nested more than [`MAX_DEPTH`] deep, function calls (an object with `@call`
1459/// and `args`) nested more than [`MAX_CALL_DEPTH`] deep in each other's
1460/// arguments, and `@path` or `path` strings that are not JSON Pointers (relative
1461/// or absolute; a `~` must be `~0` or `~1`). `depth` counts the message itself
1462/// as 1, as the SDKs count it inside the batch.
1463fn limits_and_paths(value: &Value, at: &str, depth: usize, calls: usize) -> Result<(), Problem> {
1464    if depth > MAX_DEPTH {
1465        return Err(problem(
1466            Code::RecursionLimitExceeded,
1467            None,
1468            at.to_string(),
1469            format!(
1470                "Global recursion limit exceeded: Depth > {MAX_DEPTH}; nest values less deeply"
1471            ),
1472        ));
1473    }
1474    match value {
1475        Value::Array(items) => {
1476            for (index, item) in items.iter().enumerate() {
1477                limits_and_paths(item, &format!("{at}/{index}"), depth + 1, calls)?;
1478            }
1479        }
1480        Value::Object(map) => {
1481            for key in ["path", "@path"] {
1482                if let Some(Value::String(path)) = map.get(key) {
1483                    if !pointer_syntax(path) {
1484                        return Err(problem(
1485                            Code::ValidationFailed,
1486                            None,
1487                            format!("{at}/{}", segment(key)),
1488                            format!(
1489                                "Invalid path syntax: '{path}' is not a JSON Pointer (a ~ must be written ~0, and a / inside a key ~1)"
1490                            ),
1491                        ));
1492                    }
1493                }
1494            }
1495            let is_call = map.contains_key("@call") && map.contains_key("args");
1496            if is_call && calls >= MAX_CALL_DEPTH {
1497                return Err(problem(
1498                    Code::RecursionLimitExceeded,
1499                    None,
1500                    at.to_string(),
1501                    format!(
1502                        "Recursion limit exceeded: functionCall depth > {MAX_CALL_DEPTH}; nest fewer function calls"
1503                    ),
1504                ));
1505            }
1506            for (key, item) in map {
1507                let nested = if is_call && key == "args" {
1508                    calls + 1
1509                } else {
1510                    calls
1511                };
1512                limits_and_paths(item, &format!("{at}/{}", segment(key)), depth + 1, nested)?;
1513            }
1514        }
1515        _ => {}
1516    }
1517    Ok(())
1518}
1519
1520/// Whether `path` is a JSON Pointer, absolute or relative: every `~` escapes
1521/// `0` or `1`.
1522fn pointer_syntax(path: &str) -> bool {
1523    let mut chars = path.chars();
1524    while let Some(c) = chars.next() {
1525        if c == '~' && !matches!(chars.next(), Some('0' | '1')) {
1526            return false;
1527        }
1528    }
1529    true
1530}
1531
1532fn reach<'a>(edges: &'a BTreeMap<&str, Vec<String>>, start: &'a str) -> BTreeSet<&'a str> {
1533    let mut seen = BTreeSet::new();
1534    let mut queue = vec![start];
1535    while let Some(node) = queue.pop() {
1536        if seen.insert(node) {
1537            for child in edges.get(node).into_iter().flatten() {
1538                queue.push(child.as_str());
1539            }
1540        }
1541    }
1542    seen
1543}