Skip to main content

adk_surface/genui/
a2ui.rs

1//! The A2UI v0.9.1 model (spec 3.3 §6.1 `genui`): the messages an agent sends a renderer and
2//! a renderer sends back, dynamic strings, the data model, JSON lines, stable component ids
3//! and capability sets. It is the internal form a drawing is stored and checked in;
4//! [`super::wire`] writes it in A2UI 1.0 (the default) or v0.9.1 and reads either.
5//!
6//! Ported from `adk-ui` (commit `5a82754`) onto adk-core 3.
7
8use std::collections::BTreeMap;
9
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14use super::catalog::{Catalogs, FORMS_CATALOG_ID};
15
16/// The A2UI version every envelope carries.
17pub const A2UI_VERSION: &str = "v0.9.1";
18
19/// The media type of an A2UI payload.
20pub const A2UI_MIME_TYPE: &str = "application/a2ui+json";
21
22/// What can go wrong reading A2UI (spec 3.3 §6.1 `genui`).
23#[derive(Debug, thiserror::Error)]
24pub enum A2uiError {
25    /// A JSON line is not an A2UI message.
26    #[error("line {line} is not an A2UI v0.9.1 message: {source}. Send one message per line.")]
27    Line {
28        /// The line's number, from 1.
29        line: usize,
30        /// Why it does not parse.
31        #[source]
32        source: serde_json::Error,
33    },
34    /// A data model path is not a JSON pointer.
35    #[error("'{path}' is not a data model path: a path starts with '/', like '/user/name'")]
36    Path {
37        /// The path.
38        path: String,
39    },
40}
41
42/// One agent-to-renderer message: its version and its body (A2UI v0.9.1
43/// `server_to_client.json`).
44///
45/// # Example
46///
47/// ```rust
48/// use adk_surface::genui::{A2uiBody, A2uiMessage};
49///
50/// let message = A2uiMessage::create_surface("invoice-10");
51/// let wire = serde_json::to_value(&message).unwrap();
52/// assert_eq!(wire["version"], "v0.9.1");
53/// assert_eq!(wire["createSurface"]["surfaceId"], "invoice-10");
54/// assert!(matches!(message.body, A2uiBody::CreateSurface(_)));
55/// ```
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
57pub struct A2uiMessage {
58    /// The protocol version, `v0.9.1`.
59    pub version: String,
60    /// What the message does.
61    #[serde(flatten)]
62    pub body: A2uiBody,
63}
64
65/// What an [`A2uiMessage`] does.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
67#[serde(rename_all = "camelCase")]
68pub enum A2uiBody {
69    /// Starts a surface.
70    CreateSurface(CreateSurface),
71    /// Sets a surface's components.
72    UpdateComponents(UpdateComponents),
73    /// Sets or removes a value in a surface's data model.
74    UpdateDataModel(UpdateDataModel),
75    /// Removes a surface.
76    DeleteSurface(DeleteSurface),
77}
78
79/// The body of a `createSurface` message.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
81#[serde(rename_all = "camelCase", deny_unknown_fields)]
82pub struct CreateSurface {
83    /// The surface's id.
84    pub surface_id: String,
85    /// The catalog its components come from.
86    pub catalog_id: String,
87    /// Theme parameters. Drawn surfaces carry none: the home draws them in its own colours.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub theme: Option<Value>,
90    /// Whether the renderer sends the data model back with every action.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub send_data_model: Option<bool>,
93}
94
95/// The body of an `updateComponents` message.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
97#[serde(rename_all = "camelCase", deny_unknown_fields)]
98pub struct UpdateComponents {
99    /// The surface's id.
100    pub surface_id: String,
101    /// Every component of the surface, one with id `root`.
102    pub components: Vec<Value>,
103}
104
105/// The body of an `updateDataModel` message.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
107#[serde(rename_all = "camelCase", deny_unknown_fields)]
108pub struct UpdateDataModel {
109    /// The surface's id.
110    pub surface_id: String,
111    /// Where in the data model, as a JSON pointer; absent or `/` is the whole model.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub path: Option<String>,
114    /// The value set at `path`; absent or `null` removes it.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub value: Option<Value>,
117}
118
119/// The body of a `deleteSurface` message.
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
121#[serde(rename_all = "camelCase", deny_unknown_fields)]
122pub struct DeleteSurface {
123    /// The surface's id.
124    pub surface_id: String,
125}
126
127impl A2uiMessage {
128    fn new(body: A2uiBody) -> Self {
129        Self { version: A2UI_VERSION.to_string(), body }
130    }
131
132    /// A `createSurface` for `surface_id` on the `forms` 1.0 catalog, with no theme.
133    pub fn create_surface(surface_id: impl Into<String>) -> Self {
134        Self::new(A2uiBody::CreateSurface(CreateSurface {
135            surface_id: surface_id.into(),
136            catalog_id: FORMS_CATALOG_ID.to_string(),
137            theme: None,
138            send_data_model: None,
139        }))
140    }
141
142    /// An `updateComponents` setting every component of `surface_id`.
143    pub fn update_components(surface_id: impl Into<String>, components: Vec<Value>) -> Self {
144        Self::new(A2uiBody::UpdateComponents(UpdateComponents {
145            surface_id: surface_id.into(),
146            components,
147        }))
148    }
149
150    /// An `updateDataModel` setting `value` at `path` of `surface_id`'s data model.
151    pub fn update_data_model(
152        surface_id: impl Into<String>,
153        path: Option<String>,
154        value: Option<Value>,
155    ) -> Self {
156        Self::new(A2uiBody::UpdateDataModel(UpdateDataModel {
157            surface_id: surface_id.into(),
158            path,
159            value,
160        }))
161    }
162
163    /// A `deleteSurface` for `surface_id`.
164    pub fn delete_surface(surface_id: impl Into<String>) -> Self {
165        Self::new(A2uiBody::DeleteSurface(DeleteSurface { surface_id: surface_id.into() }))
166    }
167
168    /// The surface the message is for.
169    pub fn surface_id(&self) -> &str {
170        match &self.body {
171            A2uiBody::CreateSurface(body) => &body.surface_id,
172            A2uiBody::UpdateComponents(body) => &body.surface_id,
173            A2uiBody::UpdateDataModel(body) => &body.surface_id,
174            A2uiBody::DeleteSurface(body) => &body.surface_id,
175        }
176    }
177}
178
179/// One renderer-to-agent message: an action a person took, or an error the renderer
180/// reports (A2UI v0.9.1 `client_to_server.json`).
181///
182/// A drawn surface's actions never reach the agent this way: a person's Send becomes a
183/// requested call through the engine (spec 3.3 §7.4 rule 5). The type reads what an
184/// A2UI renderer sends.
185///
186/// # Example
187///
188/// ```rust
189/// use adk_surface::genui::{A2uiClientBody, A2uiClientMessage};
190///
191/// let message: A2uiClientMessage = serde_json::from_value(serde_json::json!({
192///     "version": "v0.9.1",
193///     "action": {
194///         "name": "send",
195///         "surfaceId": "invoice-10",
196///         "sourceComponentId": "send-button",
197///         "timestamp": "2026-10-26T10:03:00Z",
198///         "context": {}
199///     }
200/// }))
201/// .unwrap();
202/// assert!(matches!(message.body, A2uiClientBody::Action(ref action) if action.name == "send"));
203/// ```
204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
205pub struct A2uiClientMessage {
206    /// The protocol version, `v0.9.1`.
207    pub version: String,
208    /// What the renderer reports.
209    #[serde(flatten)]
210    pub body: A2uiClientBody,
211}
212
213/// What an [`A2uiClientMessage`] reports.
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
215#[serde(rename_all = "camelCase")]
216pub enum A2uiClientBody {
217    /// A person used a control that dispatches an event.
218    Action(ClientAction),
219    /// The renderer could not show a message.
220    Error(ClientError),
221}
222
223/// A person used a control that dispatches an event.
224#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
225#[serde(rename_all = "camelCase")]
226pub struct ClientAction {
227    /// The event's name.
228    pub name: String,
229    /// The surface it happened on.
230    pub surface_id: String,
231    /// The component that dispatched it.
232    pub source_component_id: String,
233    /// When, in RFC 3339.
234    pub timestamp: String,
235    /// The event's context, with bound values resolved.
236    #[serde(default)]
237    pub context: Value,
238}
239
240/// The renderer could not show a message.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
242#[serde(rename_all = "camelCase")]
243pub struct ClientError {
244    /// `VALIDATION_FAILED`, or another code.
245    pub code: String,
246    /// The surface.
247    pub surface_id: String,
248    /// Where in the message, as a JSON pointer.
249    pub path: String,
250    /// What went wrong.
251    pub message: String,
252}
253
254/// A string a component shows: a literal, a binding to the data model, or a function call
255/// that returns a string (A2UI v0.9.1 `DynamicString`).
256///
257/// # Example
258///
259/// ```rust
260/// use adk_surface::genui::DynamicString;
261/// use serde_json::json;
262///
263/// let bound: DynamicString = serde_json::from_value(json!({ "path": "/to" })).unwrap();
264/// assert_eq!(bound, DynamicString::path("/to"));
265/// assert_eq!(serde_json::to_value(DynamicString::literal("To")).unwrap(), json!("To"));
266/// ```
267#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
268#[serde(untagged)]
269pub enum DynamicString {
270    /// The text itself.
271    Literal(String),
272    /// The value at a data model path.
273    Binding(DataBinding),
274    /// A function's result.
275    Call(FunctionCall),
276}
277
278impl DynamicString {
279    /// The text `value`.
280    pub fn literal(value: impl Into<String>) -> Self {
281        Self::Literal(value.into())
282    }
283
284    /// The value at `path`.
285    pub fn path(path: impl Into<String>) -> Self {
286        Self::Binding(DataBinding { path: path.into() })
287    }
288}
289
290/// A binding to a data model value: an absolute JSON pointer such as `/user/name`, or a path
291/// relative to the list item a template renders.
292#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
293#[serde(deny_unknown_fields)]
294pub struct DataBinding {
295    /// The path.
296    pub path: String,
297}
298
299/// A call of a catalog function.
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
301#[serde(rename_all = "camelCase", deny_unknown_fields)]
302pub struct FunctionCall {
303    /// The function's name.
304    pub call: String,
305    /// Its named arguments.
306    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
307    pub args: BTreeMap<String, Value>,
308    /// The type it returns.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub return_type: Option<String>,
311}
312
313/// A surface's data model: the JSON its components bind to.
314///
315/// # Example
316///
317/// ```rust
318/// use adk_surface::genui::DataModel;
319/// use serde_json::json;
320///
321/// let mut model = DataModel::default();
322/// model.apply(Some("/invoice/to"), Some(json!("ana@example.com")))?;
323/// assert_eq!(model.get("/invoice/to"), Some(&json!("ana@example.com")));
324/// model.apply(Some("/invoice/to"), None)?;
325/// assert_eq!(model.value(), &json!({ "invoice": {} }));
326/// # Ok::<(), adk_surface::genui::A2uiError>(())
327/// ```
328#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
329#[serde(transparent)]
330pub struct DataModel(Value);
331
332impl DataModel {
333    /// A data model holding `value`.
334    pub fn new(value: Value) -> Self {
335        Self(value)
336    }
337
338    /// The whole model.
339    pub fn value(&self) -> &Value {
340        &self.0
341    }
342
343    /// The value at `pointer`, or `None`.
344    pub fn get(&self, pointer: &str) -> Option<&Value> {
345        if pointer.is_empty() || pointer == "/" {
346            return Some(&self.0);
347        }
348        self.0.pointer(pointer)
349    }
350
351    /// Applies an `updateDataModel`: sets `value` at `path`, creating the objects on the way,
352    /// or removes what is there when `value` is `None` or `null`. An absent path or `/` is the
353    /// whole model.
354    ///
355    /// # Errors
356    ///
357    /// Returns [`A2uiError::Path`] when `path` does not start with `/`.
358    pub fn apply(&mut self, path: Option<&str>, value: Option<Value>) -> Result<(), A2uiError> {
359        let value = value.filter(|value| !value.is_null());
360        let path = path.unwrap_or("/");
361        if path == "/" || path.is_empty() {
362            self.0 = value.unwrap_or(Value::Null);
363            return Ok(());
364        }
365        let invalid = || A2uiError::Path { path: path.to_string() };
366        let rest = path.strip_prefix('/').ok_or_else(invalid)?;
367        let tokens: Vec<String> =
368            rest.split('/').map(|token| token.replace("~1", "/").replace("~0", "~")).collect();
369        let Some((last, parents)) = tokens.split_last() else {
370            return Err(invalid());
371        };
372        let setting = value.is_some();
373        let mut node = &mut self.0;
374        for token in parents {
375            if setting && !node.is_object() && !node.is_array() {
376                *node = Value::Object(serde_json::Map::new());
377            }
378            node = match (node, setting) {
379                (Value::Object(map), true) => map
380                    .entry(token.clone())
381                    .or_insert_with(|| Value::Object(serde_json::Map::new())),
382                (Value::Object(map), false) => match map.get_mut(token) {
383                    Some(next) => next,
384                    None => return Ok(()),
385                },
386                (Value::Array(items), _) => match token.parse::<usize>() {
387                    Ok(index) if index < items.len() => &mut items[index],
388                    _ if setting => return Err(invalid()),
389                    _ => return Ok(()),
390                },
391                // Removing below a value that is not a container removes nothing.
392                _ => return Ok(()),
393            };
394        }
395        match (node, value) {
396            (Value::Object(map), Some(value)) => {
397                map.insert(last.clone(), value);
398            }
399            (Value::Object(map), None) => {
400                map.remove(last);
401            }
402            (Value::Array(items), Some(value)) => match last.parse::<usize>() {
403                Ok(index) if index < items.len() => items[index] = value,
404                Ok(index) if index == items.len() => items.push(value),
405                _ => return Err(invalid()),
406            },
407            (Value::Array(items), None) => {
408                if let Ok(index) = last.parse::<usize>()
409                    && index < items.len()
410                {
411                    items.remove(index);
412                }
413            }
414            (node, Some(value)) => {
415                let mut map = serde_json::Map::new();
416                map.insert(last.clone(), value);
417                *node = Value::Object(map);
418            }
419            (_, None) => {}
420        }
421        Ok(())
422    }
423}
424
425/// Encodes `messages` as JSON lines, one message per line.
426///
427/// # Example
428///
429/// ```rust
430/// use adk_surface::genui::{A2uiMessage, decode_jsonl, encode_jsonl};
431///
432/// let messages = vec![A2uiMessage::create_surface("s"), A2uiMessage::delete_surface("s")];
433/// let lines = encode_jsonl(&messages);
434/// assert_eq!(lines.lines().count(), 2);
435/// assert_eq!(decode_jsonl(&lines)?, messages);
436/// # Ok::<(), adk_surface::genui::A2uiError>(())
437/// ```
438pub fn encode_jsonl(messages: &[A2uiMessage]) -> String {
439    let mut out = String::new();
440    for message in messages {
441        // An A2UI message is plain JSON data, so it always serializes.
442        out.push_str(&serde_json::to_string(message).unwrap_or_default());
443        out.push('\n');
444    }
445    out
446}
447
448/// Decodes JSON lines into messages; blank lines are skipped.
449///
450/// # Errors
451///
452/// Returns [`A2uiError::Line`] for the first line that is not an A2UI message.
453pub fn decode_jsonl(text: &str) -> Result<Vec<A2uiMessage>, A2uiError> {
454    text.lines()
455        .enumerate()
456        .filter(|(_, line)| !line.trim().is_empty())
457        .map(|(index, line)| {
458            serde_json::from_str(line).map_err(|source| A2uiError::Line { line: index + 1, source })
459        })
460        .collect()
461}
462
463/// A deterministic component id from `seed`: `id_` and a 64-bit FNV-1a hash in hex.
464///
465/// # Example
466///
467/// ```rust
468/// use adk_surface::genui::stable_id;
469///
470/// assert_eq!(stable_id("form:to"), stable_id("form:to"));
471/// assert_ne!(stable_id("form:to"), stable_id("form:amount"));
472/// assert!(stable_id("x").starts_with("id_"));
473/// ```
474pub fn stable_id(seed: &str) -> String {
475    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
476    const PRIME: u64 = 0x0100_0000_01b3;
477    let hash = seed.bytes().fold(OFFSET, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(PRIME));
478    format!("id_{hash:016x}")
479}
480
481/// The catalogs a renderer or an agent supports, by A2UI version family: A2UI 1.0
482/// `renderer_capabilities.json` keys them `1.0`, and v0.9.1 `client_capabilities.json` keys
483/// them `v0.9`.
484///
485/// # Example
486///
487/// ```rust
488/// use adk_surface::genui::{A2uiCapabilities, A2uiVersion, FORMS_CATALOG_ID};
489///
490/// let wire = serde_json::to_value(A2uiCapabilities::forms()).unwrap();
491/// assert_eq!(wire["1.0"]["supportedCatalogIds"][0], FORMS_CATALOG_ID);
492/// assert_eq!(wire["v0.9"]["supportedCatalogIds"][0], FORMS_CATALOG_ID);
493///
494/// // A renderer that offers only v0.9 is written to in v0.9.1.
495/// let renderer: A2uiCapabilities = serde_json::from_value(serde_json::json!({
496///     "v0.9": { "supportedCatalogIds": [FORMS_CATALOG_ID] }
497/// })).unwrap();
498/// assert_eq!(renderer.preferred(), Some(A2uiVersion::V0_9_1));
499/// ```
500#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
501pub struct A2uiCapabilities {
502    /// What 1.0 supports.
503    #[serde(rename = "1.0", default, skip_serializing_if = "Option::is_none")]
504    pub v1_0: Option<CapabilitySet>,
505    /// What v0.9 and v0.9.1 support.
506    #[serde(rename = "v0.9", default, skip_serializing_if = "Option::is_none")]
507    pub v0_9: Option<CapabilitySet>,
508}
509
510impl A2uiCapabilities {
511    /// The `forms` 1.0 catalog only, with no inline catalogs, in 1.0 and v0.9.1: what this
512    /// home renders.
513    pub fn forms() -> Self {
514        let set = CapabilitySet {
515            supported_catalog_ids: vec![FORMS_CATALOG_ID.to_string()],
516            accepts_inline_catalogs: false,
517        };
518        Self { v1_0: Some(set.clone()), v0_9: Some(set) }
519    }
520
521    /// Every catalog in `catalogs`, `forms` first, with no inline catalogs, in 1.0 and v0.9.1:
522    /// what a home that registers extension catalogs renders.
523    pub fn of(catalogs: &Catalogs) -> Self {
524        let set = CapabilitySet {
525            supported_catalog_ids: catalogs
526                .iter()
527                .map(|catalog| catalog.id().to_string())
528                .collect(),
529            accepts_inline_catalogs: false,
530        };
531        Self { v1_0: Some(set.clone()), v0_9: Some(set) }
532    }
533
534    /// The newest version these capabilities offer, if any.
535    pub fn preferred(&self) -> Option<super::wire::A2uiVersion> {
536        use super::wire::A2uiVersion;
537        if self.v1_0.is_some() {
538            Some(A2uiVersion::V1_0)
539        } else if self.v0_9.is_some() {
540            Some(A2uiVersion::V0_9_1)
541        } else {
542            None
543        }
544    }
545}
546
547/// The catalogs supported under one A2UI version family.
548#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
549#[serde(rename_all = "camelCase")]
550pub struct CapabilitySet {
551    /// Catalog ids, by preference. In 1.0 they mix on one surface.
552    pub supported_catalog_ids: Vec<String>,
553    /// Whether catalogs sent inline are accepted. Drawn surfaces never use one.
554    #[serde(default)]
555    pub accepts_inline_catalogs: bool,
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use serde_json::json;
562
563    #[test]
564    fn messages_round_trip_through_the_upstream_wire_shape() {
565        let wire = json!({
566            "version": "v0.9.1",
567            "updateDataModel": { "surfaceId": "s", "path": "/to", "value": "ana@example.com" }
568        });
569        let message: A2uiMessage = serde_json::from_value(wire.clone()).unwrap();
570        assert_eq!(
571            message,
572            A2uiMessage::update_data_model(
573                "s",
574                Some("/to".to_string()),
575                Some(json!("ana@example.com"))
576            )
577        );
578        assert_eq!(serde_json::to_value(&message).unwrap(), wire);
579    }
580
581    #[test]
582    fn an_unknown_body_or_field_is_not_a_message() {
583        for wire in [
584            json!({ "version": "v0.9.1", "callFunction": { "call": "x" } }),
585            json!({ "version": "v0.9.1", "deleteSurface": { "surfaceId": "s", "extra": 1 } }),
586        ] {
587            assert!(serde_json::from_value::<A2uiMessage>(wire.clone()).is_err(), "{wire}");
588        }
589    }
590
591    #[test]
592    fn decoding_names_the_line_that_fails() {
593        let error = decode_jsonl(
594            "{\"version\":\"v0.9.1\",\"deleteSurface\":{\"surfaceId\":\"s\"}}\n\nnope\n",
595        )
596        .unwrap_err();
597        assert!(matches!(error, A2uiError::Line { line: 3, .. }), "{error}");
598    }
599
600    #[test]
601    fn the_data_model_sets_and_removes_values_in_objects_and_arrays() {
602        let mut model = DataModel::new(json!({ "rows": [{ "a": 1 }] }));
603        model.apply(Some("/rows/0/a"), Some(json!(2))).unwrap();
604        model.apply(Some("/rows/1"), Some(json!({ "a": 3 }))).unwrap();
605        model.apply(Some("/a~1b"), Some(json!("slash"))).unwrap();
606        assert_eq!(model.value(), &json!({ "rows": [{ "a": 2 }, { "a": 3 }], "a/b": "slash" }));
607        model.apply(Some("/rows/0"), None).unwrap();
608        model.apply(Some("/missing/deep"), None).unwrap();
609        assert_eq!(model.value(), &json!({ "rows": [{ "a": 3 }], "a/b": "slash" }));
610        assert!(model.apply(Some("rows"), Some(json!(1))).is_err());
611        assert!(model.apply(Some("/rows/7"), Some(json!(1))).is_err());
612        model.apply(None, Some(json!({ "fresh": true }))).unwrap();
613        assert_eq!(model.value(), &json!({ "fresh": true }));
614    }
615}