1use std::collections::BTreeMap;
9
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14use super::catalog::{Catalogs, FORMS_CATALOG_ID};
15
16pub const A2UI_VERSION: &str = "v0.9.1";
18
19pub const A2UI_MIME_TYPE: &str = "application/a2ui+json";
21
22#[derive(Debug, thiserror::Error)]
24pub enum A2uiError {
25 #[error("line {line} is not an A2UI v0.9.1 message: {source}. Send one message per line.")]
27 Line {
28 line: usize,
30 #[source]
32 source: serde_json::Error,
33 },
34 #[error("'{path}' is not a data model path: a path starts with '/', like '/user/name'")]
36 Path {
37 path: String,
39 },
40}
41
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
57pub struct A2uiMessage {
58 pub version: String,
60 #[serde(flatten)]
62 pub body: A2uiBody,
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
67#[serde(rename_all = "camelCase")]
68pub enum A2uiBody {
69 CreateSurface(CreateSurface),
71 UpdateComponents(UpdateComponents),
73 UpdateDataModel(UpdateDataModel),
75 DeleteSurface(DeleteSurface),
77}
78
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
81#[serde(rename_all = "camelCase", deny_unknown_fields)]
82pub struct CreateSurface {
83 pub surface_id: String,
85 pub catalog_id: String,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub theme: Option<Value>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub send_data_model: Option<bool>,
93}
94
95#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
97#[serde(rename_all = "camelCase", deny_unknown_fields)]
98pub struct UpdateComponents {
99 pub surface_id: String,
101 pub components: Vec<Value>,
103}
104
105#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
107#[serde(rename_all = "camelCase", deny_unknown_fields)]
108pub struct UpdateDataModel {
109 pub surface_id: String,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub path: Option<String>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub value: Option<Value>,
117}
118
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
121#[serde(rename_all = "camelCase", deny_unknown_fields)]
122pub struct DeleteSurface {
123 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 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 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 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 pub fn delete_surface(surface_id: impl Into<String>) -> Self {
165 Self::new(A2uiBody::DeleteSurface(DeleteSurface { surface_id: surface_id.into() }))
166 }
167
168 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
205pub struct A2uiClientMessage {
206 pub version: String,
208 #[serde(flatten)]
210 pub body: A2uiClientBody,
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
215#[serde(rename_all = "camelCase")]
216pub enum A2uiClientBody {
217 Action(ClientAction),
219 Error(ClientError),
221}
222
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
225#[serde(rename_all = "camelCase")]
226pub struct ClientAction {
227 pub name: String,
229 pub surface_id: String,
231 pub source_component_id: String,
233 pub timestamp: String,
235 #[serde(default)]
237 pub context: Value,
238}
239
240#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
242#[serde(rename_all = "camelCase")]
243pub struct ClientError {
244 pub code: String,
246 pub surface_id: String,
248 pub path: String,
250 pub message: String,
252}
253
254#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
268#[serde(untagged)]
269pub enum DynamicString {
270 Literal(String),
272 Binding(DataBinding),
274 Call(FunctionCall),
276}
277
278impl DynamicString {
279 pub fn literal(value: impl Into<String>) -> Self {
281 Self::Literal(value.into())
282 }
283
284 pub fn path(path: impl Into<String>) -> Self {
286 Self::Binding(DataBinding { path: path.into() })
287 }
288}
289
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
293#[serde(deny_unknown_fields)]
294pub struct DataBinding {
295 pub path: String,
297}
298
299#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
301#[serde(rename_all = "camelCase", deny_unknown_fields)]
302pub struct FunctionCall {
303 pub call: String,
305 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
307 pub args: BTreeMap<String, Value>,
308 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub return_type: Option<String>,
311}
312
313#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
329#[serde(transparent)]
330pub struct DataModel(Value);
331
332impl DataModel {
333 pub fn new(value: Value) -> Self {
335 Self(value)
336 }
337
338 pub fn value(&self) -> &Value {
340 &self.0
341 }
342
343 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 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 _ => 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
425pub fn encode_jsonl(messages: &[A2uiMessage]) -> String {
439 let mut out = String::new();
440 for message in messages {
441 out.push_str(&serde_json::to_string(message).unwrap_or_default());
443 out.push('\n');
444 }
445 out
446}
447
448pub 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
463pub 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
501pub struct A2uiCapabilities {
502 #[serde(rename = "1.0", default, skip_serializing_if = "Option::is_none")]
504 pub v1_0: Option<CapabilitySet>,
505 #[serde(rename = "v0.9", default, skip_serializing_if = "Option::is_none")]
507 pub v0_9: Option<CapabilitySet>,
508}
509
510impl A2uiCapabilities {
511 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 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 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
549#[serde(rename_all = "camelCase")]
550pub struct CapabilitySet {
551 pub supported_catalog_ids: Vec<String>,
553 #[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}