# Pages for agents

A built page says what can be done on it, so a program (or a model driving a
browser) need not guess: `data-mote` on every control, the `mote-agent`
block, `agent.json`, `llms.txt`, your notes in `agents.mote`, and `mote`, in
the page: the page as a few lines of text, its controls done by name, and a
call that comes back when the page is at rest. Back to
the [map](README.md).

```mote
// docs: whole
app "Todos"

shape Todo
  id: string
  title: string
  done: bool

state todos: Todo[] = [] persist
state draft = ""
state open = false

action add
  if draft.trim() == "" return
  todos.push({id: uid(), title: draft, done: false})
  draft = ""

action wipe
  todos = []

column gap=8 padding=16
  input value=draft submit=add placeholder="What next?"
  button "Add" press=add
  button "Menu" press={open = true}
  button "Clear all" press=wipe data-mote="clear"
  for t in todos key=t.id
    row gap=8
      input type=checkbox checked=t.done
      text t.title
```

## Mental model

The compiler knows every action, field, route and back-end call by name. It
writes that knowledge into what it builds, in three forms that say the same
thing (`compiler/src/agents.rs`):

1. **On the controls**: each element with a handler or a binding carries
   `data-mote="name"`.
2. **In the page**: one block,
   `<script type="application/json" id="mote-agent">`, lists the routes,
   actions (with their parameters), the page's `shortcut` lines
   (`"shortcuts": [{"keys": "mod+k", "runs": "openSearch", "fields": false}]`:
   the chords, the action they run if it is one, and whether they are heard
   while a field has the caret), state, the marked controls, and the back
   end's calls with their types.
3. **Beside the page** (`mote build`, not `--single`): the same as
   `agent.json`, and as prose in `llms.txt`.

Nothing is written by hand and nothing can drift: the names come from the
program. `agents.mote` is the author's word on top, and each name in it is
checked against the program.

A page that only shows things (no state, actions, routes or controls) has
none of it.

## data-mote

Every control is named for what it does:

| Control | `data-mote` |
|---|---|
| a press that runs an action: `press=add`, `press=remove(t.id)` | `add`, `remove` |
| a field that writes state: `input value=draft` | `draft` |
| a field that writes into a row: `checked=t.done` | `t.done` |
| a press that only sets one state: `press={open = true}` | `set-open` |
| a component's `on=` or `open=` written back | the state's name |

Select with `[data-mote="add"]`. In a list every row's control has the same
name: narrow by the row.

- A field is named for the state it writes, whatever else it does (Enter in
  it may also run an action).
- The events looked at are `press`, `submit`, `change`, `input`, in that
  order.
- A block with more than one statement gets no name of its own. Write
  `data-mote="name"` yourself to choose one; your own name always wins.
- Inside a component, a handler that is one of the component's own props
  says nothing: the name is given where the component is used.

The same names are what tests use: `[data-mote="add"]` is a stable selector
that survives restyling ([testing.md](testing.md)).

## The mote-agent block

For the page above (shortened):

```json
{"mote": 1, "app": "Todos",
 "how": "Every control carries data-mote: … Select with [data-mote=\"NAME\"]. Routes are addresses after #.",
 "routes": [{"path": "/about", "note": "Who made this."}],
 "actions": [{"name": "add", "params": [], "control": true, "note": "Adds what is in draft."}],
 "state": [{"name": "draft", "type": "string", "kept": false, "field": true}],
 "controls": [{"name": "draft", "is": "field"}, {"name": "add", "is": "press"}, {"name": "set-open", "is": "press"}],
 "server": [{"name": "count", "params": [], "gives": "number", "call": "POST /rpc/count with a JSON array of the arguments"}],
 "flows": [{"name": "Add a todo", "steps": ["type the title into draft", "press add"]}],
 "notes": ["Nothing here is destructive except clear."]}
```

- `actions[].control` says whether a control on the page runs it.
- `state[].kept` is `persist`; `state[].field` whether a field writes it.
- `server[]` also says `requires` and `live` where they apply.
- `about`, `note`s, `flows` and `notes` are there only if `agents.mote` says
  them.

