use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
fn present<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Value>, D::Error> {
Value::deserialize(deserializer).map(Some)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AgentMessage {
pub version: String,
#[serde(flatten)]
pub kind: AgentMessageKind,
}
impl AgentMessage {
pub fn new(kind: AgentMessageKind) -> Self {
Self {
version: crate::PROTOCOL_VERSION.to_string(),
kind,
}
}
pub fn surface_id(&self) -> Option<&str> {
match &self.kind {
AgentMessageKind::CreateSurface(m) => Some(&m.surface_id),
AgentMessageKind::UpdateComponents(m) => Some(&m.surface_id),
AgentMessageKind::UpdateDataModel(m) => Some(&m.surface_id),
AgentMessageKind::DeleteSurface(m) => Some(&m.surface_id),
AgentMessageKind::CallRendererFunction(m) => m.surface_id.as_deref(),
AgentMessageKind::AgentFunctionResponse(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum AgentMessageKind {
CreateSurface(CreateSurface),
UpdateComponents(UpdateComponents),
UpdateDataModel(UpdateDataModel),
DeleteSurface(DeleteSurface),
CallRendererFunction(CallRendererFunction),
AgentFunctionResponse(FunctionResponse),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CreateSurface {
pub surface_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub catalog_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub send_data_model: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub components: Option<Vec<Component>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data_model: Option<Map<String, Value>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct UpdateComponents {
pub surface_id: String,
pub components: Vec<Component>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct UpdateDataModel {
pub surface_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
pub value: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DeleteSurface {
pub surface_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CallRendererFunction {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub surface_id: Option<String>,
pub function_call_id: String,
pub call_function: FunctionCall,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FunctionCall {
#[serde(rename = "@call")]
pub call: String,
#[serde(rename = "catalogId", default, skip_serializing_if = "Option::is_none")]
pub catalog_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub args: Option<Map<String, Value>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct FunctionResponse {
pub function_call_id: String,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
pub value: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorBody>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ErrorBody {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Component {
pub id: String,
pub component: String,
#[serde(
rename = "@catalogId",
default,
skip_serializing_if = "Option::is_none"
)]
pub catalog_id: Option<String>,
#[serde(
rename = "@accessibility",
default,
skip_serializing_if = "Option::is_none"
)]
pub accessibility: Option<Value>,
#[serde(rename = "@metadata", default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(rename = "@checks", default, skip_serializing_if = "Option::is_none")]
pub checks: Option<Vec<CheckRule>>,
#[serde(flatten)]
pub properties: Map<String, Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CheckRule {
pub condition: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RendererMessage {
pub version: String,
#[serde(flatten)]
pub kind: RendererMessageKind,
}
impl RendererMessage {
pub fn new(kind: RendererMessageKind) -> Self {
Self {
version: crate::PROTOCOL_VERSION.to_string(),
kind,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum RendererMessageKind {
Action(Action),
CallAgentFunction(CallAgentFunction),
RendererFunctionResponse(FunctionResponse),
Error(RendererError),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Action {
pub name: String,
pub surface_id: String,
pub source_component_id: String,
pub timestamp: String,
pub context: Map<String, Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user_message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
impl Action {
pub fn new(
name: impl Into<String>,
surface_id: impl Into<String>,
source_component_id: impl Into<String>,
timestamp: impl Into<String>,
context: Map<String, Value>,
) -> Self {
Self {
name: name.into(),
surface_id: surface_id.into(),
source_component_id: source_component_id.into(),
timestamp: timestamp.into(),
context,
user_message: None,
metadata: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CallAgentFunction {
pub surface_id: String,
pub function_call_id: String,
pub call_function: FunctionCall,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RendererError {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub surface_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function_call_id: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn an_agent_message_round_trips_with_its_version_first() {
let wire = json!({
"version": "1.0",
"createSurface": {
"surfaceId": "s1",
"catalogId": "c",
"components": [
{"id": "root", "component": "Text", "text": {"@path": "/name"},
"@accessibility": {"label": "Name"}}
],
"dataModel": {"name": "Ada"}
}
});
let message: AgentMessage = serde_json::from_value(wire.clone()).unwrap();
let AgentMessageKind::CreateSurface(create) = &message.kind else {
panic!("not createSurface")
};
let root = &create.components.as_ref().unwrap()[0];
assert_eq!(root.component, "Text");
assert_eq!(root.properties["text"], json!({"@path": "/name"}));
assert_eq!(message.surface_id(), Some("s1"));
let back = serde_json::to_value(&message).unwrap();
assert_eq!(back, wire);
assert_eq!(
serde_json::to_string(&message).unwrap().find("\"version\""),
Some(1)
);
}
#[test]
fn a_null_value_is_kept_apart_from_a_missing_one() {
let delete: AgentMessage = serde_json::from_value(json!({
"version": "1.0",
"updateDataModel": {"surfaceId": "s", "path": "/a", "value": null}
}))
.unwrap();
let AgentMessageKind::UpdateDataModel(update) = delete.kind else {
panic!()
};
assert_eq!(update.value, Value::Null);
let response: FunctionResponse =
serde_json::from_value(json!({"functionCallId": "c", "value": null})).unwrap();
assert_eq!(response.value, Some(Value::Null));
let error: FunctionResponse = serde_json::from_value(
json!({"functionCallId": "c", "error": {"code": "X", "message": "m"}}),
)
.unwrap();
assert_eq!(error.value, None);
}
#[test]
fn an_action_serializes_as_the_specification_shows() {
let mut context = Map::new();
context.insert("isSubscribed".into(), json!(true));
let mut action = Action::new(
"submitForm",
"contact_form_1",
"submit_button",
"2026-06-02T08:57:23Z",
context,
);
action.user_message = Some("Submitted contact form".into());
let message = RendererMessage::new(RendererMessageKind::Action(action));
assert_eq!(
serde_json::to_value(&message).unwrap(),
json!({
"version": "1.0",
"action": {
"name": "submitForm",
"surfaceId": "contact_form_1",
"sourceComponentId": "submit_button",
"timestamp": "2026-06-02T08:57:23Z",
"context": {"isSubscribed": true},
"userMessage": "Submitted contact form"
}
})
);
}
}