Skip to main content

agent86_ui/runtime/
functions.rs

1//! Evaluating dynamic values: data bindings, function calls, and the basic
2//! catalog's functions, with the specification's coercion rules
3//! ("`DynamicBoolean` and `CheckRule` Coercion") and catalog resolution
4//! ("Mixable catalogs and component resolution logic").
5//!
6//! A call resolves in its own `catalogId`, else the scope's default catalog
7//! (the surface's, or, inside a `formatString` template, the template's), else
8//! it fails. The function must be declared by that catalog and implemented
9//! here; the basic catalog's functions are implemented natively, whatever
10//! catalog declares them. A function that needs a user gesture runs only in a
11//! scope that has one, and an `agentOnly` function never runs on the renderer.
12
13use super::data::{self, DataError, DataModel};
14use super::expr::{self, Part};
15use super::format;
16use super::regex::Pattern;
17use crate::catalog::{Callers, Catalog};
18use serde_json::{json, Map, Value};
19use std::cell::RefCell;
20
21/// A failure while evaluating, in the specification's error categories.
22#[derive(Debug, Clone, PartialEq, thiserror::Error)]
23#[non_exhaustive]
24pub enum EvalError {
25    /// A function failed, was refused, or a template did not parse
26    /// (`EXPRESSION_ERROR`).
27    #[error("{0}")]
28    Expression(String),
29    /// A call's catalog could not be resolved.
30    #[error("{0}")]
31    Catalog(String),
32    /// A data binding's path is not allowed.
33    #[error(transparent)]
34    Data(#[from] DataError),
35    /// A local function ran and failed (`EXECUTION_ERROR`).
36    #[error("{0}")]
37    Execution(String),
38}
39
40impl EvalError {
41    /// The category name the shared suites use.
42    pub fn category(&self) -> &'static str {
43        match self {
44            EvalError::Expression(_) => "ExpressionError",
45            EvalError::Catalog(_) => "CatalogError",
46            EvalError::Data(_) => "DataError",
47            EvalError::Execution(_) => "ExecutionError",
48        }
49    }
50}
51
52impl From<expr::ExpressionError> for EvalError {
53    fn from(error: expr::ExpressionError) -> Self {
54        EvalError::Expression(error.0)
55    }
56}
57
58fn expression<T>(message: impl Into<String>) -> Result<T, EvalError> {
59    Err(EvalError::Expression(message.into()))
60}
61
62/// Something a function asks the renderer to do (only `openUrl`, so far).
63#[derive(Debug, Clone, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum Effect {
66    /// Open this `http` or `https` URL, in response to the user's gesture.
67    OpenUrl(String),
68    /// Set this data model path (a local function's write, applied when the
69    /// action finishes).
70    SetData {
71        /// The absolute JSON Pointer.
72        path: String,
73        /// The value.
74        value: Value,
75    },
76}
77
78/// A function the embedder implements for its own catalog, run on the
79/// renderer: given the resolved arguments and its context, it returns a value
80/// or fails with a message (an `EXECUTION_ERROR`).
81pub type LocalFunction =
82    std::sync::Arc<dyn Fn(&Map<String, Value>, &Scope<'_>) -> Result<Value, String> + Send + Sync>;
83
84/// Where an expression is evaluated.
85pub struct Scope<'a> {
86    /// The surface's data model.
87    pub data: &'a DataModel,
88    /// The data context a relative path resolves against (`/` at the root, the
89    /// item's path inside a template).
90    pub path: String,
91    /// The innermost template's item index, for `@index`.
92    pub index: Option<usize>,
93    /// The catalog a call without its own `catalogId` resolves in.
94    pub catalog: Option<String>,
95    /// Whether this runs from a user gesture (an action), which functions
96    /// that need one require.
97    pub activation: bool,
98    effects: RefCell<Vec<Effect>>,
99}
100
101impl<'a> Scope<'a> {
102    /// The root scope of a surface whose default catalog is `catalog`.
103    pub fn root(data: &'a DataModel, catalog: Option<&str>) -> Self {
104        Self {
105            data,
106            path: "/".into(),
107            index: None,
108            catalog: catalog.map(String::from),
109            activation: false,
110            effects: RefCell::new(Vec::new()),
111        }
112    }
113
114    /// This scope inside a template item.
115    pub fn item(&self, path: String, index: usize) -> Scope<'a> {
116        Scope {
117            data: self.data,
118            path,
119            index: Some(index),
120            catalog: self.catalog.clone(),
121            activation: self.activation,
122            effects: RefCell::new(Vec::new()),
123        }
124    }
125
126    fn with_catalog(&self, catalog: Option<String>) -> Scope<'a> {
127        Scope {
128            data: self.data,
129            path: self.path.clone(),
130            index: self.index,
131            catalog,
132            activation: self.activation,
133            effects: RefCell::new(Vec::new()),
134        }
135    }
136
137    /// The effects functions asked for, in order, taken out of the scope.
138    pub fn take_effects(&self) -> Vec<Effect> {
139        std::mem::take(&mut self.effects.borrow_mut())
140    }
141
142    fn absorb(&self, inner: &Scope<'_>) {
143        self.effects.borrow_mut().extend(inner.take_effects());
144    }
145
146    /// Read the data model at a path relative to this scope (`None` when
147    /// absent or not allowed).
148    pub fn get(&self, path: &str) -> Option<Value> {
149        let resolved = data::resolve(&self.path, path);
150        self.data.get(&resolved).ok().flatten().cloned()
151    }
152
153    /// Ask for a data model write, for a local function: applied when the
154    /// action that ran it finishes, and dropped when it ran from a binding.
155    pub fn set(&self, path: &str, value: Value) {
156        let path = data::resolve(&self.path, path);
157        self.effects
158            .borrow_mut()
159            .push(Effect::SetData { path, value });
160    }
161}
162
163/// The `DynamicBoolean` coercion: booleans as themselves, a validation result
164/// as its `valid`, `"true"`/`"false"` in any case, a nonzero number as true,
165/// and everything else (other strings, `null`, objects, arrays) as false.
166pub fn coerce_bool(value: &Value) -> bool {
167    match value {
168        Value::Bool(b) => *b,
169        Value::Object(map) => map.get("valid").and_then(Value::as_bool).unwrap_or(false),
170        Value::String(s) => s.eq_ignore_ascii_case("true"),
171        Value::Number(n) => n.as_f64().is_some_and(|n| n != 0.0 && !n.is_nan()),
172        _ => false,
173    }
174}
175
176/// A validation result's `valid`, if the value is one.
177pub fn validity(value: &Value) -> Option<bool> {
178    value.as_object()?.get("valid")?.as_bool()
179}
180
181fn result(valid: bool, message: Option<String>) -> Value {
182    let mut map = Map::new();
183    map.insert("valid".into(), Value::Bool(valid));
184    if let Some(message) = message.filter(|_| !valid) {
185        map.insert("message".into(), Value::String(message));
186    }
187    Value::Object(map)
188}
189
190/// Evaluates dynamic values against a set of catalogs.
191#[derive(Clone)]
192pub struct Evaluator {
193    catalogs: Vec<Catalog>,
194    locals: Vec<(String, crate::catalog::FunctionDef, LocalFunction)>,
195}
196
197impl std::fmt::Debug for Evaluator {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        f.debug_struct("Evaluator")
200            .field(
201                "catalogs",
202                &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
203            )
204            .field(
205                "locals",
206                &self
207                    .locals
208                    .iter()
209                    .map(|(name, _, _)| name)
210                    .collect::<Vec<_>>(),
211            )
212            .finish()
213    }
214}
215
216const NATIVE: &[&str] = &[
217    "required",
218    "regex",
219    "length",
220    "numeric",
221    "email",
222    "formatString",
223    "formatNumber",
224    "formatCurrency",
225    "formatDate",
226    "pluralize",
227    "openUrl",
228    "and",
229    "or",
230    "not",
231];
232
233impl Evaluator {
234    /// An evaluator over the catalogs a surface may use.
235    pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Self {
236        Self {
237            catalogs: catalogs.into_iter().collect(),
238            locals: Vec::new(),
239        }
240    }
241
242    /// Implement a function on the renderer: `def` says who may call it and
243    /// whether it needs a gesture, as a catalog entry would. A registered
244    /// function can be called from any of the evaluator's catalogs.
245    pub fn register(
246        &mut self,
247        name: impl Into<String>,
248        def: crate::catalog::FunctionDef,
249        function: LocalFunction,
250    ) {
251        let name = name.into();
252        self.locals.retain(|(existing, _, _)| *existing != name);
253        self.locals.push((name, def, function));
254    }
255
256    /// An evaluator over the basic catalog alone.
257    pub fn basic() -> Self {
258        Self::new([Catalog::basic().clone()])
259    }
260
261    fn catalog(&self, id: &str) -> Option<&Catalog> {
262        self.catalogs.iter().find(|catalog| catalog.id() == id)
263    }
264
265    /// Resolve a dynamic value: a `{"@path": ...}` reads the data model (absent
266    /// is `null`), a `{"@call": ...}` calls the function, an array resolves
267    /// element by element, and any other object is a literal (its `@@` keys
268    /// unescaped to `@`). A literal object with a single-`@` key is refused,
269    /// as the specification reserves that namespace.
270    pub fn evaluate(&self, value: &Value, scope: &Scope<'_>) -> Result<Value, EvalError> {
271        match value {
272            Value::Object(map) => {
273                if let Some(path) = map.get("@path").and_then(Value::as_str) {
274                    let resolved = data::resolve(&scope.path, path);
275                    return Ok(scope.data.get(&resolved)?.cloned().unwrap_or(Value::Null));
276                }
277                if map.get("@call").is_some_and(Value::is_string) {
278                    return self.call(map, scope);
279                }
280                let mut literal = Map::new();
281                for (key, inner) in map {
282                    let key = if let Some(rest) = key.strip_prefix("@@") {
283                        format!("@{rest}")
284                    } else if key.starts_with('@') {
285                        return expression(format!("'{key}' is a reserved key"));
286                    } else {
287                        key.clone()
288                    };
289                    literal.insert(key, inner.clone());
290                }
291                Ok(Value::Object(literal))
292            }
293            Value::Array(items) => items
294                .iter()
295                .map(|item| self.evaluate(item, scope))
296                .collect::<Result<Vec<_>, _>>()
297                .map(Value::Array),
298            other => Ok(other.clone()),
299        }
300    }
301
302    /// Call a function: `{"@call": name, "catalogId"?: ..., "args"?: {...}}`.
303    pub fn call(&self, call: &Map<String, Value>, scope: &Scope<'_>) -> Result<Value, EvalError> {
304        let name = call
305            .get("@call")
306            .and_then(Value::as_str)
307            .unwrap_or_default();
308        let empty = Map::new();
309        let raw_args = call
310            .get("args")
311            .and_then(Value::as_object)
312            .unwrap_or(&empty);
313        if name == "@index" {
314            let Some(index) = scope.index else {
315                return expression("@index function can only be evaluated inside a collection template iteration scope.");
316            };
317            let offset = match raw_args.get("offset") {
318                Some(value) => format::to_number(&self.evaluate(value, scope)?),
319                None => 0.0,
320            };
321            return Ok(expr::number_value(index as f64 + offset));
322        }
323        if name.starts_with('@') {
324            return expression(format!("Unknown system function '{name}'"));
325        }
326        let catalog_id = match call.get("catalogId").and_then(Value::as_str) {
327            Some(id) => id.to_string(),
328            None => scope.catalog.clone().ok_or_else(|| {
329                EvalError::Catalog(format!(
330                    "Cannot resolve function '{name}': the call names no catalogId and the surface has no default catalogId"
331                ))
332            })?,
333        };
334        let catalog = self
335            .catalog(&catalog_id)
336            .ok_or_else(|| EvalError::Catalog(format!("Catalog not found: {catalog_id}")))?;
337        let local = self.locals.iter().find(|(local, _, _)| local == name);
338        let Some(def) = catalog.function(name).or(local.map(|(_, def, _)| def)) else {
339            return expression(format!(
340                "Function '{name}' is not defined in catalog '{catalog_id}'"
341            ));
342        };
343        if def.callers == Callers::AgentOnly {
344            return expression(format!(
345                "Function '{name}' is agentOnly and cannot be called by renderer"
346            ));
347        }
348        if def.requires_user_activation && !scope.activation {
349            return expression(format!(
350                "Function '{name}' requires user activation: it can only run from an action"
351            ));
352        }
353        if local.is_none() && !NATIVE.contains(&name) {
354            return expression(format!(
355                "Function '{name}' of catalog '{catalog_id}' has no implementation in this renderer"
356            ));
357        }
358        // Nested calls resolve in their own catalog or the scope's default;
359        // only a formatString template passes its catalog on.
360        let mut args = Map::new();
361        for (key, value) in raw_args {
362            args.insert(key.clone(), self.evaluate(value, scope)?);
363        }
364        match local {
365            Some((_, _, function)) => function(&args, scope).map_err(EvalError::Execution),
366            None => self.native(name, &args, &catalog_id, scope),
367        }
368    }
369
370    fn native(
371        &self,
372        name: &str,
373        args: &Map<String, Value>,
374        catalog_id: &str,
375        scope: &Scope<'_>,
376    ) -> Result<Value, EvalError> {
377        let arg = |key: &str| args.get(key).unwrap_or(&Value::Null);
378        let number = |key: &str| args.get(key).map(format::to_number).filter(|n| !n.is_nan());
379        let decimals =
380            || -> Option<usize> { number("decimals").map(|d| d.clamp(0.0, 20.0).round() as usize) };
381        let grouping = || args.get("grouping").is_none_or(coerce_bool);
382        Ok(match name {
383            "required" => {
384                let present = match arg("value") {
385                    Value::Null => false,
386                    Value::String(s) => !s.is_empty(),
387                    Value::Array(items) => !items.is_empty(),
388                    _ => true,
389                };
390                result(present, Some("This field is required.".into()))
391            }
392            "regex" => {
393                let pattern = arg("pattern").as_str().unwrap_or_default();
394                let compiled = Pattern::compile(pattern).map_err(|refusal| {
395                    EvalError::Expression(format!(
396                        "Invalid or unsafe regex pattern ({}): {pattern}",
397                        refusal.as_str()
398                    ))
399                })?;
400                let value = format::to_string(arg("value"));
401                if value.chars().count() > super::regex::MAX_VALUE_CODE_POINTS {
402                    result(
403                        false,
404                        Some("Value exceeds the maximum length for pattern matching.".into()),
405                    )
406                } else {
407                    result(
408                        compiled.test(&value),
409                        Some("Value does not match required pattern.".into()),
410                    )
411                }
412            }
413            "length" => {
414                let length = match arg("value") {
415                    Value::String(s) => s.encode_utf16().count() as f64,
416                    Value::Array(items) => items.len() as f64,
417                    _ => 0.0,
418                };
419                match (number("min"), number("max")) {
420                    (Some(min), _) if length < min => result(
421                        false,
422                        Some(format!("Minimum length is {}.", format::number_string(min))),
423                    ),
424                    (_, Some(max)) if length > max => result(
425                        false,
426                        Some(format!("Maximum length is {}.", format::number_string(max))),
427                    ),
428                    _ => result(true, None),
429                }
430            }
431            "numeric" => {
432                let value = format::to_number(arg("value"));
433                if value.is_nan() {
434                    result(false, Some("Value must be a valid number.".into()))
435                } else {
436                    match (number("min"), number("max")) {
437                        (Some(min), _) if value < min => result(
438                            false,
439                            Some(format!("Minimum value is {}.", format::number_string(min))),
440                        ),
441                        (_, Some(max)) if value > max => result(
442                            false,
443                            Some(format!("Maximum value is {}.", format::number_string(max))),
444                        ),
445                        _ => result(true, None),
446                    }
447                }
448            }
449            "email" => {
450                let valid = arg("value").as_str().is_some_and(is_email);
451                if valid {
452                    result(true, None)
453                } else {
454                    json!({
455                        "valid": false,
456                        "code": "INVALID_EMAIL",
457                        "severity": "error",
458                        "message": "Please enter a valid email address (e.g. user@example.com)."
459                    })
460                }
461            }
462            "formatString" => match arg("value") {
463                Value::String(template) => {
464                    Value::String(self.template(template, catalog_id, scope)?)
465                }
466                other => Value::String(format::to_string(other)),
467            },
468            "formatNumber" => Value::String(format::format_number(
469                format::to_number(arg("value")),
470                decimals(),
471                grouping(),
472            )),
473            "formatCurrency" => Value::String(format::format_currency(
474                format::to_number(arg("value")),
475                &format::to_string(arg("currency")),
476                decimals(),
477                grouping(),
478            )),
479            "formatDate" => Value::String(format::format_date(
480                arg("value"),
481                &format::to_string(arg("format")),
482            )),
483            "pluralize" => {
484                let category = format::plural_category(format::to_number(arg("value")), |key| {
485                    args.contains_key(key)
486                });
487                let chosen = args.get(category).or_else(|| args.get("other"));
488                Value::String(chosen.map(format::to_string).unwrap_or_default())
489            }
490            "openUrl" => {
491                let url = format::to_string(arg("url"));
492                let trimmed = url.trim();
493                let lower = trimmed.to_ascii_lowercase();
494                if !(lower.starts_with("https://") || lower.starts_with("http://")) {
495                    return expression(format!(
496                        "openUrl only opens http and https URLs, not {trimmed:?}"
497                    ));
498                }
499                scope
500                    .effects
501                    .borrow_mut()
502                    .push(Effect::OpenUrl(trimmed.to_string()));
503                Value::Null
504            }
505            "and" | "or" => {
506                let values = arg("values")
507                    .as_array()
508                    .map(Vec::as_slice)
509                    .unwrap_or_default();
510                if values.len() < 2 {
511                    return expression(format!("{name} requires at least 2 values"));
512                }
513                Value::Bool(if name == "and" {
514                    values.iter().all(coerce_bool)
515                } else {
516                    values.iter().any(coerce_bool)
517                })
518            }
519            "not" => Value::Bool(!coerce_bool(arg("value"))),
520            _ => return expression(format!("Function '{name}' has no implementation")),
521        })
522    }
523
524    /// Evaluate a `formatString` template: its calls resolve in the catalog the
525    /// `formatString` call resolved to, and every part becomes text.
526    fn template(
527        &self,
528        template: &str,
529        catalog_id: &str,
530        scope: &Scope<'_>,
531    ) -> Result<String, EvalError> {
532        let parts = expr::parse(template)?;
533        let inner = scope.with_catalog(Some(catalog_id.to_string()));
534        let mut out = String::new();
535        for part in &parts {
536            let value = self.evaluate(&part_value(part, catalog_id), &inner)?;
537            out.push_str(&format::to_string(&value));
538        }
539        scope.absorb(&inner);
540        Ok(out)
541    }
542}
543
544/// A template part as a dynamic value: a binding as `{"@path"}`, a call as
545/// `{"@call"}` in the template's catalog (system functions stay catalogless).
546fn part_value(part: &Part, catalog_id: &str) -> Value {
547    match part {
548        Part::Literal(value) => value.clone(),
549        Part::Path(path) => json!({ "@path": path }),
550        Part::Call { name, args } => {
551            let args: Map<String, Value> = args
552                .iter()
553                .map(|(key, value)| (key.clone(), part_value(value, catalog_id)))
554                .collect();
555            let mut call = Map::new();
556            call.insert("@call".into(), Value::String(name.clone()));
557            call.insert("args".into(), Value::Object(args));
558            if !name.starts_with('@') {
559                call.insert("catalogId".into(), Value::String(catalog_id.into()));
560            }
561            Value::Object(call)
562        }
563    }
564}
565
566/// The email check every reference SDK uses:
567/// `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`.
568fn is_email(value: &str) -> bool {
569    static EMAIL: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
570    EMAIL
571        .get_or_init(|| {
572            regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
573                .expect("email pattern")
574        })
575        .is_match(value)
576}