Skip to main content

TypeScript SDK reference

The broods package ships three clients:

ClientImportCredentialUse it to
BroodsClientbroodsRuntime keyRun agents over HTTP and SSE
WebSocketClientbroodsRuntime keyRun and steer agents over one socket
BroodsAccountClientbroods/accountAccount key or role sessionCreate and change config while your app runs

There is no Python SDK yet. Call the HTTP API directly.

Install​

bun add broods # or: npm install broods

ai is the Vercel AI SDK and a peer dependency. npm and bun install it for you. On a package manager that skips peers, add it yourself, or valid agent configs fail to compile.

Generated references​

broods dev and broods deploy write typed references to broods/_generated/api.ts. The folder is empty until the first sync.

import { api } from "./broods/_generated/api";

api.agents.myAgent; // AgentReference: id, project, stage, endpoint
api.channels.myTelegram; // ChannelReference: type, agent, webhook path
api.workspaces.notes; // workspace id
api.sandboxes.lambda; // sandbox id

Pass an AgentReference to the client. It carries the routing metadata, and the gateway rejects a reference whose scope does not match the key.

BroodsClient​

import { BroodsClient, signUserToken } from "broods";

const client = new BroodsClient({
userToken: await signUserToken({ userId: "me" }),
});
OptionDefault
apiKeyThe runtime key. BROODS_API_KEY, loaded from .env and .env.local
baseUrlBROODS_BASE_URL, then BROODS_HOST, then https://gateway.broods.app
hostHostname form of baseUrl. gateway.broods.app becomes https://gateway.broods.app
userTokenNone. The signed-in user's token, or a function that returns a fresh one per call
fetchGlobal fetch

The runtime key, bsk_..., is scoped to one project and stage. It reaches only agents with publicAccess: true in that stage.

User tokens​

An agent created now requires a user token beside the runtime key, so a visitor cannot read or steer another user's conversation by guessing its key. Sign one on your server with the stage's signing secret, and hand it to the client.

import { signUserToken } from "broods";

const token = await signUserToken({ userId: "user_123" });
FieldDefault
userIdRequired. Your id for the user. Letters, digits and ._@+=-, 128 at most
conversationsAny key. Or the only conversation keys this user may use
credentialNone. The user's own bearer, sent to hosted MCP servers only
ttlMs10 minutes. 60 at most
secretBROODS_USER_TOKEN_SECRET, which broods dev and deploy write

Never call signUserToken in a browser: the signing secret speaks for every user of the stage. Conversation keys and event ids come back under the user, as bsu:<userId>:<key>; pass either form back. See Users behind the runtime key.

Methods​

MethodReturnsWhat it does
run(agent, input){ text, events, output }Streams a run and collects the text, parts and structured output
stream(agent, input)AsyncGenerator<AgentStreamPart>Yields AI SDK stream parts, plus structured-output, as they arrive
runAsync(agent, input)AsyncAgentRunStarts a background run, returns runId and statusUrl
continue(agent, { conversationKey })AsyncAgentRunRe-enters a run that stopped on the step cap or a provider fault
answer(agent, { conversationKey, answers })AnswersAcceptedAnswers an awaiting_input run's prompts; the run resumes in the background
getAsyncStatus(runOrUrl)AsyncStatusOne status snapshot. { status: "not_found" } on 404
waitForAsyncStatus(runOrUrl, options)AsyncStatusPolls until a settled status or timeout
agent(ref)AgentHandleBinds run, stream, runAsync, continue, answer to one agent
channelWebhookUrl(ref)stringWebhook URL for a generated channel reference
accountWebhookUrl(accountId, type)stringProduction webhook URL for a channel type
stageWebhookUrl(accountId, endpointId, type)stringWebhook URL pinned to one non-production stage

AsyncAgentRun has runId, eventId, statusUrl, conversationKey, poll() and wait(options). wait and waitForAsyncStatus take intervalMs, default 2000, timeoutMs, default 180000, and signal, and return on completed, failed, expired, awaiting_approval, awaiting_input or not_found.

const result = await client.run(api.agents.myAgent, { input: "Hello" });

