Appearance
Agents and events
An agent plugin is an async generator that yields events. This page lists everything it receives and everything it can yield. For a walkthrough, see Connect your first agent.
Preview
The TypeScript SDK is being designed in the open. APIs on this page may change before the first release.
The agent function
Each entry in your manifest's agents list has a matching file, src/agents/<name>.ts, whose default export is the agent:
ts
import { text, type AgentContext } from '@agentplaygrounds/sdk'
export default async function* myAgent(context: AgentContext) {
yield text('Hello!')
}Signature
ts
type Agent<Preferences = {}> = (context: AgentContext<Preferences>) => AsyncIterable<AgentEvent>When it's called
The app calls your agent once for each reply it should write. In a room where it's the only agent, that's every message the person sends. In a room with several agents, the app decides who gets a turn:
- The agents the message
@mentions, if any, wherever in the message they're written. - Otherwise the room's moderator.
- Otherwise every agent.
Your agent is also called when another agent hands it work, when a hand off it asked a result from comes back, and when someone uses a button on a surface it sent. turn says which of these it is; action is set for a button. See Working with other agents and Actions on your surfaces. An agent just made from a directory is called once more, in its new DM, with no message: turn.reason is "introduce", and it says hello.
A reply begins with the first event you yield and is complete when your generator returns. Everything you yield in between belongs to that reply.
AgentContext
| Property | Type | Description |
|---|---|---|
room | Room | The room, with its newest finished messages (the app sends up to 100). Read-only for agents: change the room by yielding events. |
message | Message or undefined | The message this reply responds to, also the last item in room.messages. Not set when the call is for an action or an introduce turn, so read it as message?.text. |
action | SurfaceAction or undefined | Set when the call is for an action on one of this agent's surfaces. |
agent | AgentInfo | This agent as the person set it up: its id, name and instructions. For an agent from a directory, also its remoteId on the service and its emoji there. |
self | Member | Which member of the room this agent is, with its handle, role and description. A member from a directory also carries its pal (a shape and a color) and emoji, as the service lists it. |
connection | { id: string } or undefined | For an agent from a directory: the connection it runs over, by the record id the connection's connect was given. Use it to reach the same scoped storage and secrets. |
turn | Turn | Why this agent was called, whether it may pass and how many turns are left. |
unseen | Message[] | Catch-up: the room's finished messages since this agent's last turn, oldest first, without its own and without message. Empty when nothing new was said since its last turn, or since it joined the room. A turn that failed, or was stopped before it said anything, doesn't use up its catch-up: the next turn gets those messages again. |
otherRooms | OtherRoom[] | The other rooms this agent is in, most recent first: each room's id, title and agents, never its messages. Only rooms with two or more agents: a DM is private, so it's never listed, in a room or anywhere else. Empty from a host that doesn't send them. |
preferences | Preferences | The agent's settings from your manifest. password values come from the Keychain. |
signal | AbortSignal | Aborted when the person stops the reply, sends a new message or cancels a task. Pass it to fetch. |
ask | Ask | Prompts, bound to this reply. |
self, turn and unseen come from the host. The app sends them in every room, including a room with one agent and an agent's DM. In a host that doesn't run rooms (see hostCapabilities), the SDK fills them in: self is this agent, turn is a mention with canPass: false and turnsLeft: 1, and unseen is empty. Code written for several agents runs unchanged in a room with one.
Turn
ts
type Turn = (
| { reason: 'mention' | 'moderator' | 'everyone' | 'introduce'; from: Member }
| { reason: 'handOff'; from: Member; handOff: HandOff }
| { reason: 'callBack'; from: Member; handOff: HandOff
outcome: 'replied' | 'passed' | 'failed' | 'stopped'; reply?: Message }
) & { canPass: boolean; turnsLeft: number }
type HandOff = { id: string; text: string; callBack: boolean }| Property | Description |
|---|---|
reason | "mention": the message mentions this agent. "moderator": no one was mentioned and this agent is the moderator. "everyone": no one was mentioned and the room has no moderator. "handOff": another agent gave this one something to do. "callBack": a hand off this agent made has finished. "introduce": the agent was just made and this is its first turn in its DM. The app starts it once, with no message; the agent says hello. See The introduction. |
from | Who caused the turn: the message's author, the agent that handed off, the agent that was handed off to and is now calling back, or the person for an introduction. |
handOff | The hand off, with its text and whether a call back was asked for. For a hand-off line, text is the lines addressed to this agent. |
outcome | On a call back: "replied", or "passed", "failed" or "stopped" when the other agent didn't answer. A failed or stopped turn still calls back. |
reply | On a call back: the other agent's message, when it said anything. Always set for "replied"; a "stopped" turn can carry a partial reply. |
canPass | Whether this turn may end with pass. True for "moderator" and "everyone", unless this agent is the room's only agent that can answer (a deleted agent stays in the room but can't); an agent that was mentioned, handed off to, called back or asked to introduce itself must reply. |
turnsLeft | Agent turns that can still start after this one before the room pauses. At 0 a hand off waits for Continue; at 1 the target answers but a call back waits. |
Events
Import these helpers from @agentplaygrounds/sdk and yield what they return.
text
ts
function text(delta: string): AgentEventAppends to the reply's current text. Yield as often as your agent produces text: the app smooths fast streams and keeps the order.
block
ts
function block<Payload>(options: {
type: string
payload: Payload
fallbackText: string
id?: string
}): BlockEvent<Payload>Adds a block, like a card, to the reply. Any plugin's block type works. If the person doesn't have a plugin that draws type, they see fallbackText.
The returned BlockEvent has an id, yours or a generated one, so you can update it later.
ts
const card = block({ type: 'acme.build', payload: { step: 'Starting' }, fallbackText: 'Build starting' })
yield card
// …
yield update(card, { step: 'Done' })update
ts
function update<Payload>(block: BlockEvent<Payload> | string, payload: Payload): AgentEventReplaces the payload of a block this agent sent, by BlockEvent or block id. The block re-renders for everyone in the room. Works on blocks from earlier replies too.
ui
ts
function ui(messages: A2UIMessage | A2UIMessage[], options: { fallbackText: string; id?: string }): BlockEventSends A2UI directly: a createSurface, with its components and data model, or messages that update a surface this agent sent earlier. Use it when your agent already produces A2UI, or to build UI without a plugin. The surface appears as a block in the reply, and is validated against its catalog; if it's invalid, your agent gets an error back and people see fallbackText.
ts
yield ui(
{
createSurface: {
surfaceId: 'flights',
catalogId: 'https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json',
components: [
{ id: 'root', component: 'Card', child: 'col' },
{ id: 'col', component: 'Column', children: ['title', 'book'] },
{ id: 'title', component: 'Text', text: 'TAP 1350, Lisbon to London, 9:40', variant: 'h4' },
{ id: 'book', component: 'Button', child: 'book-label',
action: { event: { name: 'book', context: { flight: 'TP1350' } } } },
{ id: 'book-label', component: 'Text', text: 'Book' },
],
},
},
{ fallbackText: 'TAP 1350, Lisbon to London, 9:40' },
)thinking
ts
function thinking(delta: string): AgentEventStreams the agent's reasoning, shown separately from its answer. It's expanded while the agent thinks and collapses to "Thought for 6s" when text starts.
status
ts
function status(line: string | null): AgentEventShows what the agent is doing right now, like "Searching the web…", under the conversation and in the sidebar. It clears automatically when text arrives or the reply ends; pass null to clear it yourself. Status is never saved.
newMessage
ts
function newMessage(): AgentEventStarts a new message bubble within the same reply.
connection
ts
function connection(state: 'online' | 'degraded' | 'offline'): AgentEventReports the connection to the agent's service, for agents that hold one (a gateway, a long-lived socket). The room and the sidebar show it: an offline agent's room reads as Offline, a degraded one keeps working but says so. Yield it when the state changes; it's never saved.
note
ts
function note(text: string): AgentEventA line in the room from your plugin, never as the agent's words: "Saved to Care's soul and notes." The app shows it as a quiet line after the reply, with no author, and keeps it with the room. Use it when the plugin did something on the agent's behalf that the person should know about. A host that hasn't said it shows notes (hostCapabilities().notes) drops it, and nothing is shown instead.
ts
yield text('Thanks, that covers it.')
yield note(`Saved to ${agent.name}'s soul and notes.`)endReply
ts
function endReply(): AgentEventMarks the reply complete while your generator keeps running, so the person can keep chatting. After endReply, you can only yield task and update events. Use it to report long-running work.
handOff
ts
function handOff(to: Member | string, text: string, options?: { callBack?: boolean }): AgentEventGives another member of the room something to do: to is a Member, or a member's id or handle like 'Points', and text is the request. The app starts a turn for that agent with turn.reason === 'handOff'. With callBack: true, your agent is called again when that turn ends, with turn.reason === 'callBack' and the result attached. Return after yielding it: your reply ends, and the call back arrives as a new turn.
You can only hand off to a member of the room, not to yourself and not to the person. A line of your reply that starts with @Points, a hand-off line, hands off too, without a call back; @Points anywhere else in your text hands off to no one. In a host that doesn't run rooms, handOff is sent as a hand-off line, @Points and the request.
ts
yield text('Points knows this best.')
yield handOff('Points', 'Is the Hyatt better on points or cash?', { callBack: true })
returnpass
ts
function pass(reason?: string): AgentEventEnds the reply without a message. The thread shows a quiet line, "Trip passed", which collapses to "Trip and Points passed" when several agents pass, and becomes "No one answered" if everyone called for the message passes. Yield it when your agent has nothing to add, and only when turn.canPass is true: an agent that was mentioned, handed off to or called back, or that is the room's only agent that can answer, must reply, and if it passes anyway the room says "Trip had nothing to add". In a host that doesn't run rooms, pass ends the reply with no message. reason is for your logs; people never see it.
ts
if (turn.canPass && !isForMe(message?.text)) {
yield pass('Not about the trip')
return
}hostCapabilities
ts
function hostCapabilities(): { rooms?: number; calls?: number; connections?: number; directory?: number; notes?: number }Says what the host runs beyond the basics, as it told your plugin when it loaded. The app returns all five: rooms, it runs rooms with several agents, acts on handOff and pass, and sends self, turn and unseen; calls, it calls your plugin's connections and directories and listens to notify; connections and directory, it acts on the ones in your manifest, with a Settings pane and the Agent library; notes, it shows the note event as a line in the room. A host that runs none of it returns {}. The SDK's test host returns all five unless you load the plugin with other capabilities.
Most agents never need it: handOff and pass work in any host, and the SDK sends them as text or an empty reply where they aren't understood. Check it when your agent decides what to tell its model about the room. With rooms, the host acts on handOff, pass and hand-off lines, so tell the model how to use them. Without it, nothing hands off and nothing passes: a line that starts with @Handle is text the person reads, so leave those rules out.
ts
import { hostCapabilities } from '@agentplaygrounds/sdk'
// Tell the model only what this host acts on.
const rooms = Boolean(hostCapabilities().rooms)
const rules = rooms ? [
'To hand work to another agent, start a line with @ and their handle, then a colon.',
'If you need their answer back, end that line with [[callback]].',
'If you have nothing to add, reply with exactly [[pass]].',
] : []
// [[callback]] and [[pass]] are your plugin's own convention, not SDK API (these are the OpenClaw
// plugin's). Your plugin turns them into handOff(…, { callBack: true }) and pass().It returns a copy: changing it changes nothing.
Prompts
Prompts ask the person something and wait for the answer. While a prompt is waiting, the room shows as Needs You. If the reply is stopped first, the promise rejects with an AbortError.
ask is available two ways: context.ask, bound to the reply being written, and the shared ask imported from the SDK, which works while one reply is in progress. An agent that can be writing several replies at once (one per room) should use context.ask.
ask.approval
ts
function approval(options: {
title: string
detail?: string
permission?: { action: string; resource: string; scope?: string }
}): Promise<{ allowed: boolean; remembered: boolean }>Asks for permission to do something. With a permission, the person can choose Always allow, and the room remembers a grant like "My Agent may deploy: pricing". Later requests that match are answered instantly, with remembered: true. A scope widens what a grant covers: an exact resource, a prefix ending in *, or * for anything.
ts
const answer = await ask.approval({
title: 'Delete the old logs?',
detail: '214 files, 1.2 GB',
permission: { action: 'delete files', resource: '~/Logs/2025', scope: '~/Logs/*' },
})
if (!answer.allowed) returnask.choice
ts
function choice(options: {
title: string
options: { id: string; title: string; description?: string }[]
}): Promise<{ id: string }>Asks the person to pick one option. A description is shown under the option's title.
ask.text
ts
function text(options: { title: string; placeholder?: string; secret?: boolean }): Promise<{ text: string }>Asks for a short typed answer. With secret: true the field is a password field and the answer is never shown or logged: for a code or a key the agent needs once.
Storage and secrets
ts
import { storage, secrets } from '@agentplaygrounds/sdk'
await storage.set('lastSync', Date.now())
const last = await storage.get<number>('lastSync')
await secrets.set('deviceToken', token)
const token = await secrets.get('deviceToken')storage keeps small JSON values between launches; secrets keeps strings in the Keychain, never logged and never synced in the clear. Each plugin has its own keys, invisible to others. Use them for what an agent needs to come back as itself: a device identity, a token a service issued, a cursor.
Working with other agents
In a room with several agents, the app tells your agent who it is (self), why it was called (turn) and what was said since its last turn (unseen). It can answer, hand work to another member with handOff, or stay quiet with pass. The guide, Rooms with several agents, walks through all of it.
What the app keeps for you: who gets a turn, one run per member with that member's own plugin and settings, the members list, catch-up, hand-off lines in replies, the turn limit, hand offs only to other members, call backs, one turn at a time per member in a room with several agents, replies in the order their turns start, and approvals. What your agent decides: answer, pass or hand off, to whom, and whether it wants the result.
ts
export default async function* trip({ room, self, turn, message }: AgentContext) {
if (turn.reason === 'callBack') {
// Quote the reply, so a line in it that starts with @Handle doesn't hand off again
const answer = (turn.reply?.text ?? 'no answer').replace(/^/gm, '> ')
yield text(`Points says:\n${answer}\n\nHere's the plan…`)
return
}
const points = room.members.find((m) => m.handle === 'Points')
if (self.role === 'moderator' && points && /points|miles/i.test(message?.text ?? '')) {
yield text('Points knows this best.')
yield handOff(points, 'Is the Hyatt better on points or cash?', { callBack: true })
return
}
if (turn.canPass && !isAboutTrips(message?.text)) {
yield pass()
return
}
yield text('Here is what I know…')
}Agents see each other's finished messages, with a card's fallbackText in place of the card, and never another agent's thinking or tool use. A message from an agent is never treated as coming from the person, and a hand off carries no permissions: the other agent's approvals go to the person as its own.
A member that comes from a directory also carries the look its service keeps for it: pal, a shape from the app's catalog in a brand color, and emoji. Both are optional on Member, and a plugin that puts the roster into a model's prompt can use the emoji as the member's badge.
Tasks
Tasks report long-running work, with live cards in the conversation and a row in the room's Tasks tab.
ts
function task(options: { title: string; id?: string }): TaskTask method | Description |
|---|---|
start(step?: string) | Shows the task as running |
progress(value?: number, step?: string) | Updates progress from 0 to 1, or leave out value for indeterminate, and the current step |
succeed(step?: string) | Marks it succeeded |
fail(reason: string) | Marks it failed |
Each method returns an event to yield. Finished states are final. If the person cancels a task, your signal is aborted.
ts
const deploy = task({ title: 'Deploy' })
yield deploy.start()
yield text('Deploying now. I’ll let you know when it’s live.')
yield endReply()
yield deploy.progress(0.5, 'Uploading')
yield deploy.succeed('Live')Actions on your surfaces
When someone uses a button with an event action on a surface your agent sent with ui, the app calls your agent again, with action set instead of a new message:
ts
type SurfaceAction = {
name: string // the action's event name, like "book"
surfaceId: string
context: Record<string, unknown> // the action's context, including values from bound inputs
}Handle it like any reply: yield text, update the surface or start a task.
ts
export default async function* travel({ action }: AgentContext) {
if (action?.name === 'book') {
yield status('Booking…')
// …
yield ui({ updateDataModel: { surfaceId: action.surfaceId, path: '/booked', value: true } }, {
fallbackText: 'Booked',
})
return
}
// …otherwise, answer the message
}Errors
If your agent throws, the reply is marked failed and the error's message is shown, with Retry. Throw errors with messages people can act on:
ts
if (response.status === 401) throw new Error('Your API key was rejected. Check it in the agent’s settings.')When the person stops a reply, signal is aborted and anything already shown stays in the room. You don't need to catch the resulting AbortError.