1use serde_json::{Map, Value, json};
15
16use super::catalog::Catalog;
17use super::wire::{A2uiVersion, WireError};
18
19pub const INVALID_FUNCTION_CALL: &str = "INVALID_FUNCTION_CALL";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum FunctionCaller {
26 Agent,
28 Renderer,
30}
31
32#[derive(Debug, Clone, PartialEq)]
34pub struct FunctionInvocation {
35 pub caller: FunctionCaller,
37 pub function_call_id: String,
39 pub surface_id: Option<String>,
41 pub name: String,
43 pub catalog_id: Option<String>,
45 pub args: Value,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct FunctionError {
52 pub code: String,
54 pub message: String,
56}
57
58#[derive(Debug, Clone, PartialEq)]
60pub struct FunctionResponse {
61 pub caller: FunctionCaller,
64 pub function_call_id: String,
66 pub outcome: Result<Value, FunctionError>,
68}
69
70#[derive(Debug, Clone, PartialEq)]
72pub enum FunctionMessage {
73 Call(FunctionInvocation),
75 Response(FunctionResponse),
77}
78
79pub(crate) const FUNCTION_MESSAGES: [&str; 4] = [
81 "callRendererFunction",
82 "callAgentFunction",
83 "rendererFunctionResponse",
84 "agentFunctionResponse",
85];
86
87impl FunctionInvocation {
88 pub fn refusal(&self, catalog: &Catalog) -> FunctionResponse {
108 let message = match self.caller {
109 FunctionCaller::Renderer => {
110 format!("this agent offers no functions to call; {} is not one", self.name)
111 }
112 FunctionCaller::Agent => {
113 let named = self.catalog_id.as_deref().unwrap_or_default();
114 if named != catalog.id() {
115 format!("{named} is not a catalog this renderer registers")
116 } else if catalog.functions().any(|function| function == self.name) {
117 format!(
118 "{} is rendererOnly in {named}: the renderer evaluates it while it draws, \
119 and an agent cannot call it",
120 self.name
121 )
122 } else {
123 format!("{} is not a function of {named}", self.name)
124 }
125 }
126 };
127 FunctionResponse {
128 caller: self.caller,
129 function_call_id: self.function_call_id.clone(),
130 outcome: Err(FunctionError { code: INVALID_FUNCTION_CALL.to_string(), message }),
131 }
132 }
133
134 pub fn to_wire(&self) -> Value {
136 let mut call = Map::new();
137 call.insert("@call".to_string(), json!(self.name));
138 if let Some(catalog_id) = &self.catalog_id {
139 call.insert("catalogId".to_string(), json!(catalog_id));
140 }
141 if self.args.as_object().is_some_and(|args| !args.is_empty()) {
142 call.insert("args".to_string(), self.args.clone());
143 }
144 let mut body = Map::new();
145 if let Some(surface_id) = &self.surface_id {
146 body.insert("surfaceId".to_string(), json!(surface_id));
147 }
148 body.insert("functionCallId".to_string(), json!(self.function_call_id));
149 body.insert("callFunction".to_string(), Value::Object(call));
150 let key = match self.caller {
151 FunctionCaller::Agent => "callRendererFunction",
152 FunctionCaller::Renderer => "callAgentFunction",
153 };
154 json!({ "version": A2uiVersion::V1_0.wire(), key: body })
155 }
156}
157
158impl FunctionResponse {
159 pub fn to_wire(&self) -> Value {
161 let mut body = Map::new();
162 body.insert("functionCallId".to_string(), json!(self.function_call_id));
163 match &self.outcome {
164 Ok(value) => body.insert("value".to_string(), value.clone()),
165 Err(error) => body.insert(
166 "error".to_string(),
167 json!({ "code": error.code, "message": error.message }),
168 ),
169 };
170 let key = match self.caller {
171 FunctionCaller::Agent => "rendererFunctionResponse",
172 FunctionCaller::Renderer => "agentFunctionResponse",
173 };
174 json!({ "version": A2uiVersion::V1_0.wire(), key: body })
175 }
176}
177
178pub fn read_function_message(message: &Value) -> Result<Option<FunctionMessage>, WireError> {
201 let Some(kind) = FUNCTION_MESSAGES.into_iter().find(|kind| message.get(*kind).is_some()) else {
202 return Ok(None);
203 };
204 let version = message.get("version").and_then(Value::as_str);
205 if version != Some(A2uiVersion::V1_0.wire()) {
206 return Err(WireError::new(
207 "/version",
208 format!("{kind} is A2UI 1.0; this message says version {}", version.unwrap_or("none")),
209 ));
210 }
211 let at = format!("/{kind}");
212 let body = message[kind]
213 .as_object()
214 .ok_or_else(|| WireError::new(&at, format!("{kind} is an object")))?;
215 let text = |key: &str| body.get(key).and_then(Value::as_str).map(str::to_string);
216 let function_call_id = text("functionCallId").ok_or_else(|| {
217 WireError::new(&format!("{at}/functionCallId"), "a functionCallId is required")
218 })?;
219 match kind {
220 "callRendererFunction" | "callAgentFunction" => {
221 let caller = if kind == "callRendererFunction" {
222 FunctionCaller::Agent
223 } else {
224 FunctionCaller::Renderer
225 };
226 let call_at = format!("{at}/callFunction");
227 let call = body
228 .get("callFunction")
229 .and_then(Value::as_object)
230 .ok_or_else(|| WireError::new(&call_at, "a callFunction object is required"))?;
231 let name = call
232 .get("@call")
233 .and_then(Value::as_str)
234 .ok_or_else(|| {
235 WireError::new(&format!("{call_at}/@call"), "@call names the function")
236 })?
237 .to_string();
238 let catalog_id = call.get("catalogId").and_then(Value::as_str).map(str::to_string);
239 if caller == FunctionCaller::Agent && catalog_id.is_none() {
240 return Err(WireError::new(
241 &format!("{call_at}/catalogId"),
242 "callRendererFunction names the catalog of its function",
243 ));
244 }
245 let surface_id = text("surfaceId");
246 if caller == FunctionCaller::Renderer && surface_id.is_none() {
247 return Err(WireError::new(
248 &format!("{at}/surfaceId"),
249 "callAgentFunction names the surface it came from",
250 ));
251 }
252 let args = call.get("args").cloned().unwrap_or_else(|| json!({}));
253 if !args.is_object() {
254 return Err(WireError::new(&format!("{call_at}/args"), "args is an object"));
255 }
256 Ok(Some(FunctionMessage::Call(FunctionInvocation {
257 caller,
258 function_call_id,
259 surface_id,
260 name,
261 catalog_id,
262 args,
263 })))
264 }
265 _ => {
266 let caller = if kind == "rendererFunctionResponse" {
267 FunctionCaller::Agent
268 } else {
269 FunctionCaller::Renderer
270 };
271 let outcome = match (body.get("value"), body.get("error")) {
272 (Some(value), None) => Ok(value.clone()),
273 (None, Some(error)) => {
274 let field = |key: &str| {
275 error.get(key).and_then(Value::as_str).map(str::to_string).ok_or_else(
276 || {
277 WireError::new(
278 &format!("{at}/error/{key}"),
279 format!("an error has a {key}"),
280 )
281 },
282 )
283 };
284 Err(FunctionError { code: field("code")?, message: field("message")? })
285 }
286 _ => {
287 return Err(WireError::new(
288 &at,
289 "an answer has exactly one of value and error",
290 ));
291 }
292 };
293 Ok(Some(FunctionMessage::Response(FunctionResponse {
294 caller,
295 function_call_id,
296 outcome,
297 })))
298 }
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 fn call(message: Value) -> FunctionInvocation {
307 match read_function_message(&message).unwrap() {
308 Some(FunctionMessage::Call(call)) => call,
309 other => panic!("not a call: {other:?}"),
310 }
311 }
312
313 #[test]
314 fn every_call_is_answered_invalid_with_its_reason() {
315 let forms = Catalog::forms();
316 for (message, says) in [
317 (
318 json!({ "version": "1.0", "callRendererFunction": { "functionCallId": "a",
319 "callFunction": { "@call": "formatString", "catalogId": forms.id() } } }),
320 "rendererOnly",
321 ),
322 (
323 json!({ "version": "1.0", "callRendererFunction": { "functionCallId": "b",
324 "callFunction": { "@call": "getScreenResolution", "catalogId": forms.id() } } }),
325 "not a function of",
326 ),
327 (
328 json!({ "version": "1.0", "callRendererFunction": { "functionCallId": "c",
329 "callFunction": { "@call": "x", "catalogId": "https://x.test/c.json" } } }),
330 "not a catalog this renderer registers",
331 ),
332 (
333 json!({ "version": "1.0", "callAgentFunction": { "surfaceId": "s", "functionCallId": "d",
334 "callFunction": { "@call": "lookupProvider", "args": { "id": 1 } } } }),
335 "offers no functions",
336 ),
337 ] {
338 let call = call(message.clone());
339 let answer = call.refusal(forms);
340 assert_eq!(answer.function_call_id, call.function_call_id);
341 let error = answer.outcome.as_ref().unwrap_err();
342 assert_eq!(error.code, INVALID_FUNCTION_CALL);
343 assert!(error.message.contains(says), "{message}: {}", error.message);
344 assert_eq!(
346 read_function_message(&answer.to_wire()).unwrap(),
347 Some(FunctionMessage::Response(answer))
348 );
349 assert_eq!(call.to_wire(), message, "a call writes back as read");
350 }
351 }
352
353 #[test]
354 fn what_1_0_requires_of_a_function_message_is_checked() {
355 for (message, says) in [
356 (json!({ "version": "v0.9.1", "callRendererFunction": {} }), "A2UI 1.0"),
357 (
358 json!({ "version": "1.0", "callRendererFunction": { "callFunction": {} } }),
359 "functionCallId",
360 ),
361 (
362 json!({ "version": "1.0", "callRendererFunction": { "functionCallId": "a",
363 "callFunction": { "@call": "formatNumber" } } }),
364 "catalog",
365 ),
366 (
367 json!({ "version": "1.0", "callAgentFunction": { "functionCallId": "a",
368 "callFunction": { "@call": "f" } } }),
369 "surface",
370 ),
371 (
372 json!({ "version": "1.0", "agentFunctionResponse": { "functionCallId": "a" } }),
373 "exactly one",
374 ),
375 (
376 json!({ "version": "1.0", "rendererFunctionResponse": { "functionCallId": "a",
377 "value": 1, "error": { "code": "X", "message": "y" } } }),
378 "exactly one",
379 ),
380 (
381 json!({ "version": "1.0", "rendererFunctionResponse": { "functionCallId": "a",
382 "error": { "code": "X" } } }),
383 "message",
384 ),
385 ] {
386 let error = read_function_message(&message).unwrap_err();
387 assert!(error.to_string().contains(says), "{message}: {error}");
388 }
389 }
390
391 #[test]
392 fn a_success_answer_reads_and_writes() {
393 let answer = json!({ "version": "1.0", "rendererFunctionResponse": {
394 "functionCallId": "r", "value": [1920, 1080] } });
395 let Some(FunctionMessage::Response(read)) = read_function_message(&answer).unwrap() else {
396 panic!("an answer")
397 };
398 assert_eq!(read.caller, FunctionCaller::Agent);
399 assert_eq!(read.outcome, Ok(json!([1920, 1080])));
400 assert_eq!(read.to_wire(), answer);
401 }
402}