1use serde::{Deserialize, Deserializer, Serialize};
14use serde_json::{Map, Value};
15
16fn present<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Value>, D::Error> {
20 Value::deserialize(deserializer).map(Some)
21}
22
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25#[non_exhaustive]
26pub struct AgentMessage {
27 pub version: String,
29 #[serde(flatten)]
31 pub kind: AgentMessageKind,
32}
33
34impl AgentMessage {
35 pub fn new(kind: AgentMessageKind) -> Self {
37 Self {
38 version: crate::PROTOCOL_VERSION.to_string(),
39 kind,
40 }
41 }
42
43 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59#[non_exhaustive]
60pub enum AgentMessageKind {
61 CreateSurface(CreateSurface),
63 UpdateComponents(UpdateComponents),
65 UpdateDataModel(UpdateDataModel),
67 DeleteSurface(DeleteSurface),
69 CallRendererFunction(CallRendererFunction),
71 AgentFunctionResponse(FunctionResponse),
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78#[non_exhaustive]
79pub struct CreateSurface {
80 pub surface_id: String,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub catalog_id: Option<String>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub send_data_model: Option<bool>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub components: Option<Vec<Component>>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub data_model: Option<Map<String, Value>>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub metadata: Option<Value>,
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102#[non_exhaustive]
103pub struct UpdateComponents {
104 pub surface_id: String,
106 pub components: Vec<Component>,
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112#[serde(rename_all = "camelCase")]
113#[non_exhaustive]
114pub struct UpdateDataModel {
115 pub surface_id: String,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub path: Option<String>,
120 pub value: Value,
122}
123
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub struct DeleteSurface {
129 pub surface_id: String,
131}
132
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135#[serde(rename_all = "camelCase")]
136#[non_exhaustive]
137pub struct CallRendererFunction {
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub surface_id: Option<String>,
141 pub function_call_id: String,
143 pub call_function: FunctionCall,
145}
146
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150#[non_exhaustive]
151pub struct FunctionCall {
152 #[serde(rename = "@call")]
154 pub call: String,
155 #[serde(rename = "catalogId", default, skip_serializing_if = "Option::is_none")]
157 pub catalog_id: Option<String>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub args: Option<Map<String, Value>>,
161}
162
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166#[non_exhaustive]
167pub struct FunctionResponse {
168 pub function_call_id: String,
170 #[serde(
172 default,
173 deserialize_with = "present",
174 skip_serializing_if = "Option::is_none"
175 )]
176 pub value: Option<Value>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub error: Option<ErrorBody>,
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184#[non_exhaustive]
185pub struct ErrorBody {
186 pub code: String,
188 pub message: String,
190}
191
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196#[non_exhaustive]
197pub struct Component {
198 pub id: String,
200 pub component: String,
202 #[serde(
204 rename = "@catalogId",
205 default,
206 skip_serializing_if = "Option::is_none"
207 )]
208 pub catalog_id: Option<String>,
209 #[serde(
211 rename = "@accessibility",
212 default,
213 skip_serializing_if = "Option::is_none"
214 )]
215 pub accessibility: Option<Value>,
216 #[serde(rename = "@metadata", default, skip_serializing_if = "Option::is_none")]
218 pub metadata: Option<Value>,
219 #[serde(rename = "@checks", default, skip_serializing_if = "Option::is_none")]
221 pub checks: Option<Vec<CheckRule>>,
222 #[serde(flatten)]
224 pub properties: Map<String, Value>,
225}
226
227#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
230#[non_exhaustive]
231pub struct CheckRule {
232 pub condition: Value,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub message: Option<String>,
238}
239
240#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242#[non_exhaustive]
243pub struct RendererMessage {
244 pub version: String,
246 #[serde(flatten)]
248 pub kind: RendererMessageKind,
249}
250
251impl RendererMessage {
252 pub fn new(kind: RendererMessageKind) -> Self {
254 Self {
255 version: crate::PROTOCOL_VERSION.to_string(),
256 kind,
257 }
258 }
259}
260
261#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase")]
264#[non_exhaustive]
265pub enum RendererMessageKind {
266 Action(Action),
268 CallAgentFunction(CallAgentFunction),
270 RendererFunctionResponse(FunctionResponse),
272 Error(RendererError),
274}
275
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278#[serde(rename_all = "camelCase")]
279#[non_exhaustive]
280pub struct Action {
281 pub name: String,
283 pub surface_id: String,
285 pub source_component_id: String,
287 pub timestamp: String,
289 pub context: Map<String, Value>,
291 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub user_message: Option<String>,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub metadata: Option<Value>,
297}
298
299impl Action {
300 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase")]
323#[non_exhaustive]
324pub struct CallAgentFunction {
325 pub surface_id: String,
327 pub function_call_id: String,
329 pub call_function: FunctionCall,
331}
332
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
335#[serde(rename_all = "camelCase")]
336#[non_exhaustive]
337pub struct RendererError {
338 pub code: String,
340 pub message: String,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub surface_id: Option<String>,
345 #[serde(default, skip_serializing_if = "Option::is_none")]
347 pub path: Option<String>,
348 #[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}