Skip to main content

agent86_ui/
message.rs

1//! The A2UI 1.0 messages, as typed Rust values.
2//!
3//! Every message on the wire is one JSON object carrying `"version": "1.0"` and
4//! exactly one key naming its kind. [`AgentMessage`] and [`RendererMessage`]
5//! keep that shape: a `version` and a flattened kind. Component properties stay
6//! JSON ([`Component::properties`]), since what they may hold is the catalog's
7//! business, not the protocol's.
8//!
9//! Deserializing is lenient about what the schema is strict about (unknown keys
10//! are kept or ignored); [`crate::Validator`] runs the schema first, so a value
11//! that reached these types through it is well-formed.
12
13use serde::{Deserialize, Deserializer, Serialize};
14use serde_json::{Map, Value};
15
16/// An explicit `null` stays `Some(Value::Null)`; only an absent field is `None`.
17/// (`value: null` in `updateDataModel` deletes, and a function may return
18/// `null`, so the two must not collapse.)
19fn present<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Value>, D::Error> {
20    Value::deserialize(deserializer).map(Some)
21}
22
23/// A message from the agent to the renderer.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25#[non_exhaustive]
26pub struct AgentMessage {
27    /// The protocol version, `"1.0"`.
28    pub version: String,
29    /// What the message does.
30    #[serde(flatten)]
31    pub kind: AgentMessageKind,
32}
33
34impl AgentMessage {
35    /// A 1.0 message of this kind.
36    pub fn new(kind: AgentMessageKind) -> Self {
37        Self {
38            version: crate::PROTOCOL_VERSION.to_string(),
39            kind,
40        }
41    }
42
43    /// The surface the message is about, when it names one.
44    pub fn surface_id(&self) -> Option<&str> {
45        match &self.kind {
46            AgentMessageKind::CreateSurface(m) => Some(&m.surface_id),
47            AgentMessageKind::UpdateComponents(m) => Some(&m.surface_id),
48            AgentMessageKind::UpdateDataModel(m) => Some(&m.surface_id),
49            AgentMessageKind::DeleteSurface(m) => Some(&m.surface_id),
50            AgentMessageKind::CallRendererFunction(m) => m.surface_id.as_deref(),
51            AgentMessageKind::AgentFunctionResponse(_) => None,
52        }
53    }
54}
55
56/// The kinds of agent-to-renderer message.
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59#[non_exhaustive]
60pub enum AgentMessageKind {
61    /// Create a surface, optionally with its components and data model.
62    CreateSurface(CreateSurface),
63    /// Add or replace components on a surface.
64    UpdateComponents(UpdateComponents),
65    /// Set or delete a value in a surface's data model.
66    UpdateDataModel(UpdateDataModel),
67    /// Remove a surface.
68    DeleteSurface(DeleteSurface),
69    /// Ask the renderer to run one of its functions.
70    CallRendererFunction(CallRendererFunction),
71    /// Answer a `callAgentFunction` from the renderer.
72    AgentFunctionResponse(FunctionResponse),
73}
74
75/// `createSurface`.
76#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78#[non_exhaustive]
79pub struct CreateSurface {
80    /// Unique for the renderer's lifetime.
81    pub surface_id: String,
82    /// The surface's default catalog.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub catalog_id: Option<String>,
85    /// Whether the renderer sends the data model back with each message.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub send_data_model: Option<bool>,
88    /// Components to start with.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub components: Option<Vec<Component>>,
91    /// The initial data model, applied before the components.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub data_model: Option<Map<String, Value>>,
94    /// Surface metadata (`extensions`).
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub metadata: Option<Value>,
97}
98
99/// `updateComponents`.
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102#[non_exhaustive]
103pub struct UpdateComponents {
104    /// The surface to update.
105    pub surface_id: String,
106    /// Components to add, or to replace by id.
107    pub components: Vec<Component>,
108}
109
110/// `updateDataModel`.
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112#[serde(rename_all = "camelCase")]
113#[non_exhaustive]
114pub struct UpdateDataModel {
115    /// The surface whose data model changes.
116    pub surface_id: String,
117    /// A JSON Pointer; absent or `/` means the whole model.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub path: Option<String>,
120    /// The new value; `null` deletes the key at `path`.
121    pub value: Value,
122}
123
124/// `deleteSurface`.
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub struct DeleteSurface {
129    /// The surface to remove.
130    pub surface_id: String,
131}
132
133/// `callRendererFunction`.
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135#[serde(rename_all = "camelCase")]
136#[non_exhaustive]
137pub struct CallRendererFunction {
138    /// The surface whose data model the call reads, if any.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub surface_id: Option<String>,
141    /// Echoed in the renderer's response.
142    pub function_call_id: String,
143    /// The call (its `catalogId` is required here).
144    pub call_function: FunctionCall,
145}
146
147/// A call to a catalog function, as it appears in bindings, checks, actions,
148/// and the function-call messages.
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150#[non_exhaustive]
151pub struct FunctionCall {
152    /// The function's name.
153    #[serde(rename = "@call")]
154    pub call: String,
155    /// The catalog to resolve it in, overriding the surface's default.
156    #[serde(rename = "catalogId", default, skip_serializing_if = "Option::is_none")]
157    pub catalog_id: Option<String>,
158    /// The arguments, as the function's schema defines them.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub args: Option<Map<String, Value>>,
161}
162
163/// `agentFunctionResponse` and `rendererFunctionResponse`: a value or an error.
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166#[non_exhaustive]
167pub struct FunctionResponse {
168    /// The id of the call this answers.
169    pub function_call_id: String,
170    /// The result, when the call succeeded (`null` is a result).
171    #[serde(
172        default,
173        deserialize_with = "present",
174        skip_serializing_if = "Option::is_none"
175    )]
176    pub value: Option<Value>,
177    /// The failure, when it did not.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub error: Option<ErrorBody>,
180}
181
182/// A function response's `error`.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184#[non_exhaustive]
185pub struct ErrorBody {
186    /// A machine-readable code.
187    pub code: String,
188    /// What went wrong.
189    pub message: String,
190}
191
192/// One component on a surface. `id` and `component` are the protocol's; the
193/// `@`-prefixed fields are its envelope mixins; everything else is the
194/// catalog's, kept as JSON in [`Component::properties`].
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196#[non_exhaustive]
197pub struct Component {
198    /// Unique on its surface; a UAX #31 identifier.
199    pub id: String,
200    /// The component type, from the catalog.
201    pub component: String,
202    /// The catalog to resolve the type in, overriding the surface's default.
203    #[serde(
204        rename = "@catalogId",
205        default,
206        skip_serializing_if = "Option::is_none"
207    )]
208    pub catalog_id: Option<String>,
209    /// `label`, `description`, `live`, and `hidden`, for assistive technologies.
210    #[serde(
211        rename = "@accessibility",
212        default,
213        skip_serializing_if = "Option::is_none"
214    )]
215    pub accessibility: Option<Value>,
216    /// Vendor metadata (`extensions`).
217    #[serde(rename = "@metadata", default, skip_serializing_if = "Option::is_none")]
218    pub metadata: Option<Value>,
219    /// Renderer-side checks, on checkable components.
220    #[serde(rename = "@checks", default, skip_serializing_if = "Option::is_none")]
221    pub checks: Option<Vec<CheckRule>>,
222    /// The catalog's properties for this type (`text`, `children`, `action`, ...).
223    #[serde(flatten)]
224    pub properties: Map<String, Value>,
225}
226
227/// One `@checks` rule: a condition (a binding or a function call) and the
228/// message to show when it fails.
229#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
230#[non_exhaustive]
231pub struct CheckRule {
232    /// A `{"@path": ...}` or a function call, evaluating to a boolean or a
233    /// validation result.
234    pub condition: Value,
235    /// The fallback message.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub message: Option<String>,
238}
239
240/// A message from the renderer to the agent.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242#[non_exhaustive]
243pub struct RendererMessage {
244    /// The protocol version, `"1.0"`.
245    pub version: String,
246    /// What the message reports.
247    #[serde(flatten)]
248    pub kind: RendererMessageKind,
249}
250
251impl RendererMessage {
252    /// A 1.0 message of this kind.
253    pub fn new(kind: RendererMessageKind) -> Self {
254        Self {
255            version: crate::PROTOCOL_VERSION.to_string(),
256            kind,
257        }
258    }
259}
260
261/// The kinds of renderer-to-agent message.
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase")]
264#[non_exhaustive]
265pub enum RendererMessageKind {
266    /// The user did something a component's action sends to the agent.
267    Action(Action),
268    /// The renderer asks the agent to run a function.
269    CallAgentFunction(CallAgentFunction),
270    /// The answer to a `callRendererFunction`.
271    RendererFunctionResponse(FunctionResponse),
272    /// A validation, integrity, or evaluation error on the renderer.
273    Error(RendererError),
274}
275
276/// `action`: a user interaction with a component whose action is an event.
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278#[serde(rename_all = "camelCase")]
279#[non_exhaustive]
280pub struct Action {
281    /// The event's name, from the component's `action.event.name`.
282    pub name: String,
283    /// The surface it happened on.
284    pub surface_id: String,
285    /// The component that triggered it.
286    pub source_component_id: String,
287    /// When, as an RFC 3339 date-time.
288    pub timestamp: String,
289    /// The event's `context`, with every binding resolved.
290    pub context: Map<String, Value>,
291    /// The event's `userMessage`, resolved.
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub user_message: Option<String>,
294    /// Renderer metadata (`extensions`).
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub metadata: Option<Value>,
297}
298
299impl Action {
300    /// An action as a renderer reports it.
301    pub fn new(
302        name: impl Into<String>,
303        surface_id: impl Into<String>,
304        source_component_id: impl Into<String>,
305        timestamp: impl Into<String>,
306        context: Map<String, Value>,
307    ) -> Self {
308        Self {
309            name: name.into(),
310            surface_id: surface_id.into(),
311            source_component_id: source_component_id.into(),
312            timestamp: timestamp.into(),
313            context,
314            user_message: None,
315            metadata: None,
316        }
317    }
318}
319
320/// `callAgentFunction`.
321#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase")]
323#[non_exhaustive]
324pub struct CallAgentFunction {
325    /// The surface the call came from.
326    pub surface_id: String,
327    /// To be echoed in the agent's response.
328    pub function_call_id: String,
329    /// The call.
330    pub call_function: FunctionCall,
331}
332
333/// A renderer's `error` message.
334#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
335#[serde(rename_all = "camelCase")]
336#[non_exhaustive]
337pub struct RendererError {
338    /// `VALIDATION_FAILED`, `UNALLOWED_PARENT`, `INTEGRITY_ERROR`, ...
339    pub code: String,
340    /// What went wrong.
341    pub message: String,
342    /// The surface, for surface errors.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub surface_id: Option<String>,
345    /// A JSON Pointer to the offending field, for validation errors.
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub path: Option<String>,
348    /// The function call, for function invocation errors.
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub function_call_id: Option<String>,
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use serde_json::json;
357
358    #[test]
359    fn an_agent_message_round_trips_with_its_version_first() {
360        let wire = json!({
361            "version": "1.0",
362            "createSurface": {
363                "surfaceId": "s1",
364                "catalogId": "c",
365                "components": [
366                    {"id": "root", "component": "Text", "text": {"@path": "/name"},
367                     "@accessibility": {"label": "Name"}}
368                ],
369                "dataModel": {"name": "Ada"}
370            }
371        });
372        let message: AgentMessage = serde_json::from_value(wire.clone()).unwrap();
373        let AgentMessageKind::CreateSurface(create) = &message.kind else {
374            panic!("not createSurface")
375        };
376        let root = &create.components.as_ref().unwrap()[0];
377        assert_eq!(root.component, "Text");
378        assert_eq!(root.properties["text"], json!({"@path": "/name"}));
379        assert_eq!(message.surface_id(), Some("s1"));
380        let back = serde_json::to_value(&message).unwrap();
381        assert_eq!(back, wire);
382        assert_eq!(
383            serde_json::to_string(&message).unwrap().find("\"version\""),
384            Some(1)
385        );
386    }
387
388    #[test]
389    fn a_null_value_is_kept_apart_from_a_missing_one() {
390        let delete: AgentMessage = serde_json::from_value(json!({
391            "version": "1.0",
392            "updateDataModel": {"surfaceId": "s", "path": "/a", "value": null}
393        }))
394        .unwrap();
395        let AgentMessageKind::UpdateDataModel(update) = delete.kind else {
396            panic!()
397        };
398        assert_eq!(update.value, Value::Null);
399
400        let response: FunctionResponse =
401            serde_json::from_value(json!({"functionCallId": "c", "value": null})).unwrap();
402        assert_eq!(response.value, Some(Value::Null));
403        let error: FunctionResponse = serde_json::from_value(
404            json!({"functionCallId": "c", "error": {"code": "X", "message": "m"}}),
405        )
406        .unwrap();
407        assert_eq!(error.value, None);
408    }
409
410    #[test]
411    fn an_action_serializes_as_the_specification_shows() {
412        let mut context = Map::new();
413        context.insert("isSubscribed".into(), json!(true));
414        let mut action = Action::new(
415            "submitForm",
416            "contact_form_1",
417            "submit_button",
418            "2026-06-02T08:57:23Z",
419            context,
420        );
421        action.user_message = Some("Submitted contact form".into());
422        let message = RendererMessage::new(RendererMessageKind::Action(action));
423        assert_eq!(
424            serde_json::to_value(&message).unwrap(),
425            json!({
426                "version": "1.0",
427                "action": {
428                    "name": "submitForm",
429                    "surfaceId": "contact_form_1",
430                    "sourceComponentId": "submit_button",
431                    "timestamp": "2026-06-02T08:57:23Z",
432                    "context": {"isSubscribed": true},
433                    "userMessage": "Submitted contact form"
434                }
435            })
436        );
437    }
438}