for await (const part of client.stream(api.agents.myAgent, {
input: "Tell me a story.",
})) {
if (part.type === "text-delta") process.stdout.write(part.text);
}

const job = await client.runAsync(api.agents.myAgent, {
input: "Write the report.",
});
const status = await job.wait({ timeoutMs: 300_000 });

Run input​

Pass exactly one of input or events.

FieldDescription
inputOne user text message
eventsAI SDK model messages, for images, files, tool approval responses
conversationKeyConversation to continue. Omit for a new one
eventIdCorrelation id. Generated when omitted
idempotencyKeyRetry identity within the conversation. Defaults to eventId, bound for 7 days
modeWhat to do when the conversation is busy. steer is the default, then followup, collect, reject
systemOne-turn system message or messages, not persisted
modelPer-run call settings such as temperature, maxOutputTokens, reasoning, providerOptions
signalAbortSignal. On run and stream, aborting closes the stream and core fails the run when it next writes a frame, so a running tool call finishes first. On runAsync it cancels only the request: a run core already accepted keeps going, so pass an eventId and retry with the same one

model rejects provider, modelId, output and apiKey, so a request cannot swap the model or credentials. With a runtime key, system and model need allowRunOverrides: true on the agent, or the run fails with 403 run_overrides_disabled.

await client.run(api.agents.myAgent, {
events: [
{
role: "user",
content: [
{ type: "text", text: "What is in this image?" },
{ type: "image", image: "data:image/png;base64,iVBORw0KGgo..." },
],
},
],
model: { temperature: 0.3, reasoning: "high" },
});

Stream parts​

stream yields AgentStreamPart values: the AI SDK TextStreamPart types such as text-delta, reasoning-delta, tool-call, tool-result, finish, error and the rest, plus { type: "structured-output", output } at the end of a run whose agent sets model.output. An error part throws. Closing the stream before the run finishes aborts the run and marks it failed. Steps that already finished stay in the conversation. Use runAsync when the caller may disconnect.

Upgrading from a release where stream and run().events were typed TextStreamPart<ToolSet>: code that assigns parts to that type, or switches over part.type exhaustively, no longer compiles. Type it AgentStreamPart (exported from broods), or skip structured-output first:

for await (const part of client.stream(api.agents.myAgent, input)) {
if (part.type === "structured-output") continue;
handle(part); // TextStreamPart<ToolSet>
}

Async status​

statusMeaning
accepted, queued, applied, processingNot finished
awaiting_approvalA tool needs approval. approvals lists them
awaiting_inputThe agent asked with ask_questions. questions lists the prompts
completedDone. response and result hold the answer
failederror explains. stoppedByUser: true means a deliberate stop
expiredQueued work was never run

Answer an awaiting_input run with answer, one entry per prompt. The conversation resumes in the background as a new turn, named by eventId and runId in the result; pass runId to waitForAsyncStatus to follow it. runId is present only when a turn was started or queued, and names the last turn an answer started or queued when one call answers several prompts. answer and continue take signal like runAsync: it cancels only the request, and answers core already accepted still resume the run. Pass your own eventId and reuse it when you retry after an abort, so the retry cannot start a second run. Approve an awaiting_approval run by sending the responses as events:

const status = await job.wait();
const prompt = status.questions?.[0];
if (status.status === "awaiting_input" && prompt) {
const answered = await client.answer(api.agents.myAgent, {
conversationKey: job.conversationKey,
answers: [{ statusId: prompt.statusId, answers: { color: ["Blue"] } }],
});
if (answered.runId) await client.waitForAsyncStatus(answered.runId);
}
if (status.status === "awaiting_approval") {
await client.runAsync(api.agents.myAgent, {
conversationKey: job.conversationKey,
events: [
{
role: "tool",
content: (status.approvals ?? []).map((approval) => ({
type: "tool-approval-response",
approvalId: approval.approvalId,
approved: true,
})),
},
],
});
}

Every status core returns also carries the owning agentId, plus requestedMode, appliedMode and appliedToEventId, which say whether a busy request steered the live run or became a follow-up. See Conversations.