Read it from the page: `JSON.parse(document.querySelector("#mote-agent").textContent)`.
Both are plain JSON whatever your notes say: a `<` in `agents.mote` (`"/<workspace>/c/<channel>"`)
is itself in `agent.json` and `\u003c` in the block, which `JSON.parse` reads back as `<`.

`llms.txt` is the same as prose: the app's name, the about line, how the
controls are named, then Pages, Actions, State, The back end's calls, and
How to (the flows).

## agents.mote

A file named `agents.mote` beside the entry is your word on top of that.
Each name is checked against the program, so the notes cannot drift from it
(`H099` names what the program does have).

```mote
about "A todo list: add items, tick them off."
action add "Adds what is in draft. Type into draft first."
action wipe hidden
state draft "The title being typed."
route "/about" "Who made this."
server quote "Prices a job; slow, call it once."
model Message "What was said in a room; newest last."
note "Nothing here is destructive except clear."
flow "Add a todo"
  "type the title into draft"
  "press add"
```

| Line | Says |
|---|---|
| `about "…"` | What the app is, in a sentence. |
| `action name "…"` | What an action is for. |
| `state name "…"` | What a state holds. |
| `route "/path" "…"` | What a page is (the route in quotes, as written in the program). |
| `server name "…"` | What a `server fn` does. |
| `… hidden` | Leaves that action, state, route or call out of what agents are told. |
| `note "…"` | Anything else worth knowing. |
| `flow "Name"` + indented `"step"` lines | How to get something done. |

It is not Mote: it is a list of lines, each a word, a name and strings in
double quotes. `//` starts a comment.

