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.
64    waiter: Option<UiWaiter>,
65}
66
67impl std::fmt::Debug for UiSession {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.debug_struct("UiSession")
70            .field(
71                "catalogs",
72                &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
73            )
74            .finish_non_exhaustive()
75    }
76}
77
78impl UiSession {
79    /// A renderer that supports `catalogs`, in order of preference.
80    pub fn new(catalogs: Vec<Catalog>) -> Result<Self, CompileError> {
81        let mut runtime = Runtime::new(catalogs.clone())?;
82        runtime.set_rules(RULES);
83        Ok(Self {
84            catalogs,
85            runtime: Mutex::new(runtime),
86            egress: EgressMode::Off,
87            remote_media: false,
88            waiter: None,
89        })
90    }
91
92    /// Redact what surfaces show as the egress guardrail in `mode` redacts the
93    /// model's text.
94    pub fn with_egress(mut self, mode: EgressMode) -> Self {
95        self.egress = mode;
96        self
97    }
98
99    /// Let media load from `https` URLs too (ADR 0005: off by default, since a
100    /// fetch can track the user or carry data out in its URL).
101    pub fn with_remote_media(mut self, allow: bool) -> Self {
102        self.remote_media = allow;
103        self
104    }
105
106    /// Let a call wait for the user's answer, asking `waiter`.
107    pub fn with_waiter(mut self, waiter: Option<UiWaiter>) -> Self {
108        self.waiter = waiter;
109        self
110    }
111
112    /// Whether a call may wait: someone answers.
113    pub fn can_wait(&self) -> bool {
114        self.waiter.is_some()
115    }
116
117    /// Ask the program for the user's answer (`None`: dismissed, or nobody
118    /// answers).
119    pub fn wait(&self, request: &UiWait) -> Option<Action> {
120        self.waiter.as_ref().and_then(|waiter| waiter(request))
121    }
122
123    /// Whether `action` could have come from a surface up now: its surface
124    /// exists (and is one of `among`, when given) and holds the component it
125    /// names. What it carries is the user's and is checked as their input is.
126    pub fn check_action(&self, action: &Action, among: Option<&[String]>) -> Result<(), String> {
127        if action.name.is_empty() {
128            return Err("the action has no name".into());
129        }
130        if among.is_some_and(|ids| !ids.contains(&action.surface_id)) {
131            return Err(format!(
132                "the action is for surface {:?}, which this call did not draw",
133                action.surface_id
134            ));
135        }
136        let runtime = self.runtime();
137        let Some(mut components) = runtime.components(&action.surface_id) else {
138            return Err(format!("there is no surface {:?}", action.surface_id));
139        };
140        if !components
141            .any(|c| c.get("id").and_then(Value::as_str) == Some(&action.source_component_id))
142        {
143            return Err(format!(
144                "surface {:?} has no component {:?}",
145                action.surface_id, action.source_component_id
146            ));
147        }
148        Ok(())
149    }
150
151    pub fn egress(&self) -> EgressMode {
152        self.egress
153    }
154
155    pub fn remote_media(&self) -> bool {
156        self.remote_media
157    }
158
159    pub fn catalogs(&self) -> &[Catalog] {
160        &self.catalogs
161    }
162
163    fn runtime(&self) -> std::sync::MutexGuard<'_, Runtime> {
164        self.runtime.lock().unwrap_or_else(PoisonError::into_inner)
165    }
166
167    /// Validate a batch and, when it has no errors, apply it to the surfaces.
168    pub fn apply(&self, messages: &[Value]) -> Report {
169        self.runtime().apply(messages)
170    }
171
172    /// Every surface up now as the one `createSurface` that draws it as it is,
173    /// for a program that reopens a session (or draws late) to bring its screen
174    /// up to date.
175    pub fn snapshot(&self) -> Vec<AgentMessage> {
176        self.runtime()
177            .snapshot()
178            .into_iter()
179            .filter_map(|message| serde_json::from_value(message).ok())
180            .collect()
181    }
182
183    /// Rebuild the surfaces from a session's history (ADR 0005: resume replays,
184    /// nothing is stored): every `render_ui` call that drew, in order, through
185    /// the same redaction, policy, and validation as when it ran. A call that
186    /// drew is one whose result is ok or opens with what the tool writes when it
187    /// draws (a waiting call the user dismissed reports a failure, yet drew).
188    /// Steps keep calls the history's compaction summarized away. Returns how
189    /// many calls were replayed.
190    pub fn replay(
191        &self,
192        state: &crate::session::AgentState,
193        ctx: &crate::tools::ToolContext,
194    ) -> usize {
195        let mut runtime = match Runtime::new(self.catalogs.clone()) {
196            Ok(runtime) => runtime,
197            Err(_) => return 0,
198        };
199        runtime.set_rules(RULES);
200        let mut replayed = 0;
201        for step in &state.steps {
202            for call in step.tool_calls.iter().filter(|call| call.name == RENDER_UI) {
203                let drew = step
204                    .results
205                    .iter()
206                    .find(|result| result.call_id == call.id)
207                    .is_some_and(drew);
208                if !drew {
209                    continue;
210                }
211                // The history keeps the call as the model sent it, before the
212                // registry repaired an array sent as a JSON string.
213                let messages = match call.arguments.get("messages") {
214                    Some(Value::Array(messages)) => messages.clone(),
215                    Some(Value::String(text)) => match serde_json::from_str(text) {
216                        Ok(Value::Array(messages)) => messages,
217                        _ => continue,
218                    },
219                    _ => continue,
220                };
221                let messages: Vec<Value> = messages
222                    .iter()
223                    .map(|message| sanitize(message, &ctx.secrets, self.egress))
224                    .collect();
225                if !policy(&messages, &ctx.policy, self.remote_media).is_empty() {
226                    continue;
227                }
228                if runtime.apply(&messages).is_ok() {
229                    replayed += 1;
230                }
231            }
232        }
233        *self.runtime() = runtime;
234        replayed
235    }
236
237    /// The ids of the surfaces up now.
238    pub fn surface_ids(&self) -> Vec<String> {
239        self.runtime().surface_ids().map(String::from).collect()
240    }
241
242    /// The system-prompt section: how to use `render_ui`, then each catalog's
243    /// own instructions and a compact reference to its components and
244    /// functions. Rebuilt per request, like the MCP section.
245    pub fn prompt_section(&self) -> String {
246        let mut section = String::from(PROMPT);
247        let media = if self.remote_media {
248            "a data: URL, an https URL, or the path of a file in the workspace"
249        } else {
250            "a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
251        };
252        if self.can_wait() {
253            section.push_str(
254                "\n- With `\"wait\": true` the call waits for the user's first action on \
255                 the surface and returns it as its result (`[ui action] ...`). Use it for a \
256                 form you need answered before you can go on; otherwise leave it out and \
257                 carry on.",
258            );
259        }
260        section.push_str(&format!(
261            "\n- Never ask for a password, key, or token in a surface (no TextField with \
262             variant \"obscured\"): call request_secret, which asks through a masked prompt \
263             and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
264             Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
265             http and https URLs."
266        ));
267        for catalog in &self.catalogs {
268            section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
269            if let Some(instructions) = catalog.instructions() {
270                section.push('\n');
271                section.push_str(instructions.trim());
272                section.push('\n');
273            }
274            section.push_str(&reference(catalog));
275        }
276        section
277    }
278}
279
280/// What every `render_ui` prompt says, whatever the catalogs.
281const PROMPT: &str = "## agent86UI: drawing UI with render_ui
282
283You can show the user interactive UI (forms, choices, confirmations, small \
284dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
285them with its own widgets. Use it when you need a structured answer (pick one of \
286several options, fill in a few fields, confirm a plan) or when a layout says more \
287than prose. Otherwise answer in plain text.
288
289- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
290exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
291`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
292`catalogId` from below, and usually its `components` and `dataModel` inline), \
293change it later with updateComponents (a component replaces the one with the same \
294id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
295- Components are a flat list linked by id, and exactly one has the id \"root\". \
296Every child id must be defined in the same call or an earlier one.
297- A value is a literal, a binding to the surface's data model (`{\"@path\": \
298\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
299{...}}`). Input components write what the user enters back to the path they are \
300bound to. A `ChildList` is an array of ids, or a template over a list in the data \
301model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
302relative to each item.
303- A button's action is `{\"event\": {\"name\": \"submit\", \"context\": {\"name\": \
304{\"@path\": \"/form/name\"}}}}`: `context` goes inside `event`, beside `name`, never \
305beside `event`. When the user presses it, a later user message \
306reads `[ui action] submit on <surfaceId>: <context as JSON>`; the surface stays \
307up meanwhile.
308- render_ui's result is the validator's verdict. If it lists problems, nothing \
309was drawn: fix them and send the corrected messages again.
310- Renderer functions (`callRendererFunction`) and agent functions are not \
311available.";
312
313/// A compact reference to a catalog's components and functions, from their
314/// schemas: each component's properties (`?` marks an optional one) with their
315/// types, and each function's arguments and return type.
316pub fn reference(catalog: &Catalog) -> String {
317    let document = catalog.document();
318    let mut out = String::from("\nComponents:\n");
319    for (name, schema) in document
320        .get("components")
321        .and_then(Value::as_object)
322        .into_iter()
323        .flatten()
324    {
325        let (properties, required, checkable) = gather(schema);
326        let fields: Vec<String> = properties
327            .iter()
328            .filter(|(key, _)| *key != "component" && *key != "id")
329            .map(|(key, property)| {
330                let optional = if required.iter().any(|r| r == key) {
331                    ""
332                } else {
333                    "?"
334                };
335                format!("{key}{optional}: {}", type_of(property, document))
336            })
337            .collect();
338        let checks = if checkable { " (accepts @checks)" } else { "" };
339        out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
340    }
341    let functions: Vec<String> = document
342        .get("functions")
343        .and_then(Value::as_object)
344        .into_iter()
345        .flatten()
346        .filter(|(name, _)| {
347            catalog
348                .function(name)
349                .is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
350        })
351        .map(|(name, schema)| {
352            let args = schema.pointer("/properties/args");
353            let required: Vec<&str> = args
354                .and_then(|a| a.get("required"))
355                .and_then(Value::as_array)
356                .into_iter()
357                .flatten()
358                .filter_map(Value::as_str)
359                .collect();
360            let params: Vec<String> = args
361                .and_then(|a| a.get("properties"))
362                .and_then(Value::as_object)
363                .into_iter()
364                .flatten()
365                .map(|(key, property)| {
366                    let optional = if required.contains(&key.as_str()) {
367                        ""
368                    } else {
369                        "?"
370                    };
371                    format!("{key}{optional}: {}", type_of(property, document))
372                })
373                .collect();
374            let returns = schema
375                .get("returnType")
376                .and_then(Value::as_str)
377                .unwrap_or("any");
378            format!("- {name}({}) -> {returns}\n", params.join(", "))
379        })
380        .collect();
381    if !functions.is_empty() {
382        out.push_str("\nFunctions:\n");
383        out.extend(functions);
384    }
385    out
386}
387
388/// A component schema's properties and required names, from its own
389/// `properties` and its `allOf` parts, and whether it takes `@checks`.
390fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
391    let mut properties = Map::new();
392    let mut required = Vec::new();
393    let mut checkable = false;
394    let mut parts = vec![schema];
395    if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
396        parts.extend(all);
397    }
398    for part in parts {
399        if part
400            .get("$ref")
401            .and_then(Value::as_str)
402            .is_some_and(|r| r.ends_with("/Checkable"))
403        {
404            checkable = true;
405        }
406        if let Some(own) = part.get("properties").and_then(Value::as_object) {
407            for (key, value) in own {
408                properties.insert(key.clone(), value.clone());
409            }
410        }
411        required.extend(
412            part.get("required")
413                .and_then(Value::as_array)
414                .into_iter()
415                .flatten()
416                .filter_map(Value::as_str)
417                .map(String::from),
418        );
419    }
420    (properties, required, checkable)
421}
422
423/// A property's type, briefly: a common type by name, a catalog's own
424/// definition by what it is (its `Weight` is a number, not a name to guess
425/// at), an enum's values, or the JSON type.
426fn type_of(property: &Value, document: &Value) -> String {
427    if let Some(target) = property.get("$ref").and_then(Value::as_str) {
428        if let Some(local) = target.strip_prefix("#/$defs/") {
429            if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
430                if def.get("$ref").is_none() {
431                    return type_of(def, document);
432                }
433            }
434        }
435        return target.rsplit('/').next().unwrap_or(target).to_string();
436    }
437    if let Some(values) = property.get("enum").and_then(Value::as_array) {
438        return values
439            .iter()
440            .map(|v| v.to_string())
441            .collect::<Vec<_>>()
442            .join("|");
443    }
444    match property.get("type").and_then(Value::as_str) {
445        Some("array") => match property.get("items") {
446            Some(items) => format!("array of {}", type_of(items, document)),
447            None => "array".into(),
448        },
449        Some(kind) => kind.to_string(),
450        None => "any".into(),
451    }
452}
453
454/// What a `render_ui` result carries for the loop, taken out of its metadata,
455/// so it is emitted and recorded as agent86UI's own and never kept in the
456/// session: the validated messages, and the `ui_render` trace fields.
457pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
458    let messages = match metadata.remove(MESSAGES_KEY) {
459        Some(Value::Array(items)) => items
460            .into_iter()
461            .filter_map(|item| serde_json::from_value(item).ok())
462            .collect(),
463        _ => Vec::new(),
464    };
465    (messages, metadata.remove(TRACE_KEY))
466}
467
468/// What `render_ui`'s result opens with when the call drew.
469const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];
470
471/// Whether a `render_ui` result says the call drew.
472fn drew(result: &crate::types::ToolResult) -> bool {
473    let text = if result.ok {
474        result.content.as_str()
475    } else {
476        result.error.as_deref().unwrap_or_default()
477    };
478    result.ok || DREW.iter().any(|opening| text.starts_with(opening))
479}
480
481/// The surfaces a waiting call waits on, taken out of its result's metadata.
482pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
483    match metadata.remove(WAIT_KEY)? {
484        Value::Array(ids) => Some(
485            ids.into_iter()
486                .filter_map(|id| id.as_str().map(String::from))
487                .collect(),
488        ),
489        _ => None,
490    }
491}
492
493/// An action as the model reads it, a waiting call's result or the next user
494/// message: `[ui action] <name> on <surfaceId>: <context as JSON>`, then the
495/// event's `userMessage` on a line of its own when it has one.
496pub fn action_text(action: &Action) -> String {
497    let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
498    let mut text = format!(
499        "[ui action] {} on {}: {context}",
500        action.name, action.surface_id
501    );
502    if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
503        text.push('\n');
504        text.push_str(message);
505    }
506    text
507}
508
509impl crate::agent::Harness {
510    /// Wait for the user's answer to a `wait: true` call, through the prompt
511    /// queue like a secret prompt (one question at a time, declined once the
512    /// turn is cancelled), and make it the call's result. The answer goes
513    /// through the vault and the ingress guardrail, as typed input does, and is
514    /// recorded as `ui_action`, without its values.
515    pub(crate) fn ui_wait(
516        &self,
517        call: &crate::types::ToolCall,
518        drawn: crate::types::ToolResult,
519        surfaces: Vec<String>,
520        sid: &str,
521    ) -> crate::types::ToolResult {
522        use crate::tools::{failure, success};
523        let Some(ui) = self.context.ui.as_deref() else {
524            return drawn;
525        };
526        if surfaces.is_empty() {
527            return drawn;
528        }
529        let request = UiWait {
530            surface_ids: surfaces.clone(),
531        };
532        let question = crate::approval::Question {
533            tool: Some(RENDER_UI.into()),
534            call: Some(call.id.clone()),
535            ..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
536        };
537        let shown = drawn.content.clone();
538        let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
539            call_id: drawn.call_id.clone(),
540            ..result
541        };
542        let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
543            None => {
544                return answered(failure(
545                    RENDER_UI,
546                    format!(
547                        "{shown}\nThe turn was cancelled before the user answered. The surface \
548                         stays up; an action on it later comes as a user message."
549                    ),
550                ))
551            }
552            Some(None) => {
553                return answered(failure(
554                    RENDER_UI,
555                    format!(
556                        "{shown}\nThe user did not answer (they dismissed it). The surface stays \
557                         up; an action on it later comes as a user message."
558                    ),
559                ))
560            }
561            Some(Some(action)) => action,
562        };
563        if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
564            return answered(failure(
565                RENDER_UI,
566                format!("{shown}\nThe screen's answer could not be used: {why}."),
567            ));
568        }
569        let text = self.context.secrets.redact(&action_text(&action));
570        let report = self.guardrails.inspect_ingress(&text);
571        if report.flagged() {
572            self.recorder.event(
573                sid,
574                "guardrail",
575                vec![
576                    ("stage", serde_json::json!("ingress")),
577                    ("source", serde_json::json!("ui_action")),
578                    ("findings", serde_json::json!(report.summary())),
579                ],
580            );
581        }
582        self.recorder.event(
583            sid,
584            "ui_action",
585            vec![
586                ("surface", serde_json::json!(action.surface_id)),
587                ("name", serde_json::json!(action.name)),
588                ("component", serde_json::json!(action.source_component_id)),
589                ("waited", serde_json::json!(true)),
590            ],
591        );
592        if self.guardrails.should_block(&report) {
593            return answered(failure(
594                RENDER_UI,
595                format!(
596                    "{shown}\nThe user's answer was refused by the input guardrail ({}).",
597                    report.summary()
598                ),
599            ));
600        }
601        answered(success(RENDER_UI, format!("{shown}\n{text}")))
602    }
603}
604
605/// Every string in `value`, through the secret vault's redaction and, with the
606/// egress guardrail in `redact` mode, its redaction too: what a surface shows
607/// reaches the user as the model's text does. Object keys are left alone.
608pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
609    match value {
610        Value::String(text) => {
611            let text = vault.redact(text);
612            Value::String(if egress == EgressMode::Redact {
613                crate::guardrails::redact(&text).0
614            } else {
615                text
616            })
617        }
618        Value::Array(items) => Value::Array(
619            items
620                .iter()
621                .map(|item| sanitize(item, vault, egress))
622                .collect(),
623        ),
624        Value::Object(map) => Value::Object(
625            map.iter()
626                .map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
627                .collect(),
628        ),
629        other => other.clone(),
630    }
631}
632
633/// Something agent86's policy refuses in a batch (ADR 0005), where the
634/// protocol would allow it: a JSON Pointer into the batch and why.
635#[derive(Debug, Clone, PartialEq, Eq)]
636pub struct Refusal {
637    pub path: String,
638    pub message: String,
639}
640
641impl std::fmt::Display for Refusal {
642    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
643        write!(f, "REFUSED at {}: {}", self.path, self.message)
644    }
645}
646
647/// The media components of the basic catalog and the properties that load a
648/// URL. A custom catalog's component of the same name is held to the same rule.
649const MEDIA: &[(&str, &[&str])] = &[
650    ("Image", &["url"]),
651    ("Video", &["url", "posterUrl"]),
652    ("AudioPlayer", &["url"]),
653];
654
655/// What agent86 refuses in a batch the protocol allows (ADR 0005):
656/// - a `TextField` with `"variant": "obscured"`: secrets are never collected
657///   through a surface, so the value never reaches the model;
658/// - media from anywhere but a `data:` URL or a file in the workspace (or an
659///   `https` URL, with `remote_media`), and from a binding or a call, whose
660///   value is not known until the renderer resolves it;
661/// - `openUrl` with a literal URL that is not `http` or `https` (a dynamic one
662///   is the renderer's to check before it opens it, after showing it);
663/// - `callRendererFunction` and agent functions, left out of the first version.
664pub fn policy(
665    messages: &[Value],
666    jail: &crate::tools::SandboxPolicy,
667    remote_media: bool,
668) -> Vec<Refusal> {
669    let mut refusals = Vec::new();
670    let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
671    for (index, message) in messages.iter().enumerate() {
672        if message.get("callRendererFunction").is_some() {
673            refuse(
674                format!("/{index}/callRendererFunction"),
675                "renderer functions are not available here; draw with components and change \
676                 them with updateComponents and updateDataModel instead"
677                    .into(),
678            );
679        }
680        if message.get("agentFunctionResponse").is_some() {
681            refuse(
682                format!("/{index}/agentFunctionResponse"),
683                "agent functions are not available here".into(),
684            );
685        }
686        for kind in ["createSurface", "updateComponents"] {
687            let Some(components) = message
688                .get(kind)
689                .and_then(|body| body.get("components"))
690                .and_then(Value::as_array)
691            else {
692                continue;
693            };
694            for (number, component) in components.iter().enumerate() {
695                let at = format!("/{index}/{kind}/components/{number}");
696                let type_name = component.get("component").and_then(Value::as_str);
697                let id = component
698                    .get("id")
699                    .and_then(Value::as_str)
700                    .unwrap_or("this component");
701                if type_name == Some("TextField")
702                    && component.get("variant").and_then(Value::as_str) == Some("obscured")
703                {
704                    refuse(
705                        format!("{at}/variant"),
706                        format!(
707                            "TextField {id} is \"obscured\", a password field, but a surface never \
708                             collects secrets: call request_secret instead, which asks the user \
709                             through a masked prompt and never shows you the value"
710                        ),
711                    );
712                }
713                if let Some((_, properties)) =
714                    MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
715                {
716                    for property in *properties {
717                        let Some(value) = component.get(*property) else {
718                            continue;
719                        };
720                        let path = format!("{at}/{property}");
721                        match value.as_str() {
722                            Some(url) => {
723                                if let Some(why) = media_problem(url, jail, remote_media) {
724                                    refuse(path, format!("{id}'s {property} {why}"));
725                                }
726                            }
727                            None => refuse(
728                                path,
729                                format!(
730                                    "{id}'s {property} must be a literal string: what a surface \
731                                     loads is checked before it is drawn, so it cannot come from a \
732                                     binding or a function call"
733                                ),
734                            ),
735                        }
736                    }
737                }
738                open_urls(component, &at, &mut refuse);
739            }
740        }
741    }
742    refusals
743}
744
745/// Why a media URL may not load, or `None` when it may.
746fn media_problem(
747    url: &str,
748    jail: &crate::tools::SandboxPolicy,
749    remote_media: bool,
750) -> Option<String> {
751    match scheme(url) {
752        Some(scheme) if scheme == "data" => None,
753        Some(scheme) if scheme == "https" && remote_media => None,
754        Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
755            "{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
756             or carry data out in its URL): use a data: URL or a file in the workspace"
757        )),
758        Some(scheme) => Some(format!(
759            "{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
760             the workspace"
761        )),
762        None => match jail.resolve_within(url) {
763            Err(_) => Some(format!("{url:?} is outside the workspace")),
764            Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
765            Ok(_) => None,
766        },
767    }
768}
769
770/// A URL's scheme, lowercased, when it has one. A single letter before the
771/// colon is a Windows drive, not a scheme.
772fn scheme(url: &str) -> Option<String> {
773    let (scheme, _) = url.split_once(':')?;
774    let valid = scheme.len() > 1
775        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
776        && scheme
777            .chars()
778            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
779    valid.then(|| scheme.to_ascii_lowercase())
780}
781
782/// Refuse each `openUrl` call in `value` whose literal URL is not `http` or
783/// `https`.
784fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
785    match value {
786        Value::Object(map) => {
787            if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
788                if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
789                    let scheme = scheme(url);
790                    if !matches!(scheme.as_deref(), Some("http" | "https")) {
791                        refuse(
792                            format!("{at}/args/url"),
793                            format!("openUrl only opens http and https URLs, not {url:?}"),
794                        );
795                    }
796                }
797            }
798            for (key, item) in map {
799                let segment = key.replace('~', "~0").replace('/', "~1");
800                open_urls(item, &format!("{at}/{segment}"), refuse);
801            }
802        }
803        Value::Array(items) => {
804            for (index, item) in items.iter().enumerate() {
805                open_urls(item, &format!("{at}/{index}"), refuse);
806            }
807        }
808        _ => {}
809    }
810}
811
812#[cfg(test)]
813mod tests {
814    use super::*;
815
816    use crate::tools::SandboxPolicy;
817    use serde_json::json;
818
819    struct Jail(std::path::PathBuf, SandboxPolicy);
820
821    fn jail(name: &str) -> Jail {
822        let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
823        let _ = std::fs::remove_dir_all(&root);
824        std::fs::create_dir_all(root.join("img")).unwrap();
825        std::fs::write(root.join("img/cat.png"), b"png").unwrap();
826        let policy = SandboxPolicy::new(&root).unwrap();
827        Jail(root, policy)
828    }
829
830    impl Drop for Jail {
831        fn drop(&mut self) {
832            let _ = std::fs::remove_dir_all(&self.0);
833        }
834    }
835
836    fn with_components(components: Value) -> Vec<Value> {
837        vec![json!({"version": "1.0", "createSurface": {
838            "surfaceId": "s", "catalogId": "c", "components": components
839        }})]
840    }
841
842    fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
843        policy(messages, &jail.1, remote)
844            .into_iter()
845            .map(|r| format!("{} {}", r.path, r.message))
846            .collect()
847    }
848
849    #[test]
850    fn a_password_field_is_refused_with_request_secret_named() {
851        let jail = jail("obscured");
852        let got = refused(
853            &with_components(json!([
854                {"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
855                {"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
856            ])),
857            &jail,
858            false,
859        );
860        assert_eq!(got.len(), 1, "{got:?}");
861        assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
862        assert!(got[0].contains("request_secret"));
863    }
864
865    #[test]
866    fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
867        let jail = jail("media");
868        let image =
869            |url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
870        let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
871        assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
872        assert!(ok(json!("img/cat.png"), false));
873        assert!(!ok(json!("img/dog.png"), false), "missing file");
874        assert!(!ok(json!("../outside.png"), false), "outside the jail");
875        assert!(!ok(json!("https://example.com/cat.png"), false));
876        assert!(ok(json!("https://example.com/cat.png"), true));
877        assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
878        assert!(!ok(json!("file:///etc/passwd"), true));
879        let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
880        assert!(bound[0].contains("must be a literal string"), "{bound:?}");
881        // A Video's poster is held to the same rule.
882        let video = with_components(json!([{"id": "root", "component": "Video",
883            "url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
884        let got = refused(&video, &jail, false);
885        assert_eq!(got.len(), 1);
886        assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
887    }
888
889    #[test]
890    fn open_url_takes_only_http_and_https_literals() {
891        let jail = jail("open");
892        let button = |url: Value| {
893            with_components(json!([
894                {"id": "root", "component": "Button", "child": "t",
895                 "action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
896                {"id": "t", "component": "Text", "text": "Go"}
897            ]))
898        };
899        assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
900        assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
901        // A dynamic URL is the renderer's to check, after showing it.
902        assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
903        let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
904        assert_eq!(
905            got,
906            ["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
907        );
908    }
909
910    #[test]
911    fn renderer_and_agent_functions_are_refused() {
912        let jail = jail("functions");
913        let got = refused(
914            &[
915                json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
916                json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
917            ],
918            &jail,
919            false,
920        );
921        assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
922        assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
923    }
924
925    #[test]
926    fn a_drive_letter_is_not_a_scheme() {
927        assert_eq!(scheme("C:\\img\\cat.png"), None);
928        assert_eq!(scheme("HTTPS://x"), Some("https".into()));
929        assert_eq!(scheme("img/cat.png"), None);
930    }
931
932    #[test]
933    fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
934        let vault = crate::vault::SecretVault::default();
935        vault.set("API_TOKEN", "tok-abcdef-123456".into());
936        let message =
937            json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
938        let kept = sanitize(&message, &vault, EgressMode::Warn);
939        assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
940        assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
941        assert_eq!(kept["n"], 3);
942        let redacted = sanitize(&message, &vault, EgressMode::Redact);
943        assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
944        assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
945    }
946
947    #[test]
948    fn the_basic_catalog_reference_names_components_and_functions() {
949        let reference = reference(Catalog::basic());
950        assert!(
951            reference.contains(
952                "- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
953            ),
954            "{reference}"
955        );
956        assert!(reference.contains("- TextField {"), "{reference}");
957        assert!(
958            reference.contains("- formatString(value: DynamicString) -> string"),
959            "{reference}"
960        );
961        assert!(!reference.contains("component:"), "{reference}");
962    }
963
964    #[test]
965    fn the_prompt_section_carries_the_catalog_instructions() {
966        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
967        let section = session.prompt_section();
968        assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
969        assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
970        assert!(section.contains("## Catalog Guidelines"));
971        assert!(section.contains("[ui action] submit on <surfaceId>"));
972    }
973
974    #[test]
975    fn orphans_are_warnings_and_dangling_references_errors() {
976        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
977        let create = |components: Value| {
978            serde_json::json!({"version": "1.0", "createSurface": {
979                "surfaceId": "s",
980                "catalogId": agent86_ui::BASIC_CATALOG_ID,
981                "components": components,
982            }})
983        };
984        let report = session.apply(&[create(serde_json::json!([
985            {"id": "root", "component": "Column", "children": ["missing"]}
986        ]))]);
987        assert!(report.errors[0].message.starts_with("Dangling reference"));
988        let report = session.apply(&[create(serde_json::json!([
989            {"id": "root", "component": "Text", "text": "hi"},
990            {"id": "spare", "component": "Text", "text": "nobody shows me"}
991        ]))]);
992        assert!(report.is_ok(), "{:?}", report.errors);
993        assert!(report.warnings[0].message.contains("not reachable"));
994        assert_eq!(session.surface_ids(), ["s"]);
995    }
996}