Errors​

A refused request throws BroodsApiError with the server's error as fields, from a JSON body, the SSE error frame a streamed run is refused with, or a WebSocket error frame that carries a status. Branch on code, which stays stable across releases. A core older than the SDK sends no code on a streamed refusal, so code is then undefined. The message reads Run failed: 403 This agent needs a user token. (user_token_required), so code that matched the code in the message text keeps working. broods/account exports the class too.

FieldDescription
statusHTTP status
codeStable error code, such as user_token_required
typeError class, such as permission_error
serverMessageThe server's message, or the raw body when it sent no envelope
bodyThe raw response body
import { BroodsApiError } from "broods";

try {
await client.run(api.agents.myAgent, { input: "Hello" });
} catch (error) {
if (error instanceof BroodsApiError && error.code === "user_token_required") {
// sign a user token and retry
}
}

Busy conversations​

A stream call that lands on a busy conversation and is queued instead of streamed throws IngressAcceptedError. Its accepted field holds the run id, so you can poll it:

import { IngressAcceptedError } from "broods";

try {
for await (const part of client.stream(api.agents.myAgent, {
conversationKey,
mode: "followup",
input: "Then summarize.",
})) {
// ...
}
} catch (error) {
if (!(error instanceof IngressAcceptedError)) throw error;
const final = await client.waitForAsyncStatus(error.accepted);
}

WebSocketClient​

Runs agents over one socket with durable replay, steering and cancel. Also exported as BroodsWebSocketClient.

import { WebSocketClient } from "broods";

const ws = new WebSocketClient();
OptionDefault
apiKeyThe runtime key. BROODS_API_KEY. Required
userTokenNone. A user token every socket opens with
baseUrl, hostAs for BroodsClient. https becomes wss
WebSocketglobalThis.WebSocket. Pass one on older runtimes
connectTimeoutMs2000

The key travels as the Sec-WebSocket-Protocol entries broods.v1 and broods.token.<key>, never in the URL, and a user token as broods.user.<token>. subscribe and attach also take userToken, over the client's, since a token outlives no more than an hour.

MethodWhat it does
subscribe(input, handlers)Starts a run and calls handlers. Returns a subscription
stream(input)Same run as an async generator of messages
attach(input, handlers)Reattaches to a running event and replays from a cursor
subscription.sendControl(m)Sends more input to the live run. Steers by default
subscription.close()Closes the socket

subscribe takes the run input fields above plus agent, a reference, sessionId, the conversation key, and signal. An aborted signal sends cancel. attach also takes signal; aborting it closes the socket and calls onError once, but sends no cancel, so the run keeps going. Pass answers instead of input to answer an open ask_questions prompt; the resumed run streams back on the same socket.

HandlerReceives
onMessageEvery message, with output envelopes unwrapped to the stream part
onOutputThe raw output envelope { cursor, replay, data }. Store cursor to resume
onMeta{ sessionId, taskId } once the socket is ready. Safe point for sendControl
onDoneThe run finished
onErrorAn error frame or a socket failure
const sub = ws.subscribe(
{
agent: api.agents.myAgent,
sessionId: "ticket-42",
input: "Investigate the failure.",
},
{
onMeta() {
sub.sendControl({
requestId: "c1",
eventId: "turn-2",
input: "Check the gateway first.",
});
},
onMessage(message) {
if (message.type === "text-delta") process.stdout.write(message.text);
},
},
);

attach takes agentId, conversationKey, eventId, runId, requestId and an optional afterCursor. It closes its socket after onDone. When the gateway answers replay_unavailable (no such run for this caller, or a cursor it no longer keeps), it calls onError and closes; poll the run's status instead. See the WebSocket protocol for frames, and the websocket demo.

BroodsAccountClient​

Creates and changes config at runtime, for example one agent per customer. Resources you declare in broods/ belong to broods dev and broods deploy; use this client for everything created on the fly.

import { BroodsAccountClient } from "broods/account";

