# Agent bridge

`@kernelui-lib/agent` lets an AI agent running in the page read your UI and use it. It reads the page the way a screen reader does, through roles, accessible names and states, so there's no separate store of "agent state" to keep in sync. Kernel's components are real `<button>` s, `<select>` s and `<dialog>` s, so the agent sees what a person sees. It also works with any other well-built HTML.

It has no runtime dependencies and doesn't depend on Kernel's component packages. A small React hook is included. The [WebMCP](https://github.com/webmachinelearning/webmcp) integration is **experimental**: the API is a W3C Community Group draft, only available behind flags or in preview builds, and may still change. Everything else works without it.

```bash
npm install @kernelui-lib/agent
```

## Try it

Run the sample steps, or change the form yourself: the snapshot updates either way. Saving needs your approval, because submitting a form is one of the steps the bridge always asks about.

## Quick start

```tsx
import { createAgentBridge, formatSnapshot } from "@kernelui-lib/agent";

const agent = createAgentBridge({ root: document.querySelector("main") });

// What the agent sees: roles, names, values, states, and a ref per control.
console.log(formatSnapshot(agent.snapshot()));

// What the agent does: real events, so your framework's handlers run.
const result = await agent.act({
  steps: [
    { ref: "e2", action: "type", args: { text: "Ada Lovelace" } },
    { ref: "e4", action: "check" },
    { ref: "e3", action: "select", args: { value: "Team" } },
  ],
});
result.diff; // { added, removed, changed }: what changed on screen

// Expose snapshot / act / query to the browser's agent (WebMCP).
const unregister = agent.registerTools();
```

In React, the hook creates the bridge on mount and cleans up on unmount:

```tsx
import { useRef } from "react";
import { useAgentBridge } from "@kernelui-lib/agent/react";

function Settings() {
  const root = useRef<HTMLElement>(null);
  // Created on mount, tools unregistered and observers stopped on unmount.
  const agent = useAgentBridge({ root, registerTools: true });
  return <main ref={root}>{/* Kernel components */}</main>;
}
```

## The snapshot

`snapshot()` returns a tree of the controls an agent can use, plus the landmarks, headings, groups and live regions that give them context. Layout wrappers are left out and their contents move up a level. `formatSnapshot()` prints the tree as an outline that uses about a third of the tokens the JSON does:

```bash
- form "Account settings" [ref=e1]
  - textbox "Name" [ref=e2] value="" (TextField)
  - combobox "Plan" [ref=e3] value="Free" options=["Free", "Pro", "Team"] (Select)
  - switch "Email me product updates" [ref=e4] checked=false (Switch)
  - button "Invite a teammate" [ref=e5] (Button)
  - button "Save settings" [ref=e6] (Button)
```

Each node in the JSON only has the fields that apply to it:

```json
{
  "role": "switch",
  "name": "Email me product updates",
  "ref": "e4",
  "component": "Switch",
  "checked": false
}
```

- **Names** follow the accessible name computation: `aria-labelledby`, `aria-label`, `<label for>` or a wrapping label, `alt`, `<legend>`, content for buttons and links, then `title` and `placeholder`. Descriptions come from `aria-describedby`, so hints and error messages are included.
- **State**: value, checked, selected, expanded, pressed, disabled, invalid, required, read-only and focus. Each `<select>` lists its options.
- **Refs** like `e4` belong to an element for as long as it exists, so they stay the same from one snapshot to the next. They're kept in a `WeakMap`, not written into the DOM.
- **Hidden content is skipped**: `hidden`, `inert`, `aria-hidden`, closed `<details>`, closed dialogs and popovers, `display: none` and `visibility: hidden`. A tooltip is read as its trigger's description, never as something to act on.
- **Open shadow roots are read like the page.** The tree follows what a person sees: a custom element's open shadow root in place of its light children, and slotted children where their `<slot>` puts them. Hiding, scope, `data-kernel-agent-redact` and `data-kernel-agent-confirm` on a host cover its shadow content too. Kernel's own elements use light DOM; this is for third-party ones. Closed shadow roots stay closed.
- **One ref per control.** A grid cell that wraps a button, like a DatePicker day, is operated through the button, which reports the cell's `selected` state.
- **`component`** names the Kernel component behind a node. It comes from the `kernel-<Name>-*` class names both packages emit and the `kernel-*` custom element tags, using the list of components in the version you installed.

`query({ role, name, component, text })` returns the matching nodes as a flat list, so you don't have to search the tree yourself.

## Actions

`act({ steps })` runs each step the way a person would. Pointer and click events go through the element's own default action. Text uses the native value setter followed by `input` and `change` events, so React-controlled inputs update. Forms are submitted with `requestSubmit()`, and anything that opens or closes uses its own trigger. The bridge refuses a step on a hidden or disabled target, and the error says why. Steps stop at the first failure unless you pass `continueOnError`. When the DOM has settled, the result lists each step's outcome and what changed.

| Action | What happens |
| --- | --- |
| `press` | Pointer and mouse down/up, focus, then `click()` |
| `type` / `clear` | Replaces the value (or appends it with `args.append`), then fires `input` and `change` |
| `select` | `args.value` is an option's value or label. A `<select>` is set directly, and a customizable picker a person left open is closed; for a listbox or combobox, the bridge opens it and presses the option |
| `setValue` | Sets a slider, number, date, time or colour field to `args.value` through the native setter, then fires `input` and `change`. The browser snaps a range to its step, and values outside `min` / `max` are refused. An ARIA slider or spinbutton is stepped with arrow keys |
| `key` | Fires `keydown` and `keyup` for `args.key` (`"Enter"`, `"Escape"`, `"ArrowDown"`, `"Shift+Tab"`, one character), so the page's own key handlers run: Enter commits a TagInput tag. Script-made key events don't trigger browser default actions, so use `type` to enter text and `submit` to submit |
| `check` / `uncheck` / `toggle` | Presses a checkbox, radio, switch or toggle button, and does nothing if it's already in that state |
| `open` / `close` | `<details>`, popover and `aria-expanded` triggers are pressed. A combobox that ignores the click gets ArrowDown or Escape. A dialog closes with its close button, or with the `cancel` event that Escape fires |
| `focus`, `submit`, `scroll` | Focuses the element, calls `requestSubmit()` on its form, or scrolls instantly (`args.to`: top, bottom, into-view) |

## Security model

The bridge runs with your page's own privileges, so it isn't a sandbox. What it does is limit an agent to what a person could do, in the part of the page you choose, and ask a person before anything that matters:

- **Scope it to a root.** Only content inside `root` is visible or usable. `include` limits refs further, and `exclude` or `data-kernel-agent-ignore` removes a subtree entirely. Refs from outside the scope are rejected.
- **Ask before anything that matters.** By default the bridge asks a person before it submits a form (including by pressing a submit button, or pressing Enter in one of its fields), presses a danger-variant button, or acts on anything inside `data-kernel-agent-confirm`. Your `allow` policy can refuse a step, run it, or ask first. It can skip the built-in checks, but it can't skip an explicit `data-kernel-agent-confirm` marker. If no `confirm` is given, `window.confirm` is used; apps should render `ToolApproval` instead.
- **Keep the approval outside the root.** The person's Approve button must never be something the agent can press. Render it outside `root`, or inside `data-kernel-agent-ignore`.
- **Secrets are redacted.** The values of password fields, `autocomplete="one-time-code"`, card fields (`cc-number`, `cc-csc`, `cc-exp` …), and anything marked `data-kernel-agent-redact` are replaced by `"[redacted]"`, and `query` won't match on them either. The agent can still type into these fields when it's allowed to.
- **Page text is data, not instructions.** A snapshot includes whatever text the page shows, which may include text other users wrote. The WebMCP tools are marked `untrustedContentHint` so the browser's agent knows.

```tsx
<Button variant="danger" data-kernel-agent-confirm="Delete this project and its history">
  Delete project
</Button>

<form data-kernel-agent-confirm="false">{/* a search form: no prompt to submit */}</form>

<section data-kernel-agent-ignore>{/* never visible to the agent */}</section>
<input data-kernel-agent-redact name="note" />  {/* value withheld */}
```

```tsx
const agent = createAgentBridge({
  root: document.querySelector("#editor"),
  allow(step, target, { confirmReason }) {
    if (target.closest("[data-billing]")) return false;     // never
    if (step.action === "type") return true;                // always fine
    return confirmReason ? "confirm" : true;                // the default
  },
  confirm: (request) => showMyApprovalUi(request),          // Promise<boolean>
});
```

## Confirm with ToolApproval

The demo above uses this helper: each step that needs a person becomes a Kernel `ToolApproval`, and the step waits for their decision.

```tsx
import { useRef, useState, type ReactNode } from "react";
import { ToolApproval } from "@kernelui-lib/react";
import type { ConfirmRequest } from "@kernelui-lib/agent";
import { useAgentBridge } from "@kernelui-lib/agent/react";

let promptId = 0;

/** A confirm callback that shows Kernel's ToolApproval and resolves with
 * the person's decision. */
export function confirmWithToolApproval(show: (prompt: ReactNode) => void) {
  return (request: ConfirmRequest) =>
    new Promise<boolean>((resolve) => {
      show(
        <ToolApproval
          key={++promptId}
          tool={`agent.${request.step.action}`}
          onApprove={() => resolve(true)}
          onDeny={() => resolve(false)}
        >
          {request.message}
        </ToolApproval>,
      );
    });
}

export function App() {
  const root = useRef<HTMLElement>(null);
  const [prompt, setPrompt] = useState<ReactNode>(null);
  useAgentBridge({ root, confirm: confirmWithToolApproval(setPrompt), registerTools: true });
  return (
    <>
      <main ref={root}>{/* the UI the agent may use */}</main>
      {/* Outside the root, and ignored: the agent can't approve itself. */}
      <aside data-kernel-agent-ignore>{prompt}</aside>
    </>
  );
}
```

## WebMCP (experimental)

`registerTools({ prefix })` registers `kernel_snapshot`, `kernel_query` and `kernel_act` with `document.modelContext.registerTool()`, the API in the [WebMCP draft](https://webmachinelearning.github.io/webmcp/). If a browser only has the older `navigator.modelContext`, the bridge uses that instead. Each tool comes with a JSON Schema for its input, plus `readOnlyHint` and `untrustedContentHint` annotations. Calling the function it returns aborts the registration signal, which unregisters the tools. In a browser without WebMCP, it does nothing. `isWebMcpAvailable()` tells you which case you're in.

To try it, start Chrome with `--enable-features=WebMCP` (Chrome 157 has it behind that flag). Kernel's browser check runs the tools on this page through `document.modelContext.executeTool()` in that build, and against a mock of the draft in browsers without it.

```tsx
// What registerTools() does, per the WebMCP draft:
const controller = new AbortController();
await document.modelContext.registerTool(
  {
    name: "kernel_act",
    description: "Performs steps on the page the way a person would…",
    inputSchema: { type: "object", properties: { steps: { type: "array" } }, required: ["steps"] },
    annotations: { readOnlyHint: false, untrustedContentHint: true },
    async execute({ steps }) {
      const result = await agent.act({ steps });
      return { content: [{ type: "text", text: JSON.stringify(result) }] };
    },
  },
  { signal: controller.signal },
);
controller.abort(); // unregisters
```

## Without WebMCP

Nothing depends on WebMCP. An assistant panel in your app can call `snapshot()` and `act()` directly, or give its model the same tool definitions:

```tsx
import { createAgentBridge, createTools } from "@kernelui-lib/agent";

const agent = createAgentBridge({ root: document.querySelector("main") });
// The same three tools, as plain objects with JSON Schema inputs, for any
// tool-calling model API or in-page agent loop.
const tools = createTools(agent, "page");
const byName = Object.fromEntries(tools.map((tool) => [tool.name, tool]));
// …when the model calls a tool:
const output = await byName[call.name].execute(call.input);
```

## Waiting for the UI

`act()` waits for the DOM to stop changing before it returns. `settle()` waits on its own terms, and `observe()` reports changes once they stop, so an agent can react to a toast or an error without polling:

```tsx
await agent.act({ steps: [{ ref: "e9", action: "press" }] }); // waits for the DOM to settle
await agent.settle({ quiet: 200, timeout: 5000 });           // or wait longer yourself

const stop = agent.observe((diff, snapshot) => {
  // Debounced: fires once the UI has stopped changing.
  if (diff.added.some((node) => node.role === "alert")) notifyAgent(snapshot);
});
```
