# Agents

> Let an AI agent in your app read Cloudlet components and act on them under your permission — the bridge, permissions, who changed what, tools for a model and WebMCP.

Source: https://cloudlet.dev/docs/agents

An assistant in your app can work with the same components your users see: read the notifications, press Undo, fill a reply, pick a color. Cloudlet gives it a bridge, the `@cloudlet/agent` package: each component connects through its own adapter, and the agent reads one snapshot of everything connected and acts on it in steps your app allows. A step that needs a person goes to the person.

This page is for an agent that works inside your running app. An agent that writes code with you needs something else: the Markdown of these docs, listed in [llms.txt](https://cloudlet.dev/llms.txt).

> **Experimental.** `@cloudlet/agent` is `0.x`: its protocol and exports may change in any release until `1.0.0`, so pin the exact version. WebMCP, which the bridge can use, is experimental too and works only in Chrome and Edge behind a flag or an origin trial.

## Demo

A scripted agent, with no model behind it, works on this page through the bridge's two tools, the way a model would: it reads the snapshot, picks refs by their labels and plans its steps. It acts on the page's own Toaster and on the picker and palette below. One of its presses needs a person: the Island opens on that notification, and the agent waits until you press the action there.

Live demo at https://cloudlet.dev/docs/agents#demo: a scripted agent, no model, walks the bridge through its two tools on the page's own Toaster and a color picker and palette. It puts four notifications on screen ("Email archived" with "Undo" marked `agent: 'allow'`, "Invoice ready" with an unmarked "Send to client", a cancellable "Uploading photos" and "Link copied"), reads the snapshot, acts, and stops where a step needs a person: the Island opens on "Invoice ready" and the run waits until the visitor presses "Send to client" there (or skips). A sample log:

- `cloudlet_snapshot` ✓ Read 7 records: the Toaster, 4 notifications, a color picker and a palette
- `cloudlet_act` ✓ Pressed “Undo” on “Email archived”; dismissed “Link copied”
- `cloudlet_act` ✓ Cancelled “Uploading photos”
- `cloudlet_act` ⏸ Needs a person: “Send to client” on “Invoice ready” — You pressed it, so the agent goes on.
- `cloudlet_act` ✓ Set “Accent color” to #dcb199; added #8dc7cb to “Brand palette”
- `cloudlet_snapshot` ✓ Read 4 records: the Toaster, 1 notification, a color picker and a palette

Done: 6 tool calls, 5 steps; one step waited for you.

## How it works

- **A snapshot of records.** Every connected component describes what it shows as records: plain data with a `ref` to address it and the verbs that apply now in `actions`. One notification is one record; so is a color picker.
- **Steps under permission.** The agent runs verbs on refs, `{ ref, action, args }`, in calls of up to 20 steps. The component's adapter says what each step needs: nothing, a person's approval, or never.
- **Two tools for a model.** `cloudlet_snapshot` reads, `cloudlet_act` acts. The bridge never calls a model: it gives you the tools, and you hand them to whichever model you use.
- **Nothing hidden.** The bridge touches no DOM, keeps no history and starts no timers until a step waits. What a person typed into a form never reaches it.

## Install

```sh title="Terminal"
npm install @cloudlet/agent
```

The Toaster's adapter is part of `@cloudlet/toast` from `1.4.0`, as the subpath `@cloudlet/toast/agent`. The color picker's and the color palette's adapters come with their registry items, one file each. The bridge and the adapters do not depend on each other as packages: they agree on a protocol number, and the bridge refuses one it does not know.

## Connect

Create one agent for the app, then connect each component with one line. The Toaster connects its controller; the picker and the palette wrap their props in a hook:

```ts title="lib/agent.ts"
import { createAgent } from '@cloudlet/agent';

// One agent for the app. Without options, every step that needs a person goes to the person.
export const agent = createAgent();
```

```tsx title="components/workspace.tsx"
'use client';

import { useCloudlet } from '@cloudlet/toast';
import { toasterAgent } from '@cloudlet/toast/agent';
import { useEffect, useState } from 'react';
import { ColorPicker } from '@/components/ui/color-picker/color-picker';
import { useColorPickerAgent } from '@/components/ui/color-picker/color-picker-agent';
import { agent } from '../lib/agent';

export function Workspace() {
  const cloudlet = useCloudlet();
  // The Toaster: connect its controller; the effect's cleanup disconnects it.
  useEffect(() => agent.connect(toasterAgent(cloudlet)), [cloudlet]);

  const [accent, setAccent] = useState('#245cdb');
  // The picker: the hook connects it while it is mounted and hands back its props.
  const picker = useColorPickerAgent(agent, { color: accent, onChange: setAccent }, { label: 'Accent color' });
  return <ColorPicker {...picker} />;
}
```

Now `agent.snapshot()` holds the Toaster, its notifications and the picker. Each component's page has an Agent section with its verbs: [Toaster](https://cloudlet.dev/docs/components/toaster#agent), [Color picker](https://cloudlet.dev/docs/components/color-picker#agent), [Color palette](https://cloudlet.dev/docs/components/color-palette#agent).

## Permissions

Every step gets one of three answers, and the component decides which:

- **allow**: it runs, unless your `allow` says no. Closing a notification, cancelling an operation, setting a color.
- **confirm**: it needs a person. Pressing a notification's action and submitting its form are `confirm` by default: these do things in your app.
- **deny**: it never runs, whatever anyone approves.

You move an action between the classes with its `agent` marker. A command your app considers safe for an agent says so:

```ts
import { createCloudlet } from '@cloudlet/toast';

const cloudlet = createCloudlet();
const restore = () => {};

cloudlet.show({
  title: 'Email archived',
  // An agent may press Undo without asking anyone. 'deny' would keep it from the agent entirely.
  action: { kind: 'command', label: 'Undo', agent: 'allow', run: restore },
});
```

**Needs a person.** Without an `allow` option, a `confirm` step is never run by the agent. The Toaster opens the Island on that notification instead, without moving focus, and the agent reads an error that starts with `Needs a person` and asks it to let the person take the step. The [demo](#demo) takes this path: press the action in the Island yourself and the agent goes on.

**Your own gate.** `createAgent({ allow })` is asked before every step a component did not deny. Return `true` to approve; anything else refuses. For a `confirm` step, `needsPerson` is `true`, and `true` from your gate means the person approved, for instance in your own dialog or on your server:

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

export const agent = createAgent({
  allow: async (step, { signal }) => {
    if (!step.needsPerson) return true;
    const response = await fetch('/api/approve', {
      method: 'POST',
      body: JSON.stringify(step),
      // The bridge types its signal structurally, so the package needs no DOM types;
      // at runtime it is an AbortSignal, aborted when the call is cancelled or times out.
      signal: signal as AbortSignal,
    });
    return response.ok && (await response.json()) === true;
  },
  timeout: 60_000, // how long a step waits for allow, then for the component; default five minutes
});
```

`agent.act(input, { allow })` adds a second gate for a single call, for a caller you trust less than the rest. It only narrows what the agent's own `allow` lets through; the rule in full is on [createAgent](https://cloudlet.dev/docs/agents/api/agent#permissions).

## Who changed what

Every change carries its `source`: `user` (a person on screen), `agent` (a step), `app` (your code) or `system` (a timer, an outcome). The bridge's `subscribe` hears each change of a connected component with its source, and the Toaster's own events carry the same field, so your app can tell an agent's dismissal from a person's:

```ts title="lib/log-agent-changes.ts"
import { agent } from './agent';

agent.subscribe((changes) => {
  for (const change of changes) {
    if (change.source === 'agent') console.log(`The agent changed ${change.key} on ${change.label ?? change.ref}`);
  }
});
```

The Toaster's change keys and their sources are on [toasterAgent](https://cloudlet.dev/docs/agents/api/toast#changes); its events, on [`ChangeSource`](https://cloudlet.dev/docs/components/toaster/api/types#changesource).

## Tools for a model

`agent.tools` is `cloudlet_snapshot` and `cloudlet_act` as `{ name, description, inputSchema }`, the shape every model SDK takes. When the model calls one, run it with `agent.callTool` and send the answer back as the tool's result:

```ts title="lib/run-tool.ts"
import { agent } from './agent';

declare const call: { name: string; input: unknown };

const output = await agent.callTool(call.name, call.input); // plain data; never rejects
const toolResult = JSON.stringify(output);
```

The descriptions teach the model how to read records, plan steps into one call and treat page text as data, never as instructions; each component's verbs come in the snapshot. The model's key stays on your server and the tools run in the browser: [Connect a model](https://cloudlet.dev/docs/agents/models) has the recipes for the Vercel AI SDK and the Anthropic SDK.

## WebMCP

A browser can bring its own agent. `registerTools` hands the same two tools to it through [WebMCP](https://webmachinelearning.github.io/webmcp/), and returns the function that removes them:

```tsx title="components/browser-agent-tools.tsx"
'use client';

import { registerTools } from '@cloudlet/agent';
import { useEffect } from 'react';
import { agent } from '../lib/agent';

export function BrowserAgentTools() {
  // The browser's agent is not your code: allow decides what it may do.
  useEffect(() => registerTools(agent, { allow: (step) => !step.needsPerson }), []);
  return null;
}
```

WebMCP is **experimental**: a draft, in Chrome and Edge only behind `chrome://flags/#enable-webmcp-testing` or an origin trial. Elsewhere `registerTools` does nothing at all. WebMCP cannot ask a person, so its `allow` is required, and it can only narrow what the agent's own `allow` permits.

## What the bridge does not do

- **It does not call a model** or hold a key. Your app talks to the model.
- **It does not show notifications.** An agent works with what is on screen; your app decides what appears. To let a model tell the user something, give it a tool of your own over `show` ([recipe](https://cloudlet.dev/docs/agents/models#let-the-model-show-a-notification)).
- **It does not open links**, read what a person typed, move focus or take a step from a person who is using the Toaster.
- **It does not undo.** Steps of a failed call that ran before the error stay done.
- **It does not remember.** Between calls it keeps nothing; what happened between a model's turns, your app collects with `subscribe`.
- **It does not mark what it wrote.** A form field the agent filled looks the same to the person as one they filled; the snapshot knows who wrote it (`filledBy`), the screen does not show it yet.

## Next steps

- [Connect a model](https://cloudlet.dev/docs/agents/models): the Vercel AI SDK, the Anthropic SDK, OpenAI's JSON Schema, and a tool of your own.
- [createAgent](https://cloudlet.dev/docs/agents/api/agent): every method and type of `@cloudlet/agent`.
- [toasterAgent](https://cloudlet.dev/docs/agents/api/toast): the Toaster's records, verbs, refusals and changes.