const account = new BroodsAccountClient({
accountSecret: process.env.BROODS_ACCOUNT_SECRET,
});
OptionDefault
accountSecretThe account key. BROODS_ACCOUNT_SECRET, a bask_... value
sessionTokenBROODS_SESSION_TOKEN, a bsts_... value. Wins over the account key
baseUrlBROODS_BASE_URL, then https://gateway.broods.app
fetchGlobal fetch

The entry point has no dependencies and uses plain fetch, so it runs in Convex actions, Cloudflare Workers and other edge runtimes where the main broods entry cannot load.

ResourceMethods
AccountgetAccount, updateAccount, rotateSecret, deleteAccount, assumeRole, getStorageTrust, webhookUrl
AgentslistAgents, createAgent, getAgent, updateAgent, deleteAgent
EnvlistEnvVars, setEnvVar, deleteEnvVar
CronslistCrons, createCron, getCron, updateCron, deleteCron, listCronRuns
WorkspaceslistWorkspaces, createWorkspace, getWorkspace, updateWorkspace, deleteWorkspace
FileslistWorkspaceFiles, getWorkspaceFileUrl, uploadWorkspaceFile, renameWorkspaceFile, deleteWorkspaceFile
SandboxeslistSandboxes, createSandbox, getSandbox, updateSandbox, deleteSandbox, suspendSandbox, resumeSandbox, terminateSandbox, snapshotSandbox, openSandboxTerminal
MCPlistMcp(scope), createMcp, uploadMcpBundle, getMcp, updateMcp, deleteMcp
PolicieslistPolicies, createPolicy, getPolicy, updatePolicy, deletePolicy
RoleslistRoles, createRole, getRole, updateRole, deleteRole
Auditaudit.list, audit.verify, audit.getSink, audit.setSink, audit.deleteSink
ChannelslistChannels, createChannel, getChannel, updateChannel, deleteChannel
SkillslistSkills, createSkill, getSkill, uploadSkill, deleteSkill

Behavior shared by every method:

  • get* returns null on 404 and delete* returns false, so upserts need no try/catch.
  • Other failures throw BroodsAccountApiError, a BroodsApiError (see Errors).
  • Updates deep-merge config into the stored config. A null value deletes a key.
  • Secrets inside configs are encrypted at rest and come back as ********. Sending ******** back keeps the stored value.
const existing = await account.getAgent(savedAgentId);
const agent = existing
? await account.updateAgent(savedAgentId, { config: config })
: await account.createAgent({ name: `tenant-${customerId}`, config: config });

const role = await account.createRole({
name: "agents-reader",
policy: {
version: 1,
rules: [{ id: "r1", effect: "allow", actions: ["agents:read"] }],
},
});
const session = await account.assumeRole(role.roleId, { ttlSeconds: 900 });
const scoped = new BroodsAccountClient({ sessionToken: session.token });

See Security for roles and sessions, and the API reference for request and response schemas.

Log and run history pages​

With a logged-in BroodsAccountClient, use readLogPage(scope, { range, limit }) or listRuns(scope, { range, limit }). The range uses epoch milliseconds: from is inclusive, to exclusive, and the maximum width is 30 days. Each page searches at most the newest hour of that range. listRuns can search a shorter window in a busy stage.

const to = Date.now();
const range = { from: to - 24 * 60 * 60 * 1000, to: to };
const page = await account.readLogPage(scope, { range: range, limit: 50 });
if (page.incomplete) throw new Error(page.incomplete);
if (page.nextTo !== undefined) {
const older = await account.readLogPage(scope, {
range: { from: range.from, to: page.nextTo },
limit: 50,
});
if (older.incomplete) throw new Error(older.incomplete);
console.log(older.logs);
}

nextTo means more of the requested range remains to be searched, even when the page has no matching rows. Keep the original from and pass nextTo as the next to. Do not advance after incomplete; retry the same range. readLogPage accepts level and sandboxId; listRuns accepts agentId and status. Status filters apply to the fetched page, so a filtered page can contain fewer than limit runs.

The MCP tools read-logs and list-runs use these bounded pages, default to the last hour, and return the requested range plus nextTo when available. Pass from and to to query older history. The array-returning readLogs and unbounded listRuns remain available for existing SDK callers.