Skip to main content

agent86_ui/runtime/
data.rs

1//! A surface's data model: a JSON value addressed by JSON Pointers (RFC 6901),
2//! with the rules every A2UI SDK shares (the specification's conformance suite,
3//! `core/data_model.yaml`):
4//!
5//! - Empty segments collapse, so `//a///b//`, `/a/b/`, and `/a/b` are one path;
6//!   `""` and `/` are the root. `~1` unescapes to `/` before `~0` to `~`.
7//! - `null` reads as absent, and writing through it creates the containers.
8//! - A write creates missing containers: an array when the next segment is an
9//!   index, else an object. Array indices are canonical (no leading zeros), at
10//!   most [`MAX_ARRAY_INDEX`]; writing past the end pads with `null`.
11//! - Writing through a string, number, or boolean is an error, as is a
12//!   non-numeric segment on an array.
13//! - `__proto__`, `constructor`, and `prototype` are refused as segments in
14//!   every SDK, whatever its language, so models move between them unchanged.
15//! - A watcher is notified when the value at its own path changed: a write to
16//!   an ancestor, the path, or a descendant that left it the same notifies no one.
17
18use serde_json::{Map, Value};
19
20/// The largest array index a write may use.
21pub const MAX_ARRAY_INDEX: usize = 10_000;
22
23const FORBIDDEN: &[&str] = &["__proto__", "constructor", "prototype"];
24
25/// A data model operation the model or the user cannot do.
26#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27#[error("{message}")]
28pub struct DataError {
29    /// What went wrong, naming the path.
30    pub message: String,
31    /// The path as given.
32    pub path: String,
33}
34
35fn error(path: &str, message: String) -> DataError {
36    DataError {
37        message,
38        path: path.to_string(),
39    }
40}
41
42/// The segments of a JSON Pointer, unescaped, with empty segments dropped.
43/// Refuses the forbidden segments.
44pub fn segments(path: &str) -> Result<Vec<String>, DataError> {
45    let mut out = Vec::new();
46    for raw in path.split('/').filter(|s| !s.is_empty()) {
47        let segment = raw.replace("~1", "/").replace("~0", "~");
48        if FORBIDDEN.contains(&segment.as_str()) {
49            return Err(error(
50                path,
51                format!("Forbidden path segment '{segment}' in path '{path}'."),
52            ));
53        }
54        out.push(segment);
55    }
56    Ok(out)
57}
58
59/// The JSON Pointer for segments (`/` for none).
60pub fn pointer(segments: &[String]) -> String {
61    if segments.is_empty() {
62        return "/".into();
63    }
64    segments
65        .iter()
66        .map(|s| format!("/{}", s.replace('~', "~0").replace('/', "~1")))
67        .collect()
68}
69
70/// A path in its normal form: segments collapsed and re-escaped, `/` for the
71/// root.
72pub fn normalize(path: &str) -> Result<String, DataError> {
73    Ok(pointer(&segments(path)?))
74}
75
76/// Resolve `path` against a context path: an absolute path (starting with `/`)
77/// stands alone; a relative one, inside a template, extends the context; `""`
78/// and `.` are the context itself.
79pub fn resolve(context: &str, path: &str) -> String {
80    if path.starts_with('/') {
81        return path.to_string();
82    }
83    let base = context.trim_end_matches('/');
84    if path.is_empty() || path == "." {
85        return if base.is_empty() {
86            "/".into()
87        } else {
88            base.to_string()
89        };
90    }
91    format!("{base}/{path}")
92}
93
94/// A canonical array index: decimal digits, no leading zero unless `0`.
95fn index(segment: &str) -> Option<usize> {
96    let canonical = !segment.is_empty()
97        && segment.bytes().all(|b| b.is_ascii_digit())
98        && (segment == "0" || !segment.starts_with('0'));
99    if canonical {
100        segment.parse().ok()
101    } else {
102        None
103    }
104}
105
106/// An id for one watch, so the same path can be watched twice.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
108pub struct WatchId(usize);
109
110/// A surface's data model.
111#[derive(Debug, Clone, PartialEq)]
112pub struct DataModel {
113    root: Value,
114    watches: Vec<(WatchId, Vec<String>)>,
115    next: usize,
116}
117
118impl Default for DataModel {
119    fn default() -> Self {
120        Self::new(Value::Object(Map::new()))
121    }
122}
123
124impl DataModel {
125    /// A data model holding `root`.
126    pub fn new(root: Value) -> Self {
127        Self {
128            root,
129            watches: Vec::new(),
130            next: 0,
131        }
132    }
133
134    /// The whole model.
135    pub fn root(&self) -> &Value {
136        &self.root
137    }
138
139    /// The value at `path`, or `None` when it is absent or `null`.
140    pub fn get(&self, path: &str) -> Result<Option<&Value>, DataError> {
141        Ok(lookup(&self.root, &segments(path)?))
142    }
143
144    /// Watch `path`: [`DataModel::set`] and [`DataModel::delete`] report this
145    /// id when the value there changes.
146    pub fn watch(&mut self, path: &str) -> Result<WatchId, DataError> {
147        let id = WatchId(self.next);
148        self.next += 1;
149        self.watches.push((id, segments(path)?));
150        Ok(id)
151    }
152
153    /// Stop every watch.
154    pub fn dispose(&mut self) {
155        self.watches.clear();
156    }
157
158    /// Set the value at `path`, creating containers on the way; `/` replaces
159    /// the whole model. Returns the watches whose value changed.
160    pub fn set(&mut self, path: &str, value: Value) -> Result<Vec<WatchId>, DataError> {
161        let parts = segments(path)?;
162        let before = self.snapshot();
163        write(&mut self.root, &parts, path, Some(value))?;
164        Ok(self.changed(before))
165    }
166
167    /// Remove the value at `path` (an array element becomes `null`; `/` resets
168    /// the model to `{}`). Nothing is created; an absent path is a no-op.
169    pub fn delete(&mut self, path: &str) -> Result<Vec<WatchId>, DataError> {
170        let parts = segments(path)?;
171        let before = self.snapshot();
172        if parts.is_empty() {
173            self.root = Value::Object(Map::new());
174        } else if lookup_parent(&self.root, &parts).is_some() {
175            write(&mut self.root, &parts, path, None)?;
176        }
177        Ok(self.changed(before))
178    }
179
180    fn snapshot(&self) -> Vec<Option<Value>> {
181        self.watches
182            .iter()
183            .map(|(_, path)| lookup(&self.root, path).cloned())
184            .collect()
185    }
186
187    fn changed(&self, before: Vec<Option<Value>>) -> Vec<WatchId> {
188        self.watches
189            .iter()
190            .zip(before)
191            .filter(|((_, path), old)| lookup(&self.root, path) != old.as_ref())
192            .map(|((id, _), _)| *id)
193            .collect()
194    }
195}
196
197fn lookup<'a>(root: &'a Value, parts: &[String]) -> Option<&'a Value> {
198    let mut current = root;
199    for part in parts {
200        current = match current {
201            Value::Object(map) => map.get(part)?,
202            Value::Array(items) => items.get(index(part)?)?,
203            _ => return None,
204        };
205    }
206    (!current.is_null()).then_some(current)
207}
208
209/// Whether the container that would hold the last segment exists.
210fn lookup_parent<'a>(root: &'a Value, parts: &[String]) -> Option<&'a Value> {
211    let (_, parents) = parts.split_last()?;
212    let mut current = root;
213    for part in parents {
214        current = match current {
215            Value::Object(map) => map.get(part)?,
216            Value::Array(items) => items.get(index(part)?)?,
217            _ => return None,
218        };
219    }
220    matches!(current, Value::Object(_) | Value::Array(_)).then_some(current)
221}
222
223fn container_for(next: &str) -> Value {
224    if index(next).is_some() {
225        Value::Array(Vec::new())
226    } else {
227        Value::Object(Map::new())
228    }
229}
230
231/// Write `value` (or remove, for `None`) at `parts` under `root`.
232fn write(
233    root: &mut Value,
234    parts: &[String],
235    path: &str,
236    value: Option<Value>,
237) -> Result<(), DataError> {
238    let Some((last, parents)) = parts.split_last() else {
239        root.clone_from(&value.unwrap_or_else(|| Value::Object(Map::new())));
240        return Ok(());
241    };
242    let primitive = |segment: &str| {
243        error(
244            path,
245            format!("Cannot set path '{path}': segment '{segment}' is a primitive value."),
246        )
247    };
248    if !matches!(root, Value::Object(_) | Value::Array(_) | Value::Null) {
249        return Err(error(
250            path,
251            format!("Cannot set path '{path}': the data model root is a primitive value."),
252        ));
253    }
254    if root.is_null() {
255        *root = container_for(&parts[0]);
256    }
257    let mut current = root;
258    for (position, part) in parents.iter().enumerate() {
259        let next = &parts[position + 1];
260        let slot = match current {
261            Value::Object(map) => map.entry(part.clone()).or_insert(Value::Null),
262            Value::Array(items) => {
263                let i = array_index(part, path)?;
264                if i >= items.len() {
265                    items.resize(i + 1, Value::Null);
266                }
267                &mut items[i]
268            }
269            _ => return Err(primitive(part)),
270        };
271        if slot.is_null() {
272            if let Some(i) = index(next) {
273                if i > MAX_ARRAY_INDEX {
274                    return Err(too_large(path, next));
275                }
276            }
277            *slot = container_for(next);
278        } else if !matches!(slot, Value::Object(_) | Value::Array(_)) {
279            return Err(primitive(next));
280        }
281        current = slot;
282    }
283    match current {
284        Value::Object(map) => match value {
285            Some(value) => {
286                map.insert(last.clone(), value);
287            }
288            None => {
289                map.remove(last);
290            }
291        },
292        Value::Array(items) => {
293            let i = array_index(last, path)?;
294            match value {
295                Some(value) => {
296                    if i >= items.len() {
297                        items.resize(i + 1, Value::Null);
298                    }
299                    items[i] = value;
300                }
301                None => {
302                    if let Some(slot) = items.get_mut(i) {
303                        *slot = Value::Null;
304                    }
305                }
306            }
307        }
308        _ => return Err(primitive(last)),
309    }
310    Ok(())
311}
312
313fn array_index(segment: &str, path: &str) -> Result<usize, DataError> {
314    let Some(i) = index(segment) else {
315        return Err(error(
316            path,
317            format!("Cannot use non-numeric segment '{segment}' on an array in path '{path}'."),
318        ));
319    };
320    if i > MAX_ARRAY_INDEX {
321        return Err(too_large(path, segment));
322    }
323    Ok(i)
324}
325
326fn too_large(path: &str, segment: &str) -> DataError {
327    error(
328        path,
329        format!(
330            "Cannot set path '{path}': array index '{segment}' exceeds maximum supported index ({MAX_ARRAY_INDEX})."
331        ),
332    )
333}