---
language: "en"
title: "Agents"
canonical: "https://uniaria.tenphi.me/guide/agents/"
source: "docs/guide/agents.md"
index: true
---

# Agents

An agent that operates a page usually reads a screenshot or the
accessibility tree, then clicks and types one control at a time. Every
control costs it a tool call or more, and it has to work out again how each
widget opens, filters and chooses.

The agent bridge, `@uniaria/core/agent`, gives it the components instead.
`snapshot()` lists them as data: a ref, a kind, a label, the value and the
actions each one takes. `act()` runs a whole task in one call, through each
component's own definition, so validation, form values and change callbacks
run as they do for a person. On the settings screen of UI SDK's benchmark,
an agent that drove the components this way used 2 tool calls instead of 17,
and took a quarter of the time.

The bridge speaks [UI SDK](https://ui-sdk.dev)'s agent protocol: the same
three tools, input, output and messages. An agent, a tool definition or a
harness written for UI SDK drives a UniAria page unchanged.

This page is about agents that operate a page. A coding agent that writes
code with UniAria gets its docs and the `uniaria-build` skill instead: see
[Coding agents](/guide/getting-started/#coding-agents).

## Set it up

Create the bridge once, on the page, and hand its tools to your agent:

```ts
import { createAgent } from '@uniaria/core/agent';

const agent = createAgent({
  // Asked before every step; return false to refuse it.
  allow: (step) => (step.confirm ? confirmWithPerson(step.confirm) : true),
});

// The tools' names, descriptions and JSON Schemas, for a model API.
const tools = agent.tools;

// Run a tool call the model made.
const result = await agent[call.name](call.input);
```

The bridge works with every adapter: it reads the components React, Vue and
the custom elements render, with no code per framework. It sees what started
before it was created too. A page that doesn't import it pays nothing for it.

### In the browser's own agent

`registerTools()` hands the three tools to the browser's agent through
[WebMCP](https://webmachinelearning.github.io/webmcp/) where the browser has
it, and does nothing where it doesn't. That agent isn't one you wrote, so it
needs an `allow` of its own, asked after the bridge's:

```ts
import { createAgent, registerTools } from '@uniaria/core/agent';

const agent = createAgent();
const unregister = registerTools(agent, {
  allow: (step) => step.action !== 'press' || confirm(`Press ${step.args[0]}?`),
});
```

## What an agent sees

`snapshot()` lists the components a person can reach now, in page order:

```json
[
  {
    "ref": "c1",
    "component": "input",
    "actions": ["setValue", "clear"],
    "label": "Display name",
    "value": "Acme"
  },
  {
    "ref": "c2",
    "component": "switch",
    "actions": ["setChecked"],
    "label": "Auto renew",
    "checked": false
  },
  {
    "ref": "c3",
    "component": "select",
    "actions": ["setOpen", "setValue", "clear"],
    "label": "Region",
    "open": false,
    "value": null,
    "items": [
      { "value": "fra", "label": "Frankfurt" },
      { "value": "iad", "label": "Virginia" }
    ]
  },
  {
    "ref": "c4",
    "component": "dialog",
    "actions": ["setOpen", "press"],
    "label": "Delete project",
    "open": false
  }
]
```

* **`ref`** stays the component's while it is on the page. A step can also
  name a component by its label, by the text on its row ("Jane Doe" for the
  menu on her row) or by its kind ("dialog").
* **`component`** is UI SDK's name for the widget, so an agent used to UI
  SDK pages knows it. The page keeps UniAria's names in its markers.
* **State** comes under the protocol's names: `value`, `checked`, `pressed`,
  `open`, and `min`, `max`, `step`, `required`, `errors` and `placeholder`
  when they say something.
* **`items`** are a list's options or a group's radios and checkboxes, from
  their data, even while a select is closed. A list with more than ten has
  `more`, their count, instead: `query` with `within` lists them.
* **`text`** and **`buttons`** are what an open dialog or popover says and
  the buttons in it.
* **`disabled: true`** and no actions while a person can't change it:
  disabled, read-only, or behind an open modal dialog.

What is hidden from a person is left out: a closed dialog's contents, an
element under `aria-hidden`, an overlay on its way out.

A component that left the page, or that a person can no longer see, like a
field in a dialog that closed, follows with `offPage: true` and the state it
had, so an agent checks it without opening anything. A component that comes
back, like a field that remounts, takes its ref again.

### Closed sections and tabs

A component whose definition says it `reveals` others, such as a tab list or
a collapsible section, hides what it holds while it's closed. The snapshot
ends with `{ ref: "closed", closed: [...] }`, the places that are closed. A
step names a component in one by its label, and the bridge opens the way to
it first, asking `allow` for each place it opens, and leaves it open:

```ts
await agent.act({
  steps: [{ ref: 'Billing > Auto renew', action: 'setChecked', args: [false] }],
});
```

Put the place first when two hold the same label, as above. `query({ closed:
true })` reads what every closed place holds, opening each to look and going
back.

## Running a task

`act()` runs steps in order and stops at the first that fails:

```ts
await agent.act({
  steps: [
    { ref: 'Display name', action: 'setValue', args: ['Initech'] },
    { ref: 'Region', action: 'setValue', args: ['Virginia'] },
    { ref: 'Auto renew', action: 'setChecked', args: [true] },
    { ref: 'Delete project', action: 'press', args: ['Delete'] },
    { ref: 'Save', action: 'press' },
  ],
});
```

* **`setValue`** takes text, a number, or an item's label or value
  (`"Virginia"` or `"iad"`). A list that holds many takes a list.
* **`setChecked`**, **`setPressed`** and **`setOpen`** take `true` or
  `false`.
* **`press`** clicks a button by its text. A closed dialog or popover opens
  itself first to find it. UniAria takes the click as a screen reader's, so
  it runs the same handlers.
* **`expect`** checks a value, a checked state or a row's text and changes
  nothing, so an `expect` before the save guards it.
* **`clear`**, **`increment`**, **`decrement`** and **`setQuery`** (a
  combobox's text) where a component takes them.

The result says what each step changed, the components that appeared, and
every field's value after, so the agent needn't look again. A step fails, and
says why, when it names nothing on the page, when a value isn't one of a
closed list's items, when a number is out of range, or when the change
didn't take, as a controlled value the app never accepts doesn't. The
messages are written for the model: one that names nothing lists the labels
on the page.

`query()` finds components without listing the page: by the words of a
label or row (`{ text: 'renew' }`), by kind (`{ kind: 'select' }`), or a
list's items (`{ within: 'Country', text: 'ger' }`), 50 at a time with
`from`.

Calls run one at a time, in the order they were made.

## Keeping the person in charge

Three attributes mark what an agent may do alone. Each covers its element and
everything inside it, and none changes what a person sees or does:

| Mark                        | Effect                                                                                                                                  |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `data-agent-hidden`         | Left out everywhere. A step that names it fails: "isn't available to agents here".                                                      |
| `data-agent-secret`         | Its values read `"[redacted]"`, in snapshots, results and messages. Password, one-time code and card fields are by default.             |
| `data-agent-confirm="what"` | A step that changes it needs `allow` to answer `true`, with `confirm` set to the text. Without `allow`, it fails with "Needs a person". |

```html
<div data-agent-confirm="Deletes the project for everyone">
  <uni-button><button data-uni="button">Delete</button></uni-button>
</div>
```

`allow(step, { signal })` is asked before every step, with the component, the
action, its arguments, and `confirm` when the page marked it. It may return a
promise, as a dialog asking the person does; `signal` aborts when the step
stops waiting. A step `allow` doesn't answer within `timeout` (five minutes
by default) fails.

## Telling an agent's changes apart

Every change a step makes reports `source: 'agent'` in its
[change details](/guide/state/#why-a-value-changed), so the app can log, gate or
undo an agent's changes on their own:

```ts
const region = useSelect({
  onValueChange(value, { source }) {
    if (source === 'agent') audit.log('Region', value);
  },
});
```

On a custom element, the change event's `source` says the same.

`subscribe()` hears every change on the page, a person's or an agent's, with
the component's ref and label, the protocol's key (`checked`, `value`,
`open`), the value before and after, and the reason and source:

```ts
const stop = agent.subscribe((change) => {
  log.push(
    `${change.label}: ${change.key} ${change.previous} → ${change.value} (${change.source})`,
  );
});
```

A private value reads `"[redacted]"` there too, and a component an agent
can't see reports only opening and closing.

## Components

| Component     | Kind (`component`)             | State                     | Actions                                    |
| ------------- | ------------------------------ | ------------------------- | ------------------------------------------ |
| Button        | `button`                       | —                         | `press`                                    |
| ToggleButton  | `toggle`                       | `pressed`                 | `setPressed`                               |
| TextField     | `input` or `textarea`          | `value`                   | `setValue`, `clear`                        |
| NumberField   | `number-input`                 | `value`, `min`, `max`     | `setValue`, `increment`, `decrement`       |
| Checkbox      | `checkbox`                     | `checked`                 | `setChecked`                               |
| Switch        | `switch`                       | `checked`                 | `setChecked`                               |
| CheckboxGroup | `checkbox`                     | `value`, a list           | `setValue`, with its checkboxes as items   |
| RadioGroup    | `radio`                        | `value`                   | `setValue`, with its radios as items       |
| Listbox       | `listbox`                      | `value`, `multiple`       | `setValue`, `clear`                        |
| Select        | `select`                       | `open`, `value`           | `setOpen`, `setValue`, `clear`             |
| Combobox      | `combobox`                     | `open`, `value`, `query`  | `setOpen`, `setValue`, `clear`, `setQuery` |
| Autocomplete  | `autocomplete`                 | `open`, `value`           | `setOpen`, `setValue`, `clear`             |
| Dialog        | `dialog` or `alert-dialog`     | `open`, `text`, `buttons` | `setOpen`, `press`                         |
| Popover       | `popover`                      | `open`, `text`, `buttons` | `setOpen`, `press`                         |
| Tooltip       | `tooltip`                      | `open`                    | `setOpen`                                  |
| Tabs          | `tabs`                         | `value`, the tab shown    | `setValue`, with its tabs as items         |
| Field         | `field`, while it shows errors | `errors`                  | —                                          |

A radio is its group's item, and a checkbox in a group is listed on its own
too. A form isn't listed: its fields are, and its submit button is a Button.

## Your own components

A definition tells the bridge about itself through its `agent` field, written
after `connect()`. Its actions call the same functions a person's input does:

```ts
export const rating = defineBehavior({
  name: 'rating',
  // …
  setup(ctx) {
    const setRating = (value: number) =>
      ctx.props.value.set(value, changeOf('action'));
    return { setRating /* , … */ };
  },
  expose: ({ props }) => ({ value: props.value.get() }),
  connect: /* … */,
  agent: {
    kind: 'slider',
    state: { value: (state) => state.value, min: () => 1, max: () => 5 },
    actions: {
      setValue: {
        args: ['number'],
        run: (api, [value]) => api.setRating(value as number),
      },
    },
  },
});
```

Without an `agent` field, a component is listed by its name and label, and
takes `press` when its root is a button. See
[`agent` in the core API](/api/core/#agent-surface) for every field.

## Not included

* **Undo and history.** An app that wants them keeps them from the change
  callbacks, where `source` says which changes were the agent's.
* **Controls that aren't UniAria components.** A plain `<button>` inside a
  dialog is one of the dialog's `buttons`, and `press` reaches it there.
