Skip to main content

agent86_core/
agent86ui.rs

1//! agent86UI in the harness (beyond Python; ADR 0005): the model draws A2UI 1.0
2//! surfaces through `render_ui` (`crate::tools::render_ui`), checked against
3//! the renderer's catalogs by the `agent86-ui` crate, and the loop hands each
4//! validated message to the surface as a [`crate::agent::TurnEvent::Ui`].
5//!
6//! A [`UiSession`] is a surface's renderer as the agent sees it: its catalogs
7//! and the surfaces drawn so far (a headless [`Runtime`]), shared by clones of
8//! the tool context like the secret vault. It exists only when the embedder
9//! declared a renderer; sub-agents never get it.
10
11use crate::config::EgressMode;
12use agent86_ui::runtime::Runtime;
13use agent86_ui::{Action, AgentMessage, Catalog, CompileError, Report, Rules};
14use serde_json::{Map, Value};
15use std::sync::{Mutex, PoisonError};
16
17/// The tool's name.
18pub const RENDER_UI: &str = "render_ui";
19
20/// Where `render_ui` leaves the validated messages in its result's metadata,
21/// for the loop to take out and emit as `TurnEvent::Ui` before the result is
22/// recorded (so nothing new reaches the session or the trace).
23pub const MESSAGES_KEY: &str = "agent86ui_messages";
24
25/// Where it leaves what the trace's `ui_render` event records (the surfaces,
26/// the component count, the verdict), taken out the same way.
27pub const TRACE_KEY: &str = "agent86ui_trace";
28
29/// Where it names the surfaces a `wait: true` call waits on, for the loop,
30/// which asks once it has emitted the call's messages (so the program has
31/// them to draw before it is asked for an answer).
32pub const WAIT_KEY: &str = "agent86ui_wait";
33
34/// What a waiting `render_ui` call asks the program (`sdk::Ui::on_wait`): the
35/// first action the user takes on one of these surfaces, which the call has
36/// just drawn (its `TurnEvent::Ui` messages came first).
37#[derive(Debug, Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct UiWait {
40    /// The surfaces the call drew that are up, in the order it named them.
41    pub surface_ids: Vec<String>,
42}
43
44/// Answers a [`UiWait`]: the action, or `None` when the user dismissed it.
45pub type UiWaiter = std::sync::Arc<dyn Fn(&UiWait) -> Option<Action> + Send + Sync>;
46
47/// The completeness rules a `render_ui` batch is checked under: strict, but an
48/// orphan is a warning, because A2UI 1.0 has no message that removes a
49/// component, so one replaced as a child stays behind and the model could not
50/// fix the error (ADR 0005, third amendment).
51pub const RULES: Rules = Rules::STRICT.allowing_orphans(true);
52
53/// A renderer's catalogs and the surfaces drawn on it so far.
54pub struct UiSession {
55    catalogs: Vec<Catalog>,
56    runtime: Mutex<Runtime>,
57    /// The egress guardrail's mode: in `redact`, every string a surface shows
58    /// is redacted first.
59    egress: EgressMode,
60    /// Media may load from `https` URLs, not only `data:` URLs and workspace
61    /// files.
62    remote_media: bool,
63    /// Answers a waiting call, when the program can. Behind a lock, so a
64    /// surface that installs its answer after the harness is built (the
65    /// interface, once its event channel exists) can set it.
66    waiter: Mutex<Option<UiWaiter>>,
67}
68
69impl std::fmt::Debug for UiSession {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.debug_struct("UiSession")
72            .field(
73                "catalogs",
74                &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
75            )
76            .finish_non_exhaustive()
77    }
78}
79
80impl UiSession {
81    /// A renderer that supports `catalogs`, in order of preference.
82    pub fn new(catalogs: Vec<Catalog>) -> Result<Self, CompileError> {
83        let mut runtime = Runtime::new(catalogs.clone())?;
84        runtime.set_rules(RULES);
85        Ok(Self {
86            catalogs,
87            runtime: Mutex::new(runtime),
88            egress: EgressMode::Off,
89            remote_media: false,
90            waiter: Mutex::new(None),
91        })
92    }
93
94    /// Redact what surfaces show as the egress guardrail in `mode` redacts the
95    /// model's text.
96    pub fn with_egress(mut self, mode: EgressMode) -> Self {
97        self.egress = mode;
98        self
99    }
100
101    /// Let media load from `https` URLs too (ADR 0005: off by default, since a
102    /// fetch can track the user or carry data out in its URL).
103    pub fn with_remote_media(mut self, allow: bool) -> Self {
104        self.remote_media = allow;
105        self
106    }
107
108    /// Let a call wait for the user's answer, asking `waiter`.
109    pub fn with_waiter(self, waiter: Option<UiWaiter>) -> Self {
110        self.set_waiter(waiter);
111        self
112    }
113
114    /// Install (or, with `None`, remove) the answer to a waiting call. The
115    /// prompt section is rebuilt per request, so it offers `wait` from the next
116    /// request on.
117    pub fn set_waiter(&self, waiter: Option<UiWaiter>) {
118        *self.waiter.lock().unwrap_or_else(PoisonError::into_inner) = waiter;
119    }
120
121    fn waiter(&self) -> Option<UiWaiter> {
122        self.waiter
123            .lock()
124            .unwrap_or_else(PoisonError::into_inner)
125            .clone()
126    }
127
128    /// Whether a call may wait: someone answers.
129    pub fn can_wait(&self) -> bool {
130        self.waiter().is_some()
131    }
132
133    /// Ask the program for the user's answer (`None`: dismissed, or nobody
134    /// answers). The lock is not held while the program answers.
135    pub fn wait(&self, request: &UiWait) -> Option<Action> {
136        self.waiter().and_then(|waiter| waiter(request))
137    }
138
139    /// Whether `action` could have come from a surface up now: its surface
140    /// exists (and is one of `among`, when given) and holds the component it
141    /// names. What it carries is the user's and is checked as their input is.
142    pub fn check_action(&self, action: &Action, among: Option<&[String]>) -> Result<(), String> {
143        if action.name.is_empty() {
144            return Err("the action has no name".into());
145        }
146        if among.is_some_and(|ids| !ids.contains(&action.surface_id)) {
147            return Err(format!(
148                "the action is for surface {:?}, which this call did not draw",
149                action.surface_id
150            ));
151        }
152        let runtime = self.runtime();
153        let Some(mut components) = runtime.components(&action.surface_id) else {
154            return Err(format!("there is no surface {:?}", action.surface_id));
155        };
156        if !components
157            .any(|c| c.get("id").and_then(Value::as_str) == Some(&action.source_component_id))
158        {
159            return Err(format!(
160                "surface {:?} has no component {:?}",
161                action.surface_id, action.source_component_id
162            ));
163        }
164        Ok(())
165    }
166
167    /// Whether surface `id`, as drawn so far, has a Button whose action sends
168    /// an event: something the user can press to answer.
169    pub fn has_event_button(&self, id: &str) -> bool {
170        self.runtime()
171            .components(id)
172            .is_some_and(|mut components| components.any(is_event_button))
173    }
174
175    pub fn egress(&self) -> EgressMode {
176        self.egress
177    }
178
179    pub fn remote_media(&self) -> bool {
180        self.remote_media
181    }
182
183    pub fn catalogs(&self) -> &[Catalog] {
184        &self.catalogs
185    }
186
187    fn runtime(&self) -> std::sync::MutexGuard<'_, Runtime> {
188        self.runtime.lock().unwrap_or_else(PoisonError::into_inner)
189    }
190
191    /// Validate a batch and, when it has no errors, apply it to the surfaces.
192    pub fn apply(&self, messages: &[Value]) -> Report {
193        self.runtime().apply(messages)
194    }
195
196    /// Every surface up now as the one `createSurface` that draws it as it is,
197    /// for a program that reopens a session (or draws late) to bring its screen
198    /// up to date.
199    pub fn snapshot(&self) -> Vec<AgentMessage> {
200        self.runtime()
201            .snapshot()
202            .into_iter()
203            .filter_map(|message| serde_json::from_value(message).ok())
204            .collect()
205    }
206
207    /// Rebuild the surfaces from a session's history (ADR 0005: resume replays,
208    /// nothing is stored): every `render_ui` call that drew, in order, through
209    /// the same redaction, policy, and validation as when it ran. A call that
210    /// drew is one whose result is ok or opens with what the tool writes when it
211    /// draws (a waiting call the user dismissed reports a failure, yet drew).
212    /// Steps keep calls the history's compaction summarized away. Returns how
213    /// many calls were replayed.
214    pub fn replay(
215        &self,
216        state: &crate::session::AgentState,
217        ctx: &crate::tools::ToolContext,
218    ) -> usize {
219        let mut runtime = match Runtime::new(self.catalogs.clone()) {
220            Ok(runtime) => runtime,
221            Err(_) => return 0,
222        };
223        runtime.set_rules(RULES);
224        let mut replayed = 0;
225        for step in &state.steps {
226            for call in step.tool_calls.iter().filter(|call| call.name == RENDER_UI) {
227                let drew = step
228                    .results
229                    .iter()
230                    .find(|result| result.call_id == call.id)
231                    .is_some_and(drew);
232                if !drew {
233                    continue;
234                }
235                // The history keeps the call as the model sent it, before the
236                // registry repaired an array sent as a JSON string.
237                let messages = match call.arguments.get("messages") {
238                    Some(Value::Array(messages)) => messages.clone(),
239                    Some(Value::String(text)) => match serde_json::from_str(text) {
240                        Ok(Value::Array(messages)) => messages,
241                        _ => continue,
242                    },
243                    _ => continue,
244                };
245                let messages: Vec<Value> = messages
246                    .iter()
247                    .map(|message| tidy(&sanitize(message, &ctx.secrets, self.egress)).0)
248                    .collect();
249                if !policy(&messages, &ctx.policy, self.remote_media).is_empty() {
250                    continue;
251                }
252                if runtime.apply(&messages).is_ok() {
253                    replayed += 1;
254                }
255            }
256        }
257        *self.runtime() = runtime;
258        replayed
259    }
260
261    /// The ids of the surfaces up now.
262    pub fn surface_ids(&self) -> Vec<String> {
263        self.runtime().surface_ids().map(String::from).collect()
264    }
265
266    /// The system-prompt section: how to use `render_ui`, then each catalog's
267    /// own instructions and a compact reference to its components and
268    /// functions. Rebuilt per request, like the MCP section.
269    pub fn prompt_section(&self) -> String {
270        let mut section = String::from(PROMPT);
271        let media = if self.remote_media {
272            "a data: URL, an https URL, or the path of a file in the workspace"
273        } else {
274            "a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
275        };
276        if self.can_wait() {
277            section.push_str(
278                "\n- With `\"wait\": true` the call waits for the user's first action on \
279                 the surface and returns it as its result (`[ui action] ...`). Use it for a \
280                 form you need answered before you can go on; otherwise leave it out and \
281                 carry on.",
282            );
283        }
284        section.push_str(&format!(
285            "\n- Never ask for a password, key, or token in a surface (no TextField with \
286             variant \"obscured\"): call request_secret, which asks through a masked prompt \
287             and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
288             Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
289             http and https URLs."
290        ));
291        if let Some(catalog) = self.catalogs.first() {
292            section.push_str(&format!(
293                "\n\nA complete call, a choice with a Submit button (`surfaceId` goes \
294                 inside createSurface, never beside it):\n{}",
295                example(catalog.id(), self.can_wait())
296            ));
297        }
298        for catalog in &self.catalogs {
299            section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
300            if let Some(instructions) = catalog.instructions() {
301                section.push('\n');
302                section.push_str(instructions.trim());
303                section.push('\n');
304            }
305            section.push_str(&reference(catalog));
306        }
307        section
308    }
309}
310
311/// The keys that name what an A2UI 1.0 message is; an envelope holds
312/// `version` and exactly one of them.
313const KINDS: &[&str] = &[
314    "createSurface",
315    "updateComponents",
316    "updateDataModel",
317    "deleteSurface",
318    "callRendererFunction",
319    "agentFunctionResponse",
320];
321
322/// Beyond the protocol: a message whose fields sit beside its kind instead of
323/// inside it (`{"version": "1.0", "createSurface": {...}, "surfaceId": "x"}`,
324/// the mistake models make most often) has them moved in, when the kind's body
325/// does not already have them. Such a message is never valid as written, so
326/// the move only turns an error into what the model plainly meant. Returns the
327/// message and the fields moved, for the result to mention. `render_ui` and
328/// replay both apply it, so a session written either way replays the same.
329pub fn tidy(message: &Value) -> (Value, Vec<String>) {
330    let Some(envelope) = message.as_object() else {
331        return (message.clone(), Vec::new());
332    };
333    let kinds: Vec<&String> = envelope
334        .keys()
335        .filter(|key| KINDS.contains(&key.as_str()))
336        .collect();
337    let [kind] = kinds.as_slice() else {
338        return (message.clone(), Vec::new());
339    };
340    let kind = (*kind).clone();
341    let Some(body) = envelope.get(&kind).and_then(Value::as_object) else {
342        return (message.clone(), Vec::new());
343    };
344    let strays: Vec<String> = envelope
345        .keys()
346        .filter(|key| *key != "version" && **key != kind && !body.contains_key(*key))
347        .cloned()
348        .collect();
349    if strays.is_empty() {
350        return (message.clone(), Vec::new());
351    }
352    let mut envelope = envelope.clone();
353    let mut body = body.clone();
354    for key in &strays {
355        if let Some(value) = envelope.remove(key) {
356            body.insert(key.clone(), value);
357        }
358    }
359    envelope.insert(kind.clone(), Value::Object(body));
360    let moved = strays
361        .into_iter()
362        .map(|key| format!("{key} into {kind}"))
363        .collect();
364    (Value::Object(envelope), moved)
365}
366
367/// Whether a component is a Button whose action sends an event (rather than
368/// running a local function such as `openUrl`).
369pub fn is_event_button(component: &Value) -> bool {
370    component.get("component").and_then(Value::as_str) == Some("Button")
371        && component.pointer("/action/event").is_some()
372}
373
374/// The prompt's example call, on one line, in `catalog_id`.
375fn example(catalog_id: &str, wait: bool) -> String {
376    let mut call = serde_json::json!({"messages": [{"version": "1.0", "createSurface": {
377        "surfaceId": "plan",
378        "catalogId": catalog_id,
379        "components": [
380            {"id": "root", "component": "Column", "children": ["choice", "submit"]},
381            {"id": "choice", "component": "ChoicePicker", "label": "Which plan?",
382             "variant": "mutuallyExclusive", "value": {"@path": "/plan"},
383             "options": [{"label": "Basic", "value": "basic"}, {"label": "Pro", "value": "pro"}]},
384            {"id": "submit", "component": "Button", "child": "submit_label",
385             "action": {"event": {"name": "submit", "context": {"plan": {"@path": "/plan"}}}}},
386            {"id": "submit_label", "component": "Text", "text": "Submit"}
387        ],
388        "dataModel": {"plan": []}
389    }}]});
390    if wait {
391        call["wait"] = Value::Bool(true);
392    }
393    call.to_string()
394}
395
396/// What every `render_ui` prompt says, whatever the catalogs.
397const PROMPT: &str = "## agent86UI: drawing UI with render_ui
398
399You can show the user interactive UI (forms, choices, confirmations, small \
400dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
401them with its own widgets. Use it when you need a structured answer (pick one of \
402several options, fill in a few fields, confirm a plan) or when a layout says more \
403than prose. Otherwise answer in plain text.
404
405- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
406exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
407`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
408`catalogId` from below, and usually its `components` and `dataModel` inline), \
409change it later with updateComponents (a component replaces the one with the same \
410id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
411- Components are a flat list linked by id, and exactly one has the id \"root\". \
412Every child id must be defined in the same call or an earlier one. An id is an \
413identifier: letters, digits, and `_`, starting with a letter or `_` (`submit_label`, \
414never `submit-label`).
415- A value is a literal, a binding to the surface's data model (`{\"@path\": \
416\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
417{...}}`). Input components write what the user enters back to the path they are \
418bound to. A `ChildList` is an array of ids, or a template over a list in the data \
419model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
420relative to each item.
421- A button's action is `{\"event\": {\"name\": \"submit\", \"context\": {\"name\": \
422{\"@path\": \"/form/name\"}}}}`: `context` goes inside `event`, beside `name`, never \
423beside `event`. When the user presses it, a later user message \
424reads `[ui action] submit on <surfaceId>: <context as JSON>`; the surface stays \
425up meanwhile.
426- Only a Button whose action is an event sends the user's answer: choosing an \
427option or typing only changes the data model. So every form needs a Button (for \
428example Submit) whose event's `context` carries the values.
429- render_ui's result is the validator's verdict. If it lists problems, nothing \
430was drawn: fix them and send the corrected messages again.
431- Renderer functions (`callRendererFunction`) and agent functions are not \
432available.";
433
434/// A compact reference to a catalog's components and functions, from their
435/// schemas: each component's properties (`?` marks an optional one) with their
436/// types, and each function's arguments and return type.
437pub fn reference(catalog: &Catalog) -> String {
438    let document = catalog.document();
439    let mut out = String::from("\nComponents:\n");
440    for (name, schema) in document
441        .get("components")
442        .and_then(Value::as_object)
443        .into_iter()
444        .flatten()
445    {
446        let (properties, required, checkable) = gather(schema);
447        let fields: Vec<String> = properties
448            .iter()
449            .filter(|(key, _)| *key != "component" && *key != "id")
450            .map(|(key, property)| {
451                let optional = if required.iter().any(|r| r == key) {
452                    ""
453                } else {
454                    "?"
455                };
456                format!("{key}{optional}: {}", type_of(property, document))
457            })
458            .collect();
459        let checks = if checkable { " (accepts @checks)" } else { "" };
460        out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
461    }
462    let functions: Vec<String> = document
463        .get("functions")
464        .and_then(Value::as_object)
465        .into_iter()
466        .flatten()
467        .filter(|(name, _)| {
468            catalog
469                .function(name)
470                .is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
471        })
472        .map(|(name, schema)| {
473            let args = schema.pointer("/properties/args");
474            let required: Vec<&str> = args
475                .and_then(|a| a.get("required"))
476                .and_then(Value::as_array)
477                .into_iter()
478                .flatten()
479                .filter_map(Value::as_str)
480                .collect();
481            let params: Vec<String> = args
482                .and_then(|a| a.get("properties"))
483                .and_then(Value::as_object)
484                .into_iter()
485                .flatten()
486                .map(|(key, property)| {
487                    let optional = if required.contains(&key.as_str()) {
488                        ""
489                    } else {
490                        "?"
491                    };
492                    format!("{key}{optional}: {}", type_of(property, document))
493                })
494                .collect();
495            let returns = schema
496                .get("returnType")
497                .and_then(Value::as_str)
498                .unwrap_or("any");
499            format!("- {name}({}) -> {returns}\n", params.join(", "))
500        })
501        .collect();
502    if !functions.is_empty() {
503        out.push_str("\nFunctions:\n");
504        out.extend(functions);
505    }
506    out
507}
508
509/// A component schema's properties and required names, from its own
510/// `properties` and its `allOf` parts, and whether it takes `@checks`.
511fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
512    let mut properties = Map::new();
513    let mut required = Vec::new();
514    let mut checkable = false;
515    let mut parts = vec![schema];
516    if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
517        parts.extend(all);
518    }
519    for part in parts {
520        if part
521            .get("$ref")
522            .and_then(Value::as_str)
523            .is_some_and(|r| r.ends_with("/Checkable"))
524        {
525            checkable = true;
526        }
527        if let Some(own) = part.get("properties").and_then(Value::as_object) {
528            for (key, value) in own {
529                properties.insert(key.clone(), value.clone());
530            }
531        }
532        required.extend(
533            part.get("required")
534                .and_then(Value::as_array)
535                .into_iter()
536                .flatten()
537                .filter_map(Value::as_str)
538                .map(String::from),
539        );
540    }
541    (properties, required, checkable)
542}
543
544/// A property's type, briefly: a common type by name, a catalog's own
545/// definition by what it is (its `Weight` is a number, not a name to guess
546/// at), an enum's values, or the JSON type.
547fn type_of(property: &Value, document: &Value) -> String {
548    if let Some(target) = property.get("$ref").and_then(Value::as_str) {
549        if let Some(local) = target.strip_prefix("#/$defs/") {
550            if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
551                if def.get("$ref").is_none() {
552                    return type_of(def, document);
553                }
554            }
555        }
556        return target.rsplit('/').next().unwrap_or(target).to_string();
557    }
558    if let Some(values) = property.get("enum").and_then(Value::as_array) {
559        return values
560            .iter()
561            .map(|v| v.to_string())
562            .collect::<Vec<_>>()
563            .join("|");
564    }
565    match property.get("type").and_then(Value::as_str) {
566        Some("array") => match property.get("items") {
567            Some(items) => format!("array of {}", type_of(items, document)),
568            None => "array".into(),
569        },
570        Some(kind) => kind.to_string(),
571        None => "any".into(),
572    }
573}
574
575/// What a `render_ui` result carries for the loop, taken out of its metadata,
576/// so it is emitted and recorded as agent86UI's own and never kept in the
577/// session: the validated messages, and the `ui_render` trace fields.
578pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
579    let messages = match metadata.remove(MESSAGES_KEY) {
580        Some(Value::Array(items)) => items
581            .into_iter()
582            .filter_map(|item| serde_json::from_value(item).ok())
583            .collect(),
584        _ => Vec::new(),
585    };
586    (messages, metadata.remove(TRACE_KEY))
587}
588
589/// What `render_ui`'s result opens with when the call drew.
590const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];
591
592/// Whether a `render_ui` result says the call drew. A waiting call that was not
593/// answered says so first and what it drew after (earlier versions wrote the
594/// drawing first), so every line is looked at.
595fn drew(result: &crate::types::ToolResult) -> bool {
596    let text = if result.ok {
597        result.content.as_str()
598    } else {
599        result.error.as_deref().unwrap_or_default()
600    };
601    result.ok
602        || text
603            .lines()
604            .any(|line| DREW.iter().any(|opening| line.starts_with(opening)))
605}
606
607/// The surfaces a waiting call waits on, taken out of its result's metadata.
608pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
609    match metadata.remove(WAIT_KEY)? {
610        Value::Array(ids) => Some(
611            ids.into_iter()
612                .filter_map(|id| id.as_str().map(String::from))
613                .collect(),
614        ),
615        _ => None,
616    }
617}
618
619/// An action as the model reads it, a waiting call's result or the next user
620/// message: `[ui action] <name> on <surfaceId>: <context as JSON>`, then the
621/// event's `userMessage` on a line of its own when it has one.
622pub fn action_text(action: &Action) -> String {
623    let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
624    let mut text = format!(
625        "[ui action] {} on {}: {context}",
626        action.name, action.surface_id
627    );
628    if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
629        text.push('\n');
630        text.push_str(message);
631    }
632    text
633}
634
635impl crate::agent::Harness {
636    /// Declare a renderer: put `session` on the tool context and offer the
637    /// model `render_ui`. Both assembly paths (`sdk::AgentBuilder::ui` and the
638    /// binary's interface, through `setup::attach_renderer`) go through it.
639    /// Sub-agents never draw: `ToolContext::fork` drops the session.
640    pub fn attach_ui(&mut self, session: UiSession) -> Result<(), String> {
641        self.registry
642            .register(Box::new(crate::tools::render_ui::RenderUiTool))?;
643        self.context.ui = Some(std::sync::Arc::new(session));
644        Ok(())
645    }
646
647    /// Take an action from a surface no call was waiting on (ADR 0005: it
648    /// becomes the next user message): check that it could have come from a
649    /// surface up now, record it as `ui_action` (never its values), and give
650    /// the text the turn runs on, `[ui action] <name> on <surfaceId>: ...`. The
651    /// caller runs that as a plain turn, whose own vault redaction and ingress
652    /// guardrail cover it as they cover typed input. `Err` names what was
653    /// wrong, never the values, and nothing is recorded.
654    pub fn accept_ui_action(&self, sid: &str, action: &Action) -> Result<String, String> {
655        let ui = self
656            .context
657            .ui
658            .as_deref()
659            .ok_or_else(|| String::from("this agent has no renderer"))?;
660        ui.check_action(action, None)?;
661        self.recorder.event(
662            sid,
663            "ui_action",
664            vec![
665                ("surface", serde_json::json!(action.surface_id)),
666                ("name", serde_json::json!(action.name)),
667                ("component", serde_json::json!(action.source_component_id)),
668                ("waited", serde_json::json!(false)),
669            ],
670        );
671        Ok(action_text(action))
672    }
673
674    /// Wait for the user's answer to a `wait: true` call, through the prompt
675    /// queue like a secret prompt (one question at a time, declined once the
676    /// turn is cancelled), and make it the call's result. The answer goes
677    /// through the vault and the ingress guardrail, as typed input does, and is
678    /// recorded as `ui_action`, without its values.
679    pub(crate) fn ui_wait(
680        &self,
681        call: &crate::types::ToolCall,
682        drawn: crate::types::ToolResult,
683        surfaces: Vec<String>,
684        sid: &str,
685    ) -> crate::types::ToolResult {
686        use crate::tools::{failure, success};
687        let Some(ui) = self.context.ui.as_deref() else {
688            return drawn;
689        };
690        if surfaces.is_empty() {
691            return drawn;
692        }
693        let request = UiWait {
694            surface_ids: surfaces.clone(),
695        };
696        let question = crate::approval::Question {
697            tool: Some(RENDER_UI.into()),
698            call: Some(call.id.clone()),
699            ..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
700        };
701        let shown = drawn.content.clone();
702        let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
703            call_id: drawn.call_id.clone(),
704            ..result
705        };
706        let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
707            None => {
708                return answered(failure(
709                    RENDER_UI,
710                    format!(
711                        "The turn was cancelled before the user answered. The surface stays \
712                         up; an action on it later comes as a user message.\n{shown}"
713                    ),
714                ))
715            }
716            Some(None) => {
717                return answered(failure(
718                    RENDER_UI,
719                    format!(
720                        "The user did not answer (they dismissed it). The surface stays up; an \
721                         action on it later comes as a user message.\n{shown}"
722                    ),
723                ))
724            }
725            Some(Some(action)) => action,
726        };
727        if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
728            return answered(failure(
729                RENDER_UI,
730                format!("The screen's answer could not be used: {why}.\n{shown}"),
731            ));
732        }
733        let text = self.context.secrets.redact(&action_text(&action));
734        let report = self.guardrails.inspect_ingress(&text);
735        if report.flagged() {
736            self.recorder.event(
737                sid,
738                "guardrail",
739                vec![
740                    ("stage", serde_json::json!("ingress")),
741                    ("source", serde_json::json!("ui_action")),
742                    ("findings", serde_json::json!(report.summary())),
743                ],
744            );
745        }
746        self.recorder.event(
747            sid,
748            "ui_action",
749            vec![
750                ("surface", serde_json::json!(action.surface_id)),
751                ("name", serde_json::json!(action.name)),
752                ("component", serde_json::json!(action.source_component_id)),
753                ("waited", serde_json::json!(true)),
754            ],
755        );
756        if self.guardrails.should_block(&report) {
757            return answered(failure(
758                RENDER_UI,
759                format!(
760                    "The user's answer was refused by the input guardrail ({}).\n{shown}",
761                    report.summary()
762                ),
763            ));
764        }
765        answered(success(RENDER_UI, format!("{shown}\n{text}")))
766    }
767}
768
769/// Every string in `value`, through the secret vault's redaction and, with the
770/// egress guardrail in `redact` mode, its redaction too: what a surface shows
771/// reaches the user as the model's text does. Object keys are left alone.
772pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
773    match value {
774        Value::String(text) => {
775            let text = vault.redact(text);
776            Value::String(if egress == EgressMode::Redact {
777                crate::guardrails::redact(&text).0
778            } else {
779                text
780            })
781        }
782        Value::Array(items) => Value::Array(
783            items
784                .iter()
785                .map(|item| sanitize(item, vault, egress))
786                .collect(),
787        ),
788        Value::Object(map) => Value::Object(
789            map.iter()
790                .map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
791                .collect(),
792        ),
793        other => other.clone(),
794    }
795}
796
797/// Something agent86's policy refuses in a batch (ADR 0005), where the
798/// protocol would allow it: a JSON Pointer into the batch and why.
799#[derive(Debug, Clone, PartialEq, Eq)]
800pub struct Refusal {
801    pub path: String,
802    pub message: String,
803}
804
805impl std::fmt::Display for Refusal {
806    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
807        write!(f, "REFUSED at {}: {}", self.path, self.message)
808    }
809}
810
811/// The media components of the basic catalog and the properties that load a
812/// URL. A custom catalog's component of the same name is held to the same rule.
813const MEDIA: &[(&str, &[&str])] = &[
814    ("Image", &["url"]),
815    ("Video", &["url", "posterUrl"]),
816    ("AudioPlayer", &["url"]),
817];
818
819/// What agent86 refuses in a batch the protocol allows (ADR 0005):
820/// - a `TextField` with `"variant": "obscured"`: secrets are never collected
821///   through a surface, so the value never reaches the model;
822/// - media from anywhere but a `data:` URL or a file in the workspace (or an
823///   `https` URL, with `remote_media`), and from a binding or a call, whose
824///   value is not known until the renderer resolves it;
825/// - `openUrl` with a literal URL that is not `http` or `https` (a dynamic one
826///   is the renderer's to check before it opens it, after showing it);
827/// - `callRendererFunction` and agent functions, left out of the first version.
828pub fn policy(
829    messages: &[Value],
830    jail: &crate::tools::SandboxPolicy,
831    remote_media: bool,
832) -> Vec<Refusal> {
833    let mut refusals = Vec::new();
834    let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
835    for (index, message) in messages.iter().enumerate() {
836        if message.get("callRendererFunction").is_some() {
837            refuse(
838                format!("/{index}/callRendererFunction"),
839                "renderer functions are not available here; draw with components and change \
840                 them with updateComponents and updateDataModel instead"
841                    .into(),
842            );
843        }
844        if message.get("agentFunctionResponse").is_some() {
845            refuse(
846                format!("/{index}/agentFunctionResponse"),
847                "agent functions are not available here".into(),
848            );
849        }
850        for kind in ["createSurface", "updateComponents"] {
851            let Some(components) = message
852                .get(kind)
853                .and_then(|body| body.get("components"))
854                .and_then(Value::as_array)
855            else {
856                continue;
857            };
858            for (number, component) in components.iter().enumerate() {
859                let at = format!("/{index}/{kind}/components/{number}");
860                let type_name = component.get("component").and_then(Value::as_str);
861                let id = component
862                    .get("id")
863                    .and_then(Value::as_str)
864                    .unwrap_or("this component");
865                if type_name == Some("TextField")
866                    && component.get("variant").and_then(Value::as_str) == Some("obscured")
867                {
868                    refuse(
869                        format!("{at}/variant"),
870                        format!(
871                            "TextField {id} is \"obscured\", a password field, but a surface never \
872                             collects secrets: call request_secret instead, which asks the user \
873                             through a masked prompt and never shows you the value"
874                        ),
875                    );
876                }
877                if let Some((_, properties)) =
878                    MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
879                {
880                    for property in *properties {
881                        let Some(value) = component.get(*property) else {
882                            continue;
883                        };
884                        let path = format!("{at}/{property}");
885                        match value.as_str() {
886                            Some(url) => {
887                                if let Some(why) = media_problem(url, jail, remote_media) {
888                                    refuse(path, format!("{id}'s {property} {why}"));
889                                }
890                            }
891                            None => refuse(
892                                path,
893                                format!(
894                                    "{id}'s {property} must be a literal string: what a surface \
895                                     loads is checked before it is drawn, so it cannot come from a \
896                                     binding or a function call"
897                                ),
898                            ),
899                        }
900                    }
901                }
902                open_urls(component, &at, &mut refuse);
903            }
904        }
905    }
906    refusals
907}
908
909/// Why a media URL may not load, or `None` when it may.
910fn media_problem(
911    url: &str,
912    jail: &crate::tools::SandboxPolicy,
913    remote_media: bool,
914) -> Option<String> {
915    match scheme(url) {
916        Some(scheme) if scheme == "data" => None,
917        Some(scheme) if scheme == "https" && remote_media => None,
918        Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
919            "{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
920             or carry data out in its URL): use a data: URL or a file in the workspace"
921        )),
922        Some(scheme) => Some(format!(
923            "{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
924             the workspace"
925        )),
926        None => match jail.resolve_within(url) {
927            Err(_) => Some(format!("{url:?} is outside the workspace")),
928            Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
929            Ok(_) => None,
930        },
931    }
932}
933
934/// A URL's scheme, lowercased, when it has one. A single letter before the
935/// colon is a Windows drive, not a scheme.
936fn scheme(url: &str) -> Option<String> {
937    let (scheme, _) = url.split_once(':')?;
938    let valid = scheme.len() > 1
939        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
940        && scheme
941            .chars()
942            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
943    valid.then(|| scheme.to_ascii_lowercase())
944}
945
946/// Refuse each `openUrl` call in `value` whose literal URL is not `http` or
947/// `https`.
948fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
949    match value {
950        Value::Object(map) => {
951            if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
952                if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
953                    let scheme = scheme(url);
954                    if !matches!(scheme.as_deref(), Some("http" | "https")) {
955                        refuse(
956                            format!("{at}/args/url"),
957                            format!("openUrl only opens http and https URLs, not {url:?}"),
958                        );
959                    }
960                }
961            }
962            for (key, item) in map {
963                let segment = key.replace('~', "~0").replace('/', "~1");
964                open_urls(item, &format!("{at}/{segment}"), refuse);
965            }
966        }
967        Value::Array(items) => {
968            for (index, item) in items.iter().enumerate() {
969                open_urls(item, &format!("{at}/{index}"), refuse);
970            }
971        }
972        _ => {}
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    use super::*;
979
980    use crate::tools::SandboxPolicy;
981    use serde_json::json;
982
983    struct Jail(std::path::PathBuf, SandboxPolicy);
984
985    fn jail(name: &str) -> Jail {
986        let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
987        let _ = std::fs::remove_dir_all(&root);
988        std::fs::create_dir_all(root.join("img")).unwrap();
989        std::fs::write(root.join("img/cat.png"), b"png").unwrap();
990        let policy = SandboxPolicy::new(&root).unwrap();
991        Jail(root, policy)
992    }
993
994    impl Drop for Jail {
995        fn drop(&mut self) {
996            let _ = std::fs::remove_dir_all(&self.0);
997        }
998    }
999
1000    fn with_components(components: Value) -> Vec<Value> {
1001        vec![json!({"version": "1.0", "createSurface": {
1002            "surfaceId": "s", "catalogId": "c", "components": components
1003        }})]
1004    }
1005
1006    fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
1007        policy(messages, &jail.1, remote)
1008            .into_iter()
1009            .map(|r| format!("{} {}", r.path, r.message))
1010            .collect()
1011    }
1012
1013    #[test]
1014    fn a_password_field_is_refused_with_request_secret_named() {
1015        let jail = jail("obscured");
1016        let got = refused(
1017            &with_components(json!([
1018                {"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
1019                {"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
1020            ])),
1021            &jail,
1022            false,
1023        );
1024        assert_eq!(got.len(), 1, "{got:?}");
1025        assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
1026        assert!(got[0].contains("request_secret"));
1027    }
1028
1029    #[test]
1030    fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
1031        let jail = jail("media");
1032        let image =
1033            |url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
1034        let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
1035        assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
1036        assert!(ok(json!("img/cat.png"), false));
1037        assert!(!ok(json!("img/dog.png"), false), "missing file");
1038        assert!(!ok(json!("../outside.png"), false), "outside the jail");
1039        assert!(!ok(json!("https://example.com/cat.png"), false));
1040        assert!(ok(json!("https://example.com/cat.png"), true));
1041        assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
1042        assert!(!ok(json!("file:///etc/passwd"), true));
1043        let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
1044        assert!(bound[0].contains("must be a literal string"), "{bound:?}");
1045        // A Video's poster is held to the same rule.
1046        let video = with_components(json!([{"id": "root", "component": "Video",
1047            "url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
1048        let got = refused(&video, &jail, false);
1049        assert_eq!(got.len(), 1);
1050        assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
1051    }
1052
1053    #[test]
1054    fn open_url_takes_only_http_and_https_literals() {
1055        let jail = jail("open");
1056        let button = |url: Value| {
1057            with_components(json!([
1058                {"id": "root", "component": "Button", "child": "t",
1059                 "action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
1060                {"id": "t", "component": "Text", "text": "Go"}
1061            ]))
1062        };
1063        assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
1064        assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
1065        // A dynamic URL is the renderer's to check, after showing it.
1066        assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
1067        let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
1068        assert_eq!(
1069            got,
1070            ["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
1071        );
1072    }
1073
1074    #[test]
1075    fn renderer_and_agent_functions_are_refused() {
1076        let jail = jail("functions");
1077        let got = refused(
1078            &[
1079                json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
1080                json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
1081            ],
1082            &jail,
1083            false,
1084        );
1085        assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
1086        assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
1087    }
1088
1089    #[test]
1090    fn a_drive_letter_is_not_a_scheme() {
1091        assert_eq!(scheme("C:\\img\\cat.png"), None);
1092        assert_eq!(scheme("HTTPS://x"), Some("https".into()));
1093        assert_eq!(scheme("img/cat.png"), None);
1094    }
1095
1096    #[test]
1097    fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
1098        let vault = crate::vault::SecretVault::default();
1099        vault.set("API_TOKEN", "tok-abcdef-123456".into());
1100        let message =
1101            json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
1102        let kept = sanitize(&message, &vault, EgressMode::Warn);
1103        assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
1104        assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
1105        assert_eq!(kept["n"], 3);
1106        let redacted = sanitize(&message, &vault, EgressMode::Redact);
1107        assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
1108        assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
1109    }
1110
1111    #[test]
1112    fn the_basic_catalog_reference_names_components_and_functions() {
1113        let reference = reference(Catalog::basic());
1114        assert!(
1115            reference.contains(
1116                "- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
1117            ),
1118            "{reference}"
1119        );
1120        assert!(reference.contains("- TextField {"), "{reference}");
1121        assert!(
1122            reference.contains("- formatString(value: DynamicString) -> string"),
1123            "{reference}"
1124        );
1125        assert!(!reference.contains("component:"), "{reference}");
1126    }
1127
1128    #[test]
1129    fn the_prompt_section_carries_the_catalog_instructions() {
1130        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1131        let section = session.prompt_section();
1132        assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
1133        assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
1134        assert!(section.contains("## Catalog Guidelines"));
1135        assert!(section.contains("[ui action] submit on <surfaceId>"));
1136    }
1137
1138    #[test]
1139    fn fields_beside_the_kind_are_moved_inside_it() {
1140        let (tidied, moved) = tidy(&serde_json::json!({
1141            "version": "1.0",
1142            "createSurface": {"catalogId": "c", "components": []},
1143            "surfaceId": "plan"
1144        }));
1145        assert_eq!(
1146            tidied,
1147            serde_json::json!({"version": "1.0",
1148                "createSurface": {"catalogId": "c", "components": [], "surfaceId": "plan"}})
1149        );
1150        assert_eq!(moved, ["surfaceId into createSurface"]);
1151
1152        // Never over a field the body has, and never with no kind or two kinds.
1153        for message in [
1154            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}, "surfaceId": "b"}),
1155            serde_json::json!({"version": "1.0", "surfaceId": "b"}),
1156            serde_json::json!({"version": "1.0", "deleteSurface": {}, "updateDataModel": {}, "x": 1}),
1157            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}}),
1158        ] {
1159            assert_eq!(tidy(&message), (message.clone(), Vec::new()), "{message}");
1160        }
1161    }
1162
1163    #[test]
1164    fn the_prompt_s_example_is_valid() {
1165        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1166        let call: Value =
1167            serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, true)).unwrap();
1168        let messages = call["messages"].as_array().unwrap();
1169        let report = session.apply(messages);
1170        assert!(report.is_ok(), "{:?}", report.errors);
1171        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1172        let section = session.prompt_section();
1173        assert!(section.contains("surfaceId` goes inside createSurface"));
1174        assert!(
1175            !section.contains("\"wait\":true"),
1176            "no waiter, no wait in the example"
1177        );
1178    }
1179
1180    #[test]
1181    fn a_waiter_set_later_offers_wait_from_then_on() {
1182        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1183        let request = UiWait {
1184            surface_ids: vec!["s".into()],
1185        };
1186        assert!(!session.can_wait());
1187        assert!(!session.prompt_section().contains("\"wait\": true"));
1188        assert_eq!(session.wait(&request), None);
1189
1190        session.set_waiter(Some(std::sync::Arc::new(|wait: &UiWait| {
1191            Some(Action::new(
1192                "ok",
1193                wait.surface_ids[0].clone(),
1194                "root",
1195                "2026-11-22T00:00:00Z",
1196                Map::new(),
1197            ))
1198        })));
1199        assert!(session.can_wait());
1200        assert!(session.prompt_section().contains("\"wait\": true"));
1201        assert_eq!(session.wait(&request).map(|a| a.name), Some("ok".into()));
1202
1203        session.set_waiter(None);
1204        assert!(!session.can_wait());
1205    }
1206
1207    #[test]
1208    fn orphans_are_warnings_and_dangling_references_errors() {
1209        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1210        let create = |components: Value| {
1211            serde_json::json!({"version": "1.0", "createSurface": {
1212                "surfaceId": "s",
1213                "catalogId": agent86_ui::BASIC_CATALOG_ID,
1214                "components": components,
1215            }})
1216        };
1217        let report = session.apply(&[create(serde_json::json!([
1218            {"id": "root", "component": "Column", "children": ["missing"]}
1219        ]))]);
1220        assert!(report.errors[0].message.starts_with("Dangling reference"));
1221        let report = session.apply(&[create(serde_json::json!([
1222            {"id": "root", "component": "Text", "text": "hi"},
1223            {"id": "spare", "component": "Text", "text": "nobody shows me"}
1224        ]))]);
1225        assert!(report.is_ok(), "{:?}", report.errors);
1226        assert!(report.warnings[0].message.contains("not reachable"));
1227        assert_eq!(session.surface_ids(), ["s"]);
1228    }
1229}