`hidden` leaves a name out of the block, `agent.json` and `llms.txt`. It
does not remove the control or its `data-mote`, and it does not protect
anything: a `server fn` is protected by `requires signedIn` and by its own
checks ([back-end.md](back-end.md#signing-in)).

## Turning it off

`app "Name" agents=off` leaves all of it out: no `data-mote`, no block, no
files.

## mote: the page without a picture

Every page that has controls has `mote` (`self.mote`), for whatever drives
it: a model with a browser tool, a test, a script. It needs no screenshot
and no selector, and nothing is waited for by guessing a time.

```js
await mote.read()
```

```text
Shop @ /
Basket
#1 field draft "New item" =""
#2 button Add
list "Items" 2 rows
 - Apples × 2 · #3 button More · #4 button Drop
 - Bread × 1 · #5 button More · #6 button Drop
#8 link About (to #/about)
```

That is the whole page: its title and address, then a line a thing. A
control begins with its number; then what it is (`button`, `field`,
`check`, `select`, `link`, `slider`, `tab`…), its `data-mote` name where
that differs from the words on it, its words, and its state: `=value` for a
field, `on` / `off` for a checkbox, and `(disabled, open, selected,
current, invalid, required, busy)` where they hold. Words that are not a
control are a line of words; a heading is `# words`; a list says how many
rows it has and a row of a few short things is one line; a table's row is
its cells with `|` between. A picture is said by its words (`img "Team photo"`); one with
none is not said. A [chart](charts.md) is `#12 img "Visitors" (90 points, day from Sep 1 to
Nov 29. Visitors: from 706 to 1,668…)`: its name and what it shows in a sentence
(`read({within: 12})` gives its numbers, as a table). What is hidden is not there. With a dialog open
over the page, the dialog is what there is.

| Call | Gives |
|---|---|
| `mote.read()` | The page. `{within: 4}` one part of it · `{view: true}` only what is in view · `{rows: 100}` more of a long list (40 unsaid: the rest is one line, `… 460 more`) · `{text: 500}` longer runs of words. |
| `mote.read({changed: true})` | Only the lines that are not as they were at the last read: `- ` gone, `+ ` new, `~ ` a control that changed, after an `@ after:` line that says where. `(nothing changed)` otherwise. |
| `mote.press(t)`, `mote.tap(t)` | A press with the mouse; with a finger. |
| `mote.type(t, text)` | Types into a field in place of what it holds. `{add: true}` after it; `{enter: true}` then Enter. |
| `mote.check(t, on)`, `mote.pick(t, option)` | A checkbox or switch set (pressed only if it is not so already); an option chosen, by its words or its value. |
| `mote.key("mod+k", t?)` | A key or a chord, at what has the caret or at `t`. |
| `mote.hold(t, 600)`, `mote.swipe(t, "left")`, `mote.drag(t, onto)` | A finger held; one moved across (`"left"`, `"right"`, `"up"`, `"down"`, or `{x, y}`); a thing dragged onto another, or by `{x, y}`. |
| `mote.scroll(t, "end")` | A list or `"page"` scrolled: `"end"`, `"top"`, `"down"`, `"up"`, a number, or to a thing. |
| `mote.go("/about")` | To a page of the app. |
| `mote.see("words")` | Waits until the page says them; gives the line. Fails, with what the page does say, after five seconds. |
| `mote.settled()` | The page at rest: `{settled, waiting}`. |
| `mote.help()`, `mote.about()` | These calls on a dozen lines; the `mote-agent` block. |

**`t`, the thing meant**, is its number (`4`, as long as it is on the page),
its `data-mote` name (`"add"`), or the words on it (`"Add to bag"`; a part
of them will do if only one thing matches). Where several share a name,
which every row of a list does, say which by the words beside it:
`{name: "drop", text: "Bread"}` is the `drop` in the row that says Bread;
or `{name, nth: 2}`, or `{name, within: 7}`. A name that fits several
things, or none, fails with a sentence that lists them: it is never guessed.

**Every call that does something comes back when the page is at rest**,
with `{settled, changed}`: `changed` is what `read({changed: true})` would
have said. So the loop of an agent is one call a step, and it never reads
the whole page twice:

```js
await mote.type("draft", "Milk", {enter: true})
// {settled: true, changed: "@ after: #2 button Add\n- list \"Items\" 2 rows\n+ list \"Items\" 3 rows\n+  - Milk (8) × 1 · #9 button More · #10 button Drop"}
```

**At rest** means: no request out, no timer of the page's due within 300 ms
(`{timers: 1000}` to wait for later ones; one that repeats is not waited
for), nothing moving that will stop (`{motion: false}` not to wait for
that), and nothing drawn for two frames. A call to the back end 350 ms
long, a debounce, a move to another page and the list it then loads are all
waited for with nothing said. If the page is not at rest after ten seconds
(`{timeout}`), the answer says `settled: false` and `waiting: ["request
/rpc/price"]`: what it waits for, in words.

**The page's clock, in hand.** `await mote.clock.hold()` stops the page's
timers and its `Date.now()`; `await mote.clock.advance(2000)` lets two
seconds of the page's time go by at once, each timer due in them ringing in
its turn with the page at rest after each; `mote.clock.release()` gives it
back to the wall. A test of "the note goes after five seconds" takes no
five seconds, and says the five.

What it costs: a page nobody drives runs none of it. A built app serves it
as a file of its own (`mote.js`, 22 KB, 8 KB compressed) which the page
takes when something first calls `mote`; the page itself carries a line of
250 bytes. A page that is one file (`--single`, `mote dev`) carries it,
unrun. `agents=off` leaves it out with the rest.

The calls in the page make the events themselves, which is right for an
agent that can only run JavaScript in a tab. A person's press is not quite
that (the browser gives a real one focus, a caret, a context menu, a
scroll): for tests, and for an agent that has the browser's own protocol,
use the driver below, which sends real input and uses `mote` to find
things and to know when the page is at rest.

## Driving a Mote page

(A program's own tests of its page need none of what follows: a [`test "…"
page`](testing.md#a-test-of-the-page) block has this driver as `page`.)

`mote drive --out mote-drive.mjs` writes the driver: one file, no
dependencies (Node 22 or Bun, and a Chrome on the machine: `$CHROME`, or
the usual places).

```js
import { launch } from "./mote-drive.mjs";

const app = await launch("http://localhost:4870", { phone: true });
await app.type("New item", "Milk", { enter: true });       // a call to the back end is waited for
await app.tap({ name: "more", text: "Bread" });
await app.swipe("pad", "left");
await app.hold("pad", 600);
await app.tap("About");                                    // another page: waited for
console.log(await app.read());
await app.close();
```

There is no `sleep` and no `waitFor` in a script that uses it: each call
finds its thing as `mote` does, sends **real input** (the mouse, fingers and
keys of the DevTools protocol, which the browser treats as a person's),
and comes back when the page is at rest, with `{settled, changed}`. A call
made while the page is loading, or on its way to another page, waits for
it. A page that does not come to rest is an error that says what it waits
for (`{strict: false}` to be told in the answer instead).

| Call | Does |
|---|---|
| `launch(url, {phone, width, height, show, timeout, strict})` | Starts Chrome (headless unless `show`) and opens the address, or a built page's file. `phone`: 390 × 844 with fingers. |
| `attach(page)` | The same `app` on a page of Puppeteer's or Playwright's (Chromium), beside whatever else the script does with it. |
| `app.read(opts)`, `app.changed()`, `app.see(words)`, `app.find(t)`, `app.about()` | As `mote`'s. |
| `app.press(t)`, `app.tap(t)`, `app.hover(t)` | The mouse; a finger; the mouse over it. |
| `app.type(t, text, {add, enter})`, `app.key("mod+k", t?)` | Real typing; a real key. |
| `app.check(t, on)`, `app.pick(t, option)` | As `mote`'s. |
| `app.hold(t, ms)`, `app.swipe(t, way, {by, ms})`, `app.drag(t, onto, {touch})`, `app.pinch(t, scale)` | Real fingers (the mouse, for `drag`, unless `touch`). |
| `app.scroll(t, to)`, `app.go(path)`, `app.open(url)`, `app.reload()`, `app.back()` | Moving about. |
| `app.clock.hold()`, `.advance(ms)`, `.release()` | The page's clock. While it is held, the time a `hold` or a `swipe` takes is the page's too: `app.hold(t, 5000)` takes no five seconds. |
| `app.size(w, h, {touch})`, `app.scheme("dark")`, `app.shot("page.png")` | The screen, the colours, a picture. |
| `app.another(url, {fresh: true})` | Another tab; with `fresh`, another person's browser (cookies of its own). |
| `app.eval(js)`, `app.send(method, params)`, `app.errors` | Anything else in the page; the protocol itself; what the page logged as wrong. |

Without it, for an agent that has only a page and `fetch`:

1. Fetch `llms.txt` (or call `mote.about()`), then `await mote.read()`.
2. Act with `mote.press`, `mote.type` and the rest; read `changed`.
3. To call the back end directly: `POST /rpc/<name>` with the arguments as a
   JSON list ([back-end.md](back-end.md#the-wire)).

## Pitfalls

- **Names are the program's names.** Renaming an action renames its
  control. `data-mote="name"` written by hand pins a name.
- **Rows share a name.** `[data-mote="t.done"]` matches every row.
- **`--single` writes no files**: the block is in the page; `agent.json`
  and `llms.txt` come only with a full `mote build`.
- **`hidden` is not security.**
- **`agents.mote` is read from beside the entry only**, and a wrong name in
  it fails the build.

## In the source

| What | Where |
|---|---|
| All of it | `compiler/src/agents.rs`: `survey` (what the program says), `mark` and `name_of` (`data-mote`), `read` (`agents.mote`), `describe` (the block and `llms.txt`) |
| Where it joins the build | `compiler/src/build.rs`: `finish` |
| `mote` in the page | `runtime/page/agent.mote` (part `AG`): the text, finding a thing, doing a thing, at rest, the clock |
| The driver | `tools/drive/mote-drive.mjs`, written out by `mote drive` |


Recorded: `tests/expect/real_agent.txt` (the page as text, driven by name
with real input, a slow call and another page waited for, the clock held;
`tests/agent.drive.mjs` has no sleep in it).
