Skip to main content

adk_surface/genui/
functions.rs

1//! A2UI 1.0 function calls across the wire (spec 3.3 ยง6.1 `genui`): `callRendererFunction`
2//! (the agent asks the renderer to run a catalog function), `callAgentFunction` (the renderer
3//! asks the agent), and their answers, `rendererFunctionResponse` and `agentFunctionResponse`.
4//!
5//! `genui` offers no function either side may call on the other. The `forms` catalog's
6//! functions are all `rendererOnly`: formatting and checks the renderer evaluates while it
7//! draws, never on an agent's word. No agent function is offered either. So every call is
8//! answered, as A2UI 1.0 requires, with `INVALID_FUNCTION_CALL` and the reason
9//! ([`FunctionInvocation::refusal`]), and a drawing never carries a call: [`from_wire`] refuses one
10//! and points here.
11//!
12//! [`from_wire`]: super::from_wire
13
14use serde_json::{Map, Value, json};
15
16use super::catalog::Catalog;
17use super::wire::{A2uiVersion, WireError};
18
19/// The error code A2UI 1.0 answers a call with when the function may not be called by the
20/// side that asked, is not registered, or names a catalog the answering side does not know.
21pub const INVALID_FUNCTION_CALL: &str = "INVALID_FUNCTION_CALL";
22
23/// Who asks for a function call.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum FunctionCaller {
26    /// The agent asks the renderer (`callRendererFunction`).
27    Agent,
28    /// The renderer asks the agent (`callAgentFunction`).
29    Renderer,
30}
31
32/// A function call one side asks the other to run.
33#[derive(Debug, Clone, PartialEq)]
34pub struct FunctionInvocation {
35    /// Who asks.
36    pub caller: FunctionCaller,
37    /// The id the answer copies verbatim.
38    pub function_call_id: String,
39    /// The surface whose data model the call reads; required when the renderer asks.
40    pub surface_id: Option<String>,
41    /// The function's registered name (`@call`).
42    pub name: String,
43    /// The catalog that defines it; required when the agent asks.
44    pub catalog_id: Option<String>,
45    /// Its arguments (`args`), `{}` when absent.
46    pub args: Value,
47}
48
49/// Why a function call failed: `{ code, message }`.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct FunctionError {
52    /// A code such as [`INVALID_FUNCTION_CALL`] or `EXECUTION_ERROR`.
53    pub code: String,
54    /// What went wrong, in words.
55    pub message: String,
56}
57
58/// The answer to a [`FunctionInvocation`].
59#[derive(Debug, Clone, PartialEq)]
60pub struct FunctionResponse {
61    /// Who asked the call this answers: an agent's call is answered by the renderer
62    /// (`rendererFunctionResponse`), a renderer's by the agent (`agentFunctionResponse`).
63    pub caller: FunctionCaller,
64    /// The id of the call it answers.
65    pub function_call_id: String,
66    /// The value the function returned, or why it did not run.
67    pub outcome: Result<Value, FunctionError>,
68}
69
70/// An A2UI 1.0 function message.
71#[derive(Debug, Clone, PartialEq)]
72pub enum FunctionMessage {
73    /// `callRendererFunction` or `callAgentFunction`.
74    Call(FunctionInvocation),
75    /// `rendererFunctionResponse` or `agentFunctionResponse`.
76    Response(FunctionResponse),
77}
78
79/// The message keys of A2UI 1.0's function calls and their answers.
80pub(crate) const FUNCTION_MESSAGES: [&str; 4] = [
81    "callRendererFunction",
82    "callAgentFunction",
83    "rendererFunctionResponse",
84    "agentFunctionResponse",
85];
86
87impl FunctionInvocation {
88    /// The answer `genui` gives this call: `INVALID_FUNCTION_CALL`, with why. A `forms`
89    /// function is `rendererOnly`, so an agent may not call it; a renderer may call no agent
90    /// function, because none is offered.
91    ///
92    /// # Example
93    ///
94    /// ```rust
95    /// use adk_surface::genui::{Catalog, FunctionMessage, INVALID_FUNCTION_CALL, read_function_message};
96    /// use serde_json::json;
97    ///
98    /// let message = json!({ "version": "1.0", "callRendererFunction": {
99    ///     "functionCallId": "c1",
100    ///     "callFunction": { "@call": "formatString", "catalogId": Catalog::forms().id() } } });
101    /// let Some(FunctionMessage::Call(call)) = read_function_message(&message)? else { unreachable!() };
102    /// let answer = call.refusal(Catalog::forms()).to_wire();
103    /// assert_eq!(answer["rendererFunctionResponse"]["functionCallId"], "c1");
104    /// assert_eq!(answer["rendererFunctionResponse"]["error"]["code"], INVALID_FUNCTION_CALL);
105    /// # Ok::<(), adk_surface::genui::WireError>(())
106    /// ```
107    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    /// This call as an A2UI 1.0 message.
135    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    /// This answer as an A2UI 1.0 message.
160    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
178/// Reads an A2UI 1.0 function message: a call or its answer. `Ok(None)` when `message` is
179/// not one (a surface message, say).
180///
181/// # Errors
182///
183/// A function message that is not A2UI 1.0 (v0.9.1 has none), or that lacks what 1.0
184/// requires: a `functionCallId`; a `callFunction` with its `@call`; the `catalogId` of an
185/// agent's call; the `surfaceId` of a renderer's; exactly one of an answer's `value` and
186/// `error`, and an error's `code` and `message`.
187///
188/// # Example
189///
190/// ```rust
191/// use adk_surface::genui::{FunctionCaller, FunctionMessage, read_function_message};
192/// use serde_json::json;
193///
194/// let read = read_function_message(&json!({ "version": "1.0", "callAgentFunction": {
195///     "surfaceId": "s", "functionCallId": "c2", "callFunction": { "@call": "lookupProvider" } } }))?;
196/// assert!(matches!(read, Some(FunctionMessage::Call(call)) if call.caller == FunctionCaller::Renderer));
197/// assert_eq!(read_function_message(&json!({ "version": "1.0", "deleteSurface": { "surfaceId": "s" } }))?, None);
198/// # Ok::<(), adk_surface::genui::WireError>(())
199/// ```
200pub 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            // The answer reads back as what it is.
345            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}