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    /// The top-level keys of surface `surface_id`, if it is up ([`surface_keys`]).
192    pub fn surface_keys(&self, surface_id: &str) -> Vec<String> {
193        surface_keys(&self.runtime(), surface_id)
194    }
195
196    /// Validate a batch and, when it has no errors, apply it to the surfaces.
197    pub fn apply(&self, messages: &[Value]) -> Report {
198        self.runtime().apply(messages)
199    }
200
201    /// Every surface up now as the one `createSurface` that draws it as it is,
202    /// for a program that reopens a session (or draws late) to bring its screen
203    /// up to date.
204    pub fn snapshot(&self) -> Vec<AgentMessage> {
205        self.runtime()
206            .snapshot()
207            .into_iter()
208            .filter_map(|message| serde_json::from_value(message).ok())
209            .collect()
210    }
211
212    /// Rebuild the surfaces from a session's history (ADR 0005: resume replays,
213    /// nothing is stored): every `render_ui` call that drew, in order, through
214    /// the same redaction, policy, and validation as when it ran. A call that
215    /// drew is one whose result is ok or opens with what the tool writes when it
216    /// draws (a waiting call the user dismissed reports a failure, yet drew).
217    /// Steps keep calls the history's compaction summarized away. Returns how
218    /// many calls were replayed.
219    pub fn replay(
220        &self,
221        state: &crate::session::AgentState,
222        ctx: &crate::tools::ToolContext,
223    ) -> usize {
224        let mut runtime = match Runtime::new(self.catalogs.clone()) {
225            Ok(runtime) => runtime,
226            Err(_) => return 0,
227        };
228        runtime.set_rules(RULES);
229        let mut replayed = 0;
230        for step in &state.steps {
231            for call in step.tool_calls.iter().filter(|call| call.name == RENDER_UI) {
232                let drew = step
233                    .results
234                    .iter()
235                    .find(|result| result.call_id == call.id)
236                    .is_some_and(drew);
237                if !drew {
238                    continue;
239                }
240                // The history keeps the call as the model sent it, before the
241                // registry repaired an array sent as a JSON string.
242                let messages = match call.arguments.get("messages") {
243                    Some(Value::Array(messages)) => messages.clone(),
244                    Some(Value::String(text)) => match serde_json::from_str(text) {
245                        Ok(Value::Array(messages)) => messages,
246                        _ => continue,
247                    },
248                    _ => continue,
249                };
250                let messages: Vec<Value> = messages
251                    .iter()
252                    .map(|message| tidy(&sanitize(message, &ctx.secrets, self.egress)).0)
253                    .collect();
254                let (messages, _) = complete(&messages, |id| surface_keys(&runtime, id));
255                if !policy(&messages, &ctx.policy, self.remote_media).is_empty() {
256                    continue;
257                }
258                if runtime.apply(&messages).is_ok() {
259                    replayed += 1;
260                }
261            }
262        }
263        *self.runtime() = runtime;
264        replayed
265    }
266
267    /// The ids of the surfaces up now.
268    pub fn surface_ids(&self) -> Vec<String> {
269        self.runtime().surface_ids().map(String::from).collect()
270    }
271
272    /// Every surface up now as text, in surface id order, for a client that
273    /// cannot draw A2UI (ADR 0005's text fallback): a heading naming the surface,
274    /// then its components with every binding resolved ([`surface_text`]).
275    pub fn surface_texts(&self) -> Vec<String> {
276        let runtime = self.runtime();
277        let ids: Vec<String> = runtime.surface_ids().map(String::from).collect();
278        ids.iter()
279            .filter_map(|id| runtime.tree(id).map(|tree| surface_text(id, &tree)))
280            .collect()
281    }
282
283    /// The system-prompt section: how to use `render_ui`, then each catalog's
284    /// own instructions and a compact reference to its components and
285    /// functions. Rebuilt per request, like the MCP section.
286    pub fn prompt_section(&self) -> String {
287        let mut section = String::from(PROMPT);
288        let media = if self.remote_media {
289            "a data: URL, an https URL, or the path of a file in the workspace"
290        } else {
291            "a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
292        };
293        if self.can_wait() {
294            section.push_str(
295                "\n- With `\"wait\": true` the call waits for the user's first action on \
296                 the surface and returns it as its result (`[ui action] ...`). Use it for a \
297                 form you need answered before you can go on; otherwise leave it out and \
298                 carry on.",
299            );
300        }
301        section.push_str(&format!(
302            "\n- Never ask for a password, key, or token in a surface (no TextField with \
303             variant \"obscured\"): call request_secret, which asks through a masked prompt \
304             and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
305             Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
306             http and https URLs."
307        ));
308        if let Some(catalog) = self.catalogs.first() {
309            section.push_str(&format!(
310                "\n\nA complete call, a choice with a Submit button (`surfaceId` goes \
311                 inside createSurface, never beside it):\n{}",
312                example(catalog.id(), self.can_wait())
313            ));
314        }
315        for catalog in &self.catalogs {
316            section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
317            if let Some(instructions) = catalog.instructions() {
318                section.push('\n');
319                section.push_str(instructions.trim());
320                section.push('\n');
321            }
322            section.push_str(&reference(catalog));
323        }
324        section
325    }
326}
327
328/// The keys that name what an A2UI 1.0 message is; an envelope holds
329/// `version` and exactly one of them.
330const KINDS: &[&str] = &[
331    "createSurface",
332    "updateComponents",
333    "updateDataModel",
334    "deleteSurface",
335    "callRendererFunction",
336    "agentFunctionResponse",
337];
338
339/// Beyond the protocol: a message whose fields sit beside its kind instead of
340/// inside it (`{"version": "1.0", "createSurface": {...}, "surfaceId": "x"}`,
341/// the mistake models make most often) has them moved in, when the kind's body
342/// does not already have them. Such a message is never valid as written, so
343/// the move only turns an error into what the model plainly meant. Returns the
344/// message and the fields moved, for the result to mention. `render_ui` and
345/// replay both apply it, so a session written either way replays the same.
346pub fn tidy(message: &Value) -> (Value, Vec<String>) {
347    let Some(envelope) = message.as_object() else {
348        return (message.clone(), Vec::new());
349    };
350    let kinds: Vec<&String> = envelope
351        .keys()
352        .filter(|key| KINDS.contains(&key.as_str()))
353        .collect();
354    let [kind] = kinds.as_slice() else {
355        return (message.clone(), Vec::new());
356    };
357    let kind = (*kind).clone();
358    let Some(body) = envelope.get(&kind).and_then(Value::as_object) else {
359        return (message.clone(), Vec::new());
360    };
361    let strays: Vec<String> = envelope
362        .keys()
363        .filter(|key| *key != "version" && **key != kind && !body.contains_key(*key))
364        .cloned()
365        .collect();
366    if strays.is_empty() {
367        return (message.clone(), Vec::new());
368    }
369    let mut envelope = envelope.clone();
370    let mut body = body.clone();
371    for key in &strays {
372        if let Some(value) = envelope.remove(key) {
373            body.insert(key.clone(), value);
374        }
375    }
376    envelope.insert(kind.clone(), Value::Object(body));
377    let moved = strays
378        .into_iter()
379        .map(|key| format!("{key} into {kind}"))
380        .collect();
381    (Value::Object(envelope), moved)
382}
383
384/// Beyond the protocol (ADR 0006), after [`tidy`]: two shapes A2UI accepts but
385/// that do not do what the model meant are completed, so the form works.
386///
387/// - **A binding written with 0.9.1's key.** Inside components, an object that
388///   is exactly `{"path": "/..."}` is a literal object to A2UI 1.0, so a Button
389///   would send back `{"path": "/scope"}` instead of the user's choice. It
390///   becomes `{"@path": "/..."}`, and the result notes it so the model learns.
391///   (A ChildList template has `componentId` beside its `path`, so it is never
392///   touched.)
393/// - **A Button event with no `context`.** The action would carry nothing, so
394///   it gets a context binding every top-level value of its surface: the keys
395///   of the data model and the first segment of every absolute path the
396///   surface's components bind, from this batch and, for a surface drawn
397///   earlier, from `existing`. This is what the prompt promises, which keeps
398///   the deepest nesting out of every form the model writes.
399///
400/// `existing` gives the top-level keys of a surface already up
401/// ([`surface_keys`]). `render_ui` and replay both apply it, so a session
402/// replays the same. Returns the messages and the notes for the model.
403pub fn complete(
404    messages: &[Value],
405    existing: impl Fn(&str) -> Vec<String>,
406) -> (Vec<Value>, Vec<String>) {
407    let mut keys: std::collections::HashMap<String, Vec<String>> = Default::default();
408    let mut notes = Vec::new();
409    let mut out = Vec::with_capacity(messages.len());
410    for (index, message) in messages.iter().enumerate() {
411        let mut message = message.clone();
412        if let Some(create) = message.get_mut("createSurface") {
413            let id = surface_of(create);
414            let mut known = Vec::new();
415            if let Some(Value::Object(model)) = create.get("dataModel") {
416                extend_unique(&mut known, model.keys().cloned());
417            }
418            rebind(
419                create,
420                &format!("messages/{index}/createSurface"),
421                &mut notes,
422            );
423            extend_unique(&mut known, bound_keys(create.get("components")));
424            fill_contexts(create, &known);
425            keys.insert(id, known);
426        } else if let Some(update) = message.get_mut("updateComponents") {
427            let id = surface_of(update);
428            let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
429            rebind(
430                update,
431                &format!("messages/{index}/updateComponents"),
432                &mut notes,
433            );
434            extend_unique(known, bound_keys(update.get("components")));
435            fill_contexts(update, known);
436        } else if let Some(update) = message.get("updateDataModel") {
437            let id = surface_of(update);
438            let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
439            match update.get("path").and_then(Value::as_str) {
440                None | Some("" | "/") => {
441                    if let Some(Value::Object(model)) = update.get("value") {
442                        extend_unique(known, model.keys().cloned());
443                    }
444                }
445                Some(path) => extend_unique(known, top_segment(path)),
446            }
447        }
448        out.push(message);
449    }
450    (out, notes)
451}
452
453/// The top-level keys of surface `surface_id` in `runtime`: its data model's,
454/// then the first segment of every absolute path its components bind.
455pub fn surface_keys(runtime: &Runtime, surface_id: &str) -> Vec<String> {
456    let mut keys = Vec::new();
457    if let Some(Value::Object(model)) = runtime.data_model(surface_id) {
458        extend_unique(&mut keys, model.keys().cloned());
459    }
460    if let Some(components) = runtime.components(surface_id) {
461        let components = Value::Array(components.cloned().collect());
462        extend_unique(&mut keys, bound_keys(Some(&components)));
463    }
464    keys
465}
466
467fn surface_of(body: &Value) -> String {
468    body.get("surfaceId")
469        .and_then(Value::as_str)
470        .unwrap_or_default()
471        .to_owned()
472}
473
474fn extend_unique(keys: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
475    for key in more {
476        if !keys.contains(&key) {
477            keys.push(key);
478        }
479    }
480}
481
482/// The key of an absolute JSON Pointer's first segment, unescaped.
483fn top_segment(path: &str) -> Option<String> {
484    let rest = path.strip_prefix('/')?;
485    let segment = rest.split('/').next().unwrap_or_default();
486    (!segment.is_empty()).then(|| segment.replace("~1", "/").replace("~0", "~"))
487}
488
489/// The first segment of every absolute `@path` under `value`.
490fn bound_keys(value: Option<&Value>) -> Vec<String> {
491    fn walk(value: &Value, keys: &mut Vec<String>) {
492        match value {
493            Value::Object(map) => {
494                if let Some(Value::String(path)) = map.get("@path") {
495                    extend_unique(keys, top_segment(path));
496                }
497                map.values().for_each(|value| walk(value, keys));
498            }
499            Value::Array(items) => items.iter().for_each(|value| walk(value, keys)),
500            _ => {}
501        }
502    }
503    let mut keys = Vec::new();
504    if let Some(value) = value {
505        walk(value, &mut keys);
506    }
507    keys
508}
509
510/// Turn each `{"path": "/..."}` among `body`'s components into a binding,
511/// noting each component that had one.
512fn rebind(body: &mut Value, at: &str, notes: &mut Vec<String>) {
513    fn walk(value: &mut Value) -> bool {
514        match value {
515            Value::Object(map) => {
516                let lone_path = map.len() == 1
517                    && map
518                        .get("path")
519                        .and_then(Value::as_str)
520                        .is_some_and(|path| path.starts_with('/'));
521                if lone_path {
522                    let path = map.remove("path").expect("checked above");
523                    map.insert("@path".to_owned(), path);
524                    return true;
525                }
526                let mut changed = false;
527                for value in map.values_mut() {
528                    changed |= walk(value);
529                }
530                changed
531            }
532            Value::Array(items) => items
533                .iter_mut()
534                .fold(false, |changed, item| walk(item) | changed),
535            _ => false,
536        }
537    }
538    let Some(Value::Array(components)) = body.get_mut("components") else {
539        return;
540    };
541    for (index, component) in components.iter_mut().enumerate() {
542        let Value::Object(fields) = component else {
543            continue;
544        };
545        let mut changed = false;
546        for (key, value) in fields.iter_mut() {
547            if key != "id" && key != "component" {
548                changed |= walk(value);
549            }
550        }
551        if changed {
552            let id = fields.get("id").and_then(Value::as_str).unwrap_or("?");
553            notes.push(format!(
554                "Note: read {{\"path\": ...}} as {{\"@path\": ...}} in {at}/components/{index} \
555                 ({id}); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal."
556            ));
557        }
558    }
559}
560
561/// Give every event Button among `body`'s components with no `context` one
562/// binding each of `keys`.
563fn fill_contexts(body: &mut Value, keys: &[String]) {
564    let Some(Value::Array(components)) = body.get_mut("components") else {
565        return;
566    };
567    for component in components.iter_mut() {
568        if component.get("component").and_then(Value::as_str) != Some("Button") {
569            continue;
570        }
571        let Some(Value::Object(event)) = component.pointer_mut("/action/event") else {
572            continue;
573        };
574        if event.contains_key("context") {
575            continue;
576        }
577        let context: Map<String, Value> = keys
578            .iter()
579            .map(|key| {
580                let pointer = format!("/{}", key.replace('~', "~0").replace('/', "~1"));
581                (key.clone(), serde_json::json!({"@path": pointer}))
582            })
583            .collect();
584        event.insert("context".to_owned(), Value::Object(context));
585    }
586}
587
588/// Whether a component is a Button whose action sends an event (rather than
589/// running a local function such as `openUrl`).
590pub fn is_event_button(component: &Value) -> bool {
591    component.get("component").and_then(Value::as_str) == Some("Button")
592        && component.pointer("/action/event").is_some()
593}
594
595/// The prompt's example call, on one line, in `catalog_id`.
596fn example(catalog_id: &str, wait: bool) -> String {
597    let mut call = serde_json::json!({"messages": [{"version": "1.0", "createSurface": {
598        "surfaceId": "plan",
599        "catalogId": catalog_id,
600        "components": [
601            {"id": "root", "component": "Column", "children": ["choice", "submit"]},
602            {"id": "choice", "component": "ChoicePicker", "label": "Which plan?",
603             "variant": "mutuallyExclusive", "value": {"@path": "/plan"},
604             "options": [{"label": "Basic", "value": "basic"}, {"label": "Pro", "value": "pro"}]},
605            {"id": "submit", "component": "Button", "child": "submit_label",
606             "action": {"event": {"name": "submit"}}},
607            {"id": "submit_label", "component": "Text", "text": "Submit"}
608        ],
609        "dataModel": {"plan": []}
610    }}]});
611    if wait {
612        call["wait"] = Value::Bool(true);
613    }
614    call.to_string()
615}
616
617/// What every `render_ui` prompt says, whatever the catalogs.
618const PROMPT: &str = "## agent86UI: drawing UI with render_ui
619
620You can show the user interactive UI (forms, choices, confirmations, small \
621dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
622them with its own widgets. Use it when you need a structured answer (pick one of \
623several options, fill in a few fields, confirm a plan) or when a layout says more \
624than prose. Otherwise answer in plain text.
625
626- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
627exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
628`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
629`catalogId` from below, and usually its `components` and `dataModel` inline), \
630change it later with updateComponents (a component replaces the one with the same \
631id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
632- Components are a flat list linked by id, and exactly one has the id \"root\". \
633Every child id must be defined in the same call or an earlier one. An id is an \
634identifier: letters, digits, and `_`, starting with a letter or `_` (`submit_label`, \
635never `submit-label`).
636- A value is a literal, a binding to the surface's data model (`{\"@path\": \
637\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
638{...}}`). Input components write what the user enters back to the path they are \
639bound to. A `ChildList` is an array of ids, or a template over a list in the data \
640model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
641relative to each item.
642- A button's action is `{\"event\": {\"name\": \"submit\"}}`, and it sends every \
643top-level value of the surface's data model. To send something else, give the \
644event a `context` beside `name` (`{\"event\": {\"name\": \"pick\", \"context\": \
645{\"plan\": \"pro\"}}}`), never beside `event`. When the user presses it, a later \
646user message reads `[ui action] submit on <surfaceId>: <values as JSON>`; the \
647surface stays up meanwhile.
648- Only a Button whose action is an event sends the user's answer: choosing an \
649option or typing only changes the data model. So every form needs a Button (for \
650example Submit).
651- Keep each call short: a surface's JSON breaks most often when it is large. For \
652a form of more than about four inputs, send createSurface with the root and the \
653first few components, then add the rest in further calls with updateComponents, \
654sending the root again with its longer `children`; put `wait` only on the last call.
655- render_ui's result is the validator's verdict. If it lists problems, nothing \
656was drawn: fix them and send the corrected messages again.
657- Renderer functions (`callRendererFunction`) and agent functions are not \
658available.";
659
660/// A compact reference to a catalog's components and functions, from their
661/// schemas: each component's properties (`?` marks an optional one) with their
662/// types, and each function's arguments and return type.
663pub fn reference(catalog: &Catalog) -> String {
664    let document = catalog.document();
665    let mut out = String::from("\nComponents:\n");
666    for (name, schema) in document
667        .get("components")
668        .and_then(Value::as_object)
669        .into_iter()
670        .flatten()
671    {
672        let (properties, required, checkable) = gather(schema);
673        let fields: Vec<String> = properties
674            .iter()
675            .filter(|(key, _)| *key != "component" && *key != "id")
676            .map(|(key, property)| {
677                let optional = if required.iter().any(|r| r == key) {
678                    ""
679                } else {
680                    "?"
681                };
682                format!("{key}{optional}: {}", type_of(property, document))
683            })
684            .collect();
685        let checks = if checkable { " (accepts @checks)" } else { "" };
686        out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
687    }
688    let functions: Vec<String> = document
689        .get("functions")
690        .and_then(Value::as_object)
691        .into_iter()
692        .flatten()
693        .filter(|(name, _)| {
694            catalog
695                .function(name)
696                .is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
697        })
698        .map(|(name, schema)| {
699            let args = schema.pointer("/properties/args");
700            let required: Vec<&str> = args
701                .and_then(|a| a.get("required"))
702                .and_then(Value::as_array)
703                .into_iter()
704                .flatten()
705                .filter_map(Value::as_str)
706                .collect();
707            let params: Vec<String> = args
708                .and_then(|a| a.get("properties"))
709                .and_then(Value::as_object)
710                .into_iter()
711                .flatten()
712                .map(|(key, property)| {
713                    let optional = if required.contains(&key.as_str()) {
714                        ""
715                    } else {
716                        "?"
717                    };
718                    format!("{key}{optional}: {}", type_of(property, document))
719                })
720                .collect();
721            let returns = schema
722                .get("returnType")
723                .and_then(Value::as_str)
724                .unwrap_or("any");
725            format!("- {name}({}) -> {returns}\n", params.join(", "))
726        })
727        .collect();
728    if !functions.is_empty() {
729        out.push_str("\nFunctions:\n");
730        out.extend(functions);
731    }
732    out
733}
734
735/// A component schema's properties and required names, from its own
736/// `properties` and its `allOf` parts, and whether it takes `@checks`.
737fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
738    let mut properties = Map::new();
739    let mut required = Vec::new();
740    let mut checkable = false;
741    let mut parts = vec![schema];
742    if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
743        parts.extend(all);
744    }
745    for part in parts {
746        if part
747            .get("$ref")
748            .and_then(Value::as_str)
749            .is_some_and(|r| r.ends_with("/Checkable"))
750        {
751            checkable = true;
752        }
753        if let Some(own) = part.get("properties").and_then(Value::as_object) {
754            for (key, value) in own {
755                properties.insert(key.clone(), value.clone());
756            }
757        }
758        required.extend(
759            part.get("required")
760                .and_then(Value::as_array)
761                .into_iter()
762                .flatten()
763                .filter_map(Value::as_str)
764                .map(String::from),
765        );
766    }
767    (properties, required, checkable)
768}
769
770/// A property's type, briefly: a common type by name, a catalog's own
771/// definition by what it is (its `Weight` is a number, not a name to guess
772/// at), an enum's values, or the JSON type.
773fn type_of(property: &Value, document: &Value) -> String {
774    if let Some(target) = property.get("$ref").and_then(Value::as_str) {
775        if let Some(local) = target.strip_prefix("#/$defs/") {
776            if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
777                if def.get("$ref").is_none() {
778                    return type_of(def, document);
779                }
780            }
781        }
782        return target.rsplit('/').next().unwrap_or(target).to_string();
783    }
784    if let Some(values) = property.get("enum").and_then(Value::as_array) {
785        return values
786            .iter()
787            .map(|v| v.to_string())
788            .collect::<Vec<_>>()
789            .join("|");
790    }
791    match property.get("type").and_then(Value::as_str) {
792        Some("array") => match property.get("items") {
793            Some(items) => format!("array of {}", type_of(items, document)),
794            None => "array".into(),
795        },
796        Some(kind) => kind.to_string(),
797        None => "any".into(),
798    }
799}
800
801/// What a `render_ui` result carries for the loop, taken out of its metadata,
802/// so it is emitted and recorded as agent86UI's own and never kept in the
803/// session: the validated messages, and the `ui_render` trace fields.
804pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
805    let messages = match metadata.remove(MESSAGES_KEY) {
806        Some(Value::Array(items)) => items
807            .into_iter()
808            .filter_map(|item| serde_json::from_value(item).ok())
809            .collect(),
810        _ => Vec::new(),
811    };
812    (messages, metadata.remove(TRACE_KEY))
813}
814
815/// What `render_ui`'s result opens with when the call drew.
816const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];
817
818/// Whether a `render_ui` result says the call drew. A waiting call that was not
819/// answered says so first and what it drew after (earlier versions wrote the
820/// drawing first), so every line is looked at.
821fn drew(result: &crate::types::ToolResult) -> bool {
822    let text = if result.ok {
823        result.content.as_str()
824    } else {
825        result.error.as_deref().unwrap_or_default()
826    };
827    result.ok
828        || text
829            .lines()
830            .any(|line| DREW.iter().any(|opening| line.starts_with(opening)))
831}
832
833/// The surfaces a waiting call waits on, taken out of its result's metadata.
834pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
835    match metadata.remove(WAIT_KEY)? {
836        Value::Array(ids) => Some(
837            ids.into_iter()
838                .filter_map(|id| id.as_str().map(String::from))
839                .collect(),
840        ),
841        _ => None,
842    }
843}
844
845/// An action as the model reads it, a waiting call's result or the next user
846/// message: `[ui action] <name> on <surfaceId>: <context as JSON>`, then the
847/// event's `userMessage` on a line of its own when it has one.
848pub fn action_text(action: &Action) -> String {
849    let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
850    let mut text = format!(
851        "[ui action] {} on {}: {context}",
852        action.name, action.surface_id
853    );
854    if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
855        text.push('\n');
856        text.push_str(message);
857    }
858    text
859}
860
861impl crate::agent::Harness {
862    /// Declare a renderer: put `session` on the tool context and offer the
863    /// model `render_ui`. Both assembly paths (`sdk::AgentBuilder::ui` and the
864    /// binary's interface, through `setup::attach_renderer`) go through it.
865    /// Sub-agents never draw: `ToolContext::fork` drops the session.
866    pub fn attach_ui(&mut self, session: UiSession) -> Result<(), String> {
867        self.registry
868            .register(Box::new(crate::tools::render_ui::RenderUiTool))?;
869        self.context.ui = Some(std::sync::Arc::new(session));
870        Ok(())
871    }
872
873    /// Take an action from a surface no call was waiting on (ADR 0005: it
874    /// becomes the next user message): check that it could have come from a
875    /// surface up now, record it as `ui_action` (never its values), and give
876    /// the text the turn runs on, `[ui action] <name> on <surfaceId>: ...`. The
877    /// caller runs that as a plain turn, whose own vault redaction and ingress
878    /// guardrail cover it as they cover typed input. `Err` names what was
879    /// wrong, never the values, and nothing is recorded.
880    pub fn accept_ui_action(&self, sid: &str, action: &Action) -> Result<String, String> {
881        let ui = self
882            .context
883            .ui
884            .as_deref()
885            .ok_or_else(|| String::from("this agent has no renderer"))?;
886        ui.check_action(action, None)?;
887        self.recorder.event(
888            sid,
889            "ui_action",
890            vec![
891                ("surface", serde_json::json!(action.surface_id)),
892                ("name", serde_json::json!(action.name)),
893                ("component", serde_json::json!(action.source_component_id)),
894                ("waited", serde_json::json!(false)),
895            ],
896        );
897        Ok(action_text(action))
898    }
899
900    /// Wait for the user's answer to a `wait: true` call, through the prompt
901    /// queue like a secret prompt (one question at a time, declined once the
902    /// turn is cancelled), and make it the call's result. The answer goes
903    /// through the vault and the ingress guardrail, as typed input does, and is
904    /// recorded as `ui_action`, without its values.
905    pub(crate) fn ui_wait(
906        &self,
907        call: &crate::types::ToolCall,
908        drawn: crate::types::ToolResult,
909        surfaces: Vec<String>,
910        sid: &str,
911    ) -> crate::types::ToolResult {
912        use crate::tools::{failure, success};
913        let Some(ui) = self.context.ui.as_deref() else {
914            return drawn;
915        };
916        if surfaces.is_empty() {
917            return drawn;
918        }
919        let request = UiWait {
920            surface_ids: surfaces.clone(),
921        };
922        let question = crate::approval::Question {
923            tool: Some(RENDER_UI.into()),
924            call: Some(call.id.clone()),
925            ..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
926        };
927        let shown = drawn.content.clone();
928        let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
929            call_id: drawn.call_id.clone(),
930            ..result
931        };
932        let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
933            None => {
934                return answered(failure(
935                    RENDER_UI,
936                    format!(
937                        "The turn was cancelled before the user answered. The surface stays \
938                         up; an action on it later comes as a user message.\n{shown}"
939                    ),
940                ))
941            }
942            Some(None) => {
943                return answered(failure(
944                    RENDER_UI,
945                    format!(
946                        "The user did not answer (they dismissed it). The surface stays up; an \
947                         action on it later comes as a user message.\n{shown}"
948                    ),
949                ))
950            }
951            Some(Some(action)) => action,
952        };
953        if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
954            return answered(failure(
955                RENDER_UI,
956                format!("The screen's answer could not be used: {why}.\n{shown}"),
957            ));
958        }
959        let text = self.context.secrets.redact(&action_text(&action));
960        let report = self.guardrails.inspect_ingress(&text);
961        if report.flagged() {
962            self.recorder.event(
963                sid,
964                "guardrail",
965                vec![
966                    ("stage", serde_json::json!("ingress")),
967                    ("source", serde_json::json!("ui_action")),
968                    ("findings", serde_json::json!(report.summary())),
969                ],
970            );
971        }
972        self.recorder.event(
973            sid,
974            "ui_action",
975            vec![
976                ("surface", serde_json::json!(action.surface_id)),
977                ("name", serde_json::json!(action.name)),
978                ("component", serde_json::json!(action.source_component_id)),
979                ("waited", serde_json::json!(true)),
980            ],
981        );
982        if self.guardrails.should_block(&report) {
983            return answered(failure(
984                RENDER_UI,
985                format!(
986                    "The user's answer was refused by the input guardrail ({}).\n{shown}",
987                    report.summary()
988                ),
989            ));
990        }
991        answered(success(RENDER_UI, format!("{shown}\n{text}")))
992    }
993}
994
995/// Every string in `value`, through the secret vault's redaction and, with the
996/// egress guardrail in `redact` mode, its redaction too: what a surface shows
997/// reaches the user as the model's text does. Object keys are left alone.
998pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
999    match value {
1000        Value::String(text) => {
1001            let text = vault.redact(text);
1002            Value::String(if egress == EgressMode::Redact {
1003                crate::guardrails::redact(&text).0
1004            } else {
1005                text
1006            })
1007        }
1008        Value::Array(items) => Value::Array(
1009            items
1010                .iter()
1011                .map(|item| sanitize(item, vault, egress))
1012                .collect(),
1013        ),
1014        Value::Object(map) => Value::Object(
1015            map.iter()
1016                .map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
1017                .collect(),
1018        ),
1019        other => other.clone(),
1020    }
1021}
1022
1023/// Something agent86's policy refuses in a batch (ADR 0005), where the
1024/// protocol would allow it: a JSON Pointer into the batch and why.
1025#[derive(Debug, Clone, PartialEq, Eq)]
1026pub struct Refusal {
1027    pub path: String,
1028    pub message: String,
1029}
1030
1031impl std::fmt::Display for Refusal {
1032    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1033        write!(f, "REFUSED at {}: {}", self.path, self.message)
1034    }
1035}
1036
1037/// The media components of the basic catalog and the properties that load a
1038/// URL. A custom catalog's component of the same name is held to the same rule.
1039const MEDIA: &[(&str, &[&str])] = &[
1040    ("Image", &["url"]),
1041    ("Video", &["url", "posterUrl"]),
1042    ("AudioPlayer", &["url"]),
1043];
1044
1045/// What agent86 refuses in a batch the protocol allows (ADR 0005):
1046/// - a `TextField` with `"variant": "obscured"`: secrets are never collected
1047///   through a surface, so the value never reaches the model;
1048/// - media from anywhere but a `data:` URL or a file in the workspace (or an
1049///   `https` URL, with `remote_media`), and from a binding or a call, whose
1050///   value is not known until the renderer resolves it;
1051/// - `openUrl` with a literal URL that is not `http` or `https` (a dynamic one
1052///   is the renderer's to check before it opens it, after showing it);
1053/// - `callRendererFunction` and agent functions, left out of the first version.
1054pub fn policy(
1055    messages: &[Value],
1056    jail: &crate::tools::SandboxPolicy,
1057    remote_media: bool,
1058) -> Vec<Refusal> {
1059    let mut refusals = Vec::new();
1060    let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
1061    for (index, message) in messages.iter().enumerate() {
1062        if message.get("callRendererFunction").is_some() {
1063            refuse(
1064                format!("/{index}/callRendererFunction"),
1065                "renderer functions are not available here; draw with components and change \
1066                 them with updateComponents and updateDataModel instead"
1067                    .into(),
1068            );
1069        }
1070        if message.get("agentFunctionResponse").is_some() {
1071            refuse(
1072                format!("/{index}/agentFunctionResponse"),
1073                "agent functions are not available here".into(),
1074            );
1075        }
1076        for kind in ["createSurface", "updateComponents"] {
1077            let Some(components) = message
1078                .get(kind)
1079                .and_then(|body| body.get("components"))
1080                .and_then(Value::as_array)
1081            else {
1082                continue;
1083            };
1084            for (number, component) in components.iter().enumerate() {
1085                let at = format!("/{index}/{kind}/components/{number}");
1086                let type_name = component.get("component").and_then(Value::as_str);
1087                let id = component
1088                    .get("id")
1089                    .and_then(Value::as_str)
1090                    .unwrap_or("this component");
1091                if type_name == Some("TextField")
1092                    && component.get("variant").and_then(Value::as_str) == Some("obscured")
1093                {
1094                    refuse(
1095                        format!("{at}/variant"),
1096                        format!(
1097                            "TextField {id} is \"obscured\", a password field, but a surface never \
1098                             collects secrets: call request_secret instead, which asks the user \
1099                             through a masked prompt and never shows you the value"
1100                        ),
1101                    );
1102                }
1103                if let Some((_, properties)) =
1104                    MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
1105                {
1106                    for property in *properties {
1107                        let Some(value) = component.get(*property) else {
1108                            continue;
1109                        };
1110                        let path = format!("{at}/{property}");
1111                        match value.as_str() {
1112                            Some(url) => {
1113                                if let Some(why) = media_problem(url, jail, remote_media) {
1114                                    refuse(path, format!("{id}'s {property} {why}"));
1115                                }
1116                            }
1117                            None => refuse(
1118                                path,
1119                                format!(
1120                                    "{id}'s {property} must be a literal string: what a surface \
1121                                     loads is checked before it is drawn, so it cannot come from a \
1122                                     binding or a function call"
1123                                ),
1124                            ),
1125                        }
1126                    }
1127                }
1128                open_urls(component, &at, &mut refuse);
1129            }
1130        }
1131    }
1132    refusals
1133}
1134
1135/// Why a media URL may not load, or `None` when it may.
1136fn media_problem(
1137    url: &str,
1138    jail: &crate::tools::SandboxPolicy,
1139    remote_media: bool,
1140) -> Option<String> {
1141    match scheme(url) {
1142        Some(scheme) if scheme == "data" => None,
1143        Some(scheme) if scheme == "https" && remote_media => None,
1144        Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
1145            "{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
1146             or carry data out in its URL): use a data: URL or a file in the workspace"
1147        )),
1148        Some(scheme) => Some(format!(
1149            "{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
1150             the workspace"
1151        )),
1152        None => match jail.resolve_within(url) {
1153            Err(_) => Some(format!("{url:?} is outside the workspace")),
1154            Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
1155            Ok(_) => None,
1156        },
1157    }
1158}
1159
1160/// A URL's scheme, lowercased, when it has one. A single letter before the
1161/// colon is a Windows drive, not a scheme.
1162fn scheme(url: &str) -> Option<String> {
1163    let (scheme, _) = url.split_once(':')?;
1164    let valid = scheme.len() > 1
1165        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1166        && scheme
1167            .chars()
1168            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
1169    valid.then(|| scheme.to_ascii_lowercase())
1170}
1171
1172/// Refuse each `openUrl` call in `value` whose literal URL is not `http` or
1173/// `https`.
1174fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
1175    match value {
1176        Value::Object(map) => {
1177            if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
1178                if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
1179                    let scheme = scheme(url);
1180                    if !matches!(scheme.as_deref(), Some("http" | "https")) {
1181                        refuse(
1182                            format!("{at}/args/url"),
1183                            format!("openUrl only opens http and https URLs, not {url:?}"),
1184                        );
1185                    }
1186                }
1187            }
1188            for (key, item) in map {
1189                let segment = key.replace('~', "~0").replace('/', "~1");
1190                open_urls(item, &format!("{at}/{segment}"), refuse);
1191            }
1192        }
1193        Value::Array(items) => {
1194            for (index, item) in items.iter().enumerate() {
1195                open_urls(item, &format!("{at}/{index}"), refuse);
1196            }
1197        }
1198        _ => {}
1199    }
1200}
1201
1202/// A surface as plain text, for a client that cannot draw it: a heading naming
1203/// it, then a line or more per component, as the user would read it. Fields show
1204/// their values (`(empty)` when there are none), choices are lettered with the
1205/// chosen ones marked, check boxes and buttons are bracketed, media is its
1206/// description and its URL (never a `data:` one), and what has no text form
1207/// (Tabs, Modal) is named. Every string goes through
1208/// [`crate::escape::show_controls`]; the values were redacted when drawn.
1209pub fn surface_text(surface_id: &str, tree: &agent86_ui::runtime::Node) -> String {
1210    let mut lines = vec![format!(
1211        "[agent86UI surface {:?}: this client cannot draw it, so it is shown as text; \
1212         answer in your reply]",
1213        crate::escape::show_controls(surface_id)
1214    )];
1215    node_text(tree, &mut lines);
1216    lines.join("\n")
1217}
1218
1219/// A property as text: a string as it is, a number or a boolean as JSON writes
1220/// it, anything else (or nothing) empty.
1221fn prop(node: &agent86_ui::runtime::Node, key: &str) -> String {
1222    let text = match node.properties.get(key) {
1223        Some(Value::String(text)) => text.clone(),
1224        Some(Value::Null) | None => String::new(),
1225        Some(Value::Number(number)) => number.to_string(),
1226        Some(Value::Bool(flag)) => flag.to_string(),
1227        Some(other) => other.to_string(),
1228    };
1229    crate::escape::show_controls(&text)
1230}
1231
1232fn kids<'a>(node: &'a agent86_ui::runtime::Node, key: &str) -> &'a [agent86_ui::runtime::Node] {
1233    node.children
1234        .iter()
1235        .find(|(name, _)| name == key)
1236        .map(|(_, nodes)| nodes.as_slice())
1237        .unwrap_or_default()
1238}
1239
1240/// `label: rest`, or `rest` alone when there is no label.
1241fn labeled(label: &str, rest: &str) -> String {
1242    if label.is_empty() {
1243        rest.to_owned()
1244    } else {
1245        format!("{label}: {rest}")
1246    }
1247}
1248
1249fn node_text(node: &agent86_ui::runtime::Node, out: &mut Vec<String>) {
1250    if node.placeholder {
1251        out.push("…".into());
1252        return;
1253    }
1254    match node.component.as_str() {
1255        "Text" => {
1256            let text = prop(node, "text");
1257            if !text.is_empty() {
1258                out.push(text);
1259            }
1260        }
1261        "Column" | "List" | "Row" => {
1262            for child in kids(node, "children") {
1263                node_text(child, out);
1264            }
1265        }
1266        "Card" => {
1267            for child in kids(node, "child") {
1268                node_text(child, out);
1269            }
1270        }
1271        "Divider" => out.push("---".into()),
1272        "Button" => {
1273            let label: Vec<String> = kids(node, "child")
1274                .iter()
1275                .flat_map(|child| child.walk())
1276                .filter(|n| n.component == "Text")
1277                .map(|n| prop(n, "text"))
1278                .filter(|text| !text.is_empty())
1279                .collect();
1280            let label = if label.is_empty() {
1281                crate::escape::show_controls(&node.id)
1282            } else {
1283                label.join(" ").replace('\n', " ")
1284            };
1285            out.push(format!("[{label}]"));
1286        }
1287        "TextField" | "DateTimeInput" => {
1288            let value = prop(node, "value");
1289            let shown = if value.is_empty() {
1290                "(empty)".to_owned()
1291            } else {
1292                value
1293            };
1294            out.push(labeled(&prop(node, "label"), &shown));
1295        }
1296        "CheckBox" => {
1297            let checked = node.properties.get("value").and_then(Value::as_bool) == Some(true);
1298            let mark = if checked { "[x]" } else { "[ ]" };
1299            out.push(format!("{mark} {}", prop(node, "label")));
1300        }
1301        "ChoicePicker" => {
1302            let chosen: Vec<String> = match node.properties.get("value") {
1303                Some(Value::Array(items)) => items
1304                    .iter()
1305                    .filter_map(|item| item.as_str().map(String::from))
1306                    .collect(),
1307                Some(Value::String(one)) => vec![one.clone()],
1308                _ => Vec::new(),
1309            };
1310            let options = node
1311                .properties
1312                .get("options")
1313                .and_then(Value::as_array)
1314                .cloned()
1315                .unwrap_or_default();
1316            let lettered: Vec<String> = options
1317                .iter()
1318                .enumerate()
1319                .map(|(index, option)| {
1320                    let value = option.get("value").and_then(Value::as_str).unwrap_or("");
1321                    let label = match option.get("label") {
1322                        Some(Value::String(text)) => text.clone(),
1323                        Some(other) if !other.is_null() => other.to_string(),
1324                        _ => value.to_owned(),
1325                    };
1326                    let letter = char::from(b'a' + (index % 26) as u8);
1327                    let on = if chosen.iter().any(|c| c == value) {
1328                        " (chosen)"
1329                    } else {
1330                        ""
1331                    };
1332                    format!("{letter}) {}{on}", crate::escape::show_controls(&label))
1333                })
1334                .collect();
1335            out.push(labeled(&prop(node, "label"), &lettered.join("  ")));
1336        }
1337        "Slider" => {
1338            let number = |key: &str| node.properties.get(key).and_then(Value::as_f64);
1339            let show = |value: f64| {
1340                if value.fract() == 0.0 && value.abs() < 1e15 {
1341                    format!("{}", value as i64)
1342                } else {
1343                    format!("{value}")
1344                }
1345            };
1346            let (min, max) = (number("min").unwrap_or(0.0), number("max").unwrap_or(100.0));
1347            let value = number("value").unwrap_or(min);
1348            out.push(labeled(
1349                &prop(node, "label"),
1350                &format!("{} ({} to {})", show(value), show(min), show(max)),
1351            ));
1352        }
1353        kind @ ("Image" | "Video" | "AudioPlayer") => {
1354            let what = match kind {
1355                "Image" => "image",
1356                "Video" => "video",
1357                _ => "audio",
1358            };
1359            let mut text = format!("[{what}]");
1360            let description = prop(node, "description");
1361            if !description.is_empty() {
1362                text.push(' ');
1363                text.push_str(&description);
1364            }
1365            let url = prop(node, "url");
1366            if !url.is_empty() && !url.starts_with("data:") {
1367                text.push(' ');
1368                text.push_str(&url);
1369            }
1370            out.push(text);
1371        }
1372        "Icon" => out.push(format!("[{}]", prop(node, "name"))),
1373        other => {
1374            let name = if other.is_empty() { "?" } else { other };
1375            out.push(format!(
1376                "(a {} is not shown as text)",
1377                crate::escape::show_controls(name)
1378            ));
1379        }
1380    }
1381    for message in node.validation_errors() {
1382        out.push(format!("  ! {}", crate::escape::show_controls(&message)));
1383    }
1384    for error in &node.errors {
1385        out.push(format!("! {}", crate::escape::show_controls(error)));
1386    }
1387}
1388
1389#[cfg(test)]
1390mod tests {
1391    use super::*;
1392
1393    use crate::tools::SandboxPolicy;
1394    use serde_json::json;
1395
1396    struct Jail(std::path::PathBuf, SandboxPolicy);
1397
1398    fn jail(name: &str) -> Jail {
1399        let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
1400        let _ = std::fs::remove_dir_all(&root);
1401        std::fs::create_dir_all(root.join("img")).unwrap();
1402        std::fs::write(root.join("img/cat.png"), b"png").unwrap();
1403        let policy = SandboxPolicy::new(&root).unwrap();
1404        Jail(root, policy)
1405    }
1406
1407    impl Drop for Jail {
1408        fn drop(&mut self) {
1409            let _ = std::fs::remove_dir_all(&self.0);
1410        }
1411    }
1412
1413    fn with_components(components: Value) -> Vec<Value> {
1414        vec![json!({"version": "1.0", "createSurface": {
1415            "surfaceId": "s", "catalogId": "c", "components": components
1416        }})]
1417    }
1418
1419    fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
1420        policy(messages, &jail.1, remote)
1421            .into_iter()
1422            .map(|r| format!("{} {}", r.path, r.message))
1423            .collect()
1424    }
1425
1426    #[test]
1427    fn a_password_field_is_refused_with_request_secret_named() {
1428        let jail = jail("obscured");
1429        let got = refused(
1430            &with_components(json!([
1431                {"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
1432                {"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
1433            ])),
1434            &jail,
1435            false,
1436        );
1437        assert_eq!(got.len(), 1, "{got:?}");
1438        assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
1439        assert!(got[0].contains("request_secret"));
1440    }
1441
1442    #[test]
1443    fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
1444        let jail = jail("media");
1445        let image =
1446            |url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
1447        let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
1448        assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
1449        assert!(ok(json!("img/cat.png"), false));
1450        assert!(!ok(json!("img/dog.png"), false), "missing file");
1451        assert!(!ok(json!("../outside.png"), false), "outside the jail");
1452        assert!(!ok(json!("https://example.com/cat.png"), false));
1453        assert!(ok(json!("https://example.com/cat.png"), true));
1454        assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
1455        assert!(!ok(json!("file:///etc/passwd"), true));
1456        let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
1457        assert!(bound[0].contains("must be a literal string"), "{bound:?}");
1458        // A Video's poster is held to the same rule.
1459        let video = with_components(json!([{"id": "root", "component": "Video",
1460            "url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
1461        let got = refused(&video, &jail, false);
1462        assert_eq!(got.len(), 1);
1463        assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
1464    }
1465
1466    #[test]
1467    fn open_url_takes_only_http_and_https_literals() {
1468        let jail = jail("open");
1469        let button = |url: Value| {
1470            with_components(json!([
1471                {"id": "root", "component": "Button", "child": "t",
1472                 "action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
1473                {"id": "t", "component": "Text", "text": "Go"}
1474            ]))
1475        };
1476        assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
1477        assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
1478        // A dynamic URL is the renderer's to check, after showing it.
1479        assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
1480        let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
1481        assert_eq!(
1482            got,
1483            ["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
1484        );
1485    }
1486
1487    #[test]
1488    fn renderer_and_agent_functions_are_refused() {
1489        let jail = jail("functions");
1490        let got = refused(
1491            &[
1492                json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
1493                json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
1494            ],
1495            &jail,
1496            false,
1497        );
1498        assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
1499        assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
1500    }
1501
1502    #[test]
1503    fn a_drive_letter_is_not_a_scheme() {
1504        assert_eq!(scheme("C:\\img\\cat.png"), None);
1505        assert_eq!(scheme("HTTPS://x"), Some("https".into()));
1506        assert_eq!(scheme("img/cat.png"), None);
1507    }
1508
1509    #[test]
1510    fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
1511        let vault = crate::vault::SecretVault::default();
1512        vault.set("API_TOKEN", "tok-abcdef-123456".into());
1513        let message =
1514            json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
1515        let kept = sanitize(&message, &vault, EgressMode::Warn);
1516        assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
1517        assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
1518        assert_eq!(kept["n"], 3);
1519        let redacted = sanitize(&message, &vault, EgressMode::Redact);
1520        assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
1521        assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
1522    }
1523
1524    #[test]
1525    fn the_basic_catalog_reference_names_components_and_functions() {
1526        let reference = reference(Catalog::basic());
1527        assert!(
1528            reference.contains(
1529                "- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
1530            ),
1531            "{reference}"
1532        );
1533        assert!(reference.contains("- TextField {"), "{reference}");
1534        assert!(
1535            reference.contains("- formatString(value: DynamicString) -> string"),
1536            "{reference}"
1537        );
1538        assert!(!reference.contains("component:"), "{reference}");
1539    }
1540
1541    #[test]
1542    fn the_prompt_section_carries_the_catalog_instructions() {
1543        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1544        let section = session.prompt_section();
1545        assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
1546        assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
1547        assert!(section.contains("## Catalog Guidelines"));
1548        assert!(section.contains("[ui action] submit on <surfaceId>"));
1549    }
1550
1551    #[test]
1552    fn fields_beside_the_kind_are_moved_inside_it() {
1553        let (tidied, moved) = tidy(&serde_json::json!({
1554            "version": "1.0",
1555            "createSurface": {"catalogId": "c", "components": []},
1556            "surfaceId": "plan"
1557        }));
1558        assert_eq!(
1559            tidied,
1560            serde_json::json!({"version": "1.0",
1561                "createSurface": {"catalogId": "c", "components": [], "surfaceId": "plan"}})
1562        );
1563        assert_eq!(moved, ["surfaceId into createSurface"]);
1564
1565        // Never over a field the body has, and never with no kind or two kinds.
1566        for message in [
1567            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}, "surfaceId": "b"}),
1568            serde_json::json!({"version": "1.0", "surfaceId": "b"}),
1569            serde_json::json!({"version": "1.0", "deleteSurface": {}, "updateDataModel": {}, "x": 1}),
1570            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}}),
1571        ] {
1572            assert_eq!(tidy(&message), (message.clone(), Vec::new()), "{message}");
1573        }
1574    }
1575
1576    #[test]
1577    fn the_prompt_s_example_is_valid() {
1578        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1579        let call: Value =
1580            serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, true)).unwrap();
1581        let messages = call["messages"].as_array().unwrap();
1582        let report = session.apply(messages);
1583        assert!(report.is_ok(), "{:?}", report.errors);
1584        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1585        let section = session.prompt_section();
1586        assert!(section.contains("surfaceId` goes inside createSurface"));
1587        assert!(
1588            !section.contains("\"wait\":true"),
1589            "no waiter, no wait in the example"
1590        );
1591    }
1592
1593    #[test]
1594    fn a_waiter_set_later_offers_wait_from_then_on() {
1595        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1596        let request = UiWait {
1597            surface_ids: vec!["s".into()],
1598        };
1599        assert!(!session.can_wait());
1600        assert!(!session.prompt_section().contains("\"wait\": true"));
1601        assert_eq!(session.wait(&request), None);
1602
1603        session.set_waiter(Some(std::sync::Arc::new(|wait: &UiWait| {
1604            Some(Action::new(
1605                "ok",
1606                wait.surface_ids[0].clone(),
1607                "root",
1608                "2026-11-22T00:00:00Z",
1609                Map::new(),
1610            ))
1611        })));
1612        assert!(session.can_wait());
1613        assert!(session.prompt_section().contains("\"wait\": true"));
1614        assert_eq!(session.wait(&request).map(|a| a.name), Some("ok".into()));
1615
1616        session.set_waiter(None);
1617        assert!(!session.can_wait());
1618    }
1619
1620    #[test]
1621    fn orphans_are_warnings_and_dangling_references_errors() {
1622        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1623        let create = |components: Value| {
1624            serde_json::json!({"version": "1.0", "createSurface": {
1625                "surfaceId": "s",
1626                "catalogId": agent86_ui::BASIC_CATALOG_ID,
1627                "components": components,
1628            }})
1629        };
1630        let report = session.apply(&[create(serde_json::json!([
1631            {"id": "root", "component": "Column", "children": ["missing"]}
1632        ]))]);
1633        assert!(report.errors[0].message.starts_with("Dangling reference"));
1634        let report = session.apply(&[create(serde_json::json!([
1635            {"id": "root", "component": "Text", "text": "hi"},
1636            {"id": "spare", "component": "Text", "text": "nobody shows me"}
1637        ]))]);
1638        assert!(report.is_ok(), "{:?}", report.errors);
1639        assert!(report.warnings[0].message.contains("not reachable"));
1640        assert_eq!(session.surface_ids(), ["s"]);
1641    }
1642
1643    fn create_with(components: Value, data_model: Option<Value>) -> Value {
1644        let mut body = json!({
1645            "surfaceId": "s",
1646            "catalogId": agent86_ui::BASIC_CATALOG_ID,
1647            "components": components,
1648        });
1649        if let Some(model) = data_model {
1650            body["dataModel"] = model;
1651        }
1652        json!({"version": "1.0", "createSurface": body})
1653    }
1654
1655    fn submit_button() -> Value {
1656        json!({"id": "go", "component": "Button", "child": "go_label",
1657               "action": {"event": {"name": "submit"}}})
1658    }
1659
1660    #[test]
1661    fn a_button_without_context_sends_every_top_level_value() {
1662        // The data model's keys, then the first segment of every absolute path
1663        // the components bind (here one with no data model entry yet).
1664        let message = create_with(
1665            json!([
1666                {"id": "root", "component": "Column", "children": ["plan", "note", "go"]},
1667                {"id": "plan", "component": "ChoicePicker", "value": {"@path": "/plan"},
1668                 "options": [{"label": "A", "value": "a"}]},
1669                {"id": "note", "component": "TextField", "label": "Note",
1670                 "value": {"@path": "/extra/note"}},
1671                submit_button(),
1672            ]),
1673            Some(json!({"plan": [], "size": 1})),
1674        );
1675        let (messages, notes) = complete(&[message], |_| Vec::new());
1676        assert!(notes.is_empty(), "{notes:?}");
1677        assert_eq!(
1678            messages[0].pointer("/createSurface/components/3/action/event/context"),
1679            Some(&json!({
1680                "plan": {"@path": "/plan"},
1681                "size": {"@path": "/size"},
1682                "extra": {"@path": "/extra"}
1683            }))
1684        );
1685    }
1686
1687    #[test]
1688    fn a_context_the_model_gave_is_kept() {
1689        let mut button = submit_button();
1690        button["action"]["event"]["context"] = json!({"choice": "pro"});
1691        let message = create_with(
1692            json!([{"id": "root", "component": "Column", "children": ["go"]}, button]),
1693            Some(json!({"plan": []})),
1694        );
1695        let (messages, _) = complete(&[message], |_| Vec::new());
1696        assert_eq!(
1697            messages[0].pointer("/createSurface/components/1/action/event/context"),
1698            Some(&json!({"choice": "pro"}))
1699        );
1700    }
1701
1702    #[test]
1703    fn a_button_added_later_sends_the_values_of_the_surface_already_up() {
1704        let update = json!({"version": "1.0", "updateComponents": {
1705            "surfaceId": "s",
1706            "components": [submit_button()],
1707        }});
1708        let (messages, _) = complete(&[update], |id| {
1709            assert_eq!(id, "s");
1710            vec!["name".to_owned(), "a/b".to_owned()]
1711        });
1712        assert_eq!(
1713            messages[0].pointer("/updateComponents/components/0/action/event/context"),
1714            Some(&json!({"name": {"@path": "/name"}, "a/b": {"@path": "/a~1b"}}))
1715        );
1716    }
1717
1718    #[test]
1719    fn a_lone_path_is_read_as_a_binding_and_noted() {
1720        let mut button = submit_button();
1721        button["action"]["event"]["context"] = json!({"plan": {"path": "/plan"}});
1722        let message = create_with(
1723            json!([
1724                {"id": "root", "component": "Column",
1725                 "children": {"path": "/items", "componentId": "row"}},
1726                {"id": "row", "component": "Text", "text": {"path": "/label"}},
1727                button,
1728            ]),
1729            Some(json!({"items": []})),
1730        );
1731        let (messages, notes) = complete(&[message], |_| Vec::new());
1732        let components = &messages[0]["createSurface"]["components"];
1733        // A template keeps its `path`, which has a componentId beside it.
1734        assert_eq!(
1735            components[0]["children"],
1736            json!({"path": "/items", "componentId": "row"})
1737        );
1738        assert_eq!(components[1]["text"], json!({"@path": "/label"}));
1739        assert_eq!(
1740            components[2]["action"]["event"]["context"],
1741            json!({"plan": {"@path": "/plan"}})
1742        );
1743        assert_eq!(
1744            notes,
1745            [
1746                "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/1 (row); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
1747                "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/2 (go); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
1748            ]
1749        );
1750    }
1751
1752    #[test]
1753    fn the_completed_example_validates_and_its_button_sends_the_choice() {
1754        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1755        let call: Value =
1756            serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, false)).unwrap();
1757        let messages = call["messages"].as_array().unwrap().clone();
1758        let (messages, _) = complete(&messages, |id| session.surface_keys(id));
1759        assert!(session.apply(&messages).is_ok());
1760        let submit = messages[0]["createSurface"]["components"]
1761            .as_array()
1762            .unwrap()
1763            .iter()
1764            .find(|component| component["id"] == "submit")
1765            .unwrap();
1766        assert_eq!(
1767            submit["action"]["event"]["context"],
1768            json!({"plan": {"@path": "/plan"}})
1769        );
1770    }
1771
1772    #[test]
1773    fn a_surface_as_text_shows_each_component_as_the_user_reads_it() {
1774        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1775        let report = session.apply(&[serde_json::json!({"version": "1.0", "createSurface": {
1776            "surfaceId": "order",
1777            "catalogId": agent86_ui::BASIC_CATALOG_ID,
1778            "components": [
1779                {"id": "root", "component": "Column",
1780                 "children": ["title", "name", "note", "plan", "extras", "receipt", "seats",
1781                              "line", "logo", "tabs", "row"]},
1782                {"id": "title", "component": "Text", "text": "Your order\u{1b}[31m"},
1783                {"id": "name", "component": "TextField", "label": "Name", "value": {"@path": "/name"}},
1784                {"id": "note", "component": "TextField", "label": "Note", "value": {"@path": "/note"}},
1785                {"id": "plan", "component": "ChoicePicker", "label": "Plan",
1786                 "options": [{"label": "Free", "value": "free"}, {"label": "Pro", "value": "pro"}],
1787                 "value": {"@path": "/plan"}},
1788                {"id": "extras", "component": "ChoicePicker", "variant": "multipleSelection",
1789                 "options": [{"label": "Gift wrap", "value": "wrap"}, {"label": "Card", "value": "card"}],
1790                 "value": {"@path": "/extras"}},
1791                {"id": "receipt", "component": "CheckBox", "label": "Email me the receipt",
1792                 "value": {"@path": "/receipt"}},
1793                {"id": "seats", "component": "Slider", "label": "Seats", "min": 1, "max": 10,
1794                 "value": {"@path": "/seats"}},
1795                {"id": "line", "component": "Divider"},
1796                {"id": "logo", "component": "Image", "description": "Our logo",
1797                 "url": "https://example.com/logo.png"},
1798                {"id": "tabs", "component": "Tabs", "tabs": [{"title": "One", "child": "one"}]},
1799                {"id": "one", "component": "Text", "text": "inside a tab"},
1800                {"id": "row", "component": "Row", "children": ["ok", "cancel"]},
1801                {"id": "ok", "component": "Button", "child": "ok_label",
1802                 "action": {"event": {"name": "submit"}}},
1803                {"id": "ok_label", "component": "Text", "text": "OK"},
1804                {"id": "cancel", "component": "Button", "child": "cancel_label",
1805                 "action": {"event": {"name": "cancel"}}},
1806                {"id": "cancel_label", "component": "Text", "text": "Cancel"}
1807            ],
1808            "dataModel": {"name": "Ada", "note": "", "plan": ["pro"], "extras": ["wrap", "card"],
1809                          "receipt": true, "seats": 3}
1810        }})]);
1811        assert!(report.is_ok(), "{:?}", report.errors);
1812        assert_eq!(
1813            session.surface_texts(),
1814            [concat!(
1815                "[agent86UI surface \"order\": this client cannot draw it, so it is shown as ",
1816                "text; answer in your reply]\n",
1817                // The escape is shown, never sent through.
1818                "Your order\u{241b}[31m\n",
1819                "Name: Ada\n",
1820                "Note: (empty)\n",
1821                "Plan: a) Free  b) Pro (chosen)\n",
1822                "a) Gift wrap (chosen)  b) Card (chosen)\n",
1823                "[x] Email me the receipt\n",
1824                "Seats: 3 (1 to 10)\n",
1825                "---\n",
1826                "[image] Our logo https://example.com/logo.png\n",
1827                "(a Tabs is not shown as text)\n",
1828                "[OK]\n",
1829                "[Cancel]"
1830            )]
1831        );
1832    }
1833}