Connect your agent with live responses
Anyone can connect their own agent to Sonoe chat as a bot. This guide is for agents built on a language model: while the agent works, the chat shows what it's doing ("Thinking…", or any text you choose, plus its steps); then the reply streams in word by word; and when it's done, the steps stay under the message as its traza. It ends with a complete agent on the Claude API in Python and TypeScript, and with test mode, where you watch every protocol event before anyone else sees your bot.
It builds on the bot protocol: the live activity and the live replies.
What people see

- The live activity. As soon as the message arrives the bot says "Thinking…" (
estado: pensando), then whatever it's really doing, in the person's language: "Checking the time in Asia/Tokyo…". A timer shows how long it's been at it. - The steps. Each thing the agent does is a step (
pendiente,en_curso,hecho,error) with an optional detail, like the result of a tool. People can fold and unfold them. - The reply, live. The text grows word by word while the model writes it (
flujo→delta→end).

- The traza. When the bot ends the reply with
cerrar_actividad: true, the activity goes away and its steps stay under the message: "2 steps · How it did it".
Quick setup
- Create the bot in sonoeai.com → Mis bots (Create bot): a name (
/clima), its color and shape, who can add it (private: only you) and how it gets its events. - Copy its token. It's shown once, with the webhook secret. Keep it in an environment variable,
SONOE_BOT_TOKEN, never in your code. If you lose it, Rotate issues a new one and the old one stops working. - Choose how events arrive:
- Connection (SSE): your agent opens
GET /v1/bots/eventsand keeps it open. It works from anywhere (a laptop, a server behind a router) with no public URL. Best for an agent: the examples below use it. - Webhook: Sonoe POSTs each event, signed, to your HTTPS URL. Answer
2xxwithin 10 s and do the model's work afterwards, with the same calls.
- Connection (SSE): your agent opens
- Open Probar on your bot (test mode) and write to it.
The flow
For each message, the agent:
PUT /v1/bots/chats/{chat}/activity {"estado": "pensando", "texto": "Thinking…", "ttl": 45}
… the model calls a tool: the activity says so, with a step in progress
PUT /v1/bots/chats/{chat}/activity {"estado": "usando_herramienta", "texto": "Checking the time in Asia/Tokyo…",
"herramienta": {"nombre": "hora_local", "etiqueta": "Checking the time in Asia/Tokyo"},
"pasos": [{"titulo": "Checking the time in Asia/Tokyo", "estado": "en_curso"}]}
… the first word: the reply opens, and each chunk goes out as it comes
POST /v1/bots/chats/{chat}/messages {"flujo": true} → 201 {"id": 305, "estado": "escribiendo", …}
POST /v1/bots/messages/305/delta {"texto": "Right now it's "}
POST /v1/bots/messages/305/delta {"texto": "**10:39** there."}
POST /v1/bots/messages/305/end {"cerrar_actividad": true} → the finished message, with its trazaThen it acknowledges the event (POST /v1/bots/events/ack), so it doesn't come again.
Example: Python
A complete agent on the official Anthropic SDK: it listens over SSE, sets its activity, calls Claude Opus 5.5 with adaptive thinking and streaming, updates the steps while Claude uses a tool, forwards each chunk with delta and closes with end.
pip install anthropic httpx
export SONOE_BOT_TOKEN=sb_bot_… # from Mis bots
export ANTHROPIC_API_KEY=sk-ant-… # from the Claude Console
python agent.py"""A Sonoe chat bot on Claude: live activity with steps, a reply streamed word by word, and the steps kept as its traza.
pip install anthropic httpx
SONOE_BOT_TOKEN=sb_bot_… ANTHROPIC_API_KEY=sk-ant-… python agent.py
"""
import asyncio
import json
import os
import time
from datetime import datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import anthropic
import httpx
SONOE = os.environ.get("SONOE_API", "https://sonoeai.com")
# The most capable model. For a cheaper bot, use "claude-sonnet-5-5" or "claude-haiku-5-5".
MODELO = os.environ.get("CLAUDE_MODEL", "claude-opus-5-5")
claude = anthropic.AsyncAnthropic() # reads ANTHROPIC_API_KEY
sonoe = httpx.AsyncClient(base_url=SONOE, timeout=httpx.Timeout(15, read=60),
headers={"Authorization": f"Bearer {os.environ['SONOE_BOT_TOKEN']}"})
# What people read, in their language (the event's locale).
TEXTOS = {
"es": {"pensando": "Pensando…", "hora": "Mirando la hora en {z}", "escribiendo": "Escribiendo", "error": "No pude terminar."},
"en": {"pensando": "Thinking…", "hora": "Checking the time in {z}", "escribiendo": "Writing", "error": "I couldn't finish."},
"pt": {"pensando": "Pensando…", "hora": "Vendo a hora em {z}", "escribiendo": "Escrevendo", "error": "Não consegui terminar."},
"fr": {"pensando": "Je réfléchis…", "hora": "Je regarde l'heure à {z}", "escribiendo": "J'écris", "error": "Je n'ai pas pu finir."},
}
TOOLS = [{
"name": "hora_local",
"description": "The current local time in an IANA time zone, such as America/Puerto_Rico or Asia/Tokyo.",
"input_schema": {"type": "object", "properties": {"zona": {"type": "string"}}, "required": ["zona"]},
"eager_input_streaming": True,
}]
def hora_local(zona: str) -> str:
try:
return datetime.now(ZoneInfo(zona)).strftime("%H:%M (%A)")
except (ZoneInfoNotFoundError, ValueError):
return f"Unknown time zone: {zona}"
async def llamar(metodo: str, ruta: str, cuerpo: dict | None = None) -> dict:
"""One protocol call; on 429 (240 actions a minute) it waits and tries again."""
for intento in range(4):
r = await sonoe.request(metodo, ruta, json=cuerpo)
if r.status_code != 429:
r.raise_for_status()
return r.json() if r.content else {}
await asyncio.sleep(2 ** intento)
r.raise_for_status()
class Actividad:
"""«Pensando…», then custom text and steps; refreshed so its ttl (45 s) never runs out while Claude works."""
def __init__(self, chat: int):
self.chat, self.estado, self.pasos, self.extra = chat, {}, [], {}
self.vivo = asyncio.create_task(self._mantener())
async def poner(self, estado: str, texto: str, **extra) -> None:
self.estado = {"estado": estado, "texto": texto, **extra}
await llamar("PUT", f"/v1/bots/chats/{self.chat}/activity", {**self.estado, "pasos": self.pasos[-12:], "ttl": 45})
async def _mantener(self) -> None:
while True:
await asyncio.sleep(20)
if self.estado:
await self.poner(**self.estado)
class Respuesta:
"""The streamed reply: opened at the first word (a stream with no chunks for 60 s is cut), chunks every 0.25 s."""
def __init__(self, chat: int, responde_a: int | None):
self.chat, self.responde_a, self.id, self.pendiente, self.enviado, self.ultimo = chat, responde_a, None, "", "", 0.0
async def agregar(self, texto: str) -> None:
self.pendiente += texto
if time.monotonic() - self.ultimo >= 0.25:
await self.vaciar()
async def vaciar(self) -> None:
if not self.pendiente:
return
if self.id is None:
m = await llamar("POST", f"/v1/bots/chats/{self.chat}/messages", {"flujo": True, "responde_a": self.responde_a})
self.id = m["id"]
trozo, self.pendiente = self.pendiente, ""
await llamar("POST", f"/v1/bots/messages/{self.id}/delta", {"texto": trozo})
self.enviado += trozo
self.ultimo = time.monotonic()
async def terminar(self, cortado: bool = False, si_vacio: str = "…") -> None:
await self.vaciar()
if self.id is None: # nothing streamed: a plain message (it closes the activity and keeps the traza)
await llamar("POST", f"/v1/bots/chats/{self.chat}/messages", {"texto": si_vacio, "responde_a": self.responde_a})
else:
await llamar("POST", f"/v1/bots/messages/{self.id}/end", {"cerrar_actividad": True, "cortado": cortado})
def historial(e: dict) -> list[dict]:
"""The chat so far as Claude's turns: the bot's messages are «assistant», people's are «user»."""
turnos = [{"role": "assistant" if m["autor"]["tipo"] == "bot" else "user", "content": m["texto"]}
for m in e.get("contexto", []) if m.get("texto")]
while turnos and turnos[0]["role"] == "assistant":
turnos.pop(0)
return turnos + [{"role": "user", "content": e["mensaje"]["texto"]}]
async def atender(e: dict) -> None:
chat, t = e["chat"]["id"], TEXTOS.get(e.get("locale", "es")[:2], TEXTOS["en"])
actividad = Actividad(chat)
respuesta = Respuesta(chat, e["mensaje"]["id"] if e["chat"]["tipo"] == "grupo" else None) # in a group, as a reply
await actividad.poner("pensando", t["pensando"])
mensajes = historial(e)
sistema = f"You are /{e['bot']['nombre']} in Sonoe chat. Answer briefly in the language of the locale {e.get('locale', 'es')}."
try:
while True:
async with claude.beta.messages.stream(
model=MODELO, max_tokens=64000, thinking={"type": "adaptive"}, system=sistema, tools=TOOLS, messages=mensajes,
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
) as stream:
async for ev in stream:
if ev.type == "text":
if not respuesta.enviado and not respuesta.pendiente:
actividad.pasos.append({"titulo": t["escribiendo"], "estado": "en_curso"})
await actividad.poner("escribiendo", t["escribiendo"] + "…")
await respuesta.agregar(ev.text)
final = await stream.get_final_message()
usos = [b for b in final.content if b.type == "tool_use"]
if final.stop_reason != "tool_use" or not usos:
break # end_turn, refusal or max_tokens: what was streamed is the answer
mensajes.append({"role": "assistant", "content": final.content})
resultados = []
for uso in usos:
zona = uso.input.get("zona") if isinstance(uso.input, dict) else None
if not isinstance(zona, str): # eager input streaming: validate before running
resultados.append({"type": "tool_result", "tool_use_id": uso.id, "is_error": True, "content": "zona must be a string"})
continue
paso = {"titulo": t["hora"].format(z=zona)[:80], "estado": "en_curso"}
actividad.pasos.append(paso)
await actividad.poner("usando_herramienta", paso["titulo"] + "…",
herramienta={"nombre": uso.name, "etiqueta": paso["titulo"]})
salida = hora_local(zona)
paso.update(estado="hecho", detalle=salida)
resultados.append({"type": "tool_result", "tool_use_id": uso.id, "content": salida})
mensajes.append({"role": "user", "content": resultados})
await actividad.poner("pensando", t["pensando"])
for p in actividad.pasos:
p["estado"] = "hecho"
await actividad.poner("escribiendo", t["escribiendo"] + "…") # the last steps go with the message as its traza
await respuesta.terminar(si_vacio=t["error"] if final.stop_reason == "refusal" else "…")
except (anthropic.APIConnectionError, anthropic.APIStatusError) as error:
# Claude failed midway (connection, 429 or 5xx after the SDK's own retries): end with what we have, «cortado».
actividad.pasos.append({"titulo": t["error"], "estado": "error", "detalle": type(error).__name__})
await actividad.poner("escribiendo", t["error"])
await respuesta.terminar(cortado=True, si_vacio=t["error"])
finally:
actividad.vivo.cancel()
async def eventos():
"""The bot's events (SSE), reconnecting with growing waits; each is handled in its own task, then acknowledged."""
vistos, espera = set(), 1
while True:
try:
async with sonoe.stream("GET", "/v1/bots/events", timeout=httpx.Timeout(15, read=60)) as r:
r.raise_for_status()
espera, datos = 1, []
async for linea in r.aiter_lines():
if linea.startswith("data:"):
datos.append(linea[5:].strip())
elif not linea and datos:
e, datos = json.loads("\n".join(datos)), []
if e.get("id") and e["id"] not in vistos:
vistos.add(e["id"])
yield e
except (httpx.HTTPError, json.JSONDecodeError):
await asyncio.sleep(espera)
espera = min(espera * 2, 60)
async def main():
tareas = set()
async def una(e):
try:
if e["tipo"] in ("mensaje", "comando") and e.get("menciona_al_bot", True):
await atender(e)
except httpx.HTTPError as error: # Sonoe said no (a 4xx names the field): the activity goes away with its ttl
print("Sonoe:", error)
finally:
await llamar("POST", "/v1/bots/events/ack", {"ids": [e["id"]]})
async for e in eventos():
tarea = asyncio.create_task(una(e))
tareas.add(tarea)
tarea.add_done_callback(tareas.discard)
if __name__ == "__main__":
asyncio.run(main())Example: TypeScript
The same agent in TypeScript (Node 22.18 or later runs it as is; with "type": "module" in your package.json).
npm install @anthropic-ai/sdk
export SONOE_BOT_TOKEN=sb_bot_… ANTHROPIC_API_KEY=sk-ant-…
node agent.ts// A Sonoe chat bot on Claude: live activity with steps, a reply streamed word by word, and the steps kept as its traza.
//
// npm install @anthropic-ai/sdk
// SONOE_BOT_TOKEN=sb_bot_… ANTHROPIC_API_KEY=sk-ant-… node agent.ts (Node 22.18+ runs TypeScript as is)
import Anthropic from "@anthropic-ai/sdk";
const SONOE = process.env.SONOE_API ?? "https://sonoeai.com";
// The most capable model. For a cheaper bot, use "claude-sonnet-5-5" or "claude-haiku-5-5".
const MODELO = process.env.CLAUDE_MODEL ?? "claude-opus-5-5";
const TOKEN = process.env.SONOE_BOT_TOKEN;
if (!TOKEN) throw new Error("Set SONOE_BOT_TOKEN");
const claude = new Anthropic(); // reads ANTHROPIC_API_KEY
// What people read, in their language (the event's locale).
const TEXTOS: Record<string, Record<string, string>> = {
es: { pensando: "Pensando…", hora: "Mirando la hora en {z}", escribiendo: "Escribiendo", error: "No pude terminar." },
en: { pensando: "Thinking…", hora: "Checking the time in {z}", escribiendo: "Writing", error: "I couldn't finish." },
pt: { pensando: "Pensando…", hora: "Vendo a hora em {z}", escribiendo: "Escrevendo", error: "Não consegui terminar." },
fr: { pensando: "Je réfléchis…", hora: "Je regarde l'heure à {z}", escribiendo: "J'écris", error: "Je n'ai pas pu finir." },
};
const TOOLS: Anthropic.Beta.BetaTool[] = [{
name: "hora_local",
description: "The current local time in an IANA time zone, such as America/Puerto_Rico or Asia/Tokyo.",
input_schema: { type: "object", properties: { zona: { type: "string" } }, required: ["zona"] },
eager_input_streaming: true,
}];
function horaLocal(zona: string): string {
try {
return new Intl.DateTimeFormat("en-GB", { timeZone: zona, hour: "2-digit", minute: "2-digit", weekday: "long" }).format(new Date());
} catch {
return `Unknown time zone: ${zona}`;
}
}
const dormir = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** One protocol call; on 429 (240 actions a minute) it waits and tries again. */
async function llamar(metodo: string, ruta: string, cuerpo?: unknown): Promise<any> {
for (let intento = 0; ; intento++) {
const r = await fetch(SONOE + ruta, {
method: metodo, body: cuerpo === undefined ? undefined : JSON.stringify(cuerpo),
headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
});
if (r.status === 429 && intento < 3) { await dormir(1000 * 2 ** intento); continue; }
if (!r.ok) throw new Error(`Sonoe ${r.status} ${metodo} ${ruta}: ${await r.text()}`);
return r.status === 204 ? {} : r.json();
}
}
type Paso = { titulo: string; estado: "pendiente" | "en_curso" | "hecho" | "error"; detalle?: string };
/** «Pensando…», then custom text and steps; refreshed so its ttl (45 s) never runs out while Claude works. */
class Actividad {
pasos: Paso[] = [];
private estado: Record<string, unknown> | null = null;
private vivo = setInterval(() => { if (this.estado) void this.poner(this.estado); }, 20_000);
private chat: number;
constructor(chat: number) { this.chat = chat; }
poner(estado: Record<string, unknown>) {
this.estado = estado;
return llamar("PUT", `/v1/bots/chats/${this.chat}/activity`, { ...estado, pasos: this.pasos.slice(-12), ttl: 45 });
}
parar() { clearInterval(this.vivo); }
}
/** The streamed reply: opened at the first word (a stream with no chunks for 60 s is cut), chunks every 0.25 s. */
class Respuesta {
id: number | null = null;
enviado = "";
private pendiente = "";
private ultimo = 0;
private chat: number;
private respondeA: number | null;
constructor(chat: number, respondeA: number | null) { this.chat = chat; this.respondeA = respondeA; }
async agregar(texto: string) {
this.pendiente += texto;
if (Date.now() - this.ultimo >= 250) await this.vaciar();
}
async vaciar() {
if (!this.pendiente) return;
if (this.id === null) this.id = (await llamar("POST", `/v1/bots/chats/${this.chat}/messages`, { flujo: true, responde_a: this.respondeA })).id;
const trozo = this.pendiente;
this.pendiente = "";
await llamar("POST", `/v1/bots/messages/${this.id}/delta`, { texto: trozo });
this.enviado += trozo;
this.ultimo = Date.now();
}
async terminar(cortado = false, siVacio = "…") {
await this.vaciar();
if (this.id === null) await llamar("POST", `/v1/bots/chats/${this.chat}/messages`, { texto: siVacio, responde_a: this.respondeA });
else await llamar("POST", `/v1/bots/messages/${this.id}/end`, { cerrar_actividad: true, cortado });
}
}
/** The chat so far as Claude's turns: the bot's messages are «assistant», people's are «user». */
function historial(e: any): Anthropic.Beta.BetaMessageParam[] {
const turnos: Anthropic.Beta.BetaMessageParam[] = (e.contexto ?? []).filter((m: any) => m.texto)
.map((m: any) => ({ role: m.autor.tipo === "bot" ? "assistant" : "user", content: m.texto }));
while (turnos.length && turnos[0].role === "assistant") turnos.shift();
return [...turnos, { role: "user", content: e.mensaje.texto }];
}
async function atender(e: any) {
const chat: number = e.chat.id;
const t = TEXTOS[(e.locale ?? "es").slice(0, 2)] ?? TEXTOS.en;
const actividad = new Actividad(chat);
const respuesta = new Respuesta(chat, e.chat.tipo === "grupo" ? e.mensaje.id : null); // in a group, as a reply
await actividad.poner({ estado: "pensando", texto: t.pensando });
const mensajes = historial(e);
const system = `You are /${e.bot.nombre} in Sonoe chat. Answer briefly in the language of the locale ${e.locale ?? "es"}.`;
try {
let final: Anthropic.Beta.BetaMessage;
while (true) {
const stream = claude.beta.messages.stream({
model: MODELO, max_tokens: 64000, thinking: { type: "adaptive" }, system, tools: TOOLS, messages: mensajes,
betas: ["server-side-fallback-2026-07-01"], fallbacks: "default",
});
for await (const ev of stream) {
if (ev.type === "content_block_delta" && ev.delta.type === "text_delta") {
if (!respuesta.enviado && respuesta.id === null && !actividad.pasos.some((p) => p.titulo === t.escribiendo)) {
actividad.pasos.push({ titulo: t.escribiendo, estado: "en_curso" });
await actividad.poner({ estado: "escribiendo", texto: `${t.escribiendo}…` });
}
await respuesta.agregar(ev.delta.text);
}
}
final = await stream.finalMessage();
const usos = final.content.filter((b): b is Anthropic.Beta.BetaToolUseBlock => b.type === "tool_use");
if (final.stop_reason !== "tool_use" || !usos.length) break; // end_turn, refusal or max_tokens
mensajes.push({ role: "assistant", content: final.content });
const resultados: Anthropic.Beta.BetaToolResultBlockParam[] = [];
for (const uso of usos) {
const zona = (uso.input as { zona?: unknown })?.zona;
if (typeof zona !== "string") { // eager input streaming: validate before running
resultados.push({ type: "tool_result", tool_use_id: uso.id, is_error: true, content: "zona must be a string" });
continue;
}
const paso: Paso = { titulo: t.hora.replace("{z}", zona).slice(0, 80), estado: "en_curso" };
actividad.pasos.push(paso);
await actividad.poner({ estado: "usando_herramienta", texto: `${paso.titulo}…`, herramienta: { nombre: uso.name, etiqueta: paso.titulo } });
const salida = horaLocal(zona);
Object.assign(paso, { estado: "hecho", detalle: salida });
resultados.push({ type: "tool_result", tool_use_id: uso.id, content: salida });
}
mensajes.push({ role: "user", content: resultados });
await actividad.poner({ estado: "pensando", texto: t.pensando });
}
for (const p of actividad.pasos) p.estado = "hecho";
await actividad.poner({ estado: "escribiendo", texto: `${t.escribiendo}…` }); // the last steps go with the message as its traza
await respuesta.terminar(false, final.stop_reason === "refusal" ? t.error : "…");
} catch (error) {
// Claude failed midway (connection, 429 or 5xx after the SDK's own retries): end with what we have, «cortado».
if (!(error instanceof Anthropic.APIError)) throw error; // APIConnectionError is an APIError too
actividad.pasos.push({ titulo: t.error, estado: "error", detalle: error.constructor.name });
await actividad.poner({ estado: "escribiendo", texto: t.error });
await respuesta.terminar(true, t.error);
} finally {
actividad.parar();
}
}
/** The bot's events (SSE), reconnecting with growing waits. */
async function* eventos(): AsyncGenerator<any> {
const vistos = new Set<number>();
for (let espera = 1000; ; espera = Math.min(espera * 2, 60_000)) {
try {
const r = await fetch(`${SONOE}/v1/bots/events`, { headers: { Authorization: `Bearer ${TOKEN}`, Accept: "text/event-stream" } });
if (!r.ok || !r.body) throw new Error(`Sonoe ${r.status}`);
espera = 1000;
let resto = "";
for await (const trozo of r.body.pipeThrough(new TextDecoderStream())) {
resto += trozo;
let fin: number;
while ((fin = resto.indexOf("\n\n")) >= 0) {
const datos = resto.slice(0, fin).split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join("\n");
resto = resto.slice(fin + 2);
if (!datos) continue;
const e = JSON.parse(datos);
if (e.id && !vistos.has(e.id)) { vistos.add(e.id); yield e; }
}
}
} catch (error) {
console.error("Reconnecting:", (error as Error).message);
}
await dormir(espera);
}
}
for await (const e of eventos()) {
// Each event in its own task, acknowledged when it's handled (it comes again if the bot falls over before).
void (async () => {
try {
if ((e.tipo === "mensaje" || e.tipo === "comando") && e.menciona_al_bot !== false) await atender(e);
} catch (error) {
console.error((error as Error).message);
} finally {
await llamar("POST", "/v1/bots/events/ack", { ids: [e.id] });
}
})();
}How the examples behave
- The model.
claude-opus-5-5withthinking: {type: "adaptive"}: Claude decides how much to think. For a cheaper bot, setCLAUDE_MODELtoclaude-sonnet-5-5orclaude-haiku-5-5; nothing else changes. - Streaming.
client.beta.messages.stream(…)gives each text chunk as it's written, andget_final_message()/finalMessage()the whole message, with itsstop_reasonand tool calls. - Refusals. The examples opt into server-side fallbacks (
fallbacks: "default", betaserver-side-fallback-2026-07-01): if the model declines for a policy reason, the API retries on the recommended model inside the same call. Drop those two parameters to turn it off. - The reply opens at the first word. Thinking can take a while, and a stream with no chunks for 60 s is closed by Sonoe (
cortado). Until the first word, the activity says what's happening. - Chunks every 0.25 s. A delta per token would hit the limit of 1,200 chunks a minute; grouping them keeps the text smooth.
- The activity stays alive. Its
ttlis 45 s and it's refreshed every 20 s while Claude works; if the agent goes down, it disappears on its own. - Steps for tools. Each tool call is a step
en_cursowhile it runs andhechowith its result asdetalle. The tool's input is validated before running it (eager input streaming hands it over as it's written). - If Claude fails midway (connection,
429or5xxafter the SDK's retries), the agent adds a step withestado: error, then sendsendwith what it streamed and"cortado": true: the message shows it was cut off. If nothing was streamed yet, it sends a short plain message instead. - Rate limits. A
429from Sonoe (240 actions a minute per bot) waits and retries. Each event is acknowledged once handled; if the agent falls over first, it comes again when it reconnects (use itsidto skip repeats).
Reference
Activity states
estado | Extra | Reads as |
|---|---|---|
pensando | — | Thinking… |
buscando | consulta | Searching "…" |
leyendo | fuente {titulo, url} | Reading … |
usando_herramienta | herramienta {nombre, etiqueta} | the label |
escribiendo | — | Typing… |
esperando_respuesta | — | Waiting for your answer… |
listo | — | (removed) |
texto replaces the state's name with your own words, in the person's locale.
Steps, ttl and traza
pasos: up to 12, each{titulo, estado, detalle}withestadopendiente·en_curso·hecho·error. Send all of them on every update: they replace the previous ones.ttl: seconds the activity stays without news (1–120, 30 by default). Update it before then, or end it.traza: a message sent withcerrar_actividad: true(the default) ends the activity and keeps its last state and steps as the message'straza.DELETE /v1/bots/chats/{chat}/activityends it without a trace.
A streamed reply
| Call | Body | What happens |
|---|---|---|
POST /v1/bots/chats/{chat}/messages | {"flujo": true} (and responde_a) | 201: the message, estado: escribiendo |
POST /v1/bots/messages/{id}/delta | {"texto": "…"} | the text grows live; 409 once it's closed |
POST /v1/bots/messages/{id}/end | {"texto"?, "bloques"?, "cerrar_actividad"?, "cortado"?} | the finished message; texto replaces what was streamed, cortado: true marks it as cut off |
The phone notification goes out at end, not on every chunk. After 60 s without chunks Sonoe closes it with what it had, marked cortado.
Limits
| What | How much |
|---|---|
Bot actions (not GET) | 240 a minute |
| Stream chunks | 1,200 a minute |
| Message | 4,000 characters, 10 blocks |
| Activity | ttl 1–120 s, 12 steps |
| Stream without chunks | closed after 60 s |
Going over: 429. The whole protocol, with every event, block and limit: Sonoe chat bots.
Test mode
Every bot of yours has a private sandbox: Mis bots → your bot → Probar. It's a normal Sonoe chat between you and your bot, so you see exactly what people will see, live: the activity and its steps, the reply growing, the blocks and buttons, the traza.

- The log (on the right; a bottom sheet on a phone) lists, live and newest first, each event Sonoe handed your bot (and how: SSE,
?stream=0or webhook, with the webhook's HTTP status) and each call your bot made: the method and route, the HTTP status, how long it took, a summary of what it sent, and the API's error when there is one (a409delta afterend, a422naming the invalid field, a429). It also shows when the activity'sttlran out or a stream was cut, and the pace of the last stream (chunks, characters, characters per second). Tap a line to see everything that travelled. Tokens and secrets are always redacted. - Quick actions: Send a test message, Simulate a button (it lists the buttons and list options your bot sent in this chat and taps one: your bot gets the
accionevent), Copy event (the selected line as JSON) and Clear (the chat's messages and the log; the bot stays). - Not connected: if your bot has no SSE stream open, or its webhook isn't answering
2xx, test mode says so, with how many events are waiting and how to connect it. - Isolated: test chats are labelled Test, only you see them, they're not in your inbox, don't notify, don't count in your bot's stats, and are deleted after 7 days. Your bot sees
"chat": {"prueba": true}in their events, in case it wants to behave differently there.