createAgent

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

On this page

@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; this page is the full contract.

signature
import type { Agent, AgentOptions } from '@cloudlet/agent';

declare function createAgent(options?: AgentOptions): Agent;
NameTypeDescription
optionsAgentOptionsOptional. The options below.
returnsAgentThe 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.

OptionTypeDefaultDescription
allowAllow—Asked before every step a component did not deny. Without it, steps that need a person go to the person; see Permissions.
timeoutnumber300000How long a step waits for allow, and then for the component, in milliseconds. A finite positive number.

Agent

MemberTypeDescription
connect(component: AgentComponent) => () => voidAdds 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) => () => voidHears 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.
toolsreadonly AgentTool[]cloudlet_act and cloudlet_snapshot for a model: the same frozen array for every agent.
callToolAgentCallToolRuns 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:

FieldTypeDescription
refstringThe record that changed.
componentstringIts kind, as in the snapshot.
labelstringOptional. How a person names it, so a removed record still means something.
keystringWhat changed; each component documents its keys.
valueAgentValueThe value after the change.
previousAgentValueThe value before it.
reasonstringOptional. 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:

OptionTypeDescription
signalAgentSignalCancels the call: a step waiting for allow or for the component stops waiting, and nothing further runs.
allowAllowA second gate for this call only; see Permissions.

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

VariantFieldsDescription
{ ok: true }steps: readonly ActStepResult[]Every step ran.
{ ok: false }error: { step, message }, stepsstep 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:

TypeDefinitionDescription
AgentSnapshotToolResult{ entries, verbs }What cloudlet_snapshot answers: the records, and what the verbs of each kind present do (AgentVerbs). It takes {} or nothing.
AgentActToolResultActResult & { changes, changesDropped? }What cloudlet_act answers: the call's result and the AgentChanges 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.
AgentCallTooloverloads by nameNarrows 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).

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

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:

OptionTypeDescription
allowAllowRequired. The second gate for the browser's agent. WebMCP has no way to ask a person, so the app decides here.
onError(error: unknown) => voidOptional. 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, useColorPickerAgent and useColorPaletteAgent; a new component of the kit ships with its own.

MemberTypeDescription
protocol1The protocol version; the agent refuses any other.
namestringUnique among connected components, [a-z][a-z0-9-]*.
snapshot() => readonly AgentEntry[]The current records, in reading order.
subscribe(listener: (changes?: readonly AgentChange[]) => void) => () => voidCalls the listener whenever snapshot() may return something new, with the changes when it knows them.
check(step: AgentStepCall) => AgentStepCheckOptional, 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) => AgentSummonOutcomeOptional. Brings a confirm step nobody approved in front of a person, without moving focus.
verbsAgentVerbsOptional. What each verb does, by kind of record: { [component]: { [verb]: text } }.
TypeDefinitionDescription
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.
AgentRunOutcomedone, failed, unavailable or staleThe answer of run: { status: 'done', result?, gone? }, { status: 'failed', message }, { status: 'unavailable', message? }, { status: 'stale' }.
AgentSummonOutcomeboolean | { 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.
AgentValuestring | 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.