# createAgent

> The bridge of @cloudlet/agent — the factory, the agent's methods, the tools for a model, registerTools and every type an adapter implements.

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

`@cloudlet/agent` is **experimental**: it is `0.x`, and its protocol and exports may change in any release until `1.0.0`, so pin the exact version. What the bridge is for and how to wire it is in [Agents](https://cloudlet.dev/docs/agents); this page is the full contract.

```ts title="signature"
import type { Agent, AgentOptions } from '@cloudlet/agent';

declare function createAgent(options?: AgentOptions): Agent;
```

| Name | Type | Description |
|---|---|---|
| `options` | `AgentOptions` | Optional. The [options](#options) below. |
| returns | `Agent` | The bridge: one snapshot over every connected component, and steps through them. Its functions are bound. |

Creating an agent touches no DOM and starts no timers until a step waits, so it works on the server, in a worker and before any component mounts. A wrong option throws a `TypeError`.

## Options

`AgentOptions`, every field optional.

| Option | Type | Default | Description |
|---|---|---|---|
| `allow` | `Allow` | — | Asked before every step a component did not deny. Without it, steps that need a person go to the person; see [Permissions](#permissions). |
| `timeout` | `number` | `300000` | How long a step waits for `allow`, and then for the component, in milliseconds. A finite positive number. |

## Agent

| Member | Type | Description |
|---|---|---|
| `connect` | `(component: AgentComponent) => () => void` | Adds a component's records to the snapshot; returns the function that removes them, which does nothing the second time. |
| `snapshot` | `() => readonly AgentEntry[]` | Records of every connected component, in connection order, as one frozen array. The same array comes back until something changes. |
| `subscribe` | `(listener: (changes: readonly AgentChange[]) => void) => () => void` | Hears every change of the snapshot, with what changed and who changed it. |
| `act` | `(input: ActInput, options?: ActOptions) => Promise<ActResult>` | Runs steps in order and stops at the first error. Never rejects. |
| `tools` | `readonly AgentTool[]` | `cloudlet_act` and `cloudlet_snapshot` for a model: the same frozen array for every agent. |
| `callTool` | `AgentCallTool` | Runs a tool by name with the input a model sent and answers plain data. Never rejects. |

`useSyncExternalStore(agent.subscribe, agent.snapshot)` works as it is.

### connect

`connect` throws a `TypeError` for an unknown `protocol` (only `1` is understood), a name outside `[a-z][a-z0-9-]*`, a name already connected, missing `snapshot` or `subscribe`, `check` without `run` (or the other way round), a step method that is not a function, and `verbs` that is not an object of objects of strings. The agent copies `verbs` when the component connects.

### subscribe

The listener receives a frozen array of `AgentChange` records, empty when the snapshot changed with no author: time passing, a component connected or disconnected. A listener that takes no argument fits too. Every listener runs even if one throws; the error is rethrown in a microtask. A component that reports more than 1000 changes at once has the whole report refused, and a record of an unknown shape is skipped and reported through `reportError`.

`AgentChange`:

| Field | Type | Description |
|---|---|---|
| `ref` | `string` | The record that changed. |
| `component` | `string` | Its kind, as in the snapshot. |
| `label` | `string` | Optional. How a person names it, so a removed record still means something. |
| `key` | `string` | What changed; each component documents its keys. |
| `value` | `AgentValue` | The value after the change. |
| `previous` | `AgentValue` | The value before it. |
| `reason` | `string` | Optional. Why, when the component has a word for it. |
| `source` | `'user' \| 'agent' \| 'app' \| 'system'` | Who made the change: a person on screen, an agent through `act`, the app's own code, or the component itself (a timer, an outcome). |

### act

`ActInput` is `{ steps }` and nothing else: one to 20 `AgentStep` records, `{ ref, action, args? }`, where `action` is a verb from the record's `actions` and `args` a list of plain values. The whole input is checked before the first step, so a malformed call runs nothing and says what to change. Calls of one agent run one at a time: a call made while a step waits for `allow` waits too, so an agent cannot approve its own step with a second call.

`ActOptions`:

| Option | Type | Description |
|---|---|---|
| `signal` | `AgentSignal` | Cancels the call: a step waiting for `allow` or for the component stops waiting, and nothing further runs. |
| `allow` | `Allow` | A second gate for this call only; see [Permissions](#permissions). |

`ActResult` is frozen plain data, safe for JSON and `structuredClone`. Steps that ran before an error stay done; there is no rollback.

| Variant | Fields | Description |
|---|---|---|
| `{ ok: true }` | `steps: readonly ActStepResult[]` | Every step ran. |
| `{ ok: false }` | `error: { step, message }`, `steps` | `step` is the failing step's index from zero; `message` is written for the agent to read and act on. |

`ActStepResult` is `{ step, ref, result?, gone? }`: `step` counts from zero, `result` is what the component reported (`'pending'` when it was still working at the timeout), `gone: true` means the step removed its record. A throwing `allow` or component is never thrown again: a page gets the error through `reportError`, any other runtime in `console.error`.

### tools and callTool

`AgentTool` is `{ name, description, inputSchema }`: `name` is an `AgentToolName`, `'cloudlet_act'` or `'cloudlet_snapshot'`, and `inputSchema` a plain JSON Schema. The descriptions are written for a model that sees only them; they name no component, because each adapter describes its own verbs in `verbs`.

`callTool(name, input, options)` takes the same `ActOptions` as `act`, and answers an `AgentToolResult`:

| Type | Definition | Description |
|---|---|---|
| `AgentSnapshotToolResult` | `{ entries, verbs }` | What `cloudlet_snapshot` answers: the records, and what the verbs of each kind present do (`AgentVerbs`). It takes `{}` or nothing. |
| `AgentActToolResult` | `ActResult & { changes, changesDropped? }` | What `cloudlet_act` answers: the call's result and the `AgentChange`s heard from the moment the call started running until it answered, from any source. It keeps the newest 200; when a call heard more (say, it waited for `allow` beside a busy component), `changesDropped` counts the older ones left out. |
| `AgentToolError` | `{ ok: false, error: { message } }` | An unknown name, input `cloudlet_snapshot` does not take, or a snapshot a component failed to give. |
| `AgentCallTool` | overloads by name | Narrows the answer for the two known names. |

Between calls the bridge keeps nothing: what changed between a model's turns, collect with `subscribe` yourself ([Connect a model](https://cloudlet.dev/docs/agents/models#changes-between-turns)).

## Permissions

Each component says what a step needs, as an `AgentPermission`: `'allow'` (it runs unless your `allow` says no), `'confirm'` (it runs only when your `allow` returns `true`, otherwise the person is asked) or `'deny'` (it never runs, and `allow` is not asked).

`Allow` is `(step: AllowStep, context: { signal }) => boolean | PromiseLike<boolean>`. `AllowStep` is `{ ref, action, args, needsPerson }`: `needsPerson` is `true` for a `confirm` step, and then return `true` only if the person (or the app on their behalf) approved it. Only `true` approves; `false`, any other value, a throw, a rejection and no answer within `timeout` refuse. `signal` aborts when the call is cancelled or the timeout elapses, so a pending question can be withdrawn.

A refused `confirm` step is not lost: the component brings it in front of the person (the Toaster opens the Island on it) and the agent reads `Needs a person`, with a sentence to ask them to take it.

**The second gate.** `ActOptions.allow`, and the `allow` of `registerTools`, is a gate for one caller you trust less than the agent's other users. It only narrows:

- it is asked after the agent's `allow` approved the step, with the same question, and only then;
- a step that needs a person comes with `needsPerson: true`, and its `true` answers for the person together with the agent's gate; without the agent's `allow` such a step cannot be approved, so it goes to the person and the second gate is not asked;
- a step of the `allow` class on an agent without `allow` is asked here only;
- each answer has the whole `timeout`; cancelling withdraws the pending question;
- a refusal reads as one from the agent's `allow`.

## registerTools

```ts title="signature"
import type { Agent, RegisterToolsOptions } from '@cloudlet/agent';

declare function registerTools(agent: Agent, options: RegisterToolsOptions): () => void;
```

Hands `cloudlet_snapshot` and `cloudlet_act` to the browser's own agent through WebMCP (`document.modelContext.registerTool`) and returns the function that removes both. **Experimental:** WebMCP is a draft, available in Chrome and Edge only behind a flag or an origin trial. Where `document.modelContext` is missing it does nothing, writes nothing and returns a function that does nothing.

`RegisterToolsOptions`:

| Option | Type | Description |
|---|---|---|
| `allow` | `Allow` | Required. The second gate for the browser's agent. WebMCP has no way to ask a person, so the app decides here. |
| `onError` | `(error: unknown) => void` | Optional. Hears a registration that failed (a name already taken, a frame without the `tools` permission). By default `reportError`. |

`cloudlet_snapshot` is registered with `readOnlyHint` and `untrustedContentHint`, `cloudlet_act` with `consequentialHint` and `untrustedContentHint`. A tool's `execute` never throws: failures come back as `{ ok: false, error: { message } }`. Registering again after the removal works, so an effect that runs twice leaves no duplicate. `registerTools` throws a `TypeError` for something that is not an agent, or a missing `allow`.

## Writing an adapter

A component reaches the bridge through an adapter that builds an `AgentComponent`. The kit's adapters are [`toasterAgent`](https://cloudlet.dev/docs/agents/api/toast), [`useColorPickerAgent`](https://cloudlet.dev/docs/components/color-picker#agent) and [`useColorPaletteAgent`](https://cloudlet.dev/docs/components/color-palette#agent); a new component of the kit ships with its own.

| Member | Type | Description |
|---|---|---|
| `protocol` | `1` | The protocol version; the agent refuses any other. |
| `name` | `string` | Unique among connected components, `[a-z][a-z0-9-]*`. |
| `snapshot` | `() => readonly AgentEntry[]` | The current records, in reading order. |
| `subscribe` | `(listener: (changes?: readonly AgentChange[]) => void) => () => void` | Calls the listener whenever `snapshot()` may return something new, with the changes when it knows them. |
| `check` | `(step: AgentStepCall) => AgentStepCheck` | Optional, with `run`. Whether a step can run now and under which permission; synchronous, no side effects. |
| `run` | `(step: AgentStepCall, context: AgentRunContext) => AgentRunOutcome \| PromiseLike<AgentRunOutcome>` | Optional, with `check`. Runs an approved step, checking again first. |
| `summon` | `(step: AgentStepCall) => AgentSummonOutcome` | Optional. Brings a `confirm` step nobody approved in front of a person, without moving focus. |
| `verbs` | `AgentVerbs` | Optional. What each verb does, by kind of record: `{ [component]: { [verb]: text } }`. |

| Type | Definition | Description |
|---|---|---|
| `AgentEntry` | `{ ref, component, actions, [key]: unknown }` | One record. `ref` is unique across the agent, `actions` lists the verbs that apply now; the other keys are state the component describes. |
| `AgentStepCall` | `{ ref, action, args }` | A step as a component receives it, `args` always present. |
| `AgentStepCheck` | `{ available: true, permission, names? }` or `{ available: false, message? }` | The answer of `check`. `names` (`AgentStepNames`, `{ target, within? }`) is how a person names the thing pressed and what it belongs to, for the bridge's messages. |
| `AgentRunContext` | `{ signal, approved }` | `approved` is the permission the bridge cleared; a step that now needs more answers `stale`. |
| `AgentRunOutcome` | `done`, `failed`, `unavailable` or `stale` | The answer of `run`: `{ status: 'done', result?, gone? }`, `{ status: 'failed', message }`, `{ status: 'unavailable', message? }`, `{ status: 'stale' }`. |
| `AgentSummonOutcome` | `boolean \| { reached, note }` | Whether the step is in front of the person now; `note` replaces the bridge's sentence about where they find it. |
| `AgentSignal` | `{ aborted, reason, throwIfAborted, addEventListener, removeEventListener }` | A cancellation signal as the bridge reads it. Structural, so the package needs no DOM types; every signal the bridge hands out is an `AbortSignal` at runtime. |
| `AgentValue` | `string \| number \| boolean \| null \| readonly AgentValue[] \| { [key]: AgentValue }` | Plain data: what survives JSON and `structuredClone` alike, finite numbers only. A record key that is not plain data is left out and reported